]> Cypherpunks repositories - gostls13.git/commitdiff
go/token: add (*File).LineStart, which returns Pos for a given line
authorAlan Donovan <adonovan@google.com>
Fri, 7 Sep 2018 13:54:38 +0000 (09:54 -0400)
committerAlan Donovan <adonovan@google.com>
Mon, 10 Sep 2018 18:29:25 +0000 (18:29 +0000)
LineStart returns the position of the start of a given line.
Like MergeLine, it panics if the 1-based line number is invalid.

This function is especially useful in programs that occasionally
handle non-Go files such as assembly but wish to use the token.Pos
mechanism to identify file positions.

Change-Id: I5f774c0690074059553cdb38c0f681f5aafc8da1
Reviewed-on: https://go-review.googlesource.com/134075
Reviewed-by: Robert Griesemer <gri@golang.org>
src/go/token/position.go
src/go/token/position_test.go

index 241133fe263b393379d54c6dc8cc7d0e2bdbab73..3f5a390078d0d561ab8d22cf8affc9790527cb73 100644 (file)
@@ -146,7 +146,7 @@ func (f *File) AddLine(offset int) {
 // MergeLine will panic if given an invalid line number.
 //
 func (f *File) MergeLine(line int) {
-       if line <= 0 {
+       if line < 1 {
                panic("illegal line number (line numbering starts at 1)")
        }
        f.mutex.Lock()
@@ -209,6 +209,21 @@ func (f *File) SetLinesForContent(content []byte) {
        f.mutex.Unlock()
 }
 
+// LineStart returns the Pos value of the start of the specified line.
+// It ignores any alternative positions set using AddLineColumnInfo.
+// LineStart panics if the 1-based line number is invalid.
+func (f *File) LineStart(line int) Pos {
+       if line < 1 {
+               panic("illegal line number (line numbering starts at 1)")
+       }
+       f.mutex.Lock()
+       defer f.mutex.Unlock()
+       if line > len(f.lines) {
+               panic("illegal line number")
+       }
+       return Pos(f.base + f.lines[line-1])
+}
+
 // A lineInfo object describes alternative file, line, and column
 // number information (such as provided via a //line directive)
 // for a given file offset.
index 63984bc872c824113058bd1526fa6b85f631a467..7d465dffa621f719f54dcb577db243f6d6fa83d8 100644 (file)
@@ -324,3 +324,18 @@ done
                checkPos(t, "3. Position", got3, want)
        }
 }
+
+func TestLineStart(t *testing.T) {
+       const src = "one\ntwo\nthree\n"
+       fset := NewFileSet()
+       f := fset.AddFile("input", -1, len(src))
+       f.SetLinesForContent([]byte(src))
+
+       for line := 1; line <= 3; line++ {
+               pos := f.LineStart(line)
+               position := fset.Position(pos)
+               if position.Line != line || position.Column != 1 {
+                       t.Errorf("LineStart(%d) returned wrong pos %d: %s", line, pos, position)
+               }
+       }
+}