-
Notifications
You must be signed in to change notification settings - Fork 153
/
fileset.go
92 lines (79 loc) · 1.91 KB
/
fileset.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package token
import (
"github.com/influxdata/flux/ast"
)
type FileSet struct {
files []*File
}
func (f *FileSet) AddFile(filename string, size int) *File {
file := NewFile(filename, size)
f.files = append(f.files, file)
return file
}
type File struct {
name string
lines []int // lines contains the offset of the first character for each line (the first entry is always 0)
sz int
}
func NewFile(name string, sz int) *File {
return &File{
name: name,
lines: []int{0},
sz: sz,
}
}
func (f *File) AddLine(offset int) {
f.lines = append(f.lines, offset)
}
func (f *File) Name() string {
return f.name
}
// Offset returns the offset for the given line/column.
func (f *File) Offset(pos ast.Position) int {
if pos.Line == 0 || pos.Column == 0 {
return -1
}
offset := f.lines[pos.Line-1]
return offset + pos.Column - 1
}
func (f *File) Base() int {
return 1
}
func (f *File) Size() int {
return f.sz
}
func (f *File) Pos(offset int) Pos {
return Pos(offset + 1)
}
func (f *File) Position(pos Pos) ast.Position {
offset := int(pos) - 1
i := searchInts(f.lines, offset)
return ast.Position{
Line: i + 1,
Column: offset - f.lines[i] + 1,
}
}
// This is copied from the go source code:
// https://golang.org/src/go/token/position.go
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 := i + (j-i)/2 // avoid overflow when computing h
// i ≤ h < j
if a[h] <= x {
i = h + 1
} else {
j = h
}
}
return i - 1
}