2 * @fileoverview This rule sets a specific indentation style and width for your code
5 * @author Vitaly Puzrin
6 * @author Gyandeep Singh
11 //------------------------------------------------------------------------------
13 //------------------------------------------------------------------------------
15 const astUtils
= require("./utils/ast-utils");
17 //------------------------------------------------------------------------------
19 //------------------------------------------------------------------------------
21 const KNOWN_NODES
= new Set([
22 "AssignmentExpression",
26 "ArrowFunctionExpression",
37 "ConditionalExpression",
42 "ExperimentalRestProperty",
43 "ExperimentalSpreadProperty",
44 "ExpressionStatement",
48 "FunctionDeclaration",
73 "TaggedTemplateExpression",
81 "VariableDeclaration",
91 "JSXMemberExpression",
93 "JSXExpressionContainer",
100 "ExportDefaultDeclaration",
101 "ExportNamedDeclaration",
102 "ExportAllDeclaration",
106 "ImportDefaultSpecifier",
107 "ImportNamespaceSpecifier",
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.
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.
133 * Creates an empty map
134 * @param {number} maxKey The maximum key
136 constructor(maxKey
) {
138 // Initializing the array with the maximum expected size avoids dynamic reallocations that could degrade performance.
139 this._values
= Array(maxKey
+ 1);
143 * Inserts an entry into the map.
144 * @param {number} key The entry's key
145 * @param {any} value The entry's value
149 this._values
[key
] = value
;
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.
157 findLastNotAfter(key
) {
158 const values
= this._values
;
160 for (let index
= key
; index
>= 0; index
--) {
161 const value
= values
[index
];
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
176 deleteRange(start
, end
) {
177 this._values
.fill(void 0, start
, end
);
182 * A helper class to get token-based info related to indentation
187 * @param {SourceCode} sourceCode A SourceCode object
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
);
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
);
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
207 getFirstTokenOfLine(token
) {
208 return this.firstTokensByLineNumber
.get(token
.loc
.start
.line
);
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
216 isFirstTokenOfLine(token
) {
217 return this.getFirstTokenOfLine(token
) === token
;
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
225 getTokenIndent(token
) {
226 return this.sourceCode
.text
.slice(token
.range
[0] - token
.loc
.start
.column
, token
.range
[0]);
231 * A class to store information on desired offsets of tokens from each other
233 class OffsetStorage
{
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
241 constructor(tokenInfo
, indentSize
, indentType
, maxIndex
) {
242 this._tokenInfo
= tokenInfo
;
243 this._indentSize
= indentSize
;
244 this._indentType
= indentType
;
246 this._indexMap
= new IndexMap(maxIndex
);
247 this._indexMap
.insert(0, { offset
: 0, from: null, force
: false });
249 this._lockedFirstTokens
= new WeakMap();
250 this._desiredIndentCache
= new WeakMap();
251 this._ignoredTokens
= new WeakSet();
254 _getOffsetDescriptor(token
) {
255 return this._indexMap
.findLastNotAfter(token
.range
[0]);
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
266 matchOffsetOf(baseToken
, offsetToken
) {
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.
275 this._lockedFirstTokens
.set(offsetToken
, baseToken
);
279 * Sets the desired offset of a token.
281 * This uses a line-based offset collapsing behavior to handle tokens on the same line.
282 * For example, consider the following two cases:
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.
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.
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.
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:
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).
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
334 setDesiredOffset(token
, fromToken
, offset
) {
335 return this.setDesiredOffsets(token
.range
, fromToken
, offset
);
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.
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:
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
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.
363 setDesiredOffsets(range
, fromToken
, offset
, force
) {
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:
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 }
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.
379 const descriptorToInsert
= { offset
, from: fromToken
, force
};
381 const descriptorAfterRange
= this._indexMap
.findLastNotAfter(range
[1]);
383 const fromTokenIsInRange
= fromToken
&& fromToken
.range
[0] >= range
[0] && fromToken
.range
[1] <= range
[1];
384 const fromTokenDescriptor
= fromTokenIsInRange
&& this._getOffsetDescriptor(fromToken
);
386 // First, remove any existing nodes in the range from the map.
387 this._indexMap
.deleteRange(range
[0] + 1, range
[1]);
389 // Insert a new node into the map for this range
390 this._indexMap
.insert(range
[0], descriptorToInsert
);
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.
396 if (fromTokenIsInRange
) {
397 this._indexMap
.insert(fromToken
.range
[0], fromTokenDescriptor
);
398 this._indexMap
.insert(fromToken
.range
[1], descriptorToInsert
);
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.
405 this._indexMap
.insert(range
[1], descriptorAfterRange
);
409 * Gets the desired indent of a token
410 * @param {Token} token The token
411 * @returns {string} The desired indent of the token
413 getDesiredIndent(token
) {
414 if (!this._desiredIndentCache
.has(token
)) {
416 if (this._ignoredTokens
.has(token
)) {
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.
422 this._desiredIndentCache
.set(
424 this._tokenInfo
.getTokenIndent(token
)
426 } else if (this._lockedFirstTokens
.has(token
)) {
427 const firstToken
= this._lockedFirstTokens
.get(token
);
429 this._desiredIndentCache
.set(
432 // (indentation for the first element's line)
433 this.getDesiredIndent(this._tokenInfo
.getFirstTokenOfLine(firstToken
)) +
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
)
439 const offsetInfo
= this._getOffsetDescriptor(token
);
442 offsetInfo
.from.loc
.start
.line
=== token
.loc
.start
.line
&&
443 !/^\s*?\n/u.test(token
.value
) &&
445 ) ? 0 : offsetInfo
.offset
* this._indentSize
;
447 this._desiredIndentCache
.set(
449 (offsetInfo
.from ? this.getDesiredIndent(offsetInfo
.from) : "") + this._indentType
.repeat(offset
)
453 return this._desiredIndentCache
.get(token
);
457 * Ignores a token, preventing it from being reported.
458 * @param {Token} token The token
462 if (this._tokenInfo
.isFirstTokenOfLine(token
)) {
463 this._ignoredTokens
.add(token
);
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
472 getFirstDependency(token
) {
473 return this._getOffsetDescriptor(token
).from;
477 const ELEMENT_LIST_SCHEMA
= {
484 enum: ["first", "off"]
489 /** @type {import('../shared/types').Rule} */
495 description
: "Enforce consistent indentation",
497 url
: "https://eslint.org/docs/latest/rules/indent"
500 fixable
: "whitespace",
522 VariableDeclarator
: {
528 var: ELEMENT_LIST_SCHEMA
,
529 let: ELEMENT_LIST_SCHEMA
,
530 const: ELEMENT_LIST_SCHEMA
532 additionalProperties
: false
558 FunctionDeclaration
: {
561 parameters
: ELEMENT_LIST_SCHEMA
,
567 additionalProperties
: false
569 FunctionExpression
: {
572 parameters
: ELEMENT_LIST_SCHEMA
,
578 additionalProperties
: false
588 additionalProperties
: false
593 arguments
: ELEMENT_LIST_SCHEMA
595 additionalProperties
: false
597 ArrayExpression
: ELEMENT_LIST_SCHEMA
,
598 ObjectExpression
: ELEMENT_LIST_SCHEMA
,
599 ImportDeclaration
: ELEMENT_LIST_SCHEMA
,
600 flatTernaryExpressions
: {
604 offsetTernaryExpressions
: {
622 additionalProperties
: false
626 wrongIndentation
: "Expected indentation of {{expected}} but found {{actual}}."
631 const DEFAULT_VARIABLE_INDENT
= 1;
632 const DEFAULT_PARAMETER_INDENT
= 1;
633 const DEFAULT_FUNCTION_BODY_INDENT
= 1;
635 let indentType
= "space";
639 VariableDeclarator
: {
640 var: DEFAULT_VARIABLE_INDENT
,
641 let: DEFAULT_VARIABLE_INDENT
,
642 const: DEFAULT_VARIABLE_INDENT
645 FunctionDeclaration
: {
646 parameters
: DEFAULT_PARAMETER_INDENT
,
647 body
: DEFAULT_FUNCTION_BODY_INDENT
649 FunctionExpression
: {
650 parameters
: DEFAULT_PARAMETER_INDENT
,
651 body
: DEFAULT_FUNCTION_BODY_INDENT
654 body
: DEFAULT_FUNCTION_BODY_INDENT
657 arguments
: DEFAULT_PARAMETER_INDENT
662 ImportDeclaration
: 1,
663 flatTernaryExpressions
: false,
665 ignoreComments
: false
668 if (context
.options
.length
) {
669 if (context
.options
[0] === "tab") {
673 indentSize
= context
.options
[0];
674 indentType
= "space";
677 if (context
.options
[1]) {
678 Object
.assign(options
, context
.options
[1]);
680 if (typeof options
.VariableDeclarator
=== "number" || options
.VariableDeclarator
=== "first") {
681 options
.VariableDeclarator
= {
682 var: options
.VariableDeclarator
,
683 let: options
.VariableDeclarator
,
684 const: options
.VariableDeclarator
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();
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
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"
708 if (actualSpaces
> 0) {
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'
714 foundStatement
= indentType
=== "space" ? actualSpaces
: `${actualSpaces} ${foundSpacesWord}`;
715 } else if (actualTabs
> 0) {
716 foundStatement
= indentType
=== "tab" ? actualTabs
: `${actualTabs} ${foundTabsWord}`;
718 foundStatement
= "0";
721 expected
: expectedStatement
,
722 actual
: foundStatement
727 * Reports a given indent violation
728 * @param {Token} token Token violating the indent rule
729 * @param {string} neededIndent Expected indentation string
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
;
739 messageId
: "wrongIndentation",
740 data
: createErrorMessageData(neededIndent
.length
, numSpaces
, numTabs
),
742 start
: { line
: token
.loc
.start
.line
, column
: 0 },
743 end
: { line
: token
.loc
.start
.line
, column
: token
.loc
.start
.column
}
746 const range
= [token
.range
[0] - token
.loc
.start
.column
, token
.range
[0]];
747 const newText
= neededIndent
;
749 return fixer
.replaceTextRange(range
, newText
);
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
760 function validateTokenIndent(token
, desiredIndent
) {
761 const indentation
= tokenInfo
.getTokenIndent(token
);
763 return indentation
=== desiredIndent
||
765 // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
766 indentation
.includes(" ") && indentation
.includes("\t");
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
774 function isOuterIIFE(node
) {
777 * Verify that the node is an IIFE
779 if (!node
.parent
|| node
.parent
.type
!== "CallExpression" || node
.parent
.callee
!== node
) {
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.
788 let statement
= node
.parent
&& node
.parent
.parent
;
791 statement
.type
=== "UnaryExpression" && ["!", "~", "+", "-"].includes(statement
.operator
) ||
792 statement
.type
=== "AssignmentExpression" ||
793 statement
.type
=== "LogicalExpression" ||
794 statement
.type
=== "SequenceExpression" ||
795 statement
.type
=== "VariableDeclarator"
797 statement
= statement
.parent
;
800 return (statement
.type
=== "ExpressionStatement" || statement
.type
=== "VariableDeclaration") && statement
.parent
.type
=== "Program";
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.
809 function countTrailingLinebreaks(string
) {
810 const trailingWhitespace
= string
.match(/\s*$/u)[0];
811 const linebreakMatches
= trailingWhitespace
.match(astUtils
.createGlobalLinebreakMatcher());
813 return linebreakMatches
=== null ? 0 : linebreakMatches
.length
;
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
824 function addElementListIndent(elements
, startToken
, endToken
, offset
) {
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
831 function getFirstToken(element
) {
832 let token
= sourceCode
.getTokenBefore(element
);
834 while (astUtils
.isOpeningParenToken(token
) && token
!== startToken
) {
835 token
= sourceCode
.getTokenBefore(token
);
837 return sourceCode
.getTokenAfter(token
);
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]],
844 typeof offset
=== "number" ? offset
: 1
846 offsets
.setDesiredOffset(endToken
, startToken
, 0);
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]) {
852 elements
.forEach((element
, index
) => {
855 // Skip holes in arrays
858 if (offset
=== "off") {
860 // Ignore the first token of every element if the "off" option is used
861 offsets
.ignoreToken(getFirstToken(element
));
864 // Offset the following elements correctly relative to the first element
868 if (offset
=== "first" && tokenInfo
.isFirstTokenOfLine(getFirstToken(element
))) {
869 offsets
.matchOffsetOf(getFirstToken(elements
[0]), getFirstToken(element
));
871 const previousElement
= elements
[index
- 1];
872 const firstTokenOfPreviousElement
= previousElement
&& getFirstToken(previousElement
);
873 const previousElementLastToken
= previousElement
&& sourceCode
.getLastToken(previousElement
);
877 previousElementLastToken
.loc
.end
.line
- countTrailingLinebreaks(previousElementLastToken
.value
) > startToken
.loc
.end
.line
879 offsets
.setDesiredOffsets(
880 [previousElement
.range
[1], element
.range
[1]],
881 firstTokenOfPreviousElement
,
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
895 function addBlocklessNodeIndent(node
) {
896 if (node
.type
!== "BlockStatement") {
897 const lastParentToken
= sourceCode
.getTokenBefore(node
, astUtils
.isNotOpeningParenToken
);
899 let firstBodyToken
= sourceCode
.getFirstToken(node
);
900 let lastBodyToken
= sourceCode
.getLastToken(node
);
903 astUtils
.isOpeningParenToken(sourceCode
.getTokenBefore(firstBodyToken
)) &&
904 astUtils
.isClosingParenToken(sourceCode
.getTokenAfter(lastBodyToken
))
906 firstBodyToken
= sourceCode
.getTokenBefore(firstBodyToken
);
907 lastBodyToken
= sourceCode
.getTokenAfter(lastBodyToken
);
910 offsets
.setDesiredOffsets([firstBodyToken
.range
[0], lastBodyToken
.range
[1]], lastParentToken
, 1);
915 * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`)
916 * @param {ASTNode} node A CallExpression or NewExpression node
919 function addFunctionCallIndent(node
) {
922 if (node
.arguments
.length
) {
923 openingParen
= sourceCode
.getFirstTokenBetween(node
.callee
, node
.arguments
[0], astUtils
.isOpeningParenToken
);
925 openingParen
= sourceCode
.getLastToken(node
, 1);
927 const closingParen
= sourceCode
.getLastToken(node
);
929 parameterParens
.add(openingParen
);
930 parameterParens
.add(closingParen
);
933 * If `?.` token exists, set desired offset for that.
934 * This logic is copied from `MemberExpression`'s.
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
945 : firstTokenOfCallee
;
947 offsets
.setDesiredOffset(dotToken
, offsetBase
, 1);
950 const offsetAfterToken
= node
.callee
.type
=== "TaggedTemplateExpression" ? sourceCode
.getFirstToken(node
.callee
.quasi
) : openingParen
;
951 const offsetToken
= sourceCode
.getTokenBefore(offsetAfterToken
);
953 offsets
.setDesiredOffset(openingParen
, offsetToken
, 0);
955 addElementListIndent(node
.arguments
, openingParen
, closingParen
, options
.CallExpression
.arguments
);
959 * Checks the indentation of parenthesized values, given a list of tokens in a program
960 * @param {Token[]} tokens A list of tokens
963 function addParensIndent(tokens
) {
964 const parenStack
= [];
965 const parenPairs
= [];
967 tokens
.forEach(nextToken
=> {
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
});
977 parenPairs
.forEach(pair
=> {
978 const leftParen
= pair
.left
;
979 const rightParen
= pair
.right
;
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
));
985 parenthesizedTokens
.forEach(token
=> {
986 if (!parenthesizedTokens
.has(offsets
.getFirstDependency(token
))) {
987 offsets
.setDesiredOffset(token
, leftParen
, 1);
992 offsets
.setDesiredOffset(rightParen
, leftParen
, 0);
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
1002 function ignoreNode(node
) {
1003 const unknownNodeTokens
= new Set(sourceCode
.getTokens(node
, { includeComments
: true }));
1005 unknownNodeTokens
.forEach(token
=> {
1006 if (!unknownNodeTokens
.has(offsets
.getFirstDependency(token
))) {
1007 const firstTokenOfLine
= tokenInfo
.getFirstTokenOfLine(token
);
1009 if (token
=== firstTokenOfLine
) {
1010 offsets
.ignoreToken(token
);
1012 offsets
.setDesiredOffset(token
, firstTokenOfLine
, 0);
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.
1024 function isOnFirstLineOfStatement(token
, leafNode
) {
1025 let node
= leafNode
;
1027 while (node
.parent
&& !node
.parent
.type
.endsWith("Statement") && !node
.parent
.type
.endsWith("Declaration")) {
1032 return !node
|| node
.loc
.start
.line
=== token
.loc
.start
.line
;
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.
1043 function hasBlankLinesBetween(firstToken
, secondToken
) {
1044 const firstTokenLine
= firstToken
.loc
.end
.line
;
1045 const secondTokenLine
= secondToken
.loc
.start
.line
;
1047 if (firstTokenLine
=== secondTokenLine
|| firstTokenLine
=== secondTokenLine
- 1) {
1051 for (let line
= firstTokenLine
+ 1; line
< secondTokenLine
; ++line
) {
1052 if (!tokenInfo
.firstTokensByLineNumber
.has(line
)) {
1060 const ignoredNodeFirstTokens
= new Set();
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
);
1067 addElementListIndent(node
.elements
, openingBracket
, closingBracket
, options
.ArrayExpression
);
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
1077 addElementListIndent(node
.properties
, openingCurly
, closingCurly
, options
.ObjectExpression
);
1080 ArrowFunctionExpression(node
) {
1081 const maybeOpeningParen
= sourceCode
.getFirstToken(node
, { skip
: node
.async
? 1 : 0 });
1083 if (astUtils
.isOpeningParenToken(maybeOpeningParen
)) {
1084 const openingParen
= maybeOpeningParen
;
1085 const closingParen
= sourceCode
.getTokenBefore(node
.body
, astUtils
.isClosingParenToken
);
1087 parameterParens
.add(openingParen
);
1088 parameterParens
.add(closingParen
);
1089 addElementListIndent(node
.params
, openingParen
, closingParen
, options
.FunctionExpression
.parameters
);
1092 addBlocklessNodeIndent(node
.body
);
1095 AssignmentExpression(node
) {
1096 const operator
= sourceCode
.getFirstTokenBetween(node
.left
, node
.right
, token
=> token
.value
=== node
.operator
);
1098 offsets
.setDesiredOffsets([operator
.range
[0], node
.range
[1]], sourceCode
.getLastToken(node
.left
), 1);
1099 offsets
.ignoreToken(operator
);
1100 offsets
.ignoreToken(sourceCode
.getTokenAfter(operator
));
1103 "BinaryExpression, LogicalExpression"(node
) {
1104 const operator
= sourceCode
.getFirstTokenBetween(node
.left
, node
.right
, token
=> token
.value
=== node
.operator
);
1107 * For backwards compatibility, don't check BinaryExpression indents, e.g.
1112 const tokenAfterOperator
= sourceCode
.getTokenAfter(operator
);
1114 offsets
.ignoreToken(operator
);
1115 offsets
.ignoreToken(tokenAfterOperator
);
1116 offsets
.setDesiredOffset(tokenAfterOperator
, operator
, 0);
1119 "BlockStatement, ClassBody"(node
) {
1120 let blockIndentLevel
;
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
;
1129 blockIndentLevel
= 1;
1133 * For blocks that aren't lone statements, ensure that the opening curly brace
1134 * is aligned with the parent.
1136 if (!astUtils
.STATEMENT_LIST_PARENTS
.has(node
.parent
.type
)) {
1137 offsets
.setDesiredOffset(sourceCode
.getFirstToken(node
), sourceCode
.getFirstToken(node
.parent
), 0);
1140 addElementListIndent(node
.body
, sourceCode
.getFirstToken(node
), sourceCode
.getLastToken(node
), blockIndentLevel
);
1143 CallExpression
: addFunctionCallIndent
,
1145 "ClassDeclaration[superClass], ClassExpression[superClass]"(node
) {
1146 const classToken
= sourceCode
.getFirstToken(node
);
1147 const extendsToken
= sourceCode
.getTokenBefore(node
.superClass
, astUtils
.isNotOpeningParenToken
);
1149 offsets
.setDesiredOffsets([extendsToken
.range
[0], node
.body
.range
[0]], classToken
, 1);
1152 ConditionalExpression(node
) {
1153 const firstToken
= sourceCode
.getFirstToken(node
);
1155 // `flatTernaryExpressions` option is for the following style:
1160 if (!options
.flatTernaryExpressions
||
1161 !astUtils
.isTokenOnSameLine(node
.test
, node
.consequent
) ||
1162 isOnFirstLineOfStatement(firstToken
, node
)
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
=== ":");
1167 const firstConsequentToken
= sourceCode
.getTokenAfter(questionMarkToken
);
1168 const lastConsequentToken
= sourceCode
.getTokenBefore(colonToken
);
1169 const firstAlternateToken
= sourceCode
.getTokenAfter(colonToken
);
1171 offsets
.setDesiredOffset(questionMarkToken
, firstToken
, 1);
1172 offsets
.setDesiredOffset(colonToken
, firstToken
, 1);
1174 offsets
.setDesiredOffset(firstConsequentToken
, firstToken
, firstConsequentToken
.type
=== "Punctuator" &&
1175 options
.offsetTernaryExpressions
? 2 : 1);
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:
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
1187 if (lastConsequentToken
.loc
.end
.line
=== firstAlternateToken
.loc
.start
.line
) {
1188 offsets
.setDesiredOffset(firstAlternateToken
, firstConsequentToken
, 0);
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:
1197 * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
1198 * having no expected indentation.
1200 offsets
.setDesiredOffset(firstAlternateToken
, firstToken
, firstAlternateToken
.type
=== "Punctuator" &&
1201 options
.offsetTernaryExpressions
? 2 : 1);
1206 "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement, WithStatement": node
=> addBlocklessNodeIndent(node
.body
),
1208 ExportNamedDeclaration(node
) {
1209 if (node
.declaration
=== null) {
1210 const closingCurly
= sourceCode
.getLastToken(node
, astUtils
.isClosingBraceToken
);
1212 // Indent the specifiers in `export {foo, bar, baz}`
1213 addElementListIndent(node
.specifiers
, sourceCode
.getFirstToken(node
, { skip
: 1 }), closingCurly
, 1);
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);
1223 ForStatement(node
) {
1224 const forOpeningParen
= sourceCode
.getFirstToken(node
, 1);
1227 offsets
.setDesiredOffsets(node
.init
.range
, forOpeningParen
, 1);
1230 offsets
.setDesiredOffsets(node
.test
.range
, forOpeningParen
, 1);
1233 offsets
.setDesiredOffsets(node
.update
.range
, forOpeningParen
, 1);
1235 addBlocklessNodeIndent(node
.body
);
1238 "FunctionDeclaration, FunctionExpression"(node
) {
1239 const closingParen
= sourceCode
.getTokenBefore(node
.body
);
1240 const openingParen
= sourceCode
.getTokenBefore(node
.params
.length
? node
.params
[0] : closingParen
);
1242 parameterParens
.add(openingParen
);
1243 parameterParens
.add(closingParen
);
1244 addElementListIndent(node
.params
, openingParen
, closingParen
, options
[node
.type
].parameters
);
1248 addBlocklessNodeIndent(node
.consequent
);
1249 if (node
.alternate
&& node
.alternate
.type
!== "IfStatement") {
1250 addBlocklessNodeIndent(node
.alternate
);
1255 * For blockless nodes with semicolon-first style, don't indent the semicolon.
1259 * ; [1, 2, 3].map(foo)
1261 * Traversal into the node sets indentation of the semicolon, so we need to override it on exit.
1263 ":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement, WithStatement):exit"(node
) {
1266 if (node
.type
=== "IfStatement") {
1267 nodesToCheck
= [node
.consequent
];
1268 if (node
.alternate
) {
1269 nodesToCheck
.push(node
.alternate
);
1272 nodesToCheck
= [node
.body
];
1275 for (const nodeToCheck
of nodesToCheck
) {
1276 const lastToken
= sourceCode
.getLastToken(nodeToCheck
);
1278 if (astUtils
.isSemicolonToken(lastToken
)) {
1279 const tokenBeforeLast
= sourceCode
.getTokenBefore(lastToken
);
1280 const tokenAfterLast
= sourceCode
.getTokenAfter(lastToken
);
1282 // override indentation of `;` only if its line looks like a semicolon-first style line
1284 !astUtils
.isTokenOnSameLine(tokenBeforeLast
, lastToken
) &&
1286 astUtils
.isTokenOnSameLine(lastToken
, tokenAfterLast
)
1288 offsets
.setDesiredOffset(
1290 sourceCode
.getFirstToken(node
),
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
);
1303 addElementListIndent(node
.specifiers
.filter(specifier
=> specifier
.type
=== "ImportSpecifier"), openingCurly
, closingCurly
, options
.ImportDeclaration
);
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
=== ";");
1311 const end
= semiToken
&& semiToken
.range
[1] === sourceToken
.range
[1] ? node
.range
[1] : sourceToken
.range
[1];
1313 offsets
.setDesiredOffsets([fromToken
.range
[0], end
], sourceCode
.getFirstToken(node
), 1);
1317 ImportExpression(node
) {
1318 const openingParen
= sourceCode
.getFirstToken(node
, 1);
1319 const closingParen
= sourceCode
.getLastToken(node
);
1321 parameterParens
.add(openingParen
);
1322 parameterParens
.add(closingParen
);
1323 offsets
.setDesiredOffset(openingParen
, sourceCode
.getTokenBefore(openingParen
), 0);
1325 addElementListIndent([node
.source
], openingParen
, closingParen
, options
.CallExpression
.arguments
);
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
);
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
;
1340 if (node
.computed
) {
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);
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.
1351 * Otherwise, match against the first token of the object, e.g.
1354 * .baz // <-- offset by 1 from `foo`
1356 const offsetBase
= lastObjectToken
.loc
.end
.line
=== firstPropertyToken
.loc
.start
.line
1360 if (typeof options
.MemberExpression
=== "number") {
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
);
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.
1369 offsets
.setDesiredOffset(secondNonObjectToken
, node
.computed
? firstNonObjectToken
: offsetBase
, options
.MemberExpression
);
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
);
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);
1382 NewExpression(node
) {
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
);
1393 if (!node
.shorthand
&& !node
.method
&& node
.kind
=== "init") {
1394 const colon
= sourceCode
.getFirstTokenBetween(node
.key
, node
.value
, astUtils
.isColonToken
);
1396 offsets
.ignoreToken(sourceCode
.getTokenAfter(colon
));
1400 PropertyDefinition(node
) {
1401 const firstToken
= sourceCode
.getFirstToken(node
);
1402 const maybeSemicolonToken
= sourceCode
.getLastToken(node
);
1403 let keyLastToken
= null;
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]];
1411 if (bracketTokenL
!== firstToken
) {
1412 offsets
.setDesiredOffset(bracketTokenL
, firstToken
, 0);
1414 offsets
.setDesiredOffsets(keyRange
, bracketTokenL
, 1);
1415 offsets
.setDesiredOffset(bracketTokenR
, bracketTokenL
, 0);
1417 const idToken
= keyLastToken
= sourceCode
.getFirstToken(node
.key
);
1419 if (idToken
!== firstToken
) {
1420 offsets
.setDesiredOffset(idToken
, firstToken
, 1);
1424 // Indent initializer.
1426 const eqToken
= sourceCode
.getTokenBefore(node
.value
, astUtils
.isEqToken
);
1427 const valueToken
= sourceCode
.getTokenAfter(eqToken
);
1429 offsets
.setDesiredOffset(eqToken
, keyLastToken
, 1);
1430 offsets
.setDesiredOffset(valueToken
, eqToken
, 1);
1431 if (astUtils
.isSemicolonToken(maybeSemicolonToken
)) {
1432 offsets
.setDesiredOffset(maybeSemicolonToken
, eqToken
, 1);
1434 } else if (astUtils
.isSemicolonToken(maybeSemicolonToken
)) {
1435 offsets
.setDesiredOffset(maybeSemicolonToken
, keyLastToken
, 1);
1440 const openingCurly
= sourceCode
.getFirstToken(node
, { skip
: 1 }); // skip the `static` token
1441 const closingCurly
= sourceCode
.getLastToken(node
);
1443 addElementListIndent(node
.body
, openingCurly
, closingCurly
, options
.StaticBlock
.body
);
1446 SwitchStatement(node
) {
1447 const openingCurly
= sourceCode
.getTokenAfter(node
.discriminant
, astUtils
.isOpeningBraceToken
);
1448 const closingCurly
= sourceCode
.getLastToken(node
);
1450 offsets
.setDesiredOffsets([openingCurly
.range
[1], closingCurly
.range
[0]], openingCurly
, options
.SwitchCase
);
1452 if (node
.cases
.length
) {
1453 sourceCode
.getTokensBetween(
1454 node
.cases
[node
.cases
.length
- 1],
1456 { includeComments
: true, filter
: astUtils
.isCommentToken
}
1457 ).forEach(token
=> offsets
.ignoreToken(token
));
1462 if (!(node
.consequent
.length
=== 1 && node
.consequent
[0].type
=== "BlockStatement")) {
1463 const caseKeyword
= sourceCode
.getFirstToken(node
);
1464 const tokenAfterCurrentCase
= sourceCode
.getTokenAfter(node
);
1466 offsets
.setDesiredOffsets([caseKeyword
.range
[1], tokenAfterCurrentCase
.range
[0]], caseKeyword
, 1);
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
)
1478 offsets
.setDesiredOffsets([previousQuasi
.range
[1], nextQuasi
.range
[0]], tokenToAlignFrom
, 1);
1479 offsets
.setDesiredOffset(sourceCode
.getFirstToken(nextQuasi
), tokenToAlignFrom
, 0);
1483 VariableDeclaration(node
) {
1484 let variableIndent
= Object
.prototype.hasOwnProperty
.call(options
.VariableDeclarator
, node
.kind
)
1485 ? options
.VariableDeclarator
[node
.kind
]
1486 : DEFAULT_VARIABLE_INDENT
;
1488 const firstToken
= sourceCode
.getFirstToken(node
),
1489 lastToken
= sourceCode
.getLastToken(node
);
1491 if (options
.VariableDeclarator
[node
.kind
] === "first") {
1492 if (node
.declarations
.length
> 1) {
1493 addElementListIndent(
1502 variableIndent
= DEFAULT_VARIABLE_INDENT
;
1505 if (node
.declarations
[node
.declarations
.length
- 1].loc
.start
.line
> node
.loc
.start
.line
) {
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:
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
1526 offsets
.setDesiredOffsets(node
.range
, firstToken
, variableIndent
, true);
1528 offsets
.setDesiredOffsets(node
.range
, firstToken
, variableIndent
);
1531 if (astUtils
.isSemicolonToken(lastToken
)) {
1532 offsets
.ignoreToken(lastToken
);
1536 VariableDeclarator(node
) {
1538 const equalOperator
= sourceCode
.getTokenBefore(node
.init
, astUtils
.isNotOpeningParenToken
);
1539 const tokenAfterOperator
= sourceCode
.getTokenAfter(equalOperator
);
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);
1548 "JSXAttribute[value]"(node
) {
1549 const equalsToken
= sourceCode
.getFirstTokenBetween(node
.name
, node
.value
, token
=> token
.type
=== "Punctuator" && token
.value
=== "=");
1551 offsets
.setDesiredOffsets([equalsToken
.range
[0], node
.value
.range
[1]], sourceCode
.getFirstToken(node
.name
), 1);
1555 if (node
.closingElement
) {
1556 addElementListIndent(node
.children
, sourceCode
.getFirstToken(node
.openingElement
), sourceCode
.getFirstToken(node
.closingElement
), 1);
1560 JSXOpeningElement(node
) {
1561 const firstToken
= sourceCode
.getFirstToken(node
);
1564 if (node
.selfClosing
) {
1565 closingToken
= sourceCode
.getLastToken(node
, { skip
: 1 });
1566 offsets
.setDesiredOffset(sourceCode
.getLastToken(node
), closingToken
, 0);
1568 closingToken
= sourceCode
.getLastToken(node
);
1570 offsets
.setDesiredOffsets(node
.name
.range
, sourceCode
.getFirstToken(node
));
1571 addElementListIndent(node
.attributes
, firstToken
, closingToken
, 1);
1574 JSXClosingElement(node
) {
1575 const firstToken
= sourceCode
.getFirstToken(node
);
1577 offsets
.setDesiredOffsets(node
.name
.range
, firstToken
, 1);
1581 const firstOpeningToken
= sourceCode
.getFirstToken(node
.openingFragment
);
1582 const firstClosingToken
= sourceCode
.getFirstToken(node
.closingFragment
);
1584 addElementListIndent(node
.children
, firstOpeningToken
, firstClosingToken
, 1);
1587 JSXOpeningFragment(node
) {
1588 const firstToken
= sourceCode
.getFirstToken(node
);
1589 const closingToken
= sourceCode
.getLastToken(node
);
1591 offsets
.setDesiredOffsets(node
.range
, firstToken
, 1);
1592 offsets
.matchOffsetOf(firstToken
, closingToken
);
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
;
1601 offsets
.setDesiredOffsets(node
.range
, firstToken
, 1);
1602 offsets
.matchOffsetOf(firstToken
, tokenToMatch
);
1605 JSXExpressionContainer(node
) {
1606 const openingCurly
= sourceCode
.getFirstToken(node
);
1607 const closingCurly
= sourceCode
.getLastToken(node
);
1609 offsets
.setDesiredOffsets(
1610 [openingCurly
.range
[1], closingCurly
.range
[0]],
1616 JSXSpreadAttribute(node
) {
1617 const openingCurly
= sourceCode
.getFirstToken(node
);
1618 const closingCurly
= sourceCode
.getLastToken(node
);
1620 offsets
.setDesiredOffsets(
1621 [openingCurly
.range
[1], closingCurly
.range
[0]],
1628 const firstToken
= sourceCode
.getFirstToken(node
);
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);
1637 const listenerCallQueue
= [];
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.
1645 const offsetListeners
= {};
1647 for (const [selector
, listener
] of Object
.entries(baseOffsetListeners
)) {
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.
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.
1662 * To avoid this, the `Identifier` listener isn't called until traversal finishes and all
1663 * ignored nodes are known.
1665 offsetListeners
[selector
] = node
=> listenerCallQueue
.push({ listener
, node
});
1668 // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set.
1669 const ignoredNodes
= new Set();
1673 * @param {ASTNode} node The node to ignore
1676 function addToIgnoredNodes(node
) {
1677 ignoredNodes
.add(node
);
1678 ignoredNodeFirstTokens
.add(sourceCode
.getFirstToken(node
));
1681 const ignoredNodeListeners
= options
.ignoredNodes
.reduce(
1682 (listeners
, ignoredSelector
) => Object
.assign(listeners
, { [ignoredSelector
]: addToIgnoredNodes
}),
1687 * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation
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.
1694 return Object
.assign(
1696 ignoredNodeListeners
,
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
);
1707 // If ignoreComments option is enabled, ignore all comment tokens.
1708 if (options
.ignoreComments
) {
1709 sourceCode
.getAllComments()
1710 .forEach(comment
=> offsets
.ignoreToken(comment
));
1713 // Invoke the queued offset listeners for the nodes that aren't ignored.
1715 .filter(nodeInfo
=> !ignoredNodes
.has(nodeInfo
.node
))
1716 .forEach(nodeInfo
=> nodeInfo
.listener(nodeInfo
.node
));
1718 // Update the offsets for ignored nodes to prevent their child tokens from being reported.
1719 ignoredNodes
.forEach(ignoreNode
);
1721 addParensIndent(sourceCode
.ast
.tokens
);
1724 * Create a Map from (tokenOrComment) => (precedingToken).
1725 * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly.
1727 const precedingTokens
= sourceCode
.ast
.comments
.reduce((commentMap
, comment
) => {
1728 const tokenOrCommentBefore
= sourceCode
.getTokenBefore(comment
, { includeComments
: true });
1730 return commentMap
.set(comment
, commentMap
.has(tokenOrCommentBefore
) ? commentMap
.get(tokenOrCommentBefore
) : tokenOrCommentBefore
);
1733 sourceCode
.lines
.forEach((line
, lineIndex
) => {
1734 const lineNumber
= lineIndex
+ 1;
1736 if (!tokenInfo
.firstTokensByLineNumber
.has(lineNumber
)) {
1738 // Don't check indentation on blank lines
1742 const firstTokenOfLine
= tokenInfo
.firstTokensByLineNumber
.get(lineNumber
);
1744 if (firstTokenOfLine
.loc
.start
.line
!== lineNumber
) {
1746 // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice.
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
);
1757 * If a comment precedes a line that begins with a semicolon token, align to that token, i.e.
1761 * ;(async () => {})()
1763 if (tokenAfter
&& astUtils
.isSemicolonToken(tokenAfter
) && !astUtils
.isTokenOnSameLine(firstTokenOfLine
, tokenAfter
)) {
1764 offsets
.setDesiredOffset(firstTokenOfLine
, tokenAfter
, 0);
1767 // If a comment matches the expected indentation of the token immediately before or after, don't report it.
1769 mayAlignWithBefore
&& validateTokenIndent(firstTokenOfLine
, offsets
.getDesiredIndent(tokenBefore
)) ||
1770 mayAlignWithAfter
&& validateTokenIndent(firstTokenOfLine
, offsets
.getDesiredIndent(tokenAfter
))
1776 // If the token matches the expected indentation, don't report it.
1777 if (validateTokenIndent(firstTokenOfLine
, offsets
.getDesiredIndent(firstTokenOfLine
))) {
1781 // Otherwise, report the token/comment.
1782 report(firstTokenOfLine
, offsets
.getDesiredIndent(firstTokenOfLine
));