-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
TokenInfo.ts
63 lines (57 loc) · 1.93 KB
/
TokenInfo.ts
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
// The following code is adapted from the the code in eslint.
// License: https://github.com/eslint/eslint/blob/48700fc8408f394887cdedd071b22b757700fdcb/LICENSE
import { TSESLint, TSESTree } from '@typescript-eslint/experimental-utils';
/**
* A helper class to get token-based info related to indentation
*/
export class TokenInfo {
private readonly sourceCode: TSESLint.SourceCode;
public readonly firstTokensByLineNumber: Map<number, TSESTree.Token>;
constructor(sourceCode: TSESLint.SourceCode) {
this.sourceCode = sourceCode;
this.firstTokensByLineNumber = sourceCode.tokensAndComments.reduce(
(map, token) => {
if (!map.has(token.loc.start.line)) {
map.set(token.loc.start.line, token);
}
if (
!map.has(token.loc.end.line) &&
sourceCode.text
.slice(token.range[1] - token.loc.end.column, token.range[1])
.trim()
) {
map.set(token.loc.end.line, token);
}
return map;
},
new Map<number, TSESTree.Token>(),
);
}
/**
* Gets the first token on a given token's line
* @returns The first token on the given line
*/
public getFirstTokenOfLine(
token: TSESTree.Token | TSESTree.Node,
): TSESTree.Token {
return this.firstTokensByLineNumber.get(token.loc.start.line)!;
}
/**
* Determines whether a token is the first token in its line
* @returns `true` if the token is the first on its line
*/
public isFirstTokenOfLine(token: TSESTree.Token): boolean {
return this.getFirstTokenOfLine(token) === token;
}
/**
* Get the actual indent of a token
* @param token Token to examine. This should be the first token on its line.
* @returns The indentation characters that precede the token
*/
public getTokenIndent(token: TSESTree.Token): string {
return this.sourceCode.text.slice(
token.range[0] - token.loc.start.column,
token.range[0],
);
}
}