github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/src/go/token/position.go (about)

     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.
     4  
     5  package token
     6  
     7  import (
     8  	"fmt"
     9  	"sort"
    10  	"sync"
    11  )
    12  
    13  // -----------------------------------------------------------------------------
    14  // Positions
    15  
    16  // Position describes an arbitrary source position
    17  // including the file, line, and column location.
    18  // A Position is valid if the line number is > 0.
    19  //
    20  type Position struct {
    21  	Filename string // filename, if any
    22  	Offset   int    // offset, starting at 0
    23  	Line     int    // line number, starting at 1
    24  	Column   int    // column number, starting at 1 (byte count)
    25  }
    26  
    27  // IsValid reports whether the position is valid.
    28  func (pos *Position) IsValid() bool { return pos.Line > 0 }
    29  
    30  // String returns a string in one of several forms:
    31  //
    32  //	file:line:column    valid position with file name
    33  //	line:column         valid position without file name
    34  //	file                invalid position with file name
    35  //	-                   invalid position without file name
    36  //
    37  func (pos Position) String() string {
    38  	s := pos.Filename
    39  	if pos.IsValid() {
    40  		if s != "" {
    41  			s += ":"
    42  		}
    43  		s += fmt.Sprintf("%d:%d", pos.Line, pos.Column)
    44  	}
    45  	if s == "" {
    46  		s = "-"
    47  	}
    48  	return s
    49  }
    50  
    51  // Pos is a compact encoding of a source position within a file set.
    52  // It can be converted into a Position for a more convenient, but much
    53  // larger, representation.
    54  //
    55  // The Pos value for a given file is a number in the range [base, base+size],
    56  // where base and size are specified when adding the file to the file set via
    57  // AddFile.
    58  //
    59  // To create the Pos value for a specific source offset (measured in bytes),
    60  // first add the respective file to the current file set using FileSet.AddFile
    61  // and then call File.Pos(offset) for that file. Given a Pos value p
    62  // for a specific file set fset, the corresponding Position value is
    63  // obtained by calling fset.Position(p).
    64  //
    65  // Pos values can be compared directly with the usual comparison operators:
    66  // If two Pos values p and q are in the same file, comparing p and q is
    67  // equivalent to comparing the respective source file offsets. If p and q
    68  // are in different files, p < q is true if the file implied by p was added
    69  // to the respective file set before the file implied by q.
    70  //
    71  type Pos int
    72  
    73  // The zero value for Pos is NoPos; there is no file and line information
    74  // associated with it, and NoPos().IsValid() is false. NoPos is always
    75  // smaller than any other Pos value. The corresponding Position value
    76  // for NoPos is the zero value for Position.
    77  //
    78  const NoPos Pos = 0
    79  
    80  // IsValid reports whether the position is valid.
    81  func (p Pos) IsValid() bool {
    82  	return p != NoPos
    83  }
    84  
    85  // -----------------------------------------------------------------------------
    86  // File
    87  
    88  // A File is a handle for a file belonging to a FileSet.
    89  // A File has a name, size, and line offset table.
    90  //
    91  type File struct {
    92  	set  *FileSet
    93  	name string // file name as provided to AddFile
    94  	base int    // Pos value range for this file is [base...base+size]
    95  	size int    // file size as provided to AddFile
    96  
    97  	// lines and infos are protected by set.mutex
    98  	lines []int // lines contains the offset of the first character for each line (the first entry is always 0)
    99  	infos []lineInfo
   100  }
   101  
   102  // Name returns the file name of file f as registered with AddFile.
   103  func (f *File) Name() string {
   104  	return f.name
   105  }
   106  
   107  // Base returns the base offset of file f as registered with AddFile.
   108  func (f *File) Base() int {
   109  	return f.base
   110  }
   111  
   112  // Size returns the size of file f as registered with AddFile.
   113  func (f *File) Size() int {
   114  	return f.size
   115  }
   116  
   117  // LineCount returns the number of lines in file f.
   118  func (f *File) LineCount() int {
   119  	f.set.mutex.RLock()
   120  	n := len(f.lines)
   121  	f.set.mutex.RUnlock()
   122  	return n
   123  }
   124  
   125  // AddLine adds the line offset for a new line.
   126  // The line offset must be larger than the offset for the previous line
   127  // and smaller than the file size; otherwise the line offset is ignored.
   128  //
   129  func (f *File) AddLine(offset int) {
   130  	f.set.mutex.Lock()
   131  	if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size {
   132  		f.lines = append(f.lines, offset)
   133  	}
   134  	f.set.mutex.Unlock()
   135  }
   136  
   137  // MergeLine merges a line with the following line. It is akin to replacing
   138  // the newline character at the end of the line with a space (to not change the
   139  // remaining offsets). To obtain the line number, consult e.g. Position.Line.
   140  // MergeLine will panic if given an invalid line number.
   141  //
   142  func (f *File) MergeLine(line int) {
   143  	if line <= 0 {
   144  		panic("illegal line number (line numbering starts at 1)")
   145  	}
   146  	f.set.mutex.Lock()
   147  	defer f.set.mutex.Unlock()
   148  	if line >= len(f.lines) {
   149  		panic("illegal line number")
   150  	}
   151  	// To merge the line numbered <line> with the line numbered <line+1>,
   152  	// we need to remove the entry in lines corresponding to the line
   153  	// numbered <line+1>. The entry in lines corresponding to the line
   154  	// numbered <line+1> is located at index <line>, since indices in lines
   155  	// are 0-based and line numbers are 1-based.
   156  	copy(f.lines[line:], f.lines[line+1:])
   157  	f.lines = f.lines[:len(f.lines)-1]
   158  }
   159  
   160  // SetLines sets the line offsets for a file and reports whether it succeeded.
   161  // The line offsets are the offsets of the first character of each line;
   162  // for instance for the content "ab\nc\n" the line offsets are {0, 3}.
   163  // An empty file has an empty line offset table.
   164  // Each line offset must be larger than the offset for the previous line
   165  // and smaller than the file size; otherwise SetLines fails and returns
   166  // false.
   167  // Callers must not mutate the provided slice after SetLines returns.
   168  //
   169  func (f *File) SetLines(lines []int) bool {
   170  	// verify validity of lines table
   171  	size := f.size
   172  	for i, offset := range lines {
   173  		if i > 0 && offset <= lines[i-1] || size <= offset {
   174  			return false
   175  		}
   176  	}
   177  
   178  	// set lines table
   179  	f.set.mutex.Lock()
   180  	f.lines = lines
   181  	f.set.mutex.Unlock()
   182  	return true
   183  }
   184  
   185  // SetLinesForContent sets the line offsets for the given file content.
   186  // It ignores position-altering //line comments.
   187  func (f *File) SetLinesForContent(content []byte) {
   188  	var lines []int
   189  	line := 0
   190  	for offset, b := range content {
   191  		if line >= 0 {
   192  			lines = append(lines, line)
   193  		}
   194  		line = -1
   195  		if b == '\n' {
   196  			line = offset + 1
   197  		}
   198  	}
   199  
   200  	// set lines table
   201  	f.set.mutex.Lock()
   202  	f.lines = lines
   203  	f.set.mutex.Unlock()
   204  }
   205  
   206  // A lineInfo object describes alternative file and line number
   207  // information (such as provided via a //line comment in a .go
   208  // file) for a given file offset.
   209  type lineInfo struct {
   210  	// fields are exported to make them accessible to gob
   211  	Offset   int
   212  	Filename string
   213  	Line     int
   214  }
   215  
   216  // AddLineInfo adds alternative file and line number information for
   217  // a given file offset. The offset must be larger than the offset for
   218  // the previously added alternative line info and smaller than the
   219  // file size; otherwise the information is ignored.
   220  //
   221  // AddLineInfo is typically used to register alternative position
   222  // information for //line filename:line comments in source files.
   223  //
   224  func (f *File) AddLineInfo(offset int, filename string, line int) {
   225  	f.set.mutex.Lock()
   226  	if i := len(f.infos); i == 0 || f.infos[i-1].Offset < offset && offset < f.size {
   227  		f.infos = append(f.infos, lineInfo{offset, filename, line})
   228  	}
   229  	f.set.mutex.Unlock()
   230  }
   231  
   232  // Pos returns the Pos value for the given file offset;
   233  // the offset must be <= f.Size().
   234  // f.Pos(f.Offset(p)) == p.
   235  //
   236  func (f *File) Pos(offset int) Pos {
   237  	if offset > f.size {
   238  		panic("illegal file offset")
   239  	}
   240  	return Pos(f.base + offset)
   241  }
   242  
   243  // Offset returns the offset for the given file position p;
   244  // p must be a valid Pos value in that file.
   245  // f.Offset(f.Pos(offset)) == offset.
   246  //
   247  func (f *File) Offset(p Pos) int {
   248  	if int(p) < f.base || int(p) > f.base+f.size {
   249  		panic("illegal Pos value")
   250  	}
   251  	return int(p) - f.base
   252  }
   253  
   254  // Line returns the line number for the given file position p;
   255  // p must be a Pos value in that file or NoPos.
   256  //
   257  func (f *File) Line(p Pos) int {
   258  	return f.Position(p).Line
   259  }
   260  
   261  func searchLineInfos(a []lineInfo, x int) int {
   262  	return sort.Search(len(a), func(i int) bool { return a[i].Offset > x }) - 1
   263  }
   264  
   265  // unpack returns the filename and line and column number for a file offset.
   266  // If adjusted is set, unpack will return the filename and line information
   267  // possibly adjusted by //line comments; otherwise those comments are ignored.
   268  //
   269  func (f *File) unpack(offset int, adjusted bool) (filename string, line, column int) {
   270  	filename = f.name
   271  	if i := searchInts(f.lines, offset); i >= 0 {
   272  		line, column = i+1, offset-f.lines[i]+1
   273  	}
   274  	if adjusted && len(f.infos) > 0 {
   275  		// almost no files have extra line infos
   276  		if i := searchLineInfos(f.infos, offset); i >= 0 {
   277  			alt := &f.infos[i]
   278  			filename = alt.Filename
   279  			if i := searchInts(f.lines, alt.Offset); i >= 0 {
   280  				line += alt.Line - i - 1
   281  			}
   282  		}
   283  	}
   284  	return
   285  }
   286  
   287  func (f *File) position(p Pos, adjusted bool) (pos Position) {
   288  	offset := int(p) - f.base
   289  	pos.Offset = offset
   290  	pos.Filename, pos.Line, pos.Column = f.unpack(offset, adjusted)
   291  	return
   292  }
   293  
   294  // PositionFor returns the Position value for the given file position p.
   295  // If adjusted is set, the position may be adjusted by position-altering
   296  // //line comments; otherwise those comments are ignored.
   297  // p must be a Pos value in f or NoPos.
   298  //
   299  func (f *File) PositionFor(p Pos, adjusted bool) (pos Position) {
   300  	if p != NoPos {
   301  		if int(p) < f.base || int(p) > f.base+f.size {
   302  			panic("illegal Pos value")
   303  		}
   304  		pos = f.position(p, adjusted)
   305  	}
   306  	return
   307  }
   308  
   309  // Position returns the Position value for the given file position p.
   310  // Calling f.Position(p) is equivalent to calling f.PositionFor(p, true).
   311  //
   312  func (f *File) Position(p Pos) (pos Position) {
   313  	return f.PositionFor(p, true)
   314  }
   315  
   316  // -----------------------------------------------------------------------------
   317  // FileSet
   318  
   319  // A FileSet represents a set of source files.
   320  // Methods of file sets are synchronized; multiple goroutines
   321  // may invoke them concurrently.
   322  //
   323  type FileSet struct {
   324  	mutex sync.RWMutex // protects the file set
   325  	base  int          // base offset for the next file
   326  	files []*File      // list of files in the order added to the set
   327  	last  *File        // cache of last file looked up
   328  }
   329  
   330  // NewFileSet creates a new file set.
   331  func NewFileSet() *FileSet {
   332  	return &FileSet{
   333  		base: 1, // 0 == NoPos
   334  	}
   335  }
   336  
   337  // Base returns the minimum base offset that must be provided to
   338  // AddFile when adding the next file.
   339  //
   340  func (s *FileSet) Base() int {
   341  	s.mutex.RLock()
   342  	b := s.base
   343  	s.mutex.RUnlock()
   344  	return b
   345  
   346  }
   347  
   348  // AddFile adds a new file with a given filename, base offset, and file size
   349  // to the file set s and returns the file. Multiple files may have the same
   350  // name. The base offset must not be smaller than the FileSet's Base(), and
   351  // size must not be negative. As a special case, if a negative base is provided,
   352  // the current value of the FileSet's Base() is used instead.
   353  //
   354  // Adding the file will set the file set's Base() value to base + size + 1
   355  // as the minimum base value for the next file. The following relationship
   356  // exists between a Pos value p for a given file offset offs:
   357  //
   358  //	int(p) = base + offs
   359  //
   360  // with offs in the range [0, size] and thus p in the range [base, base+size].
   361  // For convenience, File.Pos may be used to create file-specific position
   362  // values from a file offset.
   363  //
   364  func (s *FileSet) AddFile(filename string, base, size int) *File {
   365  	s.mutex.Lock()
   366  	defer s.mutex.Unlock()
   367  	if base < 0 {
   368  		base = s.base
   369  	}
   370  	if base < s.base || size < 0 {
   371  		panic("illegal base or size")
   372  	}
   373  	// base >= s.base && size >= 0
   374  	f := &File{s, filename, base, size, []int{0}, nil}
   375  	base += size + 1 // +1 because EOF also has a position
   376  	if base < 0 {
   377  		panic("token.Pos offset overflow (> 2G of source code in file set)")
   378  	}
   379  	// add the file to the file set
   380  	s.base = base
   381  	s.files = append(s.files, f)
   382  	s.last = f
   383  	return f
   384  }
   385  
   386  // Iterate calls f for the files in the file set in the order they were added
   387  // until f returns false.
   388  //
   389  func (s *FileSet) Iterate(f func(*File) bool) {
   390  	for i := 0; ; i++ {
   391  		var file *File
   392  		s.mutex.RLock()
   393  		if i < len(s.files) {
   394  			file = s.files[i]
   395  		}
   396  		s.mutex.RUnlock()
   397  		if file == nil || !f(file) {
   398  			break
   399  		}
   400  	}
   401  }
   402  
   403  func searchFiles(a []*File, x int) int {
   404  	return sort.Search(len(a), func(i int) bool { return a[i].base > x }) - 1
   405  }
   406  
   407  func (s *FileSet) file(p Pos) *File {
   408  	s.mutex.RLock()
   409  	// common case: p is in last file
   410  	if f := s.last; f != nil && f.base <= int(p) && int(p) <= f.base+f.size {
   411  		s.mutex.RUnlock()
   412  		return f
   413  	}
   414  	// p is not in last file - search all files
   415  	if i := searchFiles(s.files, int(p)); i >= 0 {
   416  		f := s.files[i]
   417  		// f.base <= int(p) by definition of searchFiles
   418  		if int(p) <= f.base+f.size {
   419  			s.mutex.RUnlock()
   420  			s.mutex.Lock()
   421  			s.last = f // race is ok - s.last is only a cache
   422  			s.mutex.Unlock()
   423  			return f
   424  		}
   425  	}
   426  	s.mutex.RUnlock()
   427  	return nil
   428  }
   429  
   430  // File returns the file that contains the position p.
   431  // If no such file is found (for instance for p == NoPos),
   432  // the result is nil.
   433  //
   434  func (s *FileSet) File(p Pos) (f *File) {
   435  	if p != NoPos {
   436  		f = s.file(p)
   437  	}
   438  	return
   439  }
   440  
   441  // PositionFor converts a Pos p in the fileset into a Position value.
   442  // If adjusted is set, the position may be adjusted by position-altering
   443  // //line comments; otherwise those comments are ignored.
   444  // p must be a Pos value in s or NoPos.
   445  //
   446  func (s *FileSet) PositionFor(p Pos, adjusted bool) (pos Position) {
   447  	if p != NoPos {
   448  		if f := s.file(p); f != nil {
   449  			pos = f.position(p, adjusted)
   450  		}
   451  	}
   452  	return
   453  }
   454  
   455  // Position converts a Pos p in the fileset into a Position value.
   456  // Calling s.Position(p) is equivalent to calling s.PositionFor(p, true).
   457  //
   458  func (s *FileSet) Position(p Pos) (pos Position) {
   459  	return s.PositionFor(p, true)
   460  }
   461  
   462  // -----------------------------------------------------------------------------
   463  // Helper functions
   464  
   465  func searchInts(a []int, x int) int {
   466  	// This function body is a manually inlined version of:
   467  	//
   468  	//   return sort.Search(len(a), func(i int) bool { return a[i] > x }) - 1
   469  	//
   470  	// With better compiler optimizations, this may not be needed in the
   471  	// future, but at the moment this change improves the go/printer
   472  	// benchmark performance by ~30%. This has a direct impact on the
   473  	// speed of gofmt and thus seems worthwhile (2011-04-29).
   474  	// TODO(gri): Remove this when compilers have caught up.
   475  	i, j := 0, len(a)
   476  	for i < j {
   477  		h := i + (j-i)/2 // avoid overflow when computing h
   478  		// i ≤ h < j
   479  		if a[h] <= x {
   480  			i = h + 1
   481  		} else {
   482  			j = h
   483  		}
   484  	}
   485  	return i - 1
   486  }