1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // TODO(gri) consider making this a separate package outside the go directory.
15 // -----------------------------------------------------------------------------
18 // Position describes an arbitrary source position
19 // including the file, line, and column location.
20 // A Position is valid if the line number is > 0.
22 type Position struct {
23 Filename string // filename, if any
24 Offset int // offset, starting at 0
25 Line int // line number, starting at 1
26 Column int // column number, starting at 1 (character count)
29 // IsValid returns true if the position is valid.
30 func (pos *Position) IsValid() bool { return pos.Line > 0 }
32 // String returns a string in one of several forms:
34 // file:line:column valid position with file name
35 // line:column valid position without file name
36 // file invalid position with file name
37 // - invalid position without file name
39 func (pos Position) String() string {
45 s += fmt.Sprintf("%d:%d", pos.Line, pos.Column)
53 // Pos is a compact encoding of a source position within a file set.
54 // It can be converted into a Position for a more convenient, but much
55 // larger, representation.
57 // The Pos value for a given file is a number in the range [base, base+size],
58 // where base and size are specified when adding the file to the file set via
61 // To create the Pos value for a specific source offset, first add
62 // the respective file to the current file set (via FileSet.AddFile)
63 // and then call File.Pos(offset) for that file. Given a Pos value p
64 // for a specific file set fset, the corresponding Position value is
65 // obtained by calling fset.Position(p).
67 // Pos values can be compared directly with the usual comparison operators:
68 // If two Pos values p and q are in the same file, comparing p and q is
69 // equivalent to comparing the respective source file offsets. If p and q
70 // are in different files, p < q is true if the file implied by p was added
71 // to the respective file set before the file implied by q.
75 // The zero value for Pos is NoPos; there is no file and line information
76 // associated with it, and NoPos().IsValid() is false. NoPos is always
77 // smaller than any other Pos value. The corresponding Position value
78 // for NoPos is the zero value for Position.
82 // IsValid returns true if the position is valid.
83 func (p Pos) IsValid() bool {
87 // -----------------------------------------------------------------------------
90 // A File is a handle for a file belonging to a FileSet.
91 // A File has a name, size, and line offset table.
95 name string // file name as provided to AddFile
96 base int // Pos value range for this file is [base...base+size]
97 size int // file size as provided to AddFile
99 // lines and infos are protected by set.mutex
104 // Name returns the file name of file f as registered with AddFile.
105 func (f *File) Name() string {
109 // Base returns the base offset of file f as registered with AddFile.
110 func (f *File) Base() int {
114 // Size returns the size of file f as registered with AddFile.
115 func (f *File) Size() int {
119 // LineCount returns the number of lines in file f.
120 func (f *File) LineCount() int {
123 f.set.mutex.RUnlock()
127 // AddLine adds the line offset for a new line.
128 // The line offset must be larger than the offset for the previous line
129 // and smaller than the file size; otherwise the line offset is ignored.
131 func (f *File) AddLine(offset int) {
133 if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size {
134 f.lines = append(f.lines, offset)
139 // SetLines sets the line offsets for a file and returns true if successful.
140 // The line offsets are the offsets of the first character of each line;
141 // for instance for the content "ab\nc\n" the line offsets are {0, 3}.
142 // An empty file has an empty line offset table.
143 // Each line offset must be larger than the offset for the previous line
144 // and smaller than the file size; otherwise SetLines fails and returns
147 func (f *File) SetLines(lines []int) bool {
148 // verify validity of lines table
150 for i, offset := range lines {
151 if i > 0 && offset <= lines[i-1] || size <= offset {
163 // SetLinesForContent sets the line offsets for the given file content.
164 func (f *File) SetLinesForContent(content []byte) {
167 for offset, b := range content {
169 lines = append(lines, line)
183 // A lineInfo object describes alternative file and line number
184 // information (such as provided via a //line comment in a .go
185 // file) for a given file offset.
186 type lineInfo struct {
187 // fields are exported to make them accessible to gob
193 // AddLineInfo adds alternative file and line number information for
194 // a given file offset. The offset must be larger than the offset for
195 // the previously added alternative line info and smaller than the
196 // file size; otherwise the information is ignored.
198 // AddLineInfo is typically used to register alternative position
199 // information for //line filename:line comments in source files.
201 func (f *File) AddLineInfo(offset int, filename string, line int) {
203 if i := len(f.infos); i == 0 || f.infos[i-1].Offset < offset && offset < f.size {
204 f.infos = append(f.infos, lineInfo{offset, filename, line})
209 // Pos returns the Pos value for the given file offset;
210 // the offset must be <= f.Size().
211 // f.Pos(f.Offset(p)) == p.
213 func (f *File) Pos(offset int) Pos {
215 panic("illegal file offset")
217 return Pos(f.base + offset)
220 // Offset returns the offset for the given file position p;
221 // p must be a valid Pos value in that file.
222 // f.Offset(f.Pos(offset)) == offset.
224 func (f *File) Offset(p Pos) int {
225 if int(p) < f.base || int(p) > f.base+f.size {
226 panic("illegal Pos value")
228 return int(p) - f.base
231 // Line returns the line number for the given file position p;
232 // p must be a Pos value in that file or NoPos.
234 func (f *File) Line(p Pos) int {
235 // TODO(gri) this can be implemented much more efficiently
236 return f.Position(p).Line
239 func searchLineInfos(a []lineInfo, x int) int {
240 return sort.Search(len(a), func(i int) bool { return a[i].Offset > x }) - 1
243 // info returns the file name, line, and column number for a file offset.
244 func (f *File) info(offset int) (filename string, line, column int) {
246 if i := searchInts(f.lines, offset); i >= 0 {
247 line, column = i+1, offset-f.lines[i]+1
249 if len(f.infos) > 0 {
250 // almost no files have extra line infos
251 if i := searchLineInfos(f.infos, offset); i >= 0 {
253 filename = alt.Filename
254 if i := searchInts(f.lines, alt.Offset); i >= 0 {
255 line += alt.Line - i - 1
262 func (f *File) position(p Pos) (pos Position) {
263 offset := int(p) - f.base
265 pos.Filename, pos.Line, pos.Column = f.info(offset)
269 // Position returns the Position value for the given file position p;
270 // p must be a Pos value in that file or NoPos.
272 func (f *File) Position(p Pos) (pos Position) {
274 if int(p) < f.base || int(p) > f.base+f.size {
275 panic("illegal Pos value")
282 // -----------------------------------------------------------------------------
285 // A FileSet represents a set of source files.
286 // Methods of file sets are synchronized; multiple goroutines
287 // may invoke them concurrently.
289 type FileSet struct {
290 mutex sync.RWMutex // protects the file set
291 base int // base offset for the next file
292 files []*File // list of files in the order added to the set
293 last *File // cache of last file looked up
296 // NewFileSet creates a new file set.
297 func NewFileSet() *FileSet {
299 base: 1, // 0 == NoPos
303 // Base returns the minimum base offset that must be provided to
304 // AddFile when adding the next file.
306 func (s *FileSet) Base() int {
314 // AddFile adds a new file with a given filename, base offset, and file size
315 // to the file set s and returns the file. Multiple files may have the same
316 // name. The base offset must not be smaller than the FileSet's Base(), and
317 // size must not be negative.
319 // Adding the file will set the file set's Base() value to base + size + 1
320 // as the minimum base value for the next file. The following relationship
321 // exists between a Pos value p for a given file offset offs:
323 // int(p) = base + offs
325 // with offs in the range [0, size] and thus p in the range [base, base+size].
326 // For convenience, File.Pos may be used to create file-specific position
327 // values from a file offset.
329 func (s *FileSet) AddFile(filename string, base, size int) *File {
331 defer s.mutex.Unlock()
332 if base < s.base || size < 0 {
333 panic("illegal base or size")
335 // base >= s.base && size >= 0
336 f := &File{s, filename, base, size, []int{0}, nil}
337 base += size + 1 // +1 because EOF also has a position
339 panic("token.Pos offset overflow (> 2G of source code in file set)")
341 // add the file to the file set
343 s.files = append(s.files, f)
348 // Iterate calls f for the files in the file set in the order they were added
349 // until f returns false.
351 func (s *FileSet) Iterate(f func(*File) bool) {
355 if i < len(s.files) {
359 if file == nil || !f(file) {
365 func searchFiles(a []*File, x int) int {
366 return sort.Search(len(a), func(i int) bool { return a[i].base > x }) - 1
369 func (s *FileSet) file(p Pos) *File {
371 // common case: p is in last file
372 if f := s.last; f != nil && f.base <= int(p) && int(p) <= f.base+f.size {
376 // p is not in last file - search all files
377 if i := searchFiles(s.files, int(p)); i >= 0 {
379 // f.base <= int(p) by definition of searchFiles
380 if int(p) <= f.base+f.size {
383 s.last = f // race is ok - s.last is only a cache
392 // File returns the file that contains the position p.
393 // If no such file is found (for instance for p == NoPos),
394 // the result is nil.
396 func (s *FileSet) File(p Pos) (f *File) {
403 // Position converts a Pos in the fileset into a general Position.
404 func (s *FileSet) Position(p Pos) (pos Position) {
406 if f := s.file(p); f != nil {
413 // -----------------------------------------------------------------------------
416 func searchInts(a []int, x int) int {
417 // This function body is a manually inlined version of:
419 // return sort.Search(len(a), func(i int) bool { return a[i] > x }) - 1
421 // With better compiler optimizations, this may not be needed in the
422 // future, but at the moment this change improves the go/printer
423 // benchmark performance by ~30%. This has a direct impact on the
424 // speed of gofmt and thus seems worthwhile (2011-04-29).
425 // TODO(gri): Remove this when compilers have caught up.
428 h := i + (j-i)/2 // avoid overflow when computing h