1 | /**
|
---|
2 | * @fileoverview This rule sets a specific indentation style and width for your code
|
---|
3 | *
|
---|
4 | * @author Teddy Katz
|
---|
5 | * @author Vitaly Puzrin
|
---|
6 | * @author Gyandeep Singh
|
---|
7 | * @deprecated in ESLint v8.53.0
|
---|
8 | */
|
---|
9 |
|
---|
10 | "use strict";
|
---|
11 |
|
---|
12 | //------------------------------------------------------------------------------
|
---|
13 | // Requirements
|
---|
14 | //------------------------------------------------------------------------------
|
---|
15 |
|
---|
16 | const astUtils = require("./utils/ast-utils");
|
---|
17 |
|
---|
18 | //------------------------------------------------------------------------------
|
---|
19 | // Rule Definition
|
---|
20 | //------------------------------------------------------------------------------
|
---|
21 |
|
---|
22 | const KNOWN_NODES = new Set([
|
---|
23 | "AssignmentExpression",
|
---|
24 | "AssignmentPattern",
|
---|
25 | "ArrayExpression",
|
---|
26 | "ArrayPattern",
|
---|
27 | "ArrowFunctionExpression",
|
---|
28 | "AwaitExpression",
|
---|
29 | "BlockStatement",
|
---|
30 | "BinaryExpression",
|
---|
31 | "BreakStatement",
|
---|
32 | "CallExpression",
|
---|
33 | "CatchClause",
|
---|
34 | "ChainExpression",
|
---|
35 | "ClassBody",
|
---|
36 | "ClassDeclaration",
|
---|
37 | "ClassExpression",
|
---|
38 | "ConditionalExpression",
|
---|
39 | "ContinueStatement",
|
---|
40 | "DoWhileStatement",
|
---|
41 | "DebuggerStatement",
|
---|
42 | "EmptyStatement",
|
---|
43 | "ExperimentalRestProperty",
|
---|
44 | "ExperimentalSpreadProperty",
|
---|
45 | "ExpressionStatement",
|
---|
46 | "ForStatement",
|
---|
47 | "ForInStatement",
|
---|
48 | "ForOfStatement",
|
---|
49 | "FunctionDeclaration",
|
---|
50 | "FunctionExpression",
|
---|
51 | "Identifier",
|
---|
52 | "IfStatement",
|
---|
53 | "Literal",
|
---|
54 | "LabeledStatement",
|
---|
55 | "LogicalExpression",
|
---|
56 | "MemberExpression",
|
---|
57 | "MetaProperty",
|
---|
58 | "MethodDefinition",
|
---|
59 | "NewExpression",
|
---|
60 | "ObjectExpression",
|
---|
61 | "ObjectPattern",
|
---|
62 | "PrivateIdentifier",
|
---|
63 | "Program",
|
---|
64 | "Property",
|
---|
65 | "PropertyDefinition",
|
---|
66 | "RestElement",
|
---|
67 | "ReturnStatement",
|
---|
68 | "SequenceExpression",
|
---|
69 | "SpreadElement",
|
---|
70 | "StaticBlock",
|
---|
71 | "Super",
|
---|
72 | "SwitchCase",
|
---|
73 | "SwitchStatement",
|
---|
74 | "TaggedTemplateExpression",
|
---|
75 | "TemplateElement",
|
---|
76 | "TemplateLiteral",
|
---|
77 | "ThisExpression",
|
---|
78 | "ThrowStatement",
|
---|
79 | "TryStatement",
|
---|
80 | "UnaryExpression",
|
---|
81 | "UpdateExpression",
|
---|
82 | "VariableDeclaration",
|
---|
83 | "VariableDeclarator",
|
---|
84 | "WhileStatement",
|
---|
85 | "WithStatement",
|
---|
86 | "YieldExpression",
|
---|
87 | "JSXFragment",
|
---|
88 | "JSXOpeningFragment",
|
---|
89 | "JSXClosingFragment",
|
---|
90 | "JSXIdentifier",
|
---|
91 | "JSXNamespacedName",
|
---|
92 | "JSXMemberExpression",
|
---|
93 | "JSXEmptyExpression",
|
---|
94 | "JSXExpressionContainer",
|
---|
95 | "JSXElement",
|
---|
96 | "JSXClosingElement",
|
---|
97 | "JSXOpeningElement",
|
---|
98 | "JSXAttribute",
|
---|
99 | "JSXSpreadAttribute",
|
---|
100 | "JSXText",
|
---|
101 | "ExportDefaultDeclaration",
|
---|
102 | "ExportNamedDeclaration",
|
---|
103 | "ExportAllDeclaration",
|
---|
104 | "ExportSpecifier",
|
---|
105 | "ImportDeclaration",
|
---|
106 | "ImportSpecifier",
|
---|
107 | "ImportDefaultSpecifier",
|
---|
108 | "ImportNamespaceSpecifier",
|
---|
109 | "ImportExpression"
|
---|
110 | ]);
|
---|
111 |
|
---|
112 | /*
|
---|
113 | * General rule strategy:
|
---|
114 | * 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another
|
---|
115 | * specified token or to the first column.
|
---|
116 | * 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a
|
---|
117 | * BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly
|
---|
118 | * brace of the BlockStatement.
|
---|
119 | * 3. After traversing the AST, calculate the expected indentation levels of every token according to the
|
---|
120 | * OffsetStorage container.
|
---|
121 | * 4. For each line, compare the expected indentation of the first token to the actual indentation in the file,
|
---|
122 | * and report the token if the two values are not equal.
|
---|
123 | */
|
---|
124 |
|
---|
125 |
|
---|
126 | /**
|
---|
127 | * A mutable map that stores (key, value) pairs. The keys are numeric indices, and must be unique.
|
---|
128 | * This is intended to be a generic wrapper around a map with non-negative integer keys, so that the underlying implementation
|
---|
129 | * can easily be swapped out.
|
---|
130 | */
|
---|
131 | class IndexMap {
|
---|
132 |
|
---|
133 | /**
|
---|
134 | * Creates an empty map
|
---|
135 | * @param {number} maxKey The maximum key
|
---|
136 | */
|
---|
137 | constructor(maxKey) {
|
---|
138 |
|
---|
139 | // Initializing the array with the maximum expected size avoids dynamic reallocations that could degrade performance.
|
---|
140 | this._values = Array(maxKey + 1);
|
---|
141 | }
|
---|
142 |
|
---|
143 | /**
|
---|
144 | * Inserts an entry into the map.
|
---|
145 | * @param {number} key The entry's key
|
---|
146 | * @param {any} value The entry's value
|
---|
147 | * @returns {void}
|
---|
148 | */
|
---|
149 | insert(key, value) {
|
---|
150 | this._values[key] = value;
|
---|
151 | }
|
---|
152 |
|
---|
153 | /**
|
---|
154 | * Finds the value of the entry with the largest key less than or equal to the provided key
|
---|
155 | * @param {number} key The provided key
|
---|
156 | * @returns {*|undefined} The value of the found entry, or undefined if no such entry exists.
|
---|
157 | */
|
---|
158 | findLastNotAfter(key) {
|
---|
159 | const values = this._values;
|
---|
160 |
|
---|
161 | for (let index = key; index >= 0; index--) {
|
---|
162 | const value = values[index];
|
---|
163 |
|
---|
164 | if (value) {
|
---|
165 | return value;
|
---|
166 | }
|
---|
167 | }
|
---|
168 | return void 0;
|
---|
169 | }
|
---|
170 |
|
---|
171 | /**
|
---|
172 | * Deletes all of the keys in the interval [start, end)
|
---|
173 | * @param {number} start The start of the range
|
---|
174 | * @param {number} end The end of the range
|
---|
175 | * @returns {void}
|
---|
176 | */
|
---|
177 | deleteRange(start, end) {
|
---|
178 | this._values.fill(void 0, start, end);
|
---|
179 | }
|
---|
180 | }
|
---|
181 |
|
---|
182 | /**
|
---|
183 | * A helper class to get token-based info related to indentation
|
---|
184 | */
|
---|
185 | class TokenInfo {
|
---|
186 |
|
---|
187 | /**
|
---|
188 | * @param {SourceCode} sourceCode A SourceCode object
|
---|
189 | */
|
---|
190 | constructor(sourceCode) {
|
---|
191 | this.sourceCode = sourceCode;
|
---|
192 | this.firstTokensByLineNumber = new Map();
|
---|
193 | const tokens = sourceCode.tokensAndComments;
|
---|
194 |
|
---|
195 | for (let i = 0; i < tokens.length; i++) {
|
---|
196 | const token = tokens[i];
|
---|
197 |
|
---|
198 | if (!this.firstTokensByLineNumber.has(token.loc.start.line)) {
|
---|
199 | this.firstTokensByLineNumber.set(token.loc.start.line, token);
|
---|
200 | }
|
---|
201 | if (!this.firstTokensByLineNumber.has(token.loc.end.line) && sourceCode.text.slice(token.range[1] - token.loc.end.column, token.range[1]).trim()) {
|
---|
202 | this.firstTokensByLineNumber.set(token.loc.end.line, token);
|
---|
203 | }
|
---|
204 | }
|
---|
205 | }
|
---|
206 |
|
---|
207 | /**
|
---|
208 | * Gets the first token on a given token's line
|
---|
209 | * @param {Token|ASTNode} token a node or token
|
---|
210 | * @returns {Token} The first token on the given line
|
---|
211 | */
|
---|
212 | getFirstTokenOfLine(token) {
|
---|
213 | return this.firstTokensByLineNumber.get(token.loc.start.line);
|
---|
214 | }
|
---|
215 |
|
---|
216 | /**
|
---|
217 | * Determines whether a token is the first token in its line
|
---|
218 | * @param {Token} token The token
|
---|
219 | * @returns {boolean} `true` if the token is the first on its line
|
---|
220 | */
|
---|
221 | isFirstTokenOfLine(token) {
|
---|
222 | return this.getFirstTokenOfLine(token) === token;
|
---|
223 | }
|
---|
224 |
|
---|
225 | /**
|
---|
226 | * Get the actual indent of a token
|
---|
227 | * @param {Token} token Token to examine. This should be the first token on its line.
|
---|
228 | * @returns {string} The indentation characters that precede the token
|
---|
229 | */
|
---|
230 | getTokenIndent(token) {
|
---|
231 | return this.sourceCode.text.slice(token.range[0] - token.loc.start.column, token.range[0]);
|
---|
232 | }
|
---|
233 | }
|
---|
234 |
|
---|
235 | /**
|
---|
236 | * A class to store information on desired offsets of tokens from each other
|
---|
237 | */
|
---|
238 | class OffsetStorage {
|
---|
239 |
|
---|
240 | /**
|
---|
241 | * @param {TokenInfo} tokenInfo a TokenInfo instance
|
---|
242 | * @param {number} indentSize The desired size of each indentation level
|
---|
243 | * @param {string} indentType The indentation character
|
---|
244 | * @param {number} maxIndex The maximum end index of any token
|
---|
245 | */
|
---|
246 | constructor(tokenInfo, indentSize, indentType, maxIndex) {
|
---|
247 | this._tokenInfo = tokenInfo;
|
---|
248 | this._indentSize = indentSize;
|
---|
249 | this._indentType = indentType;
|
---|
250 |
|
---|
251 | this._indexMap = new IndexMap(maxIndex);
|
---|
252 | this._indexMap.insert(0, { offset: 0, from: null, force: false });
|
---|
253 |
|
---|
254 | this._lockedFirstTokens = new WeakMap();
|
---|
255 | this._desiredIndentCache = new WeakMap();
|
---|
256 | this._ignoredTokens = new WeakSet();
|
---|
257 | }
|
---|
258 |
|
---|
259 | _getOffsetDescriptor(token) {
|
---|
260 | return this._indexMap.findLastNotAfter(token.range[0]);
|
---|
261 | }
|
---|
262 |
|
---|
263 | /**
|
---|
264 | * Sets the offset column of token B to match the offset column of token A.
|
---|
265 | * - **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In
|
---|
266 | * most cases, `setDesiredOffset` should be used instead.
|
---|
267 | * @param {Token} baseToken The first token
|
---|
268 | * @param {Token} offsetToken The second token, whose offset should be matched to the first token
|
---|
269 | * @returns {void}
|
---|
270 | */
|
---|
271 | matchOffsetOf(baseToken, offsetToken) {
|
---|
272 |
|
---|
273 | /*
|
---|
274 | * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to
|
---|
275 | * the token that it depends on. For example, with the `ArrayExpression: first` option, the first
|
---|
276 | * token of each element in the array after the first will be mapped to the first token of the first
|
---|
277 | * element. The desired indentation of each of these tokens is computed based on the desired indentation
|
---|
278 | * of the "first" element, rather than through the normal offset mechanism.
|
---|
279 | */
|
---|
280 | this._lockedFirstTokens.set(offsetToken, baseToken);
|
---|
281 | }
|
---|
282 |
|
---|
283 | /**
|
---|
284 | * Sets the desired offset of a token.
|
---|
285 | *
|
---|
286 | * This uses a line-based offset collapsing behavior to handle tokens on the same line.
|
---|
287 | * For example, consider the following two cases:
|
---|
288 | *
|
---|
289 | * (
|
---|
290 | * [
|
---|
291 | * bar
|
---|
292 | * ]
|
---|
293 | * )
|
---|
294 | *
|
---|
295 | * ([
|
---|
296 | * bar
|
---|
297 | * ])
|
---|
298 | *
|
---|
299 | * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from
|
---|
300 | * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is
|
---|
301 | * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces)
|
---|
302 | * from the start of its line.
|
---|
303 | *
|
---|
304 | * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level
|
---|
305 | * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the
|
---|
306 | * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented
|
---|
307 | * by 1 indent level from the start of the line.
|
---|
308 | *
|
---|
309 | * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node,
|
---|
310 | * without needing to check which lines those tokens are on.
|
---|
311 | *
|
---|
312 | * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive
|
---|
313 | * behavior can occur. For example, consider the following cases:
|
---|
314 | *
|
---|
315 | * foo(
|
---|
316 | * ).
|
---|
317 | * bar(
|
---|
318 | * baz
|
---|
319 | * )
|
---|
320 | *
|
---|
321 | * foo(
|
---|
322 | * ).bar(
|
---|
323 | * baz
|
---|
324 | * )
|
---|
325 | *
|
---|
326 | * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz`
|
---|
327 | * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz`
|
---|
328 | * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no
|
---|
329 | * collapsing would occur).
|
---|
330 | *
|
---|
331 | * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and
|
---|
332 | * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed
|
---|
333 | * in the second case.
|
---|
334 | * @param {Token} token The token
|
---|
335 | * @param {Token} fromToken The token that `token` should be offset from
|
---|
336 | * @param {number} offset The desired indent level
|
---|
337 | * @returns {void}
|
---|
338 | */
|
---|
339 | setDesiredOffset(token, fromToken, offset) {
|
---|
340 | return this.setDesiredOffsets(token.range, fromToken, offset);
|
---|
341 | }
|
---|
342 |
|
---|
343 | /**
|
---|
344 | * Sets the desired offset of all tokens in a range
|
---|
345 | * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens.
|
---|
346 | * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains
|
---|
347 | * it). This means that the offset of each token is updated O(AST depth) times.
|
---|
348 | * It would not be performant to store and update the offsets for each token independently, because the rule would end
|
---|
349 | * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files.
|
---|
350 | *
|
---|
351 | * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following
|
---|
352 | * list could represent the state of the offset tree at a given point:
|
---|
353 | *
|
---|
354 | * - Tokens starting in the interval [0, 15) are aligned with the beginning of the file
|
---|
355 | * - Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token
|
---|
356 | * - Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token
|
---|
357 | * - Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token
|
---|
358 | * - Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token
|
---|
359 | *
|
---|
360 | * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using:
|
---|
361 | * `setDesiredOffsets([30, 43], fooToken, 1);`
|
---|
362 | * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied.
|
---|
363 | * @param {Token} fromToken The token that this is offset from
|
---|
364 | * @param {number} offset The desired indent level
|
---|
365 | * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false.
|
---|
366 | * @returns {void}
|
---|
367 | */
|
---|
368 | setDesiredOffsets(range, fromToken, offset, force) {
|
---|
369 |
|
---|
370 | /*
|
---|
371 | * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset
|
---|
372 | * descriptor. The tree for the example above would have the following nodes:
|
---|
373 | *
|
---|
374 | * * key: 0, value: { offset: 0, from: null }
|
---|
375 | * * key: 15, value: { offset: 1, from: barToken }
|
---|
376 | * * key: 30, value: { offset: 1, from: fooToken }
|
---|
377 | * * key: 43, value: { offset: 2, from: barToken }
|
---|
378 | * * key: 820, value: { offset: 1, from: bazToken }
|
---|
379 | *
|
---|
380 | * To find the offset descriptor for any given token, one needs to find the node with the largest key
|
---|
381 | * which is <= token.start. To make this operation fast, the nodes are stored in a map indexed by key.
|
---|
382 | */
|
---|
383 |
|
---|
384 | const descriptorToInsert = { offset, from: fromToken, force };
|
---|
385 |
|
---|
386 | const descriptorAfterRange = this._indexMap.findLastNotAfter(range[1]);
|
---|
387 |
|
---|
388 | const fromTokenIsInRange = fromToken && fromToken.range[0] >= range[0] && fromToken.range[1] <= range[1];
|
---|
389 | const fromTokenDescriptor = fromTokenIsInRange && this._getOffsetDescriptor(fromToken);
|
---|
390 |
|
---|
391 | // First, remove any existing nodes in the range from the map.
|
---|
392 | this._indexMap.deleteRange(range[0] + 1, range[1]);
|
---|
393 |
|
---|
394 | // Insert a new node into the map for this range
|
---|
395 | this._indexMap.insert(range[0], descriptorToInsert);
|
---|
396 |
|
---|
397 | /*
|
---|
398 | * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously,
|
---|
399 | * even if it's in the current range.
|
---|
400 | */
|
---|
401 | if (fromTokenIsInRange) {
|
---|
402 | this._indexMap.insert(fromToken.range[0], fromTokenDescriptor);
|
---|
403 | this._indexMap.insert(fromToken.range[1], descriptorToInsert);
|
---|
404 | }
|
---|
405 |
|
---|
406 | /*
|
---|
407 | * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following
|
---|
408 | * tokens the same as it was before.
|
---|
409 | */
|
---|
410 | this._indexMap.insert(range[1], descriptorAfterRange);
|
---|
411 | }
|
---|
412 |
|
---|
413 | /**
|
---|
414 | * Gets the desired indent of a token
|
---|
415 | * @param {Token} token The token
|
---|
416 | * @returns {string} The desired indent of the token
|
---|
417 | */
|
---|
418 | getDesiredIndent(token) {
|
---|
419 | if (!this._desiredIndentCache.has(token)) {
|
---|
420 |
|
---|
421 | if (this._ignoredTokens.has(token)) {
|
---|
422 |
|
---|
423 | /*
|
---|
424 | * If the token is ignored, use the actual indent of the token as the desired indent.
|
---|
425 | * This ensures that no errors are reported for this token.
|
---|
426 | */
|
---|
427 | this._desiredIndentCache.set(
|
---|
428 | token,
|
---|
429 | this._tokenInfo.getTokenIndent(token)
|
---|
430 | );
|
---|
431 | } else if (this._lockedFirstTokens.has(token)) {
|
---|
432 | const firstToken = this._lockedFirstTokens.get(token);
|
---|
433 |
|
---|
434 | this._desiredIndentCache.set(
|
---|
435 | token,
|
---|
436 |
|
---|
437 | // (indentation for the first element's line)
|
---|
438 | this.getDesiredIndent(this._tokenInfo.getFirstTokenOfLine(firstToken)) +
|
---|
439 |
|
---|
440 | // (space between the start of the first element's line and the first element)
|
---|
441 | this._indentType.repeat(firstToken.loc.start.column - this._tokenInfo.getFirstTokenOfLine(firstToken).loc.start.column)
|
---|
442 | );
|
---|
443 | } else {
|
---|
444 | const offsetInfo = this._getOffsetDescriptor(token);
|
---|
445 | const offset = (
|
---|
446 | offsetInfo.from &&
|
---|
447 | offsetInfo.from.loc.start.line === token.loc.start.line &&
|
---|
448 | !/^\s*?\n/u.test(token.value) &&
|
---|
449 | !offsetInfo.force
|
---|
450 | ) ? 0 : offsetInfo.offset * this._indentSize;
|
---|
451 |
|
---|
452 | this._desiredIndentCache.set(
|
---|
453 | token,
|
---|
454 | (offsetInfo.from ? this.getDesiredIndent(offsetInfo.from) : "") + this._indentType.repeat(offset)
|
---|
455 | );
|
---|
456 | }
|
---|
457 | }
|
---|
458 | return this._desiredIndentCache.get(token);
|
---|
459 | }
|
---|
460 |
|
---|
461 | /**
|
---|
462 | * Ignores a token, preventing it from being reported.
|
---|
463 | * @param {Token} token The token
|
---|
464 | * @returns {void}
|
---|
465 | */
|
---|
466 | ignoreToken(token) {
|
---|
467 | if (this._tokenInfo.isFirstTokenOfLine(token)) {
|
---|
468 | this._ignoredTokens.add(token);
|
---|
469 | }
|
---|
470 | }
|
---|
471 |
|
---|
472 | /**
|
---|
473 | * Gets the first token that the given token's indentation is dependent on
|
---|
474 | * @param {Token} token The token
|
---|
475 | * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level
|
---|
476 | */
|
---|
477 | getFirstDependency(token) {
|
---|
478 | return this._getOffsetDescriptor(token).from;
|
---|
479 | }
|
---|
480 | }
|
---|
481 |
|
---|
482 | const ELEMENT_LIST_SCHEMA = {
|
---|
483 | oneOf: [
|
---|
484 | {
|
---|
485 | type: "integer",
|
---|
486 | minimum: 0
|
---|
487 | },
|
---|
488 | {
|
---|
489 | enum: ["first", "off"]
|
---|
490 | }
|
---|
491 | ]
|
---|
492 | };
|
---|
493 |
|
---|
494 | /** @type {import('../shared/types').Rule} */
|
---|
495 | module.exports = {
|
---|
496 | meta: {
|
---|
497 | deprecated: true,
|
---|
498 | replacedBy: [],
|
---|
499 | type: "layout",
|
---|
500 |
|
---|
501 | docs: {
|
---|
502 | description: "Enforce consistent indentation",
|
---|
503 | recommended: false,
|
---|
504 | url: "https://eslint.org/docs/latest/rules/indent"
|
---|
505 | },
|
---|
506 |
|
---|
507 | fixable: "whitespace",
|
---|
508 |
|
---|
509 | schema: [
|
---|
510 | {
|
---|
511 | oneOf: [
|
---|
512 | {
|
---|
513 | enum: ["tab"]
|
---|
514 | },
|
---|
515 | {
|
---|
516 | type: "integer",
|
---|
517 | minimum: 0
|
---|
518 | }
|
---|
519 | ]
|
---|
520 | },
|
---|
521 | {
|
---|
522 | type: "object",
|
---|
523 | properties: {
|
---|
524 | SwitchCase: {
|
---|
525 | type: "integer",
|
---|
526 | minimum: 0,
|
---|
527 | default: 0
|
---|
528 | },
|
---|
529 | VariableDeclarator: {
|
---|
530 | oneOf: [
|
---|
531 | ELEMENT_LIST_SCHEMA,
|
---|
532 | {
|
---|
533 | type: "object",
|
---|
534 | properties: {
|
---|
535 | var: ELEMENT_LIST_SCHEMA,
|
---|
536 | let: ELEMENT_LIST_SCHEMA,
|
---|
537 | const: ELEMENT_LIST_SCHEMA
|
---|
538 | },
|
---|
539 | additionalProperties: false
|
---|
540 | }
|
---|
541 | ]
|
---|
542 | },
|
---|
543 | outerIIFEBody: {
|
---|
544 | oneOf: [
|
---|
545 | {
|
---|
546 | type: "integer",
|
---|
547 | minimum: 0
|
---|
548 | },
|
---|
549 | {
|
---|
550 | enum: ["off"]
|
---|
551 | }
|
---|
552 | ]
|
---|
553 | },
|
---|
554 | MemberExpression: {
|
---|
555 | oneOf: [
|
---|
556 | {
|
---|
557 | type: "integer",
|
---|
558 | minimum: 0
|
---|
559 | },
|
---|
560 | {
|
---|
561 | enum: ["off"]
|
---|
562 | }
|
---|
563 | ]
|
---|
564 | },
|
---|
565 | FunctionDeclaration: {
|
---|
566 | type: "object",
|
---|
567 | properties: {
|
---|
568 | parameters: ELEMENT_LIST_SCHEMA,
|
---|
569 | body: {
|
---|
570 | type: "integer",
|
---|
571 | minimum: 0
|
---|
572 | }
|
---|
573 | },
|
---|
574 | additionalProperties: false
|
---|
575 | },
|
---|
576 | FunctionExpression: {
|
---|
577 | type: "object",
|
---|
578 | properties: {
|
---|
579 | parameters: ELEMENT_LIST_SCHEMA,
|
---|
580 | body: {
|
---|
581 | type: "integer",
|
---|
582 | minimum: 0
|
---|
583 | }
|
---|
584 | },
|
---|
585 | additionalProperties: false
|
---|
586 | },
|
---|
587 | StaticBlock: {
|
---|
588 | type: "object",
|
---|
589 | properties: {
|
---|
590 | body: {
|
---|
591 | type: "integer",
|
---|
592 | minimum: 0
|
---|
593 | }
|
---|
594 | },
|
---|
595 | additionalProperties: false
|
---|
596 | },
|
---|
597 | CallExpression: {
|
---|
598 | type: "object",
|
---|
599 | properties: {
|
---|
600 | arguments: ELEMENT_LIST_SCHEMA
|
---|
601 | },
|
---|
602 | additionalProperties: false
|
---|
603 | },
|
---|
604 | ArrayExpression: ELEMENT_LIST_SCHEMA,
|
---|
605 | ObjectExpression: ELEMENT_LIST_SCHEMA,
|
---|
606 | ImportDeclaration: ELEMENT_LIST_SCHEMA,
|
---|
607 | flatTernaryExpressions: {
|
---|
608 | type: "boolean",
|
---|
609 | default: false
|
---|
610 | },
|
---|
611 | offsetTernaryExpressions: {
|
---|
612 | type: "boolean",
|
---|
613 | default: false
|
---|
614 | },
|
---|
615 | ignoredNodes: {
|
---|
616 | type: "array",
|
---|
617 | items: {
|
---|
618 | type: "string",
|
---|
619 | not: {
|
---|
620 | pattern: ":exit$"
|
---|
621 | }
|
---|
622 | }
|
---|
623 | },
|
---|
624 | ignoreComments: {
|
---|
625 | type: "boolean",
|
---|
626 | default: false
|
---|
627 | }
|
---|
628 | },
|
---|
629 | additionalProperties: false
|
---|
630 | }
|
---|
631 | ],
|
---|
632 | messages: {
|
---|
633 | wrongIndentation: "Expected indentation of {{expected}} but found {{actual}}."
|
---|
634 | }
|
---|
635 | },
|
---|
636 |
|
---|
637 | create(context) {
|
---|
638 | const DEFAULT_VARIABLE_INDENT = 1;
|
---|
639 | const DEFAULT_PARAMETER_INDENT = 1;
|
---|
640 | const DEFAULT_FUNCTION_BODY_INDENT = 1;
|
---|
641 |
|
---|
642 | let indentType = "space";
|
---|
643 | let indentSize = 4;
|
---|
644 | const options = {
|
---|
645 | SwitchCase: 0,
|
---|
646 | VariableDeclarator: {
|
---|
647 | var: DEFAULT_VARIABLE_INDENT,
|
---|
648 | let: DEFAULT_VARIABLE_INDENT,
|
---|
649 | const: DEFAULT_VARIABLE_INDENT
|
---|
650 | },
|
---|
651 | outerIIFEBody: 1,
|
---|
652 | FunctionDeclaration: {
|
---|
653 | parameters: DEFAULT_PARAMETER_INDENT,
|
---|
654 | body: DEFAULT_FUNCTION_BODY_INDENT
|
---|
655 | },
|
---|
656 | FunctionExpression: {
|
---|
657 | parameters: DEFAULT_PARAMETER_INDENT,
|
---|
658 | body: DEFAULT_FUNCTION_BODY_INDENT
|
---|
659 | },
|
---|
660 | StaticBlock: {
|
---|
661 | body: DEFAULT_FUNCTION_BODY_INDENT
|
---|
662 | },
|
---|
663 | CallExpression: {
|
---|
664 | arguments: DEFAULT_PARAMETER_INDENT
|
---|
665 | },
|
---|
666 | MemberExpression: 1,
|
---|
667 | ArrayExpression: 1,
|
---|
668 | ObjectExpression: 1,
|
---|
669 | ImportDeclaration: 1,
|
---|
670 | flatTernaryExpressions: false,
|
---|
671 | ignoredNodes: [],
|
---|
672 | ignoreComments: false
|
---|
673 | };
|
---|
674 |
|
---|
675 | if (context.options.length) {
|
---|
676 | if (context.options[0] === "tab") {
|
---|
677 | indentSize = 1;
|
---|
678 | indentType = "tab";
|
---|
679 | } else {
|
---|
680 | indentSize = context.options[0];
|
---|
681 | indentType = "space";
|
---|
682 | }
|
---|
683 |
|
---|
684 | if (context.options[1]) {
|
---|
685 | Object.assign(options, context.options[1]);
|
---|
686 |
|
---|
687 | if (typeof options.VariableDeclarator === "number" || options.VariableDeclarator === "first") {
|
---|
688 | options.VariableDeclarator = {
|
---|
689 | var: options.VariableDeclarator,
|
---|
690 | let: options.VariableDeclarator,
|
---|
691 | const: options.VariableDeclarator
|
---|
692 | };
|
---|
693 | }
|
---|
694 | }
|
---|
695 | }
|
---|
696 |
|
---|
697 | const sourceCode = context.sourceCode;
|
---|
698 | const tokenInfo = new TokenInfo(sourceCode);
|
---|
699 | const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t", sourceCode.text.length);
|
---|
700 | const parameterParens = new WeakSet();
|
---|
701 |
|
---|
702 | /**
|
---|
703 | * Creates an error message for a line, given the expected/actual indentation.
|
---|
704 | * @param {int} expectedAmount The expected amount of indentation characters for this line
|
---|
705 | * @param {int} actualSpaces The actual number of indentation spaces that were found on this line
|
---|
706 | * @param {int} actualTabs The actual number of indentation tabs that were found on this line
|
---|
707 | * @returns {string} An error message for this line
|
---|
708 | */
|
---|
709 | function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) {
|
---|
710 | const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs"
|
---|
711 | const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space"
|
---|
712 | const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs"
|
---|
713 | let foundStatement;
|
---|
714 |
|
---|
715 | if (actualSpaces > 0) {
|
---|
716 |
|
---|
717 | /*
|
---|
718 | * Abbreviate the message if the expected indentation is also spaces.
|
---|
719 | * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
|
---|
720 | */
|
---|
721 | foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`;
|
---|
722 | } else if (actualTabs > 0) {
|
---|
723 | foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`;
|
---|
724 | } else {
|
---|
725 | foundStatement = "0";
|
---|
726 | }
|
---|
727 | return {
|
---|
728 | expected: expectedStatement,
|
---|
729 | actual: foundStatement
|
---|
730 | };
|
---|
731 | }
|
---|
732 |
|
---|
733 | /**
|
---|
734 | * Reports a given indent violation
|
---|
735 | * @param {Token} token Token violating the indent rule
|
---|
736 | * @param {string} neededIndent Expected indentation string
|
---|
737 | * @returns {void}
|
---|
738 | */
|
---|
739 | function report(token, neededIndent) {
|
---|
740 | const actualIndent = Array.from(tokenInfo.getTokenIndent(token));
|
---|
741 | const numSpaces = actualIndent.filter(char => char === " ").length;
|
---|
742 | const numTabs = actualIndent.filter(char => char === "\t").length;
|
---|
743 |
|
---|
744 | context.report({
|
---|
745 | node: token,
|
---|
746 | messageId: "wrongIndentation",
|
---|
747 | data: createErrorMessageData(neededIndent.length, numSpaces, numTabs),
|
---|
748 | loc: {
|
---|
749 | start: { line: token.loc.start.line, column: 0 },
|
---|
750 | end: { line: token.loc.start.line, column: token.loc.start.column }
|
---|
751 | },
|
---|
752 | fix(fixer) {
|
---|
753 | const range = [token.range[0] - token.loc.start.column, token.range[0]];
|
---|
754 | const newText = neededIndent;
|
---|
755 |
|
---|
756 | return fixer.replaceTextRange(range, newText);
|
---|
757 | }
|
---|
758 | });
|
---|
759 | }
|
---|
760 |
|
---|
761 | /**
|
---|
762 | * Checks if a token's indentation is correct
|
---|
763 | * @param {Token} token Token to examine
|
---|
764 | * @param {string} desiredIndent Desired indentation of the string
|
---|
765 | * @returns {boolean} `true` if the token's indentation is correct
|
---|
766 | */
|
---|
767 | function validateTokenIndent(token, desiredIndent) {
|
---|
768 | const indentation = tokenInfo.getTokenIndent(token);
|
---|
769 |
|
---|
770 | return indentation === desiredIndent ||
|
---|
771 |
|
---|
772 | // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
|
---|
773 | indentation.includes(" ") && indentation.includes("\t");
|
---|
774 | }
|
---|
775 |
|
---|
776 | /**
|
---|
777 | * Check to see if the node is a file level IIFE
|
---|
778 | * @param {ASTNode} node The function node to check.
|
---|
779 | * @returns {boolean} True if the node is the outer IIFE
|
---|
780 | */
|
---|
781 | function isOuterIIFE(node) {
|
---|
782 |
|
---|
783 | /*
|
---|
784 | * Verify that the node is an IIFE
|
---|
785 | */
|
---|
786 | if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) {
|
---|
787 | return false;
|
---|
788 | }
|
---|
789 |
|
---|
790 | /*
|
---|
791 | * Navigate legal ancestors to determine whether this IIFE is outer.
|
---|
792 | * A "legal ancestor" is an expression or statement that causes the function to get executed immediately.
|
---|
793 | * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator.
|
---|
794 | */
|
---|
795 | let statement = node.parent && node.parent.parent;
|
---|
796 |
|
---|
797 | while (
|
---|
798 | statement.type === "UnaryExpression" && ["!", "~", "+", "-"].includes(statement.operator) ||
|
---|
799 | statement.type === "AssignmentExpression" ||
|
---|
800 | statement.type === "LogicalExpression" ||
|
---|
801 | statement.type === "SequenceExpression" ||
|
---|
802 | statement.type === "VariableDeclarator"
|
---|
803 | ) {
|
---|
804 | statement = statement.parent;
|
---|
805 | }
|
---|
806 |
|
---|
807 | return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program";
|
---|
808 | }
|
---|
809 |
|
---|
810 | /**
|
---|
811 | * Counts the number of linebreaks that follow the last non-whitespace character in a string
|
---|
812 | * @param {string} string The string to check
|
---|
813 | * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character,
|
---|
814 | * or the total number of linebreaks if the string is all whitespace.
|
---|
815 | */
|
---|
816 | function countTrailingLinebreaks(string) {
|
---|
817 | const trailingWhitespace = string.match(/\s*$/u)[0];
|
---|
818 | const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher());
|
---|
819 |
|
---|
820 | return linebreakMatches === null ? 0 : linebreakMatches.length;
|
---|
821 | }
|
---|
822 |
|
---|
823 | /**
|
---|
824 | * Check indentation for lists of elements (arrays, objects, function params)
|
---|
825 | * @param {ASTNode[]} elements List of elements that should be offset
|
---|
826 | * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '['
|
---|
827 | * @param {Token} endToken The end token of the list, e.g. ']'
|
---|
828 | * @param {number|string} offset The amount that the elements should be offset
|
---|
829 | * @returns {void}
|
---|
830 | */
|
---|
831 | function addElementListIndent(elements, startToken, endToken, offset) {
|
---|
832 |
|
---|
833 | /**
|
---|
834 | * Gets the first token of a given element, including surrounding parentheses.
|
---|
835 | * @param {ASTNode} element A node in the `elements` list
|
---|
836 | * @returns {Token} The first token of this element
|
---|
837 | */
|
---|
838 | function getFirstToken(element) {
|
---|
839 | let token = sourceCode.getTokenBefore(element);
|
---|
840 |
|
---|
841 | while (astUtils.isOpeningParenToken(token) && token !== startToken) {
|
---|
842 | token = sourceCode.getTokenBefore(token);
|
---|
843 | }
|
---|
844 | return sourceCode.getTokenAfter(token);
|
---|
845 | }
|
---|
846 |
|
---|
847 | // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden)
|
---|
848 | offsets.setDesiredOffsets(
|
---|
849 | [startToken.range[1], endToken.range[0]],
|
---|
850 | startToken,
|
---|
851 | typeof offset === "number" ? offset : 1
|
---|
852 | );
|
---|
853 | offsets.setDesiredOffset(endToken, startToken, 0);
|
---|
854 |
|
---|
855 | // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level.
|
---|
856 | if (offset === "first" && elements.length && !elements[0]) {
|
---|
857 | return;
|
---|
858 | }
|
---|
859 | elements.forEach((element, index) => {
|
---|
860 | if (!element) {
|
---|
861 |
|
---|
862 | // Skip holes in arrays
|
---|
863 | return;
|
---|
864 | }
|
---|
865 | if (offset === "off") {
|
---|
866 |
|
---|
867 | // Ignore the first token of every element if the "off" option is used
|
---|
868 | offsets.ignoreToken(getFirstToken(element));
|
---|
869 | }
|
---|
870 |
|
---|
871 | // Offset the following elements correctly relative to the first element
|
---|
872 | if (index === 0) {
|
---|
873 | return;
|
---|
874 | }
|
---|
875 | if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) {
|
---|
876 | offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element));
|
---|
877 | } else {
|
---|
878 | const previousElement = elements[index - 1];
|
---|
879 | const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement);
|
---|
880 | const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement);
|
---|
881 |
|
---|
882 | if (
|
---|
883 | previousElement &&
|
---|
884 | previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line
|
---|
885 | ) {
|
---|
886 | offsets.setDesiredOffsets(
|
---|
887 | [previousElement.range[1], element.range[1]],
|
---|
888 | firstTokenOfPreviousElement,
|
---|
889 | 0
|
---|
890 | );
|
---|
891 | }
|
---|
892 | }
|
---|
893 | });
|
---|
894 | }
|
---|
895 |
|
---|
896 | /**
|
---|
897 | * Check and decide whether to check for indentation for blockless nodes
|
---|
898 | * Scenarios are for or while statements without braces around them
|
---|
899 | * @param {ASTNode} node node to examine
|
---|
900 | * @returns {void}
|
---|
901 | */
|
---|
902 | function addBlocklessNodeIndent(node) {
|
---|
903 | if (node.type !== "BlockStatement") {
|
---|
904 | const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken);
|
---|
905 |
|
---|
906 | let firstBodyToken = sourceCode.getFirstToken(node);
|
---|
907 | let lastBodyToken = sourceCode.getLastToken(node);
|
---|
908 |
|
---|
909 | while (
|
---|
910 | astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) &&
|
---|
911 | astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken))
|
---|
912 | ) {
|
---|
913 | firstBodyToken = sourceCode.getTokenBefore(firstBodyToken);
|
---|
914 | lastBodyToken = sourceCode.getTokenAfter(lastBodyToken);
|
---|
915 | }
|
---|
916 |
|
---|
917 | offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
|
---|
918 | }
|
---|
919 | }
|
---|
920 |
|
---|
921 | /**
|
---|
922 | * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`)
|
---|
923 | * @param {ASTNode} node A CallExpression or NewExpression node
|
---|
924 | * @returns {void}
|
---|
925 | */
|
---|
926 | function addFunctionCallIndent(node) {
|
---|
927 | let openingParen;
|
---|
928 |
|
---|
929 | if (node.arguments.length) {
|
---|
930 | openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken);
|
---|
931 | } else {
|
---|
932 | openingParen = sourceCode.getLastToken(node, 1);
|
---|
933 | }
|
---|
934 | const closingParen = sourceCode.getLastToken(node);
|
---|
935 |
|
---|
936 | parameterParens.add(openingParen);
|
---|
937 | parameterParens.add(closingParen);
|
---|
938 |
|
---|
939 | /*
|
---|
940 | * If `?.` token exists, set desired offset for that.
|
---|
941 | * This logic is copied from `MemberExpression`'s.
|
---|
942 | */
|
---|
943 | if (node.optional) {
|
---|
944 | const dotToken = sourceCode.getTokenAfter(node.callee, astUtils.isQuestionDotToken);
|
---|
945 | const calleeParenCount = sourceCode.getTokensBetween(node.callee, dotToken, { filter: astUtils.isClosingParenToken }).length;
|
---|
946 | const firstTokenOfCallee = calleeParenCount
|
---|
947 | ? sourceCode.getTokenBefore(node.callee, { skip: calleeParenCount - 1 })
|
---|
948 | : sourceCode.getFirstToken(node.callee);
|
---|
949 | const lastTokenOfCallee = sourceCode.getTokenBefore(dotToken);
|
---|
950 | const offsetBase = lastTokenOfCallee.loc.end.line === openingParen.loc.start.line
|
---|
951 | ? lastTokenOfCallee
|
---|
952 | : firstTokenOfCallee;
|
---|
953 |
|
---|
954 | offsets.setDesiredOffset(dotToken, offsetBase, 1);
|
---|
955 | }
|
---|
956 |
|
---|
957 | const offsetAfterToken = node.callee.type === "TaggedTemplateExpression" ? sourceCode.getFirstToken(node.callee.quasi) : openingParen;
|
---|
958 | const offsetToken = sourceCode.getTokenBefore(offsetAfterToken);
|
---|
959 |
|
---|
960 | offsets.setDesiredOffset(openingParen, offsetToken, 0);
|
---|
961 |
|
---|
962 | addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments);
|
---|
963 | }
|
---|
964 |
|
---|
965 | /**
|
---|
966 | * Checks the indentation of parenthesized values, given a list of tokens in a program
|
---|
967 | * @param {Token[]} tokens A list of tokens
|
---|
968 | * @returns {void}
|
---|
969 | */
|
---|
970 | function addParensIndent(tokens) {
|
---|
971 | const parenStack = [];
|
---|
972 | const parenPairs = [];
|
---|
973 |
|
---|
974 | for (let i = 0; i < tokens.length; i++) {
|
---|
975 | const nextToken = tokens[i];
|
---|
976 |
|
---|
977 | if (astUtils.isOpeningParenToken(nextToken)) {
|
---|
978 | parenStack.push(nextToken);
|
---|
979 | } else if (astUtils.isClosingParenToken(nextToken)) {
|
---|
980 | parenPairs.push({ left: parenStack.pop(), right: nextToken });
|
---|
981 | }
|
---|
982 | }
|
---|
983 |
|
---|
984 | for (let i = parenPairs.length - 1; i >= 0; i--) {
|
---|
985 | const leftParen = parenPairs[i].left;
|
---|
986 | const rightParen = parenPairs[i].right;
|
---|
987 |
|
---|
988 | // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.
|
---|
989 | if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) {
|
---|
990 | const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen));
|
---|
991 |
|
---|
992 | parenthesizedTokens.forEach(token => {
|
---|
993 | if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) {
|
---|
994 | offsets.setDesiredOffset(token, leftParen, 1);
|
---|
995 | }
|
---|
996 | });
|
---|
997 | }
|
---|
998 |
|
---|
999 | offsets.setDesiredOffset(rightParen, leftParen, 0);
|
---|
1000 | }
|
---|
1001 | }
|
---|
1002 |
|
---|
1003 | /**
|
---|
1004 | * Ignore all tokens within an unknown node whose offset do not depend
|
---|
1005 | * on another token's offset within the unknown node
|
---|
1006 | * @param {ASTNode} node Unknown Node
|
---|
1007 | * @returns {void}
|
---|
1008 | */
|
---|
1009 | function ignoreNode(node) {
|
---|
1010 | const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true }));
|
---|
1011 |
|
---|
1012 | unknownNodeTokens.forEach(token => {
|
---|
1013 | if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) {
|
---|
1014 | const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token);
|
---|
1015 |
|
---|
1016 | if (token === firstTokenOfLine) {
|
---|
1017 | offsets.ignoreToken(token);
|
---|
1018 | } else {
|
---|
1019 | offsets.setDesiredOffset(token, firstTokenOfLine, 0);
|
---|
1020 | }
|
---|
1021 | }
|
---|
1022 | });
|
---|
1023 | }
|
---|
1024 |
|
---|
1025 | /**
|
---|
1026 | * Check whether the given token is on the first line of a statement.
|
---|
1027 | * @param {Token} token The token to check.
|
---|
1028 | * @param {ASTNode} leafNode The expression node that the token belongs directly.
|
---|
1029 | * @returns {boolean} `true` if the token is on the first line of a statement.
|
---|
1030 | */
|
---|
1031 | function isOnFirstLineOfStatement(token, leafNode) {
|
---|
1032 | let node = leafNode;
|
---|
1033 |
|
---|
1034 | while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) {
|
---|
1035 | node = node.parent;
|
---|
1036 | }
|
---|
1037 | node = node.parent;
|
---|
1038 |
|
---|
1039 | return !node || node.loc.start.line === token.loc.start.line;
|
---|
1040 | }
|
---|
1041 |
|
---|
1042 | /**
|
---|
1043 | * Check whether there are any blank (whitespace-only) lines between
|
---|
1044 | * two tokens on separate lines.
|
---|
1045 | * @param {Token} firstToken The first token.
|
---|
1046 | * @param {Token} secondToken The second token.
|
---|
1047 | * @returns {boolean} `true` if the tokens are on separate lines and
|
---|
1048 | * there exists a blank line between them, `false` otherwise.
|
---|
1049 | */
|
---|
1050 | function hasBlankLinesBetween(firstToken, secondToken) {
|
---|
1051 | const firstTokenLine = firstToken.loc.end.line;
|
---|
1052 | const secondTokenLine = secondToken.loc.start.line;
|
---|
1053 |
|
---|
1054 | if (firstTokenLine === secondTokenLine || firstTokenLine === secondTokenLine - 1) {
|
---|
1055 | return false;
|
---|
1056 | }
|
---|
1057 |
|
---|
1058 | for (let line = firstTokenLine + 1; line < secondTokenLine; ++line) {
|
---|
1059 | if (!tokenInfo.firstTokensByLineNumber.has(line)) {
|
---|
1060 | return true;
|
---|
1061 | }
|
---|
1062 | }
|
---|
1063 |
|
---|
1064 | return false;
|
---|
1065 | }
|
---|
1066 |
|
---|
1067 | const ignoredNodeFirstTokens = new Set();
|
---|
1068 |
|
---|
1069 | const baseOffsetListeners = {
|
---|
1070 | "ArrayExpression, ArrayPattern"(node) {
|
---|
1071 | const openingBracket = sourceCode.getFirstToken(node);
|
---|
1072 | const closingBracket = sourceCode.getTokenAfter([...node.elements].reverse().find(_ => _) || openingBracket, astUtils.isClosingBracketToken);
|
---|
1073 |
|
---|
1074 | addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression);
|
---|
1075 | },
|
---|
1076 |
|
---|
1077 | "ObjectExpression, ObjectPattern"(node) {
|
---|
1078 | const openingCurly = sourceCode.getFirstToken(node);
|
---|
1079 | const closingCurly = sourceCode.getTokenAfter(
|
---|
1080 | node.properties.length ? node.properties[node.properties.length - 1] : openingCurly,
|
---|
1081 | astUtils.isClosingBraceToken
|
---|
1082 | );
|
---|
1083 |
|
---|
1084 | addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression);
|
---|
1085 | },
|
---|
1086 |
|
---|
1087 | ArrowFunctionExpression(node) {
|
---|
1088 | const maybeOpeningParen = sourceCode.getFirstToken(node, { skip: node.async ? 1 : 0 });
|
---|
1089 |
|
---|
1090 | if (astUtils.isOpeningParenToken(maybeOpeningParen)) {
|
---|
1091 | const openingParen = maybeOpeningParen;
|
---|
1092 | const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken);
|
---|
1093 |
|
---|
1094 | parameterParens.add(openingParen);
|
---|
1095 | parameterParens.add(closingParen);
|
---|
1096 | addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters);
|
---|
1097 | }
|
---|
1098 |
|
---|
1099 | addBlocklessNodeIndent(node.body);
|
---|
1100 | },
|
---|
1101 |
|
---|
1102 | AssignmentExpression(node) {
|
---|
1103 | const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
|
---|
1104 |
|
---|
1105 | offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1);
|
---|
1106 | offsets.ignoreToken(operator);
|
---|
1107 | offsets.ignoreToken(sourceCode.getTokenAfter(operator));
|
---|
1108 | },
|
---|
1109 |
|
---|
1110 | "BinaryExpression, LogicalExpression"(node) {
|
---|
1111 | const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
|
---|
1112 |
|
---|
1113 | /*
|
---|
1114 | * For backwards compatibility, don't check BinaryExpression indents, e.g.
|
---|
1115 | * var foo = bar &&
|
---|
1116 | * baz;
|
---|
1117 | */
|
---|
1118 |
|
---|
1119 | const tokenAfterOperator = sourceCode.getTokenAfter(operator);
|
---|
1120 |
|
---|
1121 | offsets.ignoreToken(operator);
|
---|
1122 | offsets.ignoreToken(tokenAfterOperator);
|
---|
1123 | offsets.setDesiredOffset(tokenAfterOperator, operator, 0);
|
---|
1124 | },
|
---|
1125 |
|
---|
1126 | "BlockStatement, ClassBody"(node) {
|
---|
1127 | let blockIndentLevel;
|
---|
1128 |
|
---|
1129 | if (node.parent && isOuterIIFE(node.parent)) {
|
---|
1130 | blockIndentLevel = options.outerIIFEBody;
|
---|
1131 | } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) {
|
---|
1132 | blockIndentLevel = options.FunctionExpression.body;
|
---|
1133 | } else if (node.parent && node.parent.type === "FunctionDeclaration") {
|
---|
1134 | blockIndentLevel = options.FunctionDeclaration.body;
|
---|
1135 | } else {
|
---|
1136 | blockIndentLevel = 1;
|
---|
1137 | }
|
---|
1138 |
|
---|
1139 | /*
|
---|
1140 | * For blocks that aren't lone statements, ensure that the opening curly brace
|
---|
1141 | * is aligned with the parent.
|
---|
1142 | */
|
---|
1143 | if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
|
---|
1144 | offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0);
|
---|
1145 | }
|
---|
1146 |
|
---|
1147 | addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel);
|
---|
1148 | },
|
---|
1149 |
|
---|
1150 | CallExpression: addFunctionCallIndent,
|
---|
1151 |
|
---|
1152 | "ClassDeclaration[superClass], ClassExpression[superClass]"(node) {
|
---|
1153 | const classToken = sourceCode.getFirstToken(node);
|
---|
1154 | const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken);
|
---|
1155 |
|
---|
1156 | offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1);
|
---|
1157 | },
|
---|
1158 |
|
---|
1159 | ConditionalExpression(node) {
|
---|
1160 | const firstToken = sourceCode.getFirstToken(node);
|
---|
1161 |
|
---|
1162 | // `flatTernaryExpressions` option is for the following style:
|
---|
1163 | // var a =
|
---|
1164 | // foo > 0 ? bar :
|
---|
1165 | // foo < 0 ? baz :
|
---|
1166 | // /*else*/ qiz ;
|
---|
1167 | if (!options.flatTernaryExpressions ||
|
---|
1168 | !astUtils.isTokenOnSameLine(node.test, node.consequent) ||
|
---|
1169 | isOnFirstLineOfStatement(firstToken, node)
|
---|
1170 | ) {
|
---|
1171 | const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?");
|
---|
1172 | const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":");
|
---|
1173 |
|
---|
1174 | const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken);
|
---|
1175 | const lastConsequentToken = sourceCode.getTokenBefore(colonToken);
|
---|
1176 | const firstAlternateToken = sourceCode.getTokenAfter(colonToken);
|
---|
1177 |
|
---|
1178 | offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
|
---|
1179 | offsets.setDesiredOffset(colonToken, firstToken, 1);
|
---|
1180 |
|
---|
1181 | offsets.setDesiredOffset(firstConsequentToken, firstToken, firstConsequentToken.type === "Punctuator" &&
|
---|
1182 | options.offsetTernaryExpressions ? 2 : 1);
|
---|
1183 |
|
---|
1184 | /*
|
---|
1185 | * The alternate and the consequent should usually have the same indentation.
|
---|
1186 | * If they share part of a line, align the alternate against the first token of the consequent.
|
---|
1187 | * This allows the alternate to be indented correctly in cases like this:
|
---|
1188 | * foo ? (
|
---|
1189 | * bar
|
---|
1190 | * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo`
|
---|
1191 | * baz // as a result, `baz` is offset by 1 rather than 2
|
---|
1192 | * )
|
---|
1193 | */
|
---|
1194 | if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) {
|
---|
1195 | offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0);
|
---|
1196 | } else {
|
---|
1197 |
|
---|
1198 | /**
|
---|
1199 | * If the alternate and consequent do not share part of a line, offset the alternate from the first
|
---|
1200 | * token of the conditional expression. For example:
|
---|
1201 | * foo ? bar
|
---|
1202 | * : baz
|
---|
1203 | *
|
---|
1204 | * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
|
---|
1205 | * having no expected indentation.
|
---|
1206 | */
|
---|
1207 | offsets.setDesiredOffset(firstAlternateToken, firstToken, firstAlternateToken.type === "Punctuator" &&
|
---|
1208 | options.offsetTernaryExpressions ? 2 : 1);
|
---|
1209 | }
|
---|
1210 | }
|
---|
1211 | },
|
---|
1212 |
|
---|
1213 | "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement, WithStatement": node => addBlocklessNodeIndent(node.body),
|
---|
1214 |
|
---|
1215 | ExportNamedDeclaration(node) {
|
---|
1216 | if (node.declaration === null) {
|
---|
1217 | const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
|
---|
1218 |
|
---|
1219 | // Indent the specifiers in `export {foo, bar, baz}`
|
---|
1220 | addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, { skip: 1 }), closingCurly, 1);
|
---|
1221 |
|
---|
1222 | if (node.source) {
|
---|
1223 |
|
---|
1224 | // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'`
|
---|
1225 | offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1);
|
---|
1226 | }
|
---|
1227 | }
|
---|
1228 | },
|
---|
1229 |
|
---|
1230 | ForStatement(node) {
|
---|
1231 | const forOpeningParen = sourceCode.getFirstToken(node, 1);
|
---|
1232 |
|
---|
1233 | if (node.init) {
|
---|
1234 | offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1);
|
---|
1235 | }
|
---|
1236 | if (node.test) {
|
---|
1237 | offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1);
|
---|
1238 | }
|
---|
1239 | if (node.update) {
|
---|
1240 | offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1);
|
---|
1241 | }
|
---|
1242 | addBlocklessNodeIndent(node.body);
|
---|
1243 | },
|
---|
1244 |
|
---|
1245 | "FunctionDeclaration, FunctionExpression"(node) {
|
---|
1246 | const closingParen = sourceCode.getTokenBefore(node.body);
|
---|
1247 | const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen);
|
---|
1248 |
|
---|
1249 | parameterParens.add(openingParen);
|
---|
1250 | parameterParens.add(closingParen);
|
---|
1251 | addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters);
|
---|
1252 | },
|
---|
1253 |
|
---|
1254 | IfStatement(node) {
|
---|
1255 | addBlocklessNodeIndent(node.consequent);
|
---|
1256 | if (node.alternate) {
|
---|
1257 | addBlocklessNodeIndent(node.alternate);
|
---|
1258 | }
|
---|
1259 | },
|
---|
1260 |
|
---|
1261 | /*
|
---|
1262 | * For blockless nodes with semicolon-first style, don't indent the semicolon.
|
---|
1263 | * e.g.
|
---|
1264 | * if (foo)
|
---|
1265 | * bar()
|
---|
1266 | * ; [1, 2, 3].map(foo)
|
---|
1267 | *
|
---|
1268 | * Traversal into the node sets indentation of the semicolon, so we need to override it on exit.
|
---|
1269 | */
|
---|
1270 | ":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement, WithStatement):exit"(node) {
|
---|
1271 | let nodesToCheck;
|
---|
1272 |
|
---|
1273 | if (node.type === "IfStatement") {
|
---|
1274 | nodesToCheck = [node.consequent];
|
---|
1275 | if (node.alternate) {
|
---|
1276 | nodesToCheck.push(node.alternate);
|
---|
1277 | }
|
---|
1278 | } else {
|
---|
1279 | nodesToCheck = [node.body];
|
---|
1280 | }
|
---|
1281 |
|
---|
1282 | for (const nodeToCheck of nodesToCheck) {
|
---|
1283 | const lastToken = sourceCode.getLastToken(nodeToCheck);
|
---|
1284 |
|
---|
1285 | if (astUtils.isSemicolonToken(lastToken)) {
|
---|
1286 | const tokenBeforeLast = sourceCode.getTokenBefore(lastToken);
|
---|
1287 | const tokenAfterLast = sourceCode.getTokenAfter(lastToken);
|
---|
1288 |
|
---|
1289 | // override indentation of `;` only if its line looks like a semicolon-first style line
|
---|
1290 | if (
|
---|
1291 | !astUtils.isTokenOnSameLine(tokenBeforeLast, lastToken) &&
|
---|
1292 | tokenAfterLast &&
|
---|
1293 | astUtils.isTokenOnSameLine(lastToken, tokenAfterLast)
|
---|
1294 | ) {
|
---|
1295 | offsets.setDesiredOffset(
|
---|
1296 | lastToken,
|
---|
1297 | sourceCode.getFirstToken(node),
|
---|
1298 | 0
|
---|
1299 | );
|
---|
1300 | }
|
---|
1301 | }
|
---|
1302 | }
|
---|
1303 | },
|
---|
1304 |
|
---|
1305 | ImportDeclaration(node) {
|
---|
1306 | if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
|
---|
1307 | const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);
|
---|
1308 | const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
|
---|
1309 |
|
---|
1310 | addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration);
|
---|
1311 | }
|
---|
1312 |
|
---|
1313 | const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from");
|
---|
1314 | const sourceToken = sourceCode.getLastToken(node, token => token.type === "String");
|
---|
1315 | const semiToken = sourceCode.getLastToken(node, token => token.type === "Punctuator" && token.value === ";");
|
---|
1316 |
|
---|
1317 | if (fromToken) {
|
---|
1318 | const end = semiToken && semiToken.range[1] === sourceToken.range[1] ? node.range[1] : sourceToken.range[1];
|
---|
1319 |
|
---|
1320 | offsets.setDesiredOffsets([fromToken.range[0], end], sourceCode.getFirstToken(node), 1);
|
---|
1321 | }
|
---|
1322 | },
|
---|
1323 |
|
---|
1324 | ImportExpression(node) {
|
---|
1325 | const openingParen = sourceCode.getFirstToken(node, 1);
|
---|
1326 | const closingParen = sourceCode.getLastToken(node);
|
---|
1327 |
|
---|
1328 | parameterParens.add(openingParen);
|
---|
1329 | parameterParens.add(closingParen);
|
---|
1330 | offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0);
|
---|
1331 |
|
---|
1332 | addElementListIndent([node.source], openingParen, closingParen, options.CallExpression.arguments);
|
---|
1333 | },
|
---|
1334 |
|
---|
1335 | "MemberExpression, JSXMemberExpression, MetaProperty"(node) {
|
---|
1336 | const object = node.type === "MetaProperty" ? node.meta : node.object;
|
---|
1337 | const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken);
|
---|
1338 | const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken);
|
---|
1339 |
|
---|
1340 | const objectParenCount = sourceCode.getTokensBetween(object, node.property, { filter: astUtils.isClosingParenToken }).length;
|
---|
1341 | const firstObjectToken = objectParenCount
|
---|
1342 | ? sourceCode.getTokenBefore(object, { skip: objectParenCount - 1 })
|
---|
1343 | : sourceCode.getFirstToken(object);
|
---|
1344 | const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken);
|
---|
1345 | const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken;
|
---|
1346 |
|
---|
1347 | if (node.computed) {
|
---|
1348 |
|
---|
1349 | // For computed MemberExpressions, match the closing bracket with the opening bracket.
|
---|
1350 | offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0);
|
---|
1351 | offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1);
|
---|
1352 | }
|
---|
1353 |
|
---|
1354 | /*
|
---|
1355 | * If the object ends on the same line that the property starts, match against the last token
|
---|
1356 | * of the object, to ensure that the MemberExpression is not indented.
|
---|
1357 | *
|
---|
1358 | * Otherwise, match against the first token of the object, e.g.
|
---|
1359 | * foo
|
---|
1360 | * .bar
|
---|
1361 | * .baz // <-- offset by 1 from `foo`
|
---|
1362 | */
|
---|
1363 | const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line
|
---|
1364 | ? lastObjectToken
|
---|
1365 | : firstObjectToken;
|
---|
1366 |
|
---|
1367 | if (typeof options.MemberExpression === "number") {
|
---|
1368 |
|
---|
1369 | // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object.
|
---|
1370 | offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression);
|
---|
1371 |
|
---|
1372 | /*
|
---|
1373 | * For computed MemberExpressions, match the first token of the property against the opening bracket.
|
---|
1374 | * Otherwise, match the first token of the property against the object.
|
---|
1375 | */
|
---|
1376 | offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression);
|
---|
1377 | } else {
|
---|
1378 |
|
---|
1379 | // If the MemberExpression option is off, ignore the dot and the first token of the property.
|
---|
1380 | offsets.ignoreToken(firstNonObjectToken);
|
---|
1381 | offsets.ignoreToken(secondNonObjectToken);
|
---|
1382 |
|
---|
1383 | // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens.
|
---|
1384 | offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0);
|
---|
1385 | offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0);
|
---|
1386 | }
|
---|
1387 | },
|
---|
1388 |
|
---|
1389 | NewExpression(node) {
|
---|
1390 |
|
---|
1391 | // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo`
|
---|
1392 | if (node.arguments.length > 0 ||
|
---|
1393 | astUtils.isClosingParenToken(sourceCode.getLastToken(node)) &&
|
---|
1394 | astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) {
|
---|
1395 | addFunctionCallIndent(node);
|
---|
1396 | }
|
---|
1397 | },
|
---|
1398 |
|
---|
1399 | Property(node) {
|
---|
1400 | if (!node.shorthand && !node.method && node.kind === "init") {
|
---|
1401 | const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken);
|
---|
1402 |
|
---|
1403 | offsets.ignoreToken(sourceCode.getTokenAfter(colon));
|
---|
1404 | }
|
---|
1405 | },
|
---|
1406 |
|
---|
1407 | PropertyDefinition(node) {
|
---|
1408 | const firstToken = sourceCode.getFirstToken(node);
|
---|
1409 | const maybeSemicolonToken = sourceCode.getLastToken(node);
|
---|
1410 | let keyLastToken = null;
|
---|
1411 |
|
---|
1412 | // Indent key.
|
---|
1413 | if (node.computed) {
|
---|
1414 | const bracketTokenL = sourceCode.getTokenBefore(node.key, astUtils.isOpeningBracketToken);
|
---|
1415 | const bracketTokenR = keyLastToken = sourceCode.getTokenAfter(node.key, astUtils.isClosingBracketToken);
|
---|
1416 | const keyRange = [bracketTokenL.range[1], bracketTokenR.range[0]];
|
---|
1417 |
|
---|
1418 | if (bracketTokenL !== firstToken) {
|
---|
1419 | offsets.setDesiredOffset(bracketTokenL, firstToken, 0);
|
---|
1420 | }
|
---|
1421 | offsets.setDesiredOffsets(keyRange, bracketTokenL, 1);
|
---|
1422 | offsets.setDesiredOffset(bracketTokenR, bracketTokenL, 0);
|
---|
1423 | } else {
|
---|
1424 | const idToken = keyLastToken = sourceCode.getFirstToken(node.key);
|
---|
1425 |
|
---|
1426 | if (idToken !== firstToken) {
|
---|
1427 | offsets.setDesiredOffset(idToken, firstToken, 1);
|
---|
1428 | }
|
---|
1429 | }
|
---|
1430 |
|
---|
1431 | // Indent initializer.
|
---|
1432 | if (node.value) {
|
---|
1433 | const eqToken = sourceCode.getTokenBefore(node.value, astUtils.isEqToken);
|
---|
1434 | const valueToken = sourceCode.getTokenAfter(eqToken);
|
---|
1435 |
|
---|
1436 | offsets.setDesiredOffset(eqToken, keyLastToken, 1);
|
---|
1437 | offsets.setDesiredOffset(valueToken, eqToken, 1);
|
---|
1438 | if (astUtils.isSemicolonToken(maybeSemicolonToken)) {
|
---|
1439 | offsets.setDesiredOffset(maybeSemicolonToken, eqToken, 1);
|
---|
1440 | }
|
---|
1441 | } else if (astUtils.isSemicolonToken(maybeSemicolonToken)) {
|
---|
1442 | offsets.setDesiredOffset(maybeSemicolonToken, keyLastToken, 1);
|
---|
1443 | }
|
---|
1444 | },
|
---|
1445 |
|
---|
1446 | StaticBlock(node) {
|
---|
1447 | const openingCurly = sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token
|
---|
1448 | const closingCurly = sourceCode.getLastToken(node);
|
---|
1449 |
|
---|
1450 | addElementListIndent(node.body, openingCurly, closingCurly, options.StaticBlock.body);
|
---|
1451 | },
|
---|
1452 |
|
---|
1453 | SwitchStatement(node) {
|
---|
1454 | const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken);
|
---|
1455 | const closingCurly = sourceCode.getLastToken(node);
|
---|
1456 |
|
---|
1457 | offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase);
|
---|
1458 |
|
---|
1459 | if (node.cases.length) {
|
---|
1460 | sourceCode.getTokensBetween(
|
---|
1461 | node.cases[node.cases.length - 1],
|
---|
1462 | closingCurly,
|
---|
1463 | { includeComments: true, filter: astUtils.isCommentToken }
|
---|
1464 | ).forEach(token => offsets.ignoreToken(token));
|
---|
1465 | }
|
---|
1466 | },
|
---|
1467 |
|
---|
1468 | SwitchCase(node) {
|
---|
1469 | if (!(node.consequent.length === 1 && node.consequent[0].type === "BlockStatement")) {
|
---|
1470 | const caseKeyword = sourceCode.getFirstToken(node);
|
---|
1471 | const tokenAfterCurrentCase = sourceCode.getTokenAfter(node);
|
---|
1472 |
|
---|
1473 | offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1);
|
---|
1474 | }
|
---|
1475 | },
|
---|
1476 |
|
---|
1477 | TemplateLiteral(node) {
|
---|
1478 | node.expressions.forEach((expression, index) => {
|
---|
1479 | const previousQuasi = node.quasis[index];
|
---|
1480 | const nextQuasi = node.quasis[index + 1];
|
---|
1481 | const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line
|
---|
1482 | ? sourceCode.getFirstToken(previousQuasi)
|
---|
1483 | : null;
|
---|
1484 |
|
---|
1485 | offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1);
|
---|
1486 | offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0);
|
---|
1487 | });
|
---|
1488 | },
|
---|
1489 |
|
---|
1490 | VariableDeclaration(node) {
|
---|
1491 | let variableIndent = Object.prototype.hasOwnProperty.call(options.VariableDeclarator, node.kind)
|
---|
1492 | ? options.VariableDeclarator[node.kind]
|
---|
1493 | : DEFAULT_VARIABLE_INDENT;
|
---|
1494 |
|
---|
1495 | const firstToken = sourceCode.getFirstToken(node),
|
---|
1496 | lastToken = sourceCode.getLastToken(node);
|
---|
1497 |
|
---|
1498 | if (options.VariableDeclarator[node.kind] === "first") {
|
---|
1499 | if (node.declarations.length > 1) {
|
---|
1500 | addElementListIndent(
|
---|
1501 | node.declarations,
|
---|
1502 | firstToken,
|
---|
1503 | lastToken,
|
---|
1504 | "first"
|
---|
1505 | );
|
---|
1506 | return;
|
---|
1507 | }
|
---|
1508 |
|
---|
1509 | variableIndent = DEFAULT_VARIABLE_INDENT;
|
---|
1510 | }
|
---|
1511 |
|
---|
1512 | if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) {
|
---|
1513 |
|
---|
1514 | /*
|
---|
1515 | * VariableDeclarator indentation is a bit different from other forms of indentation, in that the
|
---|
1516 | * indentation of an opening bracket sometimes won't match that of a closing bracket. For example,
|
---|
1517 | * the following indentations are correct:
|
---|
1518 | *
|
---|
1519 | * var foo = {
|
---|
1520 | * ok: true
|
---|
1521 | * };
|
---|
1522 | *
|
---|
1523 | * var foo = {
|
---|
1524 | * ok: true,
|
---|
1525 | * },
|
---|
1526 | * bar = 1;
|
---|
1527 | *
|
---|
1528 | * Account for when exiting the AST (after indentations have already been set for the nodes in
|
---|
1529 | * the declaration) by manually increasing the indentation level of the tokens in this declarator
|
---|
1530 | * on the same line as the start of the declaration, provided that there are declarators that
|
---|
1531 | * follow this one.
|
---|
1532 | */
|
---|
1533 | offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true);
|
---|
1534 | } else {
|
---|
1535 | offsets.setDesiredOffsets(node.range, firstToken, variableIndent);
|
---|
1536 | }
|
---|
1537 |
|
---|
1538 | if (astUtils.isSemicolonToken(lastToken)) {
|
---|
1539 | offsets.ignoreToken(lastToken);
|
---|
1540 | }
|
---|
1541 | },
|
---|
1542 |
|
---|
1543 | VariableDeclarator(node) {
|
---|
1544 | if (node.init) {
|
---|
1545 | const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken);
|
---|
1546 | const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator);
|
---|
1547 |
|
---|
1548 | offsets.ignoreToken(equalOperator);
|
---|
1549 | offsets.ignoreToken(tokenAfterOperator);
|
---|
1550 | offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1);
|
---|
1551 | offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0);
|
---|
1552 | }
|
---|
1553 | },
|
---|
1554 |
|
---|
1555 | "JSXAttribute[value]"(node) {
|
---|
1556 | const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "=");
|
---|
1557 |
|
---|
1558 | offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1);
|
---|
1559 | },
|
---|
1560 |
|
---|
1561 | JSXElement(node) {
|
---|
1562 | if (node.closingElement) {
|
---|
1563 | addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1);
|
---|
1564 | }
|
---|
1565 | },
|
---|
1566 |
|
---|
1567 | JSXOpeningElement(node) {
|
---|
1568 | const firstToken = sourceCode.getFirstToken(node);
|
---|
1569 | let closingToken;
|
---|
1570 |
|
---|
1571 | if (node.selfClosing) {
|
---|
1572 | closingToken = sourceCode.getLastToken(node, { skip: 1 });
|
---|
1573 | offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0);
|
---|
1574 | } else {
|
---|
1575 | closingToken = sourceCode.getLastToken(node);
|
---|
1576 | }
|
---|
1577 | offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node));
|
---|
1578 | addElementListIndent(node.attributes, firstToken, closingToken, 1);
|
---|
1579 | },
|
---|
1580 |
|
---|
1581 | JSXClosingElement(node) {
|
---|
1582 | const firstToken = sourceCode.getFirstToken(node);
|
---|
1583 |
|
---|
1584 | offsets.setDesiredOffsets(node.name.range, firstToken, 1);
|
---|
1585 | },
|
---|
1586 |
|
---|
1587 | JSXFragment(node) {
|
---|
1588 | const firstOpeningToken = sourceCode.getFirstToken(node.openingFragment);
|
---|
1589 | const firstClosingToken = sourceCode.getFirstToken(node.closingFragment);
|
---|
1590 |
|
---|
1591 | addElementListIndent(node.children, firstOpeningToken, firstClosingToken, 1);
|
---|
1592 | },
|
---|
1593 |
|
---|
1594 | JSXOpeningFragment(node) {
|
---|
1595 | const firstToken = sourceCode.getFirstToken(node);
|
---|
1596 | const closingToken = sourceCode.getLastToken(node);
|
---|
1597 |
|
---|
1598 | offsets.setDesiredOffsets(node.range, firstToken, 1);
|
---|
1599 | offsets.matchOffsetOf(firstToken, closingToken);
|
---|
1600 | },
|
---|
1601 |
|
---|
1602 | JSXClosingFragment(node) {
|
---|
1603 | const firstToken = sourceCode.getFirstToken(node);
|
---|
1604 | const slashToken = sourceCode.getLastToken(node, { skip: 1 });
|
---|
1605 | const closingToken = sourceCode.getLastToken(node);
|
---|
1606 | const tokenToMatch = astUtils.isTokenOnSameLine(slashToken, closingToken) ? slashToken : closingToken;
|
---|
1607 |
|
---|
1608 | offsets.setDesiredOffsets(node.range, firstToken, 1);
|
---|
1609 | offsets.matchOffsetOf(firstToken, tokenToMatch);
|
---|
1610 | },
|
---|
1611 |
|
---|
1612 | JSXExpressionContainer(node) {
|
---|
1613 | const openingCurly = sourceCode.getFirstToken(node);
|
---|
1614 | const closingCurly = sourceCode.getLastToken(node);
|
---|
1615 |
|
---|
1616 | offsets.setDesiredOffsets(
|
---|
1617 | [openingCurly.range[1], closingCurly.range[0]],
|
---|
1618 | openingCurly,
|
---|
1619 | 1
|
---|
1620 | );
|
---|
1621 | },
|
---|
1622 |
|
---|
1623 | JSXSpreadAttribute(node) {
|
---|
1624 | const openingCurly = sourceCode.getFirstToken(node);
|
---|
1625 | const closingCurly = sourceCode.getLastToken(node);
|
---|
1626 |
|
---|
1627 | offsets.setDesiredOffsets(
|
---|
1628 | [openingCurly.range[1], closingCurly.range[0]],
|
---|
1629 | openingCurly,
|
---|
1630 | 1
|
---|
1631 | );
|
---|
1632 | },
|
---|
1633 |
|
---|
1634 | "*"(node) {
|
---|
1635 | const firstToken = sourceCode.getFirstToken(node);
|
---|
1636 |
|
---|
1637 | // Ensure that the children of every node are indented at least as much as the first token.
|
---|
1638 | if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) {
|
---|
1639 | offsets.setDesiredOffsets(node.range, firstToken, 0);
|
---|
1640 | }
|
---|
1641 | }
|
---|
1642 | };
|
---|
1643 |
|
---|
1644 | const listenerCallQueue = [];
|
---|
1645 |
|
---|
1646 | /*
|
---|
1647 | * To ignore the indentation of a node:
|
---|
1648 | * 1. Don't call the node's listener when entering it (if it has a listener)
|
---|
1649 | * 2. Don't set any offsets against the first token of the node.
|
---|
1650 | * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets.
|
---|
1651 | */
|
---|
1652 | const offsetListeners = {};
|
---|
1653 |
|
---|
1654 | for (const [selector, listener] of Object.entries(baseOffsetListeners)) {
|
---|
1655 |
|
---|
1656 | /*
|
---|
1657 | * Offset listener calls are deferred until traversal is finished, and are called as
|
---|
1658 | * part of the final `Program:exit` listener. This is necessary because a node might
|
---|
1659 | * be matched by multiple selectors.
|
---|
1660 | *
|
---|
1661 | * Example: Suppose there is an offset listener for `Identifier`, and the user has
|
---|
1662 | * specified in configuration that `MemberExpression > Identifier` should be ignored.
|
---|
1663 | * Due to selector specificity rules, the `Identifier` listener will get called first. However,
|
---|
1664 | * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener
|
---|
1665 | * should not have been called at all. Without doing extra selector matching, we don't know
|
---|
1666 | * whether the Identifier matches the `MemberExpression > Identifier` selector until the
|
---|
1667 | * `MemberExpression > Identifier` listener is called.
|
---|
1668 | *
|
---|
1669 | * To avoid this, the `Identifier` listener isn't called until traversal finishes and all
|
---|
1670 | * ignored nodes are known.
|
---|
1671 | */
|
---|
1672 | offsetListeners[selector] = node => listenerCallQueue.push({ listener, node });
|
---|
1673 | }
|
---|
1674 |
|
---|
1675 | // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set.
|
---|
1676 | const ignoredNodes = new Set();
|
---|
1677 |
|
---|
1678 | /**
|
---|
1679 | * Ignores a node
|
---|
1680 | * @param {ASTNode} node The node to ignore
|
---|
1681 | * @returns {void}
|
---|
1682 | */
|
---|
1683 | function addToIgnoredNodes(node) {
|
---|
1684 | ignoredNodes.add(node);
|
---|
1685 | ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node));
|
---|
1686 | }
|
---|
1687 |
|
---|
1688 | const ignoredNodeListeners = options.ignoredNodes.reduce(
|
---|
1689 | (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }),
|
---|
1690 | {}
|
---|
1691 | );
|
---|
1692 |
|
---|
1693 | /*
|
---|
1694 | * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation
|
---|
1695 | * at the end.
|
---|
1696 | *
|
---|
1697 | * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears
|
---|
1698 | * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored,
|
---|
1699 | * so those listeners wouldn't be called anyway.
|
---|
1700 | */
|
---|
1701 | return Object.assign(
|
---|
1702 | offsetListeners,
|
---|
1703 | ignoredNodeListeners,
|
---|
1704 | {
|
---|
1705 | "*:exit"(node) {
|
---|
1706 |
|
---|
1707 | // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it.
|
---|
1708 | if (!KNOWN_NODES.has(node.type)) {
|
---|
1709 | addToIgnoredNodes(node);
|
---|
1710 | }
|
---|
1711 | },
|
---|
1712 | "Program:exit"() {
|
---|
1713 |
|
---|
1714 | // If ignoreComments option is enabled, ignore all comment tokens.
|
---|
1715 | if (options.ignoreComments) {
|
---|
1716 | sourceCode.getAllComments()
|
---|
1717 | .forEach(comment => offsets.ignoreToken(comment));
|
---|
1718 | }
|
---|
1719 |
|
---|
1720 | // Invoke the queued offset listeners for the nodes that aren't ignored.
|
---|
1721 | for (let i = 0; i < listenerCallQueue.length; i++) {
|
---|
1722 | const nodeInfo = listenerCallQueue[i];
|
---|
1723 |
|
---|
1724 | if (!ignoredNodes.has(nodeInfo.node)) {
|
---|
1725 | nodeInfo.listener(nodeInfo.node);
|
---|
1726 | }
|
---|
1727 | }
|
---|
1728 |
|
---|
1729 | // Update the offsets for ignored nodes to prevent their child tokens from being reported.
|
---|
1730 | ignoredNodes.forEach(ignoreNode);
|
---|
1731 |
|
---|
1732 | addParensIndent(sourceCode.ast.tokens);
|
---|
1733 |
|
---|
1734 | /*
|
---|
1735 | * Create a Map from (tokenOrComment) => (precedingToken).
|
---|
1736 | * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly.
|
---|
1737 | */
|
---|
1738 | const precedingTokens = new WeakMap();
|
---|
1739 |
|
---|
1740 | for (let i = 0; i < sourceCode.ast.comments.length; i++) {
|
---|
1741 | const comment = sourceCode.ast.comments[i];
|
---|
1742 |
|
---|
1743 | const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
|
---|
1744 | const hasToken = precedingTokens.has(tokenOrCommentBefore) ? precedingTokens.get(tokenOrCommentBefore) : tokenOrCommentBefore;
|
---|
1745 |
|
---|
1746 | precedingTokens.set(comment, hasToken);
|
---|
1747 | }
|
---|
1748 |
|
---|
1749 | for (let i = 1; i < sourceCode.lines.length + 1; i++) {
|
---|
1750 |
|
---|
1751 | if (!tokenInfo.firstTokensByLineNumber.has(i)) {
|
---|
1752 |
|
---|
1753 | // Don't check indentation on blank lines
|
---|
1754 | continue;
|
---|
1755 | }
|
---|
1756 |
|
---|
1757 | const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(i);
|
---|
1758 |
|
---|
1759 | if (firstTokenOfLine.loc.start.line !== i) {
|
---|
1760 |
|
---|
1761 | // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice.
|
---|
1762 | continue;
|
---|
1763 | }
|
---|
1764 |
|
---|
1765 | if (astUtils.isCommentToken(firstTokenOfLine)) {
|
---|
1766 | const tokenBefore = precedingTokens.get(firstTokenOfLine);
|
---|
1767 | const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0];
|
---|
1768 | const mayAlignWithBefore = tokenBefore && !hasBlankLinesBetween(tokenBefore, firstTokenOfLine);
|
---|
1769 | const mayAlignWithAfter = tokenAfter && !hasBlankLinesBetween(firstTokenOfLine, tokenAfter);
|
---|
1770 |
|
---|
1771 | /*
|
---|
1772 | * If a comment precedes a line that begins with a semicolon token, align to that token, i.e.
|
---|
1773 | *
|
---|
1774 | * let foo
|
---|
1775 | * // comment
|
---|
1776 | * ;(async () => {})()
|
---|
1777 | */
|
---|
1778 | if (tokenAfter && astUtils.isSemicolonToken(tokenAfter) && !astUtils.isTokenOnSameLine(firstTokenOfLine, tokenAfter)) {
|
---|
1779 | offsets.setDesiredOffset(firstTokenOfLine, tokenAfter, 0);
|
---|
1780 | }
|
---|
1781 |
|
---|
1782 | // If a comment matches the expected indentation of the token immediately before or after, don't report it.
|
---|
1783 | if (
|
---|
1784 | mayAlignWithBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) ||
|
---|
1785 | mayAlignWithAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter))
|
---|
1786 | ) {
|
---|
1787 | continue;
|
---|
1788 | }
|
---|
1789 | }
|
---|
1790 |
|
---|
1791 | // If the token matches the expected indentation, don't report it.
|
---|
1792 | if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) {
|
---|
1793 | continue;
|
---|
1794 | }
|
---|
1795 |
|
---|
1796 | // Otherwise, report the token/comment.
|
---|
1797 | report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine));
|
---|
1798 | }
|
---|
1799 | }
|
---|
1800 | }
|
---|
1801 | );
|
---|
1802 | }
|
---|
1803 | };
|
---|