forked from dop251/goja
-
Notifications
You must be signed in to change notification settings - Fork 0
/
srcfile.go
84 lines (70 loc) · 1.43 KB
/
srcfile.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
package goja
import (
"fmt"
"github.com/go-sourcemap/sourcemap"
"sort"
"strings"
)
type Position struct {
Line, Col int
}
type SrcFile struct {
name string
src string
lineOffsets []int
lastScannedOffset int
sourceMap *sourcemap.Consumer
}
func NewSrcFile(name, src string, sourceMap *sourcemap.Consumer) *SrcFile {
return &SrcFile{
name: name,
src: src,
sourceMap: sourceMap,
}
}
func (f *SrcFile) Position(offset int) Position {
var line int
if offset > f.lastScannedOffset {
line = f.scanTo(offset)
} else {
line = sort.Search(len(f.lineOffsets), func(x int) bool { return f.lineOffsets[x] > offset }) - 1
}
var lineStart int
if line >= 0 {
lineStart = f.lineOffsets[line]
}
row := line + 2
col := offset - lineStart + 1
if f.sourceMap != nil {
if _, _, row, col, ok := f.sourceMap.Source(row, col); ok {
return Position{
Line: row,
Col: col,
}
}
}
return Position{
Line: row,
Col: col,
}
}
func (f *SrcFile) scanTo(offset int) int {
o := f.lastScannedOffset
for o < offset {
p := strings.Index(f.src[o:], "\n")
if p == -1 {
f.lastScannedOffset = len(f.src)
return len(f.lineOffsets) - 1
}
o = o + p + 1
f.lineOffsets = append(f.lineOffsets, o)
}
f.lastScannedOffset = o
if o == offset {
return len(f.lineOffsets) - 1
}
return len(f.lineOffsets) - 2
}
func (p Position) String() string {
return fmt.Sprintf("%d:%d", p.Line, p.Col)
}