Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80744 views
1
import {Parser} from "./state"
2
import {lineBreakG} from "./whitespace"
3
4
// These are used when `options.locations` is on, for the
5
// `startLoc` and `endLoc` properties.
6
7
export class Position {
8
constructor(line, col) {
9
this.line = line
10
this.column = col
11
}
12
13
offset(n) {
14
return new Position(this.line, this.column + n)
15
}
16
}
17
18
export class SourceLocation {
19
constructor(p, start, end) {
20
this.start = start
21
this.end = end
22
if (p.sourceFile !== null) this.source = p.sourceFile
23
}
24
}
25
26
// The `getLineInfo` function is mostly useful when the
27
// `locations` option is off (for performance reasons) and you
28
// want to find the line/column position for a given character
29
// offset. `input` should be the code string that the offset refers
30
// into.
31
32
export function getLineInfo(input, offset) {
33
for (let line = 1, cur = 0;;) {
34
lineBreakG.lastIndex = cur
35
let match = lineBreakG.exec(input)
36
if (match && match.index < offset) {
37
++line
38
cur = match.index + match[0].length
39
} else {
40
return new Position(line, offset - cur)
41
}
42
}
43
}
44
45
const pp = Parser.prototype
46
47
// This function is used to raise exceptions on parse errors. It
48
// takes an offset integer (into the current `input`) to indicate
49
// the location of the error, attaches the position to the end
50
// of the error message, and then raises a `SyntaxError` with that
51
// message.
52
53
pp.raise = function(pos, message) {
54
let loc = getLineInfo(this.input, pos)
55
message += " (" + loc.line + ":" + loc.column + ")"
56
let err = new SyntaxError(message)
57
err.pos = pos; err.loc = loc; err.raisedAt = this.pos
58
throw err
59
}
60
61
pp.curPosition = function() {
62
return new Position(this.curLine, this.pos - this.lineStart)
63
}
64
65