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