This repository has been archived by the owner on Jul 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSourceLoc.js
68 lines (56 loc) · 1.61 KB
/
SourceLoc.js
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
class SourceLoc {
constructor(startIdx, endIdx) {
this.startIdx = startIdx;
this.endIdx = endIdx;
}
get startLineNumber() {
return SourceLoc.codeMap[this.startIdx];
}
get endLineNumber() {
return SourceLoc.codeMap[this.endIdx - 1];
}
get startPos() { return this.startIdx; }
get endPos() { return this.endIdx; }
get contents() {
return SourceLoc.code.slice(this.startIdx, this.endIdx);
}
equals(sourceLoc) {
return this.startIdx === sourceLoc.startIdx && this.endIdx === sourceLoc.endIdx;
}
contains(sourceLoc) {
return this.startIdx <= sourceLoc.startIdx && sourceLoc.endIdx <= this.endIdx;
}
strictlyContains(sourceLoc) {
return this.contains(sourceLoc) && !this.equals(sourceLoc);
}
containsIdx(pos) {
return this.startIdx <= pos && pos < this.endIdx;
}
join(other) {
const startIdx = this.startIdx < other.startIdx ? this.startIdx : other.startIdx;
const endIdx = this.endIdx > other.endIdx ? this.endIdx : other.endIdx;
return new SourceLoc(startIdx, endIdx);
}
toAST() {
return dict(
str('startIdx'), this.startIdx,
str('endIdx'), this.endIdx
);
}
trimmed() {
const trimmedContents = trimRight(this.contents);
return new SourceLoc(this.startIdx, this.endIdx - (this.contents.length - trimmedContents.length));
}
static setupCodeMap(code) {
SourceLoc.code = code;
SourceLoc.codeMap = {};
let lineNumber = 1;
range(0, code.length-1).forEach(i => {
const char = code.charAt(i);
if (char === '\n') {
lineNumber++;
}
SourceLoc.codeMap[i] = lineNumber;
});
}
}