diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-16 19:23:18 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-16 19:23:18 +0000 |
commit | 43a123c1ae6613b3efeed291fa552ecd909d3acf (patch) | |
tree | fd92518b7024bc74031f78a1cf9e454b65e73665 /src/go/token | |
parent | Initial commit. (diff) | |
download | golang-1.20-43a123c1ae6613b3efeed291fa552ecd909d3acf.tar.xz golang-1.20-43a123c1ae6613b3efeed291fa552ecd909d3acf.zip |
Adding upstream version 1.20.14.upstream/1.20.14upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/go/token')
-rw-r--r-- | src/go/token/example_test.go | 77 | ||||
-rw-r--r-- | src/go/token/position.go | 556 | ||||
-rw-r--r-- | src/go/token/position_bench_test.go | 24 | ||||
-rw-r--r-- | src/go/token/position_test.go | 477 | ||||
-rw-r--r-- | src/go/token/serialize.go | 70 | ||||
-rw-r--r-- | src/go/token/serialize_test.go | 105 | ||||
-rw-r--r-- | src/go/token/token.go | 341 | ||||
-rw-r--r-- | src/go/token/token_test.go | 33 |
8 files changed, 1683 insertions, 0 deletions
diff --git a/src/go/token/example_test.go b/src/go/token/example_test.go new file mode 100644 index 0000000..0011703 --- /dev/null +++ b/src/go/token/example_test.go @@ -0,0 +1,77 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package token_test + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" +) + +func Example_retrievePositionInfo() { + fset := token.NewFileSet() + + const src = `package main + +import "fmt" + +import "go/token" + +//line :1:5 +type p = token.Pos + +const bad = token.NoPos + +//line fake.go:42:11 +func ok(pos p) bool { + return pos != bad +} + +/*line :7:9*/func main() { + fmt.Println(ok(bad) == bad.IsValid()) +} +` + + f, err := parser.ParseFile(fset, "main.go", src, 0) + if err != nil { + fmt.Println(err) + return + } + + // Print the location and kind of each declaration in f. + for _, decl := range f.Decls { + // Get the filename, line, and column back via the file set. + // We get both the relative and absolute position. + // The relative position is relative to the last line directive. + // The absolute position is the exact position in the source. + pos := decl.Pos() + relPosition := fset.Position(pos) + absPosition := fset.PositionFor(pos, false) + + // Either a FuncDecl or GenDecl, since we exit on error. + kind := "func" + if gen, ok := decl.(*ast.GenDecl); ok { + kind = gen.Tok.String() + } + + // If the relative and absolute positions differ, show both. + fmtPosition := relPosition.String() + if relPosition != absPosition { + fmtPosition += "[" + absPosition.String() + "]" + } + + fmt.Printf("%s: %s\n", fmtPosition, kind) + } + + //Output: + // + // main.go:3:1: import + // main.go:5:1: import + // main.go:1:5[main.go:8:1]: type + // main.go:3:1[main.go:10:1]: const + // fake.go:42:11[main.go:13:1]: func + // fake.go:7:9[main.go:17:14]: func +} diff --git a/src/go/token/position.go b/src/go/token/position.go new file mode 100644 index 0000000..cbc2ddb --- /dev/null +++ b/src/go/token/position.go @@ -0,0 +1,556 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package token + +import ( + "fmt" + "sort" + "sync" + "sync/atomic" +) + +// ----------------------------------------------------------------------------- +// Positions + +// Position describes an arbitrary source position +// including the file, line, and column location. +// A Position is valid if the line number is > 0. +type Position struct { + Filename string // filename, if any + Offset int // offset, starting at 0 + Line int // line number, starting at 1 + Column int // column number, starting at 1 (byte count) +} + +// IsValid reports whether the position is valid. +func (pos *Position) IsValid() bool { return pos.Line > 0 } + +// String returns a string in one of several forms: +// +// file:line:column valid position with file name +// file:line valid position with file name but no column (column == 0) +// line:column valid position without file name +// line valid position without file name and no column (column == 0) +// file invalid position with file name +// - invalid position without file name +func (pos Position) String() string { + s := pos.Filename + if pos.IsValid() { + if s != "" { + s += ":" + } + s += fmt.Sprintf("%d", pos.Line) + if pos.Column != 0 { + s += fmt.Sprintf(":%d", pos.Column) + } + } + if s == "" { + s = "-" + } + return s +} + +// Pos is a compact encoding of a source position within a file set. +// It can be converted into a Position for a more convenient, but much +// larger, representation. +// +// The Pos value for a given file is a number in the range [base, base+size], +// where base and size are specified when a file is added to the file set. +// The difference between a Pos value and the corresponding file base +// corresponds to the byte offset of that position (represented by the Pos value) +// from the beginning of the file. Thus, the file base offset is the Pos value +// representing the first byte in the file. +// +// To create the Pos value for a specific source offset (measured in bytes), +// first add the respective file to the current file set using FileSet.AddFile +// and then call File.Pos(offset) for that file. Given a Pos value p +// for a specific file set fset, the corresponding Position value is +// obtained by calling fset.Position(p). +// +// Pos values can be compared directly with the usual comparison operators: +// If two Pos values p and q are in the same file, comparing p and q is +// equivalent to comparing the respective source file offsets. If p and q +// are in different files, p < q is true if the file implied by p was added +// to the respective file set before the file implied by q. +type Pos int + +// The zero value for Pos is NoPos; there is no file and line information +// associated with it, and NoPos.IsValid() is false. NoPos is always +// smaller than any other Pos value. The corresponding Position value +// for NoPos is the zero value for Position. +const NoPos Pos = 0 + +// IsValid reports whether the position is valid. +func (p Pos) IsValid() bool { + return p != NoPos +} + +// ----------------------------------------------------------------------------- +// File + +// A File is a handle for a file belonging to a FileSet. +// A File has a name, size, and line offset table. +type File struct { + name string // file name as provided to AddFile + base int // Pos value range for this file is [base...base+size] + size int // file size as provided to AddFile + + // lines and infos are protected by mutex + mutex sync.Mutex + lines []int // lines contains the offset of the first character for each line (the first entry is always 0) + infos []lineInfo +} + +// Name returns the file name of file f as registered with AddFile. +func (f *File) Name() string { + return f.name +} + +// Base returns the base offset of file f as registered with AddFile. +func (f *File) Base() int { + return f.base +} + +// Size returns the size of file f as registered with AddFile. +func (f *File) Size() int { + return f.size +} + +// LineCount returns the number of lines in file f. +func (f *File) LineCount() int { + f.mutex.Lock() + n := len(f.lines) + f.mutex.Unlock() + return n +} + +// AddLine adds the line offset for a new line. +// The line offset must be larger than the offset for the previous line +// and smaller than the file size; otherwise the line offset is ignored. +func (f *File) AddLine(offset int) { + f.mutex.Lock() + if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size { + f.lines = append(f.lines, offset) + } + f.mutex.Unlock() +} + +// MergeLine merges a line with the following line. It is akin to replacing +// the newline character at the end of the line with a space (to not change the +// remaining offsets). To obtain the line number, consult e.g. Position.Line. +// MergeLine will panic if given an invalid line number. +func (f *File) MergeLine(line int) { + if line < 1 { + panic(fmt.Sprintf("invalid line number %d (should be >= 1)", line)) + } + f.mutex.Lock() + defer f.mutex.Unlock() + if line >= len(f.lines) { + panic(fmt.Sprintf("invalid line number %d (should be < %d)", line, len(f.lines))) + } + // To merge the line numbered <line> with the line numbered <line+1>, + // we need to remove the entry in lines corresponding to the line + // numbered <line+1>. The entry in lines corresponding to the line + // numbered <line+1> is located at index <line>, since indices in lines + // are 0-based and line numbers are 1-based. + copy(f.lines[line:], f.lines[line+1:]) + f.lines = f.lines[:len(f.lines)-1] +} + +// SetLines sets the line offsets for a file and reports whether it succeeded. +// The line offsets are the offsets of the first character of each line; +// for instance for the content "ab\nc\n" the line offsets are {0, 3}. +// An empty file has an empty line offset table. +// Each line offset must be larger than the offset for the previous line +// and smaller than the file size; otherwise SetLines fails and returns +// false. +// Callers must not mutate the provided slice after SetLines returns. +func (f *File) SetLines(lines []int) bool { + // verify validity of lines table + size := f.size + for i, offset := range lines { + if i > 0 && offset <= lines[i-1] || size <= offset { + return false + } + } + + // set lines table + f.mutex.Lock() + f.lines = lines + f.mutex.Unlock() + return true +} + +// SetLinesForContent sets the line offsets for the given file content. +// It ignores position-altering //line comments. +func (f *File) SetLinesForContent(content []byte) { + var lines []int + line := 0 + for offset, b := range content { + if line >= 0 { + lines = append(lines, line) + } + line = -1 + if b == '\n' { + line = offset + 1 + } + } + + // set lines table + f.mutex.Lock() + f.lines = lines + 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(fmt.Sprintf("invalid line number %d (should be >= 1)", line)) + } + f.mutex.Lock() + defer f.mutex.Unlock() + if line > len(f.lines) { + panic(fmt.Sprintf("invalid line number %d (should be < %d)", line, len(f.lines))) + } + 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. +type lineInfo struct { + // fields are exported to make them accessible to gob + Offset int + Filename string + Line, Column int +} + +// AddLineInfo is like AddLineColumnInfo with a column = 1 argument. +// It is here for backward-compatibility for code prior to Go 1.11. +func (f *File) AddLineInfo(offset int, filename string, line int) { + f.AddLineColumnInfo(offset, filename, line, 1) +} + +// AddLineColumnInfo adds alternative file, line, and column number +// information for a given file offset. The offset must be larger +// than the offset for the previously added alternative line info +// and smaller than the file size; otherwise the information is +// ignored. +// +// AddLineColumnInfo is typically used to register alternative position +// information for line directives such as //line filename:line:column. +func (f *File) AddLineColumnInfo(offset int, filename string, line, column int) { + f.mutex.Lock() + if i := len(f.infos); (i == 0 || f.infos[i-1].Offset < offset) && offset < f.size { + f.infos = append(f.infos, lineInfo{offset, filename, line, column}) + } + f.mutex.Unlock() +} + +// Pos returns the Pos value for the given file offset; +// the offset must be <= f.Size(). +// f.Pos(f.Offset(p)) == p. +func (f *File) Pos(offset int) Pos { + if offset > f.size { + panic(fmt.Sprintf("invalid file offset %d (should be <= %d)", offset, f.size)) + } + return Pos(f.base + offset) +} + +// Offset returns the offset for the given file position p; +// p must be a valid Pos value in that file. +// f.Offset(f.Pos(offset)) == offset. +func (f *File) Offset(p Pos) int { + if int(p) < f.base || int(p) > f.base+f.size { + panic(fmt.Sprintf("invalid Pos value %d (should be in [%d, %d])", p, f.base, f.base+f.size)) + } + return int(p) - f.base +} + +// Line returns the line number for the given file position p; +// p must be a Pos value in that file or NoPos. +func (f *File) Line(p Pos) int { + return f.Position(p).Line +} + +func searchLineInfos(a []lineInfo, x int) int { + return sort.Search(len(a), func(i int) bool { return a[i].Offset > x }) - 1 +} + +// unpack returns the filename and line and column number for a file offset. +// If adjusted is set, unpack will return the filename and line information +// possibly adjusted by //line comments; otherwise those comments are ignored. +func (f *File) unpack(offset int, adjusted bool) (filename string, line, column int) { + f.mutex.Lock() + filename = f.name + if i := searchInts(f.lines, offset); i >= 0 { + line, column = i+1, offset-f.lines[i]+1 + } + if adjusted && len(f.infos) > 0 { + // few files have extra line infos + if i := searchLineInfos(f.infos, offset); i >= 0 { + alt := &f.infos[i] + filename = alt.Filename + if i := searchInts(f.lines, alt.Offset); i >= 0 { + // i+1 is the line at which the alternative position was recorded + d := line - (i + 1) // line distance from alternative position base + line = alt.Line + d + if alt.Column == 0 { + // alternative column is unknown => relative column is unknown + // (the current specification for line directives requires + // this to apply until the next PosBase/line directive, + // not just until the new newline) + column = 0 + } else if d == 0 { + // the alternative position base is on the current line + // => column is relative to alternative column + column = alt.Column + (offset - alt.Offset) + } + } + } + } + // TODO(mvdan): move Unlock back under Lock with a defer statement once + // https://go.dev/issue/38471 is fixed to remove the performance penalty. + f.mutex.Unlock() + return +} + +func (f *File) position(p Pos, adjusted bool) (pos Position) { + offset := int(p) - f.base + pos.Offset = offset + pos.Filename, pos.Line, pos.Column = f.unpack(offset, adjusted) + return +} + +// PositionFor returns the Position value for the given file position p. +// If adjusted is set, the position may be adjusted by position-altering +// //line comments; otherwise those comments are ignored. +// p must be a Pos value in f or NoPos. +func (f *File) PositionFor(p Pos, adjusted bool) (pos Position) { + if p != NoPos { + if int(p) < f.base || int(p) > f.base+f.size { + panic(fmt.Sprintf("invalid Pos value %d (should be in [%d, %d])", p, f.base, f.base+f.size)) + } + pos = f.position(p, adjusted) + } + return +} + +// Position returns the Position value for the given file position p. +// Calling f.Position(p) is equivalent to calling f.PositionFor(p, true). +func (f *File) Position(p Pos) (pos Position) { + return f.PositionFor(p, true) +} + +// ----------------------------------------------------------------------------- +// FileSet + +// A FileSet represents a set of source files. +// Methods of file sets are synchronized; multiple goroutines +// may invoke them concurrently. +// +// The byte offsets for each file in a file set are mapped into +// distinct (integer) intervals, one interval [base, base+size] +// per file. Base represents the first byte in the file, and size +// is the corresponding file size. A Pos value is a value in such +// an interval. By determining the interval a Pos value belongs +// to, the file, its file base, and thus the byte offset (position) +// the Pos value is representing can be computed. +// +// When adding a new file, a file base must be provided. That can +// be any integer value that is past the end of any interval of any +// file already in the file set. For convenience, FileSet.Base provides +// such a value, which is simply the end of the Pos interval of the most +// recently added file, plus one. Unless there is a need to extend an +// interval later, using the FileSet.Base should be used as argument +// for FileSet.AddFile. +// +// A File may be removed from a FileSet when it is no longer needed. +// This may reduce memory usage in a long-running application. +type FileSet struct { + mutex sync.RWMutex // protects the file set + base int // base offset for the next file + files []*File // list of files in the order added to the set + last atomic.Pointer[File] // cache of last file looked up +} + +// NewFileSet creates a new file set. +func NewFileSet() *FileSet { + return &FileSet{ + base: 1, // 0 == NoPos + } +} + +// Base returns the minimum base offset that must be provided to +// AddFile when adding the next file. +func (s *FileSet) Base() int { + s.mutex.RLock() + b := s.base + s.mutex.RUnlock() + return b + +} + +// AddFile adds a new file with a given filename, base offset, and file size +// to the file set s and returns the file. Multiple files may have the same +// name. The base offset must not be smaller than the FileSet's Base(), and +// size must not be negative. As a special case, if a negative base is provided, +// the current value of the FileSet's Base() is used instead. +// +// Adding the file will set the file set's Base() value to base + size + 1 +// as the minimum base value for the next file. The following relationship +// exists between a Pos value p for a given file offset offs: +// +// int(p) = base + offs +// +// with offs in the range [0, size] and thus p in the range [base, base+size]. +// For convenience, File.Pos may be used to create file-specific position +// values from a file offset. +func (s *FileSet) AddFile(filename string, base, size int) *File { + // Allocate f outside the critical section. + f := &File{name: filename, size: size, lines: []int{0}} + + s.mutex.Lock() + defer s.mutex.Unlock() + if base < 0 { + base = s.base + } + if base < s.base { + panic(fmt.Sprintf("invalid base %d (should be >= %d)", base, s.base)) + } + f.base = base + if size < 0 { + panic(fmt.Sprintf("invalid size %d (should be >= 0)", size)) + } + // base >= s.base && size >= 0 + base += size + 1 // +1 because EOF also has a position + if base < 0 { + panic("token.Pos offset overflow (> 2G of source code in file set)") + } + // add the file to the file set + s.base = base + s.files = append(s.files, f) + s.last.Store(f) + return f +} + +// RemoveFile removes a file from the FileSet so that subsequent +// queries for its Pos interval yield a negative result. +// This reduces the memory usage of a long-lived FileSet that +// encounters an unbounded stream of files. +// +// Removing a file that does not belong to the set has no effect. +func (s *FileSet) RemoveFile(file *File) { + s.last.CompareAndSwap(file, nil) // clear last file cache + + s.mutex.Lock() + defer s.mutex.Unlock() + + if i := searchFiles(s.files, file.base); i >= 0 && s.files[i] == file { + last := &s.files[len(s.files)-1] + s.files = append(s.files[:i], s.files[i+1:]...) + *last = nil // don't prolong lifetime when popping last element + } +} + +// Iterate calls f for the files in the file set in the order they were added +// until f returns false. +func (s *FileSet) Iterate(f func(*File) bool) { + for i := 0; ; i++ { + var file *File + s.mutex.RLock() + if i < len(s.files) { + file = s.files[i] + } + s.mutex.RUnlock() + if file == nil || !f(file) { + break + } + } +} + +func searchFiles(a []*File, x int) int { + return sort.Search(len(a), func(i int) bool { return a[i].base > x }) - 1 +} + +func (s *FileSet) file(p Pos) *File { + // common case: p is in last file. + if f := s.last.Load(); f != nil && f.base <= int(p) && int(p) <= f.base+f.size { + return f + } + + s.mutex.RLock() + defer s.mutex.RUnlock() + + // p is not in last file - search all files + if i := searchFiles(s.files, int(p)); i >= 0 { + f := s.files[i] + // f.base <= int(p) by definition of searchFiles + if int(p) <= f.base+f.size { + // Update cache of last file. A race is ok, + // but an exclusive lock causes heavy contention. + s.last.Store(f) + return f + } + } + return nil +} + +// File returns the file that contains the position p. +// If no such file is found (for instance for p == NoPos), +// the result is nil. +func (s *FileSet) File(p Pos) (f *File) { + if p != NoPos { + f = s.file(p) + } + return +} + +// PositionFor converts a Pos p in the fileset into a Position value. +// If adjusted is set, the position may be adjusted by position-altering +// //line comments; otherwise those comments are ignored. +// p must be a Pos value in s or NoPos. +func (s *FileSet) PositionFor(p Pos, adjusted bool) (pos Position) { + if p != NoPos { + if f := s.file(p); f != nil { + return f.position(p, adjusted) + } + } + return +} + +// Position converts a Pos p in the fileset into a Position value. +// Calling s.Position(p) is equivalent to calling s.PositionFor(p, true). +func (s *FileSet) Position(p Pos) (pos Position) { + return s.PositionFor(p, true) +} + +// ----------------------------------------------------------------------------- +// Helper functions + +func searchInts(a []int, x int) int { + // This function body is a manually inlined version of: + // + // return sort.Search(len(a), func(i int) bool { return a[i] > x }) - 1 + // + // With better compiler optimizations, this may not be needed in the + // future, but at the moment this change improves the go/printer + // benchmark performance by ~30%. This has a direct impact on the + // speed of gofmt and thus seems worthwhile (2011-04-29). + // TODO(gri): Remove this when compilers have caught up. + i, j := 0, len(a) + for i < j { + h := int(uint(i+j) >> 1) // avoid overflow when computing h + // i ≤ h < j + if a[h] <= x { + i = h + 1 + } else { + j = h + } + } + return i - 1 +} diff --git a/src/go/token/position_bench_test.go b/src/go/token/position_bench_test.go new file mode 100644 index 0000000..41be728 --- /dev/null +++ b/src/go/token/position_bench_test.go @@ -0,0 +1,24 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package token + +import ( + "testing" +) + +func BenchmarkSearchInts(b *testing.B) { + data := make([]int, 10000) + for i := 0; i < 10000; i++ { + data[i] = i + } + const x = 8 + if r := searchInts(data, x); r != x { + b.Errorf("got index = %d; want %d", r, x) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + searchInts(data, x) + } +} diff --git a/src/go/token/position_test.go b/src/go/token/position_test.go new file mode 100644 index 0000000..65cb242 --- /dev/null +++ b/src/go/token/position_test.go @@ -0,0 +1,477 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package token + +import ( + "fmt" + "math/rand" + "reflect" + "sync" + "testing" +) + +func checkPos(t *testing.T, msg string, got, want Position) { + if got.Filename != want.Filename { + t.Errorf("%s: got filename = %q; want %q", msg, got.Filename, want.Filename) + } + if got.Offset != want.Offset { + t.Errorf("%s: got offset = %d; want %d", msg, got.Offset, want.Offset) + } + if got.Line != want.Line { + t.Errorf("%s: got line = %d; want %d", msg, got.Line, want.Line) + } + if got.Column != want.Column { + t.Errorf("%s: got column = %d; want %d", msg, got.Column, want.Column) + } +} + +func TestNoPos(t *testing.T) { + if NoPos.IsValid() { + t.Errorf("NoPos should not be valid") + } + var fset *FileSet + checkPos(t, "nil NoPos", fset.Position(NoPos), Position{}) + fset = NewFileSet() + checkPos(t, "fset NoPos", fset.Position(NoPos), Position{}) +} + +var tests = []struct { + filename string + source []byte // may be nil + size int + lines []int +}{ + {"a", []byte{}, 0, []int{}}, + {"b", []byte("01234"), 5, []int{0}}, + {"c", []byte("\n\n\n\n\n\n\n\n\n"), 9, []int{0, 1, 2, 3, 4, 5, 6, 7, 8}}, + {"d", nil, 100, []int{0, 5, 10, 20, 30, 70, 71, 72, 80, 85, 90, 99}}, + {"e", nil, 777, []int{0, 80, 100, 120, 130, 180, 267, 455, 500, 567, 620}}, + {"f", []byte("package p\n\nimport \"fmt\""), 23, []int{0, 10, 11}}, + {"g", []byte("package p\n\nimport \"fmt\"\n"), 24, []int{0, 10, 11}}, + {"h", []byte("package p\n\nimport \"fmt\"\n "), 25, []int{0, 10, 11, 24}}, +} + +func linecol(lines []int, offs int) (int, int) { + prevLineOffs := 0 + for line, lineOffs := range lines { + if offs < lineOffs { + return line, offs - prevLineOffs + 1 + } + prevLineOffs = lineOffs + } + return len(lines), offs - prevLineOffs + 1 +} + +func verifyPositions(t *testing.T, fset *FileSet, f *File, lines []int) { + for offs := 0; offs < f.Size(); offs++ { + p := f.Pos(offs) + offs2 := f.Offset(p) + if offs2 != offs { + t.Errorf("%s, Offset: got offset %d; want %d", f.Name(), offs2, offs) + } + line, col := linecol(lines, offs) + msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) + checkPos(t, msg, f.Position(f.Pos(offs)), Position{f.Name(), offs, line, col}) + checkPos(t, msg, fset.Position(p), Position{f.Name(), offs, line, col}) + } +} + +func makeTestSource(size int, lines []int) []byte { + src := make([]byte, size) + for _, offs := range lines { + if offs > 0 { + src[offs-1] = '\n' + } + } + return src +} + +func TestPositions(t *testing.T) { + const delta = 7 // a non-zero base offset increment + fset := NewFileSet() + for _, test := range tests { + // verify consistency of test case + if test.source != nil && len(test.source) != test.size { + t.Errorf("%s: inconsistent test case: got file size %d; want %d", test.filename, len(test.source), test.size) + } + + // add file and verify name and size + f := fset.AddFile(test.filename, fset.Base()+delta, test.size) + if f.Name() != test.filename { + t.Errorf("got filename %q; want %q", f.Name(), test.filename) + } + if f.Size() != test.size { + t.Errorf("%s: got file size %d; want %d", f.Name(), f.Size(), test.size) + } + if fset.File(f.Pos(0)) != f { + t.Errorf("%s: f.Pos(0) was not found in f", f.Name()) + } + + // add lines individually and verify all positions + for i, offset := range test.lines { + f.AddLine(offset) + if f.LineCount() != i+1 { + t.Errorf("%s, AddLine: got line count %d; want %d", f.Name(), f.LineCount(), i+1) + } + // adding the same offset again should be ignored + f.AddLine(offset) + if f.LineCount() != i+1 { + t.Errorf("%s, AddLine: got unchanged line count %d; want %d", f.Name(), f.LineCount(), i+1) + } + verifyPositions(t, fset, f, test.lines[0:i+1]) + } + + // add lines with SetLines and verify all positions + if ok := f.SetLines(test.lines); !ok { + t.Errorf("%s: SetLines failed", f.Name()) + } + if f.LineCount() != len(test.lines) { + t.Errorf("%s, SetLines: got line count %d; want %d", f.Name(), f.LineCount(), len(test.lines)) + } + verifyPositions(t, fset, f, test.lines) + + // add lines with SetLinesForContent and verify all positions + src := test.source + if src == nil { + // no test source available - create one from scratch + src = makeTestSource(test.size, test.lines) + } + f.SetLinesForContent(src) + if f.LineCount() != len(test.lines) { + t.Errorf("%s, SetLinesForContent: got line count %d; want %d", f.Name(), f.LineCount(), len(test.lines)) + } + verifyPositions(t, fset, f, test.lines) + } +} + +func TestLineInfo(t *testing.T) { + fset := NewFileSet() + f := fset.AddFile("foo", fset.Base(), 500) + lines := []int{0, 42, 77, 100, 210, 220, 277, 300, 333, 401} + // add lines individually and provide alternative line information + for _, offs := range lines { + f.AddLine(offs) + f.AddLineInfo(offs, "bar", 42) + } + // verify positions for all offsets + for offs := 0; offs <= f.Size(); offs++ { + p := f.Pos(offs) + _, col := linecol(lines, offs) + msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) + checkPos(t, msg, f.Position(f.Pos(offs)), Position{"bar", offs, 42, col}) + checkPos(t, msg, fset.Position(p), Position{"bar", offs, 42, col}) + } +} + +func TestFiles(t *testing.T) { + fset := NewFileSet() + for i, test := range tests { + base := fset.Base() + if i%2 == 1 { + // Setting a negative base is equivalent to + // fset.Base(), so test some of each. + base = -1 + } + fset.AddFile(test.filename, base, test.size) + j := 0 + fset.Iterate(func(f *File) bool { + if f.Name() != tests[j].filename { + t.Errorf("got filename = %s; want %s", f.Name(), tests[j].filename) + } + j++ + return true + }) + if j != i+1 { + t.Errorf("got %d files; want %d", j, i+1) + } + } +} + +// FileSet.File should return nil if Pos is past the end of the FileSet. +func TestFileSetPastEnd(t *testing.T) { + fset := NewFileSet() + for _, test := range tests { + fset.AddFile(test.filename, fset.Base(), test.size) + } + if f := fset.File(Pos(fset.Base())); f != nil { + t.Errorf("got %v, want nil", f) + } +} + +func TestFileSetCacheUnlikely(t *testing.T) { + fset := NewFileSet() + offsets := make(map[string]int) + for _, test := range tests { + offsets[test.filename] = fset.Base() + fset.AddFile(test.filename, fset.Base(), test.size) + } + for file, pos := range offsets { + f := fset.File(Pos(pos)) + if f.Name() != file { + t.Errorf("got %q at position %d, want %q", f.Name(), pos, file) + } + } +} + +// issue 4345. Test that concurrent use of FileSet.Pos does not trigger a +// race in the FileSet position cache. +func TestFileSetRace(t *testing.T) { + fset := NewFileSet() + for i := 0; i < 100; i++ { + fset.AddFile(fmt.Sprintf("file-%d", i), fset.Base(), 1031) + } + max := int32(fset.Base()) + var stop sync.WaitGroup + r := rand.New(rand.NewSource(7)) + for i := 0; i < 2; i++ { + r := rand.New(rand.NewSource(r.Int63())) + stop.Add(1) + go func() { + for i := 0; i < 1000; i++ { + fset.Position(Pos(r.Int31n(max))) + } + stop.Done() + }() + } + stop.Wait() +} + +// issue 16548. Test that concurrent use of File.AddLine and FileSet.PositionFor +// does not trigger a race in the FileSet position cache. +func TestFileSetRace2(t *testing.T) { + const N = 1e3 + var ( + fset = NewFileSet() + file = fset.AddFile("", -1, N) + ch = make(chan int, 2) + ) + + go func() { + for i := 0; i < N; i++ { + file.AddLine(i) + } + ch <- 1 + }() + + go func() { + pos := file.Pos(0) + for i := 0; i < N; i++ { + fset.PositionFor(pos, false) + } + ch <- 1 + }() + + <-ch + <-ch +} + +func TestPositionFor(t *testing.T) { + src := []byte(` +foo +b +ar +//line :100 +foobar +//line bar:3 +done +`) + + const filename = "foo" + fset := NewFileSet() + f := fset.AddFile(filename, fset.Base(), len(src)) + f.SetLinesForContent(src) + + // verify position info + for i, offs := range f.lines { + got1 := f.PositionFor(f.Pos(offs), false) + got2 := f.PositionFor(f.Pos(offs), true) + got3 := f.Position(f.Pos(offs)) + want := Position{filename, offs, i + 1, 1} + checkPos(t, "1. PositionFor unadjusted", got1, want) + checkPos(t, "1. PositionFor adjusted", got2, want) + checkPos(t, "1. Position", got3, want) + } + + // manually add //line info on lines l1, l2 + const l1, l2 = 5, 7 + f.AddLineInfo(f.lines[l1-1], "", 100) + f.AddLineInfo(f.lines[l2-1], "bar", 3) + + // unadjusted position info must remain unchanged + for i, offs := range f.lines { + got1 := f.PositionFor(f.Pos(offs), false) + want := Position{filename, offs, i + 1, 1} + checkPos(t, "2. PositionFor unadjusted", got1, want) + } + + // adjusted position info should have changed + for i, offs := range f.lines { + got2 := f.PositionFor(f.Pos(offs), true) + got3 := f.Position(f.Pos(offs)) + want := Position{filename, offs, i + 1, 1} + // manually compute wanted filename and line + line := want.Line + if i+1 >= l1 { + want.Filename = "" + want.Line = line - l1 + 100 + } + if i+1 >= l2 { + want.Filename = "bar" + want.Line = line - l2 + 3 + } + checkPos(t, "3. PositionFor adjusted", got2, want) + 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) + } + } +} + +func TestRemoveFile(t *testing.T) { + contentA := []byte("this\nis\nfileA") + contentB := []byte("this\nis\nfileB") + fset := NewFileSet() + a := fset.AddFile("fileA", -1, len(contentA)) + a.SetLinesForContent(contentA) + b := fset.AddFile("fileB", -1, len(contentB)) + b.SetLinesForContent(contentB) + + checkPos := func(pos Pos, want string) { + if got := fset.Position(pos).String(); got != want { + t.Errorf("Position(%d) = %s, want %s", pos, got, want) + } + } + checkNumFiles := func(want int) { + got := 0 + fset.Iterate(func(*File) bool { got++; return true }) + if got != want { + t.Errorf("Iterate called %d times, want %d", got, want) + } + } + + apos3 := a.Pos(3) + bpos3 := b.Pos(3) + checkPos(apos3, "fileA:1:4") + checkPos(bpos3, "fileB:1:4") + checkNumFiles(2) + + // After removal, queries on fileA fail. + fset.RemoveFile(a) + checkPos(apos3, "-") + checkPos(bpos3, "fileB:1:4") + checkNumFiles(1) + + // idempotent / no effect + fset.RemoveFile(a) + checkPos(apos3, "-") + checkPos(bpos3, "fileB:1:4") + checkNumFiles(1) +} + +func TestFileAddLineColumnInfo(t *testing.T) { + const ( + filename = "test.go" + filesize = 100 + ) + + tests := []struct { + name string + infos []lineInfo + want []lineInfo + }{ + { + name: "normal", + infos: []lineInfo{ + {Offset: 10, Filename: filename, Line: 2, Column: 1}, + {Offset: 50, Filename: filename, Line: 3, Column: 1}, + {Offset: 80, Filename: filename, Line: 4, Column: 2}, + }, + want: []lineInfo{ + {Offset: 10, Filename: filename, Line: 2, Column: 1}, + {Offset: 50, Filename: filename, Line: 3, Column: 1}, + {Offset: 80, Filename: filename, Line: 4, Column: 2}, + }, + }, + { + name: "offset1 == file size", + infos: []lineInfo{ + {Offset: filesize, Filename: filename, Line: 2, Column: 1}, + }, + want: nil, + }, + { + name: "offset1 > file size", + infos: []lineInfo{ + {Offset: filesize + 1, Filename: filename, Line: 2, Column: 1}, + }, + want: nil, + }, + { + name: "offset2 == file size", + infos: []lineInfo{ + {Offset: 10, Filename: filename, Line: 2, Column: 1}, + {Offset: filesize, Filename: filename, Line: 3, Column: 1}, + }, + want: []lineInfo{ + {Offset: 10, Filename: filename, Line: 2, Column: 1}, + }, + }, + { + name: "offset2 > file size", + infos: []lineInfo{ + {Offset: 10, Filename: filename, Line: 2, Column: 1}, + {Offset: filesize + 1, Filename: filename, Line: 3, Column: 1}, + }, + want: []lineInfo{ + {Offset: 10, Filename: filename, Line: 2, Column: 1}, + }, + }, + { + name: "offset2 == offset1", + infos: []lineInfo{ + {Offset: 10, Filename: filename, Line: 2, Column: 1}, + {Offset: 10, Filename: filename, Line: 3, Column: 1}, + }, + want: []lineInfo{ + {Offset: 10, Filename: filename, Line: 2, Column: 1}, + }, + }, + { + name: "offset2 < offset1", + infos: []lineInfo{ + {Offset: 10, Filename: filename, Line: 2, Column: 1}, + {Offset: 9, Filename: filename, Line: 3, Column: 1}, + }, + want: []lineInfo{ + {Offset: 10, Filename: filename, Line: 2, Column: 1}, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + fs := NewFileSet() + f := fs.AddFile(filename, -1, filesize) + for _, info := range test.infos { + f.AddLineColumnInfo(info.Offset, info.Filename, info.Line, info.Column) + } + if !reflect.DeepEqual(f.infos, test.want) { + t.Errorf("\ngot %+v, \nwant %+v", f.infos, test.want) + } + }) + } +} diff --git a/src/go/token/serialize.go b/src/go/token/serialize.go new file mode 100644 index 0000000..04a48d9 --- /dev/null +++ b/src/go/token/serialize.go @@ -0,0 +1,70 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package token + +type serializedFile struct { + // fields correspond 1:1 to fields with same (lower-case) name in File + Name string + Base int + Size int + Lines []int + Infos []lineInfo +} + +type serializedFileSet struct { + Base int + Files []serializedFile +} + +// Read calls decode to deserialize a file set into s; s must not be nil. +func (s *FileSet) Read(decode func(any) error) error { + var ss serializedFileSet + if err := decode(&ss); err != nil { + return err + } + + s.mutex.Lock() + s.base = ss.Base + files := make([]*File, len(ss.Files)) + for i := 0; i < len(ss.Files); i++ { + f := &ss.Files[i] + files[i] = &File{ + name: f.Name, + base: f.Base, + size: f.Size, + lines: f.Lines, + infos: f.Infos, + } + } + s.files = files + s.last.Store(nil) + s.mutex.Unlock() + + return nil +} + +// Write calls encode to serialize the file set s. +func (s *FileSet) Write(encode func(any) error) error { + var ss serializedFileSet + + s.mutex.Lock() + ss.Base = s.base + files := make([]serializedFile, len(s.files)) + for i, f := range s.files { + f.mutex.Lock() + files[i] = serializedFile{ + Name: f.name, + Base: f.base, + Size: f.size, + Lines: append([]int(nil), f.lines...), + Infos: append([]lineInfo(nil), f.infos...), + } + f.mutex.Unlock() + } + ss.Files = files + s.mutex.Unlock() + + return encode(ss) +} diff --git a/src/go/token/serialize_test.go b/src/go/token/serialize_test.go new file mode 100644 index 0000000..8d97995 --- /dev/null +++ b/src/go/token/serialize_test.go @@ -0,0 +1,105 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package token + +import ( + "bytes" + "encoding/gob" + "fmt" + "testing" +) + +// equal returns nil if p and q describe the same file set; +// otherwise it returns an error describing the discrepancy. +func equal(p, q *FileSet) error { + if p == q { + // avoid deadlock if p == q + return nil + } + + // not strictly needed for the test + p.mutex.Lock() + q.mutex.Lock() + defer q.mutex.Unlock() + defer p.mutex.Unlock() + + if p.base != q.base { + return fmt.Errorf("different bases: %d != %d", p.base, q.base) + } + + if len(p.files) != len(q.files) { + return fmt.Errorf("different number of files: %d != %d", len(p.files), len(q.files)) + } + + for i, f := range p.files { + g := q.files[i] + if f.name != g.name { + return fmt.Errorf("different filenames: %q != %q", f.name, g.name) + } + if f.base != g.base { + return fmt.Errorf("different base for %q: %d != %d", f.name, f.base, g.base) + } + if f.size != g.size { + return fmt.Errorf("different size for %q: %d != %d", f.name, f.size, g.size) + } + for j, l := range f.lines { + m := g.lines[j] + if l != m { + return fmt.Errorf("different offsets for %q", f.name) + } + } + for j, l := range f.infos { + m := g.infos[j] + if l.Offset != m.Offset || l.Filename != m.Filename || l.Line != m.Line { + return fmt.Errorf("different infos for %q", f.name) + } + } + } + + // we don't care about .last - it's just a cache + return nil +} + +func checkSerialize(t *testing.T, p *FileSet) { + var buf bytes.Buffer + encode := func(x any) error { + return gob.NewEncoder(&buf).Encode(x) + } + if err := p.Write(encode); err != nil { + t.Errorf("writing fileset failed: %s", err) + return + } + q := NewFileSet() + decode := func(x any) error { + return gob.NewDecoder(&buf).Decode(x) + } + if err := q.Read(decode); err != nil { + t.Errorf("reading fileset failed: %s", err) + return + } + if err := equal(p, q); err != nil { + t.Errorf("filesets not identical: %s", err) + } +} + +func TestSerialization(t *testing.T) { + p := NewFileSet() + checkSerialize(t, p) + // add some files + for i := 0; i < 10; i++ { + f := p.AddFile(fmt.Sprintf("file%d", i), p.Base()+i, i*100) + checkSerialize(t, p) + // add some lines and alternative file infos + line := 1000 + for offs := 0; offs < f.Size(); offs += 40 + i { + f.AddLine(offs) + if offs%7 == 0 { + f.AddLineInfo(offs, fmt.Sprintf("file%d", offs), line) + line += 33 + } + } + checkSerialize(t, p) + } +} diff --git a/src/go/token/token.go b/src/go/token/token.go new file mode 100644 index 0000000..3ae10d8 --- /dev/null +++ b/src/go/token/token.go @@ -0,0 +1,341 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package token defines constants representing the lexical tokens of the Go +// programming language and basic operations on tokens (printing, predicates). +package token + +import ( + "strconv" + "unicode" + "unicode/utf8" +) + +// Token is the set of lexical tokens of the Go programming language. +type Token int + +// The list of tokens. +const ( + // Special tokens + ILLEGAL Token = iota + EOF + COMMENT + + literal_beg + // Identifiers and basic type literals + // (these tokens stand for classes of literals) + IDENT // main + INT // 12345 + FLOAT // 123.45 + IMAG // 123.45i + CHAR // 'a' + STRING // "abc" + literal_end + + operator_beg + // Operators and delimiters + ADD // + + SUB // - + MUL // * + QUO // / + REM // % + + AND // & + OR // | + XOR // ^ + SHL // << + SHR // >> + AND_NOT // &^ + + ADD_ASSIGN // += + SUB_ASSIGN // -= + MUL_ASSIGN // *= + QUO_ASSIGN // /= + REM_ASSIGN // %= + + AND_ASSIGN // &= + OR_ASSIGN // |= + XOR_ASSIGN // ^= + SHL_ASSIGN // <<= + SHR_ASSIGN // >>= + AND_NOT_ASSIGN // &^= + + LAND // && + LOR // || + ARROW // <- + INC // ++ + DEC // -- + + EQL // == + LSS // < + GTR // > + ASSIGN // = + NOT // ! + + NEQ // != + LEQ // <= + GEQ // >= + DEFINE // := + ELLIPSIS // ... + + LPAREN // ( + LBRACK // [ + LBRACE // { + COMMA // , + PERIOD // . + + RPAREN // ) + RBRACK // ] + RBRACE // } + SEMICOLON // ; + COLON // : + operator_end + + keyword_beg + // Keywords + BREAK + CASE + CHAN + CONST + CONTINUE + + DEFAULT + DEFER + ELSE + FALLTHROUGH + FOR + + FUNC + GO + GOTO + IF + IMPORT + + INTERFACE + MAP + PACKAGE + RANGE + RETURN + + SELECT + STRUCT + SWITCH + TYPE + VAR + keyword_end + + additional_beg + // additional tokens, handled in an ad-hoc manner + TILDE + additional_end +) + +var tokens = [...]string{ + ILLEGAL: "ILLEGAL", + + EOF: "EOF", + COMMENT: "COMMENT", + + IDENT: "IDENT", + INT: "INT", + FLOAT: "FLOAT", + IMAG: "IMAG", + CHAR: "CHAR", + STRING: "STRING", + + ADD: "+", + SUB: "-", + MUL: "*", + QUO: "/", + REM: "%", + + AND: "&", + OR: "|", + XOR: "^", + SHL: "<<", + SHR: ">>", + AND_NOT: "&^", + + ADD_ASSIGN: "+=", + SUB_ASSIGN: "-=", + MUL_ASSIGN: "*=", + QUO_ASSIGN: "/=", + REM_ASSIGN: "%=", + + AND_ASSIGN: "&=", + OR_ASSIGN: "|=", + XOR_ASSIGN: "^=", + SHL_ASSIGN: "<<=", + SHR_ASSIGN: ">>=", + AND_NOT_ASSIGN: "&^=", + + LAND: "&&", + LOR: "||", + ARROW: "<-", + INC: "++", + DEC: "--", + + EQL: "==", + LSS: "<", + GTR: ">", + ASSIGN: "=", + NOT: "!", + + NEQ: "!=", + LEQ: "<=", + GEQ: ">=", + DEFINE: ":=", + ELLIPSIS: "...", + + LPAREN: "(", + LBRACK: "[", + LBRACE: "{", + COMMA: ",", + PERIOD: ".", + + RPAREN: ")", + RBRACK: "]", + RBRACE: "}", + SEMICOLON: ";", + COLON: ":", + + BREAK: "break", + CASE: "case", + CHAN: "chan", + CONST: "const", + CONTINUE: "continue", + + DEFAULT: "default", + DEFER: "defer", + ELSE: "else", + FALLTHROUGH: "fallthrough", + FOR: "for", + + FUNC: "func", + GO: "go", + GOTO: "goto", + IF: "if", + IMPORT: "import", + + INTERFACE: "interface", + MAP: "map", + PACKAGE: "package", + RANGE: "range", + RETURN: "return", + + SELECT: "select", + STRUCT: "struct", + SWITCH: "switch", + TYPE: "type", + VAR: "var", + + TILDE: "~", +} + +// String returns the string corresponding to the token tok. +// For operators, delimiters, and keywords the string is the actual +// token character sequence (e.g., for the token ADD, the string is +// "+"). For all other tokens the string corresponds to the token +// constant name (e.g. for the token IDENT, the string is "IDENT"). +func (tok Token) String() string { + s := "" + if 0 <= tok && tok < Token(len(tokens)) { + s = tokens[tok] + } + if s == "" { + s = "token(" + strconv.Itoa(int(tok)) + ")" + } + return s +} + +// A set of constants for precedence-based expression parsing. +// Non-operators have lowest precedence, followed by operators +// starting with precedence 1 up to unary operators. The highest +// precedence serves as "catch-all" precedence for selector, +// indexing, and other operator and delimiter tokens. +const ( + LowestPrec = 0 // non-operators + UnaryPrec = 6 + HighestPrec = 7 +) + +// Precedence returns the operator precedence of the binary +// operator op. If op is not a binary operator, the result +// is LowestPrecedence. +func (op Token) Precedence() int { + switch op { + case LOR: + return 1 + case LAND: + return 2 + case EQL, NEQ, LSS, LEQ, GTR, GEQ: + return 3 + case ADD, SUB, OR, XOR: + return 4 + case MUL, QUO, REM, SHL, SHR, AND, AND_NOT: + return 5 + } + return LowestPrec +} + +var keywords map[string]Token + +func init() { + keywords = make(map[string]Token, keyword_end-(keyword_beg+1)) + for i := keyword_beg + 1; i < keyword_end; i++ { + keywords[tokens[i]] = i + } +} + +// Lookup maps an identifier to its keyword token or IDENT (if not a keyword). +func Lookup(ident string) Token { + if tok, is_keyword := keywords[ident]; is_keyword { + return tok + } + return IDENT +} + +// Predicates + +// IsLiteral returns true for tokens corresponding to identifiers +// and basic type literals; it returns false otherwise. +func (tok Token) IsLiteral() bool { return literal_beg < tok && tok < literal_end } + +// IsOperator returns true for tokens corresponding to operators and +// delimiters; it returns false otherwise. +func (tok Token) IsOperator() bool { + return (operator_beg < tok && tok < operator_end) || tok == TILDE +} + +// IsKeyword returns true for tokens corresponding to keywords; +// it returns false otherwise. +func (tok Token) IsKeyword() bool { return keyword_beg < tok && tok < keyword_end } + +// IsExported reports whether name starts with an upper-case letter. +func IsExported(name string) bool { + ch, _ := utf8.DecodeRuneInString(name) + return unicode.IsUpper(ch) +} + +// IsKeyword reports whether name is a Go keyword, such as "func" or "return". +func IsKeyword(name string) bool { + // TODO: opt: use a perfect hash function instead of a global map. + _, ok := keywords[name] + return ok +} + +// IsIdentifier reports whether name is a Go identifier, that is, a non-empty +// string made up of letters, digits, and underscores, where the first character +// is not a digit. Keywords are not identifiers. +func IsIdentifier(name string) bool { + if name == "" || IsKeyword(name) { + return false + } + for i, c := range name { + if !unicode.IsLetter(c) && c != '_' && (i == 0 || !unicode.IsDigit(c)) { + return false + } + } + return true +} diff --git a/src/go/token/token_test.go b/src/go/token/token_test.go new file mode 100644 index 0000000..eff38cc --- /dev/null +++ b/src/go/token/token_test.go @@ -0,0 +1,33 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package token + +import "testing" + +func TestIsIdentifier(t *testing.T) { + tests := []struct { + name string + in string + want bool + }{ + {"Empty", "", false}, + {"Space", " ", false}, + {"SpaceSuffix", "foo ", false}, + {"Number", "123", false}, + {"Keyword", "func", false}, + + {"LettersASCII", "foo", true}, + {"MixedASCII", "_bar123", true}, + {"UppercaseKeyword", "Func", true}, + {"LettersUnicode", "fóö", true}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := IsIdentifier(test.in); got != test.want { + t.Fatalf("IsIdentifier(%q) = %t, want %v", test.in, got, test.want) + } + }) + } +} |