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