From 80c427d051c1340bc74245f715920cc092708745 Mon Sep 17 00:00:00 2001 From: Michael McLoughlin Date: Fri, 4 Jan 2019 10:57:47 -0800 Subject: [PATCH] src: type for representing file:line positions Updates #5 --- src/src.go | 28 ++++++++++++++++++++++++++++ src/src_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 src/src.go create mode 100644 src/src_test.go diff --git a/src/src.go b/src/src.go new file mode 100644 index 0000000..a4a5da9 --- /dev/null +++ b/src/src.go @@ -0,0 +1,28 @@ +package src + +import "strconv" + +// Position represents a position in a source file. +type Position struct { + Filename string + Line int // 1-up +} + +// IsValid reports whether the position is valid: Line must be positive, but +// Filename may be empty. +func (p Position) IsValid() bool { + return p.Line > 0 +} + +// String represents Position as a string. +func (p Position) String() string { + if !p.IsValid() { + return "-" + } + var s string + if p.Filename != "" { + s += p.Filename + ":" + } + s += strconv.Itoa(p.Line) + return s +} diff --git a/src/src_test.go b/src/src_test.go new file mode 100644 index 0000000..e57c17f --- /dev/null +++ b/src/src_test.go @@ -0,0 +1,27 @@ +package src_test + +import ( + "fmt" + + "github.com/mmcloughlin/avo/src" +) + +func ExamplePosition_IsValid() { + fmt.Println(src.Position{"a.go", 42}.IsValid()) + fmt.Println(src.Position{"", 42}.IsValid()) + fmt.Println(src.Position{"a.go", -1}.IsValid()) + // Output: + // true + // true + // false +} + +func ExamplePosition_String() { + fmt.Println(src.Position{"a.go", 42}) + fmt.Println(src.Position{"", 42}) + fmt.Println(src.Position{"a.go", -1}) // invalid + // Output: + // a.go:42 + // 42 + // - +}