forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlineMap.ts
More file actions
87 lines (68 loc) · 3.06 KB
/
Copy pathlineMap.ts
File metadata and controls
87 lines (68 loc) · 3.06 KB
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
85
86
87
///<reference path='references.ts' />
module TypeScript {
export interface ILineAndCharacter {
line: number;
character: number;
}
export class LineMap {
public static empty = new LineMap(() => [0], 0);
private _lineStarts: number[] = undefined;
constructor(private _computeLineStarts: () => number[], private length: number) {
}
public toJSON(key: any) {
return { lineStarts: this.lineStarts(), length: this.length };
}
public equals(other: LineMap): boolean {
return this.length === other.length &&
ArrayUtilities.sequenceEquals(this.lineStarts(), other.lineStarts(), (v1, v2) => v1 === v2);
}
public lineStarts(): number[] {
if (!this._lineStarts) {
this._lineStarts = this._computeLineStarts();
}
return this._lineStarts;
}
public lineCount(): number {
return this.lineStarts().length;
}
public getPosition(line: number, character: number): number {
return this.lineStarts()[line] + character;
}
public getLineNumberFromPosition(position: number): number {
if (position < 0 || position > this.length) {
throw Errors.argumentOutOfRange("position");
}
if (position === this.length) {
// this can happen when the user tried to get the line of items
// that are at the absolute end of this text (i.e. the EndOfLine
// token, or missing tokens that are at the end of the text).
// In this case, we want the last line in the text.
return this.lineCount() - 1;
}
// Binary search to find the right line
var lineNumber = ArrayUtilities.binarySearch(this.lineStarts(), position);
if (lineNumber < 0) {
lineNumber = (~lineNumber) - 1;
}
return lineNumber;
}
public getLineStartPosition(lineNumber: number): number {
return this.lineStarts()[lineNumber];
}
public fillLineAndCharacterFromPosition(position: number, lineAndCharacter: ILineAndCharacter): void {
if (position < 0 || position > this.length) {
throw Errors.argumentOutOfRange("position");
}
var lineNumber = this.getLineNumberFromPosition(position);
lineAndCharacter.line = lineNumber;
lineAndCharacter.character = position - this.lineStarts()[lineNumber];
}
public getLineAndCharacterFromPosition(position: number): LineAndCharacter {
if (position < 0 || position > this.length) {
throw Errors.argumentOutOfRange("position");
}
var lineNumber = this.getLineNumberFromPosition(position);
return new LineAndCharacter(lineNumber, position - this.lineStarts()[lineNumber]);
}
}
}