src: type for representing file:line positions

Updates #5
This commit is contained in:
Michael McLoughlin
2019-01-04 10:57:47 -08:00
parent 301d0c137a
commit 80c427d051
2 changed files with 55 additions and 0 deletions

28
src/src.go Normal file
View File

@@ -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
}

27
src/src_test.go Normal file
View File

@@ -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
// -
}