/
location.js
75 lines (64 loc) 路 1.77 KB
/
location.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
69
70
71
72
73
74
75
// @flow
import { lineBreakG } from "./whitespace";
export type Pos = {
start: number,
};
// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.
export class Position {
line: number;
column: number;
constructor(line: number, col: number) {
this.line = line;
this.column = col;
}
}
export class SourceLocation {
start: Position;
end: Position;
filename: string;
identifierName: ?string;
constructor(start: Position, end?: Position) {
this.start = start;
// $FlowIgnore (may start as null, but initialized later)
this.end = end;
}
}
// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.
export function getLineInfo(
startLine: number,
input: string,
offset: number,
): Position {
let line = startLine;
let lineStart = 0;
let match;
lineBreakG.lastIndex = 0;
while ((match = lineBreakG.exec(input)) && match.index < offset) {
line++;
lineStart = lineBreakG.lastIndex;
}
return new Position(line, offset - lineStart);
}
/**
* creates a new position with a non-zero column offset from the given position.
* This function should be only be used when we create AST node out of the token
* boundaries, such as TemplateElement ends before tt.templateNonTail. This
* function does not skip whitespaces.
*
* @export
* @param {Position} position
* @param {number} columnOffset
* @returns {Position}
*/
export function createPositionWithColumnOffset(
position: Position,
columnOffset: number,
) {
const { line, column } = position;
return new Position(line, column + columnOffset);
}