This repository has been archived by the owner on Apr 19, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
280 lines (238 loc) · 8.85 KB
/
index.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import type { Rule } from 'eslint';
import * as path from 'path';
import * as lex from 'pug-lexer';
import type { VDocumentFragment, VElement } from '../util-types/ast/v-ast';
import type { ParserServices } from '../util-types/parser-services';
/**
* Context that contains information about the current loop cycle.
*/
export interface TokenProcessorContext {
/**
* The current index of the loop.
*/
readonly index: number;
/**
* All tokens.
*/
readonly tokens: ReadonlyArray<lex.Token>;
}
/**
* Object with registrable callback functions to listen for a token occurrence.
*/
export type TokenProcessor = {
/**
* Callback function that is called if the token with this function name was found.
*
* The first argument is the current token and it is equals to `tokens[index]` provided from the second argument.
*
* @param token The current token.
* @param context Contains the current index and all tokens.
*/
[K in lex.LexTokenType]?: <Token extends Extract<lex.Token, lex.LexToken<K>>>(
token: Token,
context: TokenProcessorContext
) => void;
};
/**
* A container with all registered token processors and a state if these processors were already called.
*/
interface TokenProcessorsStateContainer {
/**
* A list of registered token processors.
*/
tokenProcessors: TokenProcessor[];
/**
* `true` if the container was already called, `false` otherwise.
*/
alreadyProcessed: boolean;
}
const CACHED_TOKEN_PROCESSOR_STATE_CONTAINER_MAP: Record<string, TokenProcessorsStateContainer> = {};
/**
* Process the current lint rule.
*
* It checks if the current file is a `.vue` file. If not it returns early with `{}`.
* Then it will parse the bug content with the pug-lexer and cache the result.
* If the current file was already processed by another rule, it will use the cached result.
*
* After that it will register the current rule with the given token processor
* and then it will later call all registered token processors for this file at once,
* so that only one for-loop for the tokens is needed to safe performance.
*
* @param context The eslint rule context.
* @param tokenProcessor A callback to register a token processor for the current lint rule.
* @returns The object that should be returned in the `create` function of the rule.
*/
export function processRule(context: Rule.RuleContext, tokenProcessor: () => TokenProcessor): Rule.RuleListener {
if (!checkIsVueFile(context)) {
return {};
}
const optionsHash: string = JSON.stringify(context.options);
const { tokens, text } = parsePugContent(context);
const cacheKey: string = `${optionsHash}\n${text}`;
if (tokens.length === 0) {
return {};
}
const tokenProcessorReturn: TokenProcessor = tokenProcessor();
const tokenProcessors: TokenProcessorsStateContainer | undefined =
CACHED_TOKEN_PROCESSOR_STATE_CONTAINER_MAP[cacheKey];
if (!tokenProcessors) {
CACHED_TOKEN_PROCESSOR_STATE_CONTAINER_MAP[cacheKey] = {
tokenProcessors: [],
alreadyProcessed: false
};
}
CACHED_TOKEN_PROCESSOR_STATE_CONTAINER_MAP[cacheKey]!.tokenProcessors.push(tokenProcessorReturn);
return {
'Program:exit'() {
// Within this callback, we fetch the token processors from the cache
// and process all registered token processors at once.
// !> Keep attention of which variables are usable from above's scope.
const tokenProcessorStateContainer: TokenProcessorsStateContainer = CACHED_TOKEN_PROCESSOR_STATE_CONTAINER_MAP[
cacheKey
] ?? {
tokenProcessors: [],
alreadyProcessed: true
};
if (tokenProcessorStateContainer.alreadyProcessed || tokenProcessorStateContainer.tokenProcessors.length === 0) {
return;
}
for (let index: number = 0; index < tokens.length; index++) {
const token: lex.Token = tokens[index]!;
tokenProcessorStateContainer.tokenProcessors.forEach((tokenProcessor) => {
// @ts-expect-error: just call it
tokenProcessor[token.type]?.(
// This comment only exists so that the parameters are wrapped and not affected by the `@ts-expect-error` comment.
token,
{ index, tokens }
);
});
}
tokenProcessorStateContainer.alreadyProcessed = true;
return;
}
};
}
export function checkIsVueFile(context: Rule.RuleContext): boolean {
const parserServices: ParserServices = context.parserServices;
if (parserServices.defineTemplateBodyVisitor == null) {
const filename: string = context.getFilename();
if (path.extname(filename) === '.vue') {
context.report({
loc: { line: 1, column: 0 },
message:
'Use the latest vue-eslint-parser. See also https://eslint.vuejs.org/user-guide/#what-is-the-use-the-latest-vue-eslint-parser-error.'
});
}
return false;
}
return true;
}
export interface ParsePugContentReturn {
text: string;
tokens: lex.Token[];
}
const CACHED_PUG_CONTENT_RETURN_CONTENT_MAP: Map<string, ParsePugContentReturn> = new Map();
export function parsePugContent(context: Rule.RuleContext): ParsePugContentReturn {
const cacheKey: string = context.getSourceCode().text;
const cachedValue: ParsePugContentReturn | undefined = CACHED_PUG_CONTENT_RETURN_CONTENT_MAP.get(cacheKey);
if (cachedValue) {
return cachedValue;
}
const result: ParsePugContentReturn = { text: '', tokens: [] };
const parserServices: ParserServices = context.parserServices;
// Parse the pug content to tokens
const df: VDocumentFragment | null | undefined = parserServices.getDocumentFragment?.();
if (!df) {
CACHED_PUG_CONTENT_RETURN_CONTENT_MAP.set(cacheKey, result);
return result;
}
const pugTemplateElement: VElement | undefined = df.children.find(
(node) =>
node.type === 'VElement' &&
node.name === 'template' &&
node.startTag.attributes.some(
(attr) => !attr.directive && attr.key.name === 'lang' && attr.value && attr.value.value === 'pug'
)
) as VElement | undefined;
if (!pugTemplateElement) {
CACHED_PUG_CONTENT_RETURN_CONTENT_MAP.set(cacheKey, result);
return result;
}
const rawText: string = cacheKey; // Same as `context.getSourceCode().text`
const pugText: string = rawText.slice(pugTemplateElement.startTag.range[1], pugTemplateElement.endTag?.range[0]);
const pugTokens: lex.Token[] = [];
try {
pugTokens.push(...lex(pugText));
} catch (error) {
CACHED_PUG_CONTENT_RETURN_CONTENT_MAP.set(cacheKey, result);
return result;
}
let start: number = pugTemplateElement.startTag.range[1];
if (pugTokens[0]?.type === 'newline') {
start++;
}
let end: number = start;
for (let index: number = 0; index < pugTokens.length; index++) {
const token: lex.Token = pugTokens[index]!;
const previousToken: lex.Token | undefined = pugTokens[index - 1];
if (previousToken) {
if (token.loc.start.line !== previousToken.loc.end.line) {
// Take `\n` and attribute wrapping into account
start += token.loc.start.column;
if (previousToken.type === 'attribute') {
start++;
}
} else {
const diff: number = token.loc.start.column - previousToken.loc.end.column;
// Take attribute separators and such into account
start += diff;
}
}
end = start + tokenLength(token, previousToken);
// @ts-expect-error: Add range to token
token.range = [start, end];
//// @ts-expect-error: Access range
// console.log(token.type, token.range, rawText.slice(start, end));
start = end;
}
result.text = pugText;
result.tokens = pugTokens;
CACHED_PUG_CONTENT_RETURN_CONTENT_MAP.set(cacheKey, result);
return result;
}
export function tokenLength(token: lex.Token, previousToken?: lex.Token): number {
if (token.type === 'newline') {
const length: number = token.loc.end.column - token.loc.start.column;
const diff: number = token.loc.start.line - (previousToken?.loc.end.line ?? 1);
return length + (diff - 1);
}
if (
token.type === 'end-attributes' &&
previousToken?.type === 'attribute' &&
// Detect brace on new line wrapping after last attribute
token.loc.start.line - 1 === previousToken.loc.end.line
) {
return 0;
}
if (
token.type === 'outdent' &&
previousToken &&
// Some outdents seems to be larger than one blank line
token.loc.start.line - 1 > previousToken.loc.end.line
) {
return token.loc.end.column;
}
if (token.loc.start.line === token.loc.end.line) {
return token.loc.end.column - token.loc.start.column;
}
console.debug('Please report token:', JSON.stringify(token));
return 0;
}
export function findIndexFrom<T>(
arr: ReadonlyArray<T>,
predicate: (value: T, index: number, obj: ReadonlyArray<T>) => unknown,
fromIndex: number
): number {
const index: number = arr.slice(fromIndex).findIndex(predicate);
return index === -1 ? -1 : index + fromIndex;
}