UNPKG

66.3 kBJavaScriptView Raw
1/**
2 * @fileoverview This option sets a specific tab 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
15const lodash = require("lodash");
16const astUtils = require("../ast-utils");
17const createTree = require("functional-red-black-tree");
18
19//------------------------------------------------------------------------------
20// Rule Definition
21//------------------------------------------------------------------------------
22
23const KNOWN_NODES = new Set([
24 "AssignmentExpression",
25 "AssignmentPattern",
26 "ArrayExpression",
27 "ArrayPattern",
28 "ArrowFunctionExpression",
29 "AwaitExpression",
30 "BlockStatement",
31 "BinaryExpression",
32 "BreakStatement",
33 "CallExpression",
34 "CatchClause",
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 "Program",
63 "Property",
64 "RestElement",
65 "ReturnStatement",
66 "SequenceExpression",
67 "SpreadElement",
68 "Super",
69 "SwitchCase",
70 "SwitchStatement",
71 "TaggedTemplateExpression",
72 "TemplateElement",
73 "TemplateLiteral",
74 "ThisExpression",
75 "ThrowStatement",
76 "TryStatement",
77 "UnaryExpression",
78 "UpdateExpression",
79 "VariableDeclaration",
80 "VariableDeclarator",
81 "WhileStatement",
82 "WithStatement",
83 "YieldExpression",
84 "JSXIdentifier",
85 "JSXNamespacedName",
86 "JSXMemberExpression",
87 "JSXEmptyExpression",
88 "JSXExpressionContainer",
89 "JSXElement",
90 "JSXClosingElement",
91 "JSXOpeningElement",
92 "JSXAttribute",
93 "JSXSpreadAttribute",
94 "JSXText",
95 "ExportDefaultDeclaration",
96 "ExportNamedDeclaration",
97 "ExportAllDeclaration",
98 "ExportSpecifier",
99 "ImportDeclaration",
100 "ImportSpecifier",
101 "ImportDefaultSpecifier",
102 "ImportNamespaceSpecifier"
103]);
104
105/*
106 * General rule strategy:
107 * 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another
108 * specified token or to the first column.
109 * 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a
110 * BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly
111 * brace of the BlockStatement.
112 * 3. After traversing the AST, calculate the expected indentation levels of every token according to the
113 * OffsetStorage container.
114 * 4. For each line, compare the expected indentation of the first token to the actual indentation in the file,
115 * and report the token if the two values are not equal.
116 */
117
118
119/**
120 * A mutable balanced binary search tree that stores (key, value) pairs. The keys are numeric, and must be unique.
121 * This is intended to be a generic wrapper around a balanced binary search tree library, so that the underlying implementation
122 * can easily be swapped out.
123 */
124class BinarySearchTree {
125
126 /**
127 * Creates an empty tree
128 */
129 constructor() {
130 this._rbTree = createTree();
131 }
132
133 /**
134 * Inserts an entry into the tree.
135 * @param {number} key The entry's key
136 * @param {*} value The entry's value
137 * @returns {void}
138 */
139 insert(key, value) {
140 const iterator = this._rbTree.find(key);
141
142 if (iterator.valid) {
143 this._rbTree = iterator.update(value);
144 } else {
145 this._rbTree = this._rbTree.insert(key, value);
146 }
147 }
148
149 /**
150 * Finds the entry with the largest key less than or equal to the provided key
151 * @param {number} key The provided key
152 * @returns {{key: number, value: *}|null} The found entry, or null if no such entry exists.
153 */
154 findLe(key) {
155 const iterator = this._rbTree.le(key);
156
157 return iterator && { key: iterator.key, value: iterator.value };
158 }
159
160 /**
161 * Deletes all of the keys in the interval [start, end)
162 * @param {number} start The start of the range
163 * @param {number} end The end of the range
164 * @returns {void}
165 */
166 deleteRange(start, end) {
167
168 // Exit without traversing the tree if the range has zero size.
169 if (start === end) {
170 return;
171 }
172 const iterator = this._rbTree.ge(start);
173
174 while (iterator.valid && iterator.key < end) {
175 this._rbTree = this._rbTree.remove(iterator.key);
176 iterator.next();
177 }
178 }
179}
180
181/**
182 * A helper class to get token-based info related to indentation
183 */
184class 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 */
233class 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 */
240 constructor(tokenInfo, indentSize, indentType) {
241 this._tokenInfo = tokenInfo;
242 this._indentSize = indentSize;
243 this._indentType = indentType;
244
245 this._tree = new BinarySearchTree();
246 this._tree.insert(0, { offset: 0, from: null, force: false });
247
248 this._lockedFirstTokens = new WeakMap();
249 this._desiredIndentCache = new WeakMap();
250 this._ignoredTokens = new WeakSet();
251 }
252
253 _getOffsetDescriptor(token) {
254 return this._tree.findLe(token.range[0]).value;
255 }
256
257 /**
258 * Sets the offset column of token B to match the offset column of token A.
259 * **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In
260 * most cases, `setDesiredOffset` should be used instead.
261 * @param {Token} baseToken The first token
262 * @param {Token} offsetToken The second token, whose offset should be matched to the first token
263 * @returns {void}
264 */
265 matchOffsetOf(baseToken, offsetToken) {
266
267 /*
268 * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to
269 * the token that it depends on. For example, with the `ArrayExpression: first` option, the first
270 * token of each element in the array after the first will be mapped to the first token of the first
271 * element. The desired indentation of each of these tokens is computed based on the desired indentation
272 * of the "first" element, rather than through the normal offset mechanism.
273 */
274 this._lockedFirstTokens.set(offsetToken, baseToken);
275 }
276
277 /**
278 * Sets the desired offset of a token.
279 *
280 * This uses a line-based offset collapsing behavior to handle tokens on the same line.
281 * For example, consider the following two cases:
282 *
283 * (
284 * [
285 * bar
286 * ]
287 * )
288 *
289 * ([
290 * bar
291 * ])
292 *
293 * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from
294 * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is
295 * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces)
296 * from the start of its line.
297 *
298 * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level
299 * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the
300 * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented
301 * by 1 indent level from the start of the line.
302 *
303 * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node,
304 * without needing to check which lines those tokens are on.
305 *
306 * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive
307 * behavior can occur. For example, consider the following cases:
308 *
309 * foo(
310 * ).
311 * bar(
312 * baz
313 * )
314 *
315 * foo(
316 * ).bar(
317 * baz
318 * )
319 *
320 * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz`
321 * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz`
322 * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no
323 * collapsing would occur).
324 *
325 * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and
326 * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed
327 * in the second case.
328 *
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 *
358 * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied.
359 * @param {Token} fromToken The token that this is offset from
360 * @param {number} offset The desired indent level
361 * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false.
362 * @returns {void}
363 */
364 setDesiredOffsets(range, fromToken, offset, force) {
365
366 /*
367 * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset
368 * descriptor. The tree for the example above would have the following nodes:
369 *
370 * * key: 0, value: { offset: 0, from: null }
371 * * key: 15, value: { offset: 1, from: barToken }
372 * * key: 30, value: { offset: 1, from: fooToken }
373 * * key: 43, value: { offset: 2, from: barToken }
374 * * key: 820, value: { offset: 1, from: bazToken }
375 *
376 * To find the offset descriptor for any given token, one needs to find the node with the largest key
377 * which is <= token.start. To make this operation fast, the nodes are stored in a balanced binary
378 * search tree indexed by key.
379 */
380
381 const descriptorToInsert = { offset, from: fromToken, force };
382
383 const descriptorAfterRange = this._tree.findLe(range[1]).value;
384
385 const fromTokenIsInRange = fromToken && fromToken.range[0] >= range[0] && fromToken.range[1] <= range[1];
386 const fromTokenDescriptor = fromTokenIsInRange && this._getOffsetDescriptor(fromToken);
387
388 // First, remove any existing nodes in the range from the tree.
389 this._tree.deleteRange(range[0] + 1, range[1]);
390
391 // Insert a new node into the tree for this range
392 this._tree.insert(range[0], descriptorToInsert);
393
394 /*
395 * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously,
396 * even if it's in the current range.
397 */
398 if (fromTokenIsInRange) {
399 this._tree.insert(fromToken.range[0], fromTokenDescriptor);
400 this._tree.insert(fromToken.range[1], descriptorToInsert);
401 }
402
403 /*
404 * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following
405 * tokens the same as it was before.
406 */
407 this._tree.insert(range[1], descriptorAfterRange);
408 }
409
410 /**
411 * Gets the desired indent of a token
412 * @param {Token} token The token
413 * @returns {string} The desired indent of the token
414 */
415 getDesiredIndent(token) {
416 if (!this._desiredIndentCache.has(token)) {
417
418 if (this._ignoredTokens.has(token)) {
419
420 /*
421 * If the token is ignored, use the actual indent of the token as the desired indent.
422 * This ensures that no errors are reported for this token.
423 */
424 this._desiredIndentCache.set(
425 token,
426 this._tokenInfo.getTokenIndent(token)
427 );
428 } else if (this._lockedFirstTokens.has(token)) {
429 const firstToken = this._lockedFirstTokens.get(token);
430
431 this._desiredIndentCache.set(
432 token,
433
434 // (indentation for the first element's line)
435 this.getDesiredIndent(this._tokenInfo.getFirstTokenOfLine(firstToken)) +
436
437 // (space between the start of the first element's line and the first element)
438 this._indentType.repeat(firstToken.loc.start.column - this._tokenInfo.getFirstTokenOfLine(firstToken).loc.start.column)
439 );
440 } else {
441 const offsetInfo = this._getOffsetDescriptor(token);
442 const offset = (
443 offsetInfo.from &&
444 offsetInfo.from.loc.start.line === token.loc.start.line &&
445 !/^\s*?\n/.test(token.value) &&
446 !offsetInfo.force
447 ) ? 0 : offsetInfo.offset * this._indentSize;
448
449 this._desiredIndentCache.set(
450 token,
451 (offsetInfo.from ? this.getDesiredIndent(offsetInfo.from) : "") + this._indentType.repeat(offset)
452 );
453 }
454 }
455 return this._desiredIndentCache.get(token);
456 }
457
458 /**
459 * Ignores a token, preventing it from being reported.
460 * @param {Token} token The token
461 * @returns {void}
462 */
463 ignoreToken(token) {
464 if (this._tokenInfo.isFirstTokenOfLine(token)) {
465 this._ignoredTokens.add(token);
466 }
467 }
468
469 /**
470 * Gets the first token that the given token's indentation is dependent on
471 * @param {Token} token The token
472 * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level
473 */
474 getFirstDependency(token) {
475 return this._getOffsetDescriptor(token).from;
476 }
477}
478
479const ELEMENT_LIST_SCHEMA = {
480 oneOf: [
481 {
482 type: "integer",
483 minimum: 0
484 },
485 {
486 enum: ["first", "off"]
487 }
488 ]
489};
490
491module.exports = {
492 meta: {
493 docs: {
494 description: "enforce consistent indentation",
495 category: "Stylistic Issues",
496 recommended: false,
497 url: "https://eslint.org/docs/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 },
521 VariableDeclarator: {
522 oneOf: [
523 {
524 type: "integer",
525 minimum: 0
526 },
527 {
528 type: "object",
529 properties: {
530 var: {
531 type: "integer",
532 minimum: 0
533 },
534 let: {
535 type: "integer",
536 minimum: 0
537 },
538 const: {
539 type: "integer",
540 minimum: 0
541 }
542 },
543 additionalProperties: false
544 }
545 ]
546 },
547 outerIIFEBody: {
548 type: "integer",
549 minimum: 0
550 },
551 MemberExpression: {
552 oneOf: [
553 {
554 type: "integer",
555 minimum: 0
556 },
557 {
558 enum: ["off"]
559 }
560 ]
561 },
562 FunctionDeclaration: {
563 type: "object",
564 properties: {
565 parameters: ELEMENT_LIST_SCHEMA,
566 body: {
567 type: "integer",
568 minimum: 0
569 }
570 },
571 additionalProperties: false
572 },
573 FunctionExpression: {
574 type: "object",
575 properties: {
576 parameters: ELEMENT_LIST_SCHEMA,
577 body: {
578 type: "integer",
579 minimum: 0
580 }
581 },
582 additionalProperties: false
583 },
584 CallExpression: {
585 type: "object",
586 properties: {
587 arguments: ELEMENT_LIST_SCHEMA
588 },
589 additionalProperties: false
590 },
591 ArrayExpression: ELEMENT_LIST_SCHEMA,
592 ObjectExpression: ELEMENT_LIST_SCHEMA,
593 ImportDeclaration: ELEMENT_LIST_SCHEMA,
594 flatTernaryExpressions: {
595 type: "boolean"
596 },
597 ignoredNodes: {
598 type: "array",
599 items: {
600 type: "string",
601 not: {
602 pattern: ":exit$"
603 }
604 }
605 },
606 ignoreComments: {
607 type: "boolean"
608 }
609 },
610 additionalProperties: false
611 }
612 ]
613 },
614
615 create(context) {
616 const DEFAULT_VARIABLE_INDENT = 1;
617 const DEFAULT_PARAMETER_INDENT = 1;
618 const DEFAULT_FUNCTION_BODY_INDENT = 1;
619
620 let indentType = "space";
621 let indentSize = 4;
622 const options = {
623 SwitchCase: 0,
624 VariableDeclarator: {
625 var: DEFAULT_VARIABLE_INDENT,
626 let: DEFAULT_VARIABLE_INDENT,
627 const: DEFAULT_VARIABLE_INDENT
628 },
629 outerIIFEBody: 1,
630 FunctionDeclaration: {
631 parameters: DEFAULT_PARAMETER_INDENT,
632 body: DEFAULT_FUNCTION_BODY_INDENT
633 },
634 FunctionExpression: {
635 parameters: DEFAULT_PARAMETER_INDENT,
636 body: DEFAULT_FUNCTION_BODY_INDENT
637 },
638 CallExpression: {
639 arguments: DEFAULT_PARAMETER_INDENT
640 },
641 MemberExpression: 1,
642 ArrayExpression: 1,
643 ObjectExpression: 1,
644 ImportDeclaration: 1,
645 flatTernaryExpressions: false,
646 ignoredNodes: [],
647 ignoreComments: false
648 };
649
650 if (context.options.length) {
651 if (context.options[0] === "tab") {
652 indentSize = 1;
653 indentType = "tab";
654 } else {
655 indentSize = context.options[0];
656 indentType = "space";
657 }
658
659 if (context.options[1]) {
660 lodash.merge(options, context.options[1]);
661
662 if (typeof options.VariableDeclarator === "number") {
663 options.VariableDeclarator = {
664 var: options.VariableDeclarator,
665 let: options.VariableDeclarator,
666 const: options.VariableDeclarator
667 };
668 }
669 }
670 }
671
672 const sourceCode = context.getSourceCode();
673 const tokenInfo = new TokenInfo(sourceCode);
674 const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t");
675 const parameterParens = new WeakSet();
676
677 /**
678 * Creates an error message for a line, given the expected/actual indentation.
679 * @param {int} expectedAmount The expected amount of indentation characters for this line
680 * @param {int} actualSpaces The actual number of indentation spaces that were found on this line
681 * @param {int} actualTabs The actual number of indentation tabs that were found on this line
682 * @returns {string} An error message for this line
683 */
684 function createErrorMessage(expectedAmount, actualSpaces, actualTabs) {
685 const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs"
686 const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space"
687 const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs"
688 let foundStatement;
689
690 if (actualSpaces > 0) {
691
692 /*
693 * Abbreviate the message if the expected indentation is also spaces.
694 * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
695 */
696 foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`;
697 } else if (actualTabs > 0) {
698 foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`;
699 } else {
700 foundStatement = "0";
701 }
702
703 return `Expected indentation of ${expectedStatement} but found ${foundStatement}.`;
704 }
705
706 /**
707 * Reports a given indent violation
708 * @param {Token} token Token violating the indent rule
709 * @param {string} neededIndent Expected indentation string
710 * @returns {void}
711 */
712 function report(token, neededIndent) {
713 const actualIndent = Array.from(tokenInfo.getTokenIndent(token));
714 const numSpaces = actualIndent.filter(char => char === " ").length;
715 const numTabs = actualIndent.filter(char => char === "\t").length;
716
717 context.report({
718 node: token,
719 message: createErrorMessage(neededIndent.length, numSpaces, numTabs),
720 loc: {
721 start: { line: token.loc.start.line, column: 0 },
722 end: { line: token.loc.start.line, column: token.loc.start.column }
723 },
724 fix(fixer) {
725 const range = [token.range[0] - token.loc.start.column, token.range[0]];
726 const newText = neededIndent;
727
728 return fixer.replaceTextRange(range, newText);
729 }
730 });
731 }
732
733 /**
734 * Checks if a token's indentation is correct
735 * @param {Token} token Token to examine
736 * @param {string} desiredIndent Desired indentation of the string
737 * @returns {boolean} `true` if the token's indentation is correct
738 */
739 function validateTokenIndent(token, desiredIndent) {
740 const indentation = tokenInfo.getTokenIndent(token);
741
742 return indentation === desiredIndent ||
743
744 // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
745 indentation.includes(" ") && indentation.includes("\t");
746 }
747
748 /**
749 * Check to see if the node is a file level IIFE
750 * @param {ASTNode} node The function node to check.
751 * @returns {boolean} True if the node is the outer IIFE
752 */
753 function isOuterIIFE(node) {
754
755 /*
756 * Verify that the node is an IIFE
757 */
758 if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) {
759 return false;
760 }
761
762 /*
763 * Navigate legal ancestors to determine whether this IIFE is outer.
764 * A "legal ancestor" is an expression or statement that causes the function to get executed immediately.
765 * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator.
766 */
767 let statement = node.parent && node.parent.parent;
768
769 while (
770 statement.type === "UnaryExpression" && ["!", "~", "+", "-"].indexOf(statement.operator) > -1 ||
771 statement.type === "AssignmentExpression" ||
772 statement.type === "LogicalExpression" ||
773 statement.type === "SequenceExpression" ||
774 statement.type === "VariableDeclarator"
775 ) {
776 statement = statement.parent;
777 }
778
779 return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program";
780 }
781
782 /**
783 * Check indentation for lists of elements (arrays, objects, function params)
784 * @param {ASTNode[]} elements List of elements that should be offset
785 * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '['
786 * @param {Token} endToken The end token of the list, e.g. ']'
787 * @param {number|string} offset The amount that the elements should be offset
788 * @returns {void}
789 */
790 function addElementListIndent(elements, startToken, endToken, offset) {
791
792 /**
793 * Gets the first token of a given element, including surrounding parentheses.
794 * @param {ASTNode} element A node in the `elements` list
795 * @returns {Token} The first token of this element
796 */
797 function getFirstToken(element) {
798 let token = sourceCode.getTokenBefore(element);
799
800 while (astUtils.isOpeningParenToken(token) && token !== startToken) {
801 token = sourceCode.getTokenBefore(token);
802 }
803 return sourceCode.getTokenAfter(token);
804 }
805
806 // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden)
807 offsets.setDesiredOffsets(
808 [startToken.range[1], endToken.range[0]],
809 startToken,
810 typeof offset === "number" ? offset : 1
811 );
812 offsets.setDesiredOffset(endToken, startToken, 0);
813
814 // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level.
815 if (offset === "first" && elements.length && !elements[0]) {
816 return;
817 }
818 elements.forEach((element, index) => {
819 if (!element) {
820
821 // Skip holes in arrays
822 return;
823 }
824 if (offset === "off") {
825
826 // Ignore the first token of every element if the "off" option is used
827 offsets.ignoreToken(getFirstToken(element));
828 }
829
830 // Offset the following elements correctly relative to the first element
831 if (index === 0) {
832 return;
833 }
834 if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) {
835 offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element));
836 } else {
837 const previousElement = elements[index - 1];
838 const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement);
839
840 if (previousElement && sourceCode.getLastToken(previousElement).loc.end.line > startToken.loc.end.line) {
841 offsets.setDesiredOffsets(element.range, firstTokenOfPreviousElement, 0);
842 }
843 }
844 });
845 }
846
847 /**
848 * Check and decide whether to check for indentation for blockless nodes
849 * Scenarios are for or while statements without braces around them
850 * @param {ASTNode} node node to examine
851 * @returns {void}
852 */
853 function addBlocklessNodeIndent(node) {
854 if (node.type !== "BlockStatement") {
855 const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken);
856
857 let firstBodyToken = sourceCode.getFirstToken(node);
858 let lastBodyToken = sourceCode.getLastToken(node);
859
860 while (
861 astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) &&
862 astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken))
863 ) {
864 firstBodyToken = sourceCode.getTokenBefore(firstBodyToken);
865 lastBodyToken = sourceCode.getTokenAfter(lastBodyToken);
866 }
867
868 offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
869
870 /*
871 * For blockless nodes with semicolon-first style, don't indent the semicolon.
872 * e.g.
873 * if (foo) bar()
874 * ; [1, 2, 3].map(foo)
875 */
876 const lastToken = sourceCode.getLastToken(node);
877
878 if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) {
879 offsets.setDesiredOffset(lastToken, lastParentToken, 0);
880 }
881 }
882 }
883
884 /**
885 * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`)
886 * @param {ASTNode} node A CallExpression or NewExpression node
887 * @returns {void}
888 */
889 function addFunctionCallIndent(node) {
890 let openingParen;
891
892 if (node.arguments.length) {
893 openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken);
894 } else {
895 openingParen = sourceCode.getLastToken(node, 1);
896 }
897 const closingParen = sourceCode.getLastToken(node);
898
899 parameterParens.add(openingParen);
900 parameterParens.add(closingParen);
901 offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0);
902
903 addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments);
904 }
905
906 /**
907 * Checks the indentation of parenthesized values, given a list of tokens in a program
908 * @param {Token[]} tokens A list of tokens
909 * @returns {void}
910 */
911 function addParensIndent(tokens) {
912 const parenStack = [];
913 const parenPairs = [];
914
915 tokens.forEach(nextToken => {
916
917 // Accumulate a list of parenthesis pairs
918 if (astUtils.isOpeningParenToken(nextToken)) {
919 parenStack.push(nextToken);
920 } else if (astUtils.isClosingParenToken(nextToken)) {
921 parenPairs.unshift({ left: parenStack.pop(), right: nextToken });
922 }
923 });
924
925 parenPairs.forEach(pair => {
926 const leftParen = pair.left;
927 const rightParen = pair.right;
928
929 // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.
930 if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) {
931 const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen));
932
933 parenthesizedTokens.forEach(token => {
934 if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) {
935 offsets.setDesiredOffset(token, leftParen, 1);
936 }
937 });
938 }
939
940 offsets.setDesiredOffset(rightParen, leftParen, 0);
941 });
942 }
943
944 /**
945 * Ignore all tokens within an unknown node whose offset do not depend
946 * on another token's offset within the unknown node
947 * @param {ASTNode} node Unknown Node
948 * @returns {void}
949 */
950 function ignoreNode(node) {
951 const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true }));
952
953 unknownNodeTokens.forEach(token => {
954 if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) {
955 const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token);
956
957 if (token === firstTokenOfLine) {
958 offsets.ignoreToken(token);
959 } else {
960 offsets.setDesiredOffset(token, firstTokenOfLine, 0);
961 }
962 }
963 });
964 }
965
966 /**
967 * Check whether the given token is on the first line of a statement.
968 * @param {Token} token The token to check.
969 * @param {ASTNode} leafNode The expression node that the token belongs directly.
970 * @returns {boolean} `true` if the token is on the first line of a statement.
971 */
972 function isOnFirstLineOfStatement(token, leafNode) {
973 let node = leafNode;
974
975 while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) {
976 node = node.parent;
977 }
978 node = node.parent;
979
980 return !node || node.loc.start.line === token.loc.start.line;
981 }
982
983 const baseOffsetListeners = {
984 "ArrayExpression, ArrayPattern"(node) {
985 const openingBracket = sourceCode.getFirstToken(node);
986 const closingBracket = sourceCode.getTokenAfter(lodash.findLast(node.elements) || openingBracket, astUtils.isClosingBracketToken);
987
988 addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression);
989 },
990
991 "ObjectExpression, ObjectPattern"(node) {
992 const openingCurly = sourceCode.getFirstToken(node);
993 const closingCurly = sourceCode.getTokenAfter(
994 node.properties.length ? node.properties[node.properties.length - 1] : openingCurly,
995 astUtils.isClosingBraceToken
996 );
997
998 addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression);
999 },
1000
1001 ArrowFunctionExpression(node) {
1002 const firstToken = sourceCode.getFirstToken(node);
1003
1004 if (astUtils.isOpeningParenToken(firstToken)) {
1005 const openingParen = firstToken;
1006 const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken);
1007
1008 parameterParens.add(openingParen);
1009 parameterParens.add(closingParen);
1010 addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters);
1011 }
1012 addBlocklessNodeIndent(node.body);
1013
1014 let arrowToken;
1015
1016 if (node.params.length) {
1017 arrowToken = sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isArrowToken);
1018 } else {
1019 arrowToken = sourceCode.getFirstToken(node, astUtils.isArrowToken);
1020 }
1021 offsets.setDesiredOffset(arrowToken, sourceCode.getFirstToken(node), 0);
1022 },
1023
1024 AssignmentExpression(node) {
1025 const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
1026
1027 offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1);
1028 offsets.ignoreToken(operator);
1029 offsets.ignoreToken(sourceCode.getTokenAfter(operator));
1030 },
1031
1032 "BinaryExpression, LogicalExpression"(node) {
1033 const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
1034
1035 /*
1036 * For backwards compatibility, don't check BinaryExpression indents, e.g.
1037 * var foo = bar &&
1038 * baz;
1039 */
1040
1041 const tokenAfterOperator = sourceCode.getTokenAfter(operator);
1042
1043 offsets.ignoreToken(operator);
1044 offsets.ignoreToken(tokenAfterOperator);
1045 offsets.setDesiredOffset(tokenAfterOperator, operator, 0);
1046 },
1047
1048 "BlockStatement, ClassBody"(node) {
1049
1050 let blockIndentLevel;
1051
1052 if (node.parent && isOuterIIFE(node.parent)) {
1053 blockIndentLevel = options.outerIIFEBody;
1054 } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) {
1055 blockIndentLevel = options.FunctionExpression.body;
1056 } else if (node.parent && node.parent.type === "FunctionDeclaration") {
1057 blockIndentLevel = options.FunctionDeclaration.body;
1058 } else {
1059 blockIndentLevel = 1;
1060 }
1061
1062 /*
1063 * For blocks that aren't lone statements, ensure that the opening curly brace
1064 * is aligned with the parent.
1065 */
1066 if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
1067 offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0);
1068 }
1069 addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel);
1070 },
1071
1072 CallExpression: addFunctionCallIndent,
1073
1074
1075 "ClassDeclaration[superClass], ClassExpression[superClass]"(node) {
1076 const classToken = sourceCode.getFirstToken(node);
1077 const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken);
1078
1079 offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1);
1080 },
1081
1082 ConditionalExpression(node) {
1083 const firstToken = sourceCode.getFirstToken(node);
1084
1085 // `flatTernaryExpressions` option is for the following style:
1086 // var a =
1087 // foo > 0 ? bar :
1088 // foo < 0 ? baz :
1089 // /*else*/ qiz ;
1090 if (!options.flatTernaryExpressions ||
1091 !astUtils.isTokenOnSameLine(node.test, node.consequent) ||
1092 isOnFirstLineOfStatement(firstToken, node)
1093 ) {
1094 const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?");
1095 const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":");
1096
1097 const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken);
1098 const lastConsequentToken = sourceCode.getTokenBefore(colonToken);
1099 const firstAlternateToken = sourceCode.getTokenAfter(colonToken);
1100
1101 offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
1102 offsets.setDesiredOffset(colonToken, firstToken, 1);
1103
1104 offsets.setDesiredOffset(firstConsequentToken, firstToken, 1);
1105
1106 /*
1107 * The alternate and the consequent should usually have the same indentation.
1108 * If they share part of a line, align the alternate against the first token of the consequent.
1109 * This allows the alternate to be indented correctly in cases like this:
1110 * foo ? (
1111 * bar
1112 * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo`
1113 * baz // as a result, `baz` is offset by 1 rather than 2
1114 * )
1115 */
1116 if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) {
1117 offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0);
1118 } else {
1119
1120 /**
1121 * If the alternate and consequent do not share part of a line, offset the alternate from the first
1122 * token of the conditional expression. For example:
1123 * foo ? bar
1124 * : baz
1125 *
1126 * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
1127 * having no expected indentation.
1128 */
1129 offsets.setDesiredOffset(firstAlternateToken, firstToken, 1);
1130 }
1131
1132 offsets.setDesiredOffsets([questionMarkToken.range[1], colonToken.range[0]], firstConsequentToken, 0);
1133 offsets.setDesiredOffsets([colonToken.range[1], node.range[1]], firstAlternateToken, 0);
1134 }
1135 },
1136
1137 "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement": node => addBlocklessNodeIndent(node.body),
1138
1139 ExportNamedDeclaration(node) {
1140 if (node.declaration === null) {
1141 const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
1142
1143 // Indent the specifiers in `export {foo, bar, baz}`
1144 addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, { skip: 1 }), closingCurly, 1);
1145
1146 if (node.source) {
1147
1148 // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'`
1149 offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1);
1150 }
1151 }
1152 },
1153
1154 ForStatement(node) {
1155 const forOpeningParen = sourceCode.getFirstToken(node, 1);
1156
1157 if (node.init) {
1158 offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1);
1159 }
1160 if (node.test) {
1161 offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1);
1162 }
1163 if (node.update) {
1164 offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1);
1165 }
1166 addBlocklessNodeIndent(node.body);
1167 },
1168
1169 "FunctionDeclaration, FunctionExpression"(node) {
1170 const closingParen = sourceCode.getTokenBefore(node.body);
1171 const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen);
1172
1173 parameterParens.add(openingParen);
1174 parameterParens.add(closingParen);
1175 addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters);
1176 },
1177
1178 IfStatement(node) {
1179 addBlocklessNodeIndent(node.consequent);
1180 if (node.alternate && node.alternate.type !== "IfStatement") {
1181 addBlocklessNodeIndent(node.alternate);
1182 }
1183 },
1184
1185 ImportDeclaration(node) {
1186 if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
1187 const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);
1188 const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
1189
1190 addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration);
1191 }
1192
1193 const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from");
1194
1195 if (fromToken) {
1196 offsets.setDesiredOffsets([fromToken.range[0], node.range[1]], sourceCode.getFirstToken(node), 1);
1197 }
1198 },
1199
1200 "MemberExpression, JSXMemberExpression, MetaProperty"(node) {
1201 const object = node.type === "MetaProperty" ? node.meta : node.object;
1202 const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken);
1203 const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken);
1204
1205 const objectParenCount = sourceCode.getTokensBetween(object, node.property, { filter: astUtils.isClosingParenToken }).length;
1206 const firstObjectToken = objectParenCount
1207 ? sourceCode.getTokenBefore(object, { skip: objectParenCount - 1 })
1208 : sourceCode.getFirstToken(object);
1209 const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken);
1210 const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken;
1211
1212 if (node.computed) {
1213
1214 // For computed MemberExpressions, match the closing bracket with the opening bracket.
1215 offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0);
1216 offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1);
1217 }
1218
1219 /*
1220 * If the object ends on the same line that the property starts, match against the last token
1221 * of the object, to ensure that the MemberExpression is not indented.
1222 *
1223 * Otherwise, match against the first token of the object, e.g.
1224 * foo
1225 * .bar
1226 * .baz // <-- offset by 1 from `foo`
1227 */
1228 const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line
1229 ? lastObjectToken
1230 : firstObjectToken;
1231
1232 if (typeof options.MemberExpression === "number") {
1233
1234 // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object.
1235 offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression);
1236
1237 /*
1238 * For computed MemberExpressions, match the first token of the property against the opening bracket.
1239 * Otherwise, match the first token of the property against the object.
1240 */
1241 offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression);
1242 } else {
1243
1244 // If the MemberExpression option is off, ignore the dot and the first token of the property.
1245 offsets.ignoreToken(firstNonObjectToken);
1246 offsets.ignoreToken(secondNonObjectToken);
1247
1248 // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens.
1249 offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0);
1250 offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0);
1251 }
1252 },
1253
1254 NewExpression(node) {
1255
1256 // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo`
1257 if (node.arguments.length > 0 ||
1258 astUtils.isClosingParenToken(sourceCode.getLastToken(node)) &&
1259 astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) {
1260 addFunctionCallIndent(node);
1261 }
1262 },
1263
1264 Property(node) {
1265 if (!node.shorthand && !node.method && node.kind === "init") {
1266 const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken);
1267
1268 offsets.ignoreToken(sourceCode.getTokenAfter(colon));
1269 }
1270 },
1271
1272 SwitchStatement(node) {
1273 const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken);
1274 const closingCurly = sourceCode.getLastToken(node);
1275 const caseKeywords = node.cases.map(switchCase => sourceCode.getFirstToken(switchCase));
1276
1277 offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase);
1278
1279 node.cases.forEach((switchCase, index) => {
1280 const caseKeyword = caseKeywords[index];
1281
1282 if (!(switchCase.consequent.length === 1 && switchCase.consequent[0].type === "BlockStatement")) {
1283 const tokenAfterCurrentCase = index === node.cases.length - 1 ? closingCurly : caseKeywords[index + 1];
1284
1285 offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1);
1286 }
1287 });
1288
1289 if (node.cases.length) {
1290 sourceCode.getTokensBetween(
1291 node.cases[node.cases.length - 1],
1292 closingCurly,
1293 { includeComments: true, filter: astUtils.isCommentToken }
1294 ).forEach(token => offsets.ignoreToken(token));
1295 }
1296 },
1297
1298 TemplateLiteral(node) {
1299 node.expressions.forEach((expression, index) => {
1300 const previousQuasi = node.quasis[index];
1301 const nextQuasi = node.quasis[index + 1];
1302 const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line ? sourceCode.getFirstToken(previousQuasi) : null;
1303
1304 offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1);
1305 offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0);
1306 });
1307 },
1308
1309 VariableDeclaration(node) {
1310 const variableIndent = options.VariableDeclarator.hasOwnProperty(node.kind) ? options.VariableDeclarator[node.kind] : DEFAULT_VARIABLE_INDENT;
1311
1312 if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) {
1313
1314 /*
1315 * VariableDeclarator indentation is a bit different from other forms of indentation, in that the
1316 * indentation of an opening bracket sometimes won't match that of a closing bracket. For example,
1317 * the following indentations are correct:
1318 *
1319 * var foo = {
1320 * ok: true
1321 * };
1322 *
1323 * var foo = {
1324 * ok: true,
1325 * },
1326 * bar = 1;
1327 *
1328 * Account for when exiting the AST (after indentations have already been set for the nodes in
1329 * the declaration) by manually increasing the indentation level of the tokens in this declarator
1330 * on the same line as the start of the declaration, provided that there are declarators that
1331 * follow this one.
1332 */
1333 const firstToken = sourceCode.getFirstToken(node);
1334
1335 offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true);
1336 } else {
1337 offsets.setDesiredOffsets(node.range, sourceCode.getFirstToken(node), variableIndent);
1338 }
1339 const lastToken = sourceCode.getLastToken(node);
1340
1341 if (astUtils.isSemicolonToken(lastToken)) {
1342 offsets.ignoreToken(lastToken);
1343 }
1344 },
1345
1346 VariableDeclarator(node) {
1347 if (node.init) {
1348 const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken);
1349 const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator);
1350
1351 offsets.ignoreToken(equalOperator);
1352 offsets.ignoreToken(tokenAfterOperator);
1353 offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1);
1354 offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0);
1355 }
1356 },
1357
1358 "JSXAttribute[value]"(node) {
1359 const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "=");
1360
1361 offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1);
1362 },
1363
1364 JSXElement(node) {
1365 if (node.closingElement) {
1366 addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1);
1367 }
1368 },
1369
1370 JSXOpeningElement(node) {
1371 const firstToken = sourceCode.getFirstToken(node);
1372 let closingToken;
1373
1374 if (node.selfClosing) {
1375 closingToken = sourceCode.getLastToken(node, { skip: 1 });
1376 offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0);
1377 } else {
1378 closingToken = sourceCode.getLastToken(node);
1379 }
1380 offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node));
1381 addElementListIndent(node.attributes, firstToken, closingToken, 1);
1382 },
1383
1384 JSXClosingElement(node) {
1385 const firstToken = sourceCode.getFirstToken(node);
1386
1387 offsets.setDesiredOffsets(node.name.range, firstToken, 1);
1388 offsets.setDesiredOffset(sourceCode.getLastToken(node), firstToken, 0);
1389 },
1390
1391 JSXExpressionContainer(node) {
1392 const openingCurly = sourceCode.getFirstToken(node);
1393 const closingCurly = sourceCode.getLastToken(node);
1394
1395 offsets.setDesiredOffsets(
1396 [openingCurly.range[1], closingCurly.range[0]],
1397 openingCurly,
1398 1
1399 );
1400 offsets.setDesiredOffset(closingCurly, openingCurly, 0);
1401 }
1402 };
1403
1404 const listenerCallQueue = [];
1405
1406 /*
1407 * To ignore the indentation of a node:
1408 * 1. Don't call the node's listener when entering it (if it has a listener)
1409 * 2. Call `ignoreNode` on the node sometime after exiting it and before validating offsets.
1410 */
1411 const offsetListeners = lodash.mapValues(
1412 baseOffsetListeners,
1413
1414 /*
1415 * Offset listener calls are deferred until traversal is finished, and are called as
1416 * part of the final `Program:exit` listener. This is necessary because a node might
1417 * be matched by multiple selectors.
1418 *
1419 * Example: Suppose there is an offset listener for `Identifier`, and the user has
1420 * specified in configuration that `MemberExpression > Identifier` should be ignored.
1421 * Due to selector specificity rules, the `Identifier` listener will get called first. However,
1422 * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener
1423 * should not have been called at all. Without doing extra selector matching, we don't know
1424 * whether the Identifier matches the `MemberExpression > Identifier` selector until the
1425 * `MemberExpression > Identifier` listener is called.
1426 *
1427 * To avoid this, the `Identifier` listener isn't called until traversal finishes and all
1428 * ignored nodes are known.
1429 */
1430 listener =>
1431 node =>
1432 listenerCallQueue.push({ listener, node })
1433 );
1434
1435 // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set.
1436 const ignoredNodes = new Set();
1437 const addToIgnoredNodes = ignoredNodes.add.bind(ignoredNodes);
1438
1439 const ignoredNodeListeners = options.ignoredNodes.reduce(
1440 (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }),
1441 {}
1442 );
1443
1444 /*
1445 * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation
1446 * at the end.
1447 *
1448 * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears
1449 * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored,
1450 * so those listeners wouldn't be called anyway.
1451 */
1452 return Object.assign(
1453 offsetListeners,
1454 ignoredNodeListeners,
1455 {
1456 "*:exit"(node) {
1457
1458 // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it.
1459 if (!KNOWN_NODES.has(node.type)) {
1460 ignoredNodes.add(node);
1461 }
1462 },
1463 "Program:exit"() {
1464
1465 // If ignoreComments option is enabled, ignore all comment tokens.
1466 if (options.ignoreComments) {
1467 sourceCode.getAllComments()
1468 .forEach(comment => offsets.ignoreToken(comment));
1469 }
1470
1471 // Invoke the queued offset listeners for the nodes that aren't ignored.
1472 listenerCallQueue
1473 .filter(nodeInfo => !ignoredNodes.has(nodeInfo.node))
1474 .forEach(nodeInfo => nodeInfo.listener(nodeInfo.node));
1475
1476 // Update the offsets for ignored nodes to prevent their child tokens from being reported.
1477 ignoredNodes.forEach(ignoreNode);
1478
1479 addParensIndent(sourceCode.ast.tokens);
1480
1481 /*
1482 * Create a Map from (tokenOrComment) => (precedingToken).
1483 * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly.
1484 */
1485 const precedingTokens = sourceCode.ast.comments.reduce((commentMap, comment) => {
1486 const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
1487
1488 return commentMap.set(comment, commentMap.has(tokenOrCommentBefore) ? commentMap.get(tokenOrCommentBefore) : tokenOrCommentBefore);
1489 }, new WeakMap());
1490
1491 sourceCode.lines.forEach((line, lineIndex) => {
1492 const lineNumber = lineIndex + 1;
1493
1494 if (!tokenInfo.firstTokensByLineNumber.has(lineNumber)) {
1495
1496 // Don't check indentation on blank lines
1497 return;
1498 }
1499
1500 const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(lineNumber);
1501
1502 if (firstTokenOfLine.loc.start.line !== lineNumber) {
1503
1504 // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice.
1505 return;
1506 }
1507
1508 // If the token matches the expected expected indentation, don't report it.
1509 if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) {
1510 return;
1511 }
1512
1513 if (astUtils.isCommentToken(firstTokenOfLine)) {
1514 const tokenBefore = precedingTokens.get(firstTokenOfLine);
1515 const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0];
1516
1517 // If a comment matches the expected indentation of the token immediately before or after, don't report it.
1518 if (
1519 tokenBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) ||
1520 tokenAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter))
1521 ) {
1522 return;
1523 }
1524 }
1525
1526 // Otherwise, report the token/comment.
1527 report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine));
1528 });
1529 }
1530 }
1531 );
1532 }
1533};