2 * @fileoverview This option sets a specific tab width for your code
4 * This rule has been ported and modified from nodeca.
5 * @author Vitaly Puzrin
6 * @author Gyandeep Singh
11 //------------------------------------------------------------------------------
13 //------------------------------------------------------------------------------
15 const astUtils
= require("./utils/ast-utils");
17 //------------------------------------------------------------------------------
19 //------------------------------------------------------------------------------
21 /* istanbul ignore next: this rule has known coverage issues, but it's deprecated and shouldn't be updated in the future anyway. */
27 description
: "enforce consistent indentation",
28 category
: "Stylistic Issues",
30 url
: "https://eslint.org/docs/rules/indent-legacy"
35 replacedBy
: ["indent"],
37 fixable
: "whitespace",
91 FunctionDeclaration
: {
111 FunctionExpression
: {
170 additionalProperties
: false
174 expected
: "Expected indentation of {{expected}} but found {{actual}}."
179 const DEFAULT_VARIABLE_INDENT
= 1;
180 const DEFAULT_PARAMETER_INDENT
= null; // For backwards compatibility, don't check parameter indentation unless specified in the config
181 const DEFAULT_FUNCTION_BODY_INDENT
= 1;
183 let indentType
= "space";
187 VariableDeclarator
: {
188 var: DEFAULT_VARIABLE_INDENT
,
189 let: DEFAULT_VARIABLE_INDENT
,
190 const: DEFAULT_VARIABLE_INDENT
193 FunctionDeclaration
: {
194 parameters
: DEFAULT_PARAMETER_INDENT
,
195 body
: DEFAULT_FUNCTION_BODY_INDENT
197 FunctionExpression
: {
198 parameters
: DEFAULT_PARAMETER_INDENT
,
199 body
: DEFAULT_FUNCTION_BODY_INDENT
202 arguments
: DEFAULT_PARAMETER_INDENT
208 const sourceCode
= context
.getSourceCode();
210 if (context
.options
.length
) {
211 if (context
.options
[0] === "tab") {
214 } else /* istanbul ignore else : this will be caught by options validation */ if (typeof context
.options
[0] === "number") {
215 indentSize
= context
.options
[0];
216 indentType
= "space";
219 if (context
.options
[1]) {
220 const opts
= context
.options
[1];
222 options
.SwitchCase
= opts
.SwitchCase
|| 0;
223 const variableDeclaratorRules
= opts
.VariableDeclarator
;
225 if (typeof variableDeclaratorRules
=== "number") {
226 options
.VariableDeclarator
= {
227 var: variableDeclaratorRules
,
228 let: variableDeclaratorRules
,
229 const: variableDeclaratorRules
231 } else if (typeof variableDeclaratorRules
=== "object") {
232 Object
.assign(options
.VariableDeclarator
, variableDeclaratorRules
);
235 if (typeof opts
.outerIIFEBody
=== "number") {
236 options
.outerIIFEBody
= opts
.outerIIFEBody
;
239 if (typeof opts
.MemberExpression
=== "number") {
240 options
.MemberExpression
= opts
.MemberExpression
;
243 if (typeof opts
.FunctionDeclaration
=== "object") {
244 Object
.assign(options
.FunctionDeclaration
, opts
.FunctionDeclaration
);
247 if (typeof opts
.FunctionExpression
=== "object") {
248 Object
.assign(options
.FunctionExpression
, opts
.FunctionExpression
);
251 if (typeof opts
.CallExpression
=== "object") {
252 Object
.assign(options
.CallExpression
, opts
.CallExpression
);
255 if (typeof opts
.ArrayExpression
=== "number" || typeof opts
.ArrayExpression
=== "string") {
256 options
.ArrayExpression
= opts
.ArrayExpression
;
259 if (typeof opts
.ObjectExpression
=== "number" || typeof opts
.ObjectExpression
=== "string") {
260 options
.ObjectExpression
= opts
.ObjectExpression
;
265 const caseIndentStore
= {};
268 * Creates an error message for a line, given the expected/actual indentation.
269 * @param {int} expectedAmount The expected amount of indentation characters for this line
270 * @param {int} actualSpaces The actual number of indentation spaces that were found on this line
271 * @param {int} actualTabs The actual number of indentation tabs that were found on this line
272 * @returns {string} An error message for this line
274 function createErrorMessageData(expectedAmount
, actualSpaces
, actualTabs
) {
275 const expectedStatement
= `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs"
276 const foundSpacesWord
= `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space"
277 const foundTabsWord
= `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs"
280 if (actualSpaces
> 0 && actualTabs
> 0) {
281 foundStatement
= `${actualSpaces} ${foundSpacesWord} and ${actualTabs} ${foundTabsWord}`; // e.g. "1 space and 2 tabs"
282 } else if (actualSpaces
> 0) {
285 * Abbreviate the message if the expected indentation is also spaces.
286 * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
288 foundStatement
= indentType
=== "space" ? actualSpaces
: `${actualSpaces} ${foundSpacesWord}`;
289 } else if (actualTabs
> 0) {
290 foundStatement
= indentType
=== "tab" ? actualTabs
: `${actualTabs} ${foundTabsWord}`;
292 foundStatement
= "0";
295 expected
: expectedStatement
,
296 actual
: foundStatement
301 * Reports a given indent violation
302 * @param {ASTNode} node Node violating the indent rule
303 * @param {int} needed Expected indentation character count
304 * @param {int} gottenSpaces Indentation space count in the actual node/code
305 * @param {int} gottenTabs Indentation tab count in the actual node/code
306 * @param {Object} [loc] Error line and column location
307 * @param {boolean} isLastNodeCheck Is the error for last node check
310 function report(node
, needed
, gottenSpaces
, gottenTabs
, loc
, isLastNodeCheck
) {
311 if (gottenSpaces
&& gottenTabs
) {
313 // To avoid conflicts with `no-mixed-spaces-and-tabs`, don't report lines that have both spaces and tabs.
317 const desiredIndent
= (indentType
=== "space" ? " " : "\t").repeat(needed
);
319 const textRange
= isLastNodeCheck
320 ? [node
.range
[1] - node
.loc
.end
.column
, node
.range
[1] - node
.loc
.end
.column
+ gottenSpaces
+ gottenTabs
]
321 : [node
.range
[0] - node
.loc
.start
.column
, node
.range
[0] - node
.loc
.start
.column
+ gottenSpaces
+ gottenTabs
];
326 messageId
: "expected",
327 data
: createErrorMessageData(needed
, gottenSpaces
, gottenTabs
),
328 fix
: fixer
=> fixer
.replaceTextRange(textRange
, desiredIndent
)
333 * Get the actual indent of node
334 * @param {ASTNode|Token} node Node to examine
335 * @param {boolean} [byLastLine=false] get indent of node's last line
336 * @returns {Object} The node's indent. Contains keys `space` and `tab`, representing the indent of each character. Also
337 * contains keys `goodChar` and `badChar`, where `goodChar` is the amount of the user's desired indentation character, and
338 * `badChar` is the amount of the other indentation character.
340 function getNodeIndent(node
, byLastLine
) {
341 const token
= byLastLine
? sourceCode
.getLastToken(node
) : sourceCode
.getFirstToken(node
);
342 const srcCharsBeforeNode
= sourceCode
.getText(token
, token
.loc
.start
.column
).split("");
343 const indentChars
= srcCharsBeforeNode
.slice(0, srcCharsBeforeNode
.findIndex(char => char !== " " && char !== "\t"));
344 const spaces
= indentChars
.filter(char => char === " ").length
;
345 const tabs
= indentChars
.filter(char => char === "\t").length
;
350 goodChar
: indentType
=== "space" ? spaces
: tabs
,
351 badChar
: indentType
=== "space" ? tabs
: spaces
356 * Checks node is the first in its own start line. By default it looks by start line.
357 * @param {ASTNode} node The node to check
358 * @param {boolean} [byEndLocation=false] Lookup based on start position or end
359 * @returns {boolean} true if its the first in the its start line
361 function isNodeFirstInLine(node
, byEndLocation
) {
362 const firstToken
= byEndLocation
=== true ? sourceCode
.getLastToken(node
, 1) : sourceCode
.getTokenBefore(node
),
363 startLine
= byEndLocation
=== true ? node
.loc
.end
.line
: node
.loc
.start
.line
,
364 endLine
= firstToken
? firstToken
.loc
.end
.line
: -1;
366 return startLine
!== endLine
;
370 * Check indent for node
371 * @param {ASTNode} node Node to check
372 * @param {int} neededIndent needed indent
375 function checkNodeIndent(node
, neededIndent
) {
376 const actualIndent
= getNodeIndent(node
, false);
379 node
.type
!== "ArrayExpression" &&
380 node
.type
!== "ObjectExpression" &&
381 (actualIndent
.goodChar
!== neededIndent
|| actualIndent
.badChar
!== 0) &&
382 isNodeFirstInLine(node
)
384 report(node
, neededIndent
, actualIndent
.space
, actualIndent
.tab
);
387 if (node
.type
=== "IfStatement" && node
.alternate
) {
388 const elseToken
= sourceCode
.getTokenBefore(node
.alternate
);
390 checkNodeIndent(elseToken
, neededIndent
);
392 if (!isNodeFirstInLine(node
.alternate
)) {
393 checkNodeIndent(node
.alternate
, neededIndent
);
397 if (node
.type
=== "TryStatement" && node
.handler
) {
398 const catchToken
= sourceCode
.getFirstToken(node
.handler
);
400 checkNodeIndent(catchToken
, neededIndent
);
403 if (node
.type
=== "TryStatement" && node
.finalizer
) {
404 const finallyToken
= sourceCode
.getTokenBefore(node
.finalizer
);
406 checkNodeIndent(finallyToken
, neededIndent
);
409 if (node
.type
=== "DoWhileStatement") {
410 const whileToken
= sourceCode
.getTokenAfter(node
.body
);
412 checkNodeIndent(whileToken
, neededIndent
);
417 * Check indent for nodes list
418 * @param {ASTNode[]} nodes list of node objects
419 * @param {int} indent needed indent
422 function checkNodesIndent(nodes
, indent
) {
423 nodes
.forEach(node
=> checkNodeIndent(node
, indent
));
427 * Check last node line indent this detects, that block closed correctly
428 * @param {ASTNode} node Node to examine
429 * @param {int} lastLineIndent needed indent
432 function checkLastNodeLineIndent(node
, lastLineIndent
) {
433 const lastToken
= sourceCode
.getLastToken(node
);
434 const endIndent
= getNodeIndent(lastToken
, true);
436 if ((endIndent
.goodChar
!== lastLineIndent
|| endIndent
.badChar
!== 0) && isNodeFirstInLine(node
, true)) {
442 { line
: lastToken
.loc
.start
.line
, column
: lastToken
.loc
.start
.column
},
449 * Check last node line indent this detects, that block closed correctly
450 * This function for more complicated return statement case, where closing parenthesis may be followed by ';'
451 * @param {ASTNode} node Node to examine
452 * @param {int} firstLineIndent first line needed indent
455 function checkLastReturnStatementLineIndent(node
, firstLineIndent
) {
458 * in case if return statement ends with ');' we have traverse back to ')'
459 * otherwise we'll measure indent for ';' and replace ')'
461 const lastToken
= sourceCode
.getLastToken(node
, astUtils
.isClosingParenToken
);
462 const textBeforeClosingParenthesis
= sourceCode
.getText(lastToken
, lastToken
.loc
.start
.column
).slice(0, -1);
464 if (textBeforeClosingParenthesis
.trim()) {
466 // There are tokens before the closing paren, don't report this case
470 const endIndent
= getNodeIndent(lastToken
, true);
472 if (endIndent
.goodChar
!== firstLineIndent
) {
478 { line
: lastToken
.loc
.start
.line
, column
: lastToken
.loc
.start
.column
},
485 * Check first node line indent is correct
486 * @param {ASTNode} node Node to examine
487 * @param {int} firstLineIndent needed indent
490 function checkFirstNodeLineIndent(node
, firstLineIndent
) {
491 const startIndent
= getNodeIndent(node
, false);
493 if ((startIndent
.goodChar
!== firstLineIndent
|| startIndent
.badChar
!== 0) && isNodeFirstInLine(node
)) {
499 { line
: node
.loc
.start
.line
, column
: node
.loc
.start
.column
}
505 * Returns a parent node of given node based on a specified type
506 * if not present then return null
507 * @param {ASTNode} node node to examine
508 * @param {string} type type that is being looked for
509 * @param {string} stopAtList end points for the evaluating code
510 * @returns {ASTNode|void} if found then node otherwise null
512 function getParentNodeByType(node
, type
, stopAtList
) {
513 let parent
= node
.parent
;
514 const stopAtSet
= new Set(stopAtList
|| ["Program"]);
516 while (parent
.type
!== type
&& !stopAtSet
.has(parent
.type
) && parent
.type
!== "Program") {
517 parent
= parent
.parent
;
520 return parent
.type
=== type
? parent
: null;
524 * Returns the VariableDeclarator based on the current node
525 * if not present then return null
526 * @param {ASTNode} node node to examine
527 * @returns {ASTNode|void} if found then node otherwise null
529 function getVariableDeclaratorNode(node
) {
530 return getParentNodeByType(node
, "VariableDeclarator");
534 * Check to see if the node is part of the multi-line variable declaration.
535 * Also if its on the same line as the varNode
536 * @param {ASTNode} node node to check
537 * @param {ASTNode} varNode variable declaration node to check against
538 * @returns {boolean} True if all the above condition satisfy
540 function isNodeInVarOnTop(node
, varNode
) {
542 varNode
.parent
.loc
.start
.line
=== node
.loc
.start
.line
&&
543 varNode
.parent
.declarations
.length
> 1;
547 * Check to see if the argument before the callee node is multi-line and
548 * there should only be 1 argument before the callee node
549 * @param {ASTNode} node node to check
550 * @returns {boolean} True if arguments are multi-line
552 function isArgBeforeCalleeNodeMultiline(node
) {
553 const parent
= node
.parent
;
555 if (parent
.arguments
.length
>= 2 && parent
.arguments
[1] === node
) {
556 return parent
.arguments
[0].loc
.end
.line
> parent
.arguments
[0].loc
.start
.line
;
563 * Check to see if the node is a file level IIFE
564 * @param {ASTNode} node The function node to check.
565 * @returns {boolean} True if the node is the outer IIFE
567 function isOuterIIFE(node
) {
568 const parent
= node
.parent
;
569 let stmt
= parent
.parent
;
572 * Verify that the node is an IIEF
575 parent
.type
!== "CallExpression" ||
576 parent
.callee
!== node
) {
582 * Navigate legal ancestors to determine whether this IIEF is outer
585 stmt
.type
=== "UnaryExpression" && (
586 stmt
.operator
=== "!" ||
587 stmt
.operator
=== "~" ||
588 stmt
.operator
=== "+" ||
589 stmt
.operator
=== "-") ||
590 stmt
.type
=== "AssignmentExpression" ||
591 stmt
.type
=== "LogicalExpression" ||
592 stmt
.type
=== "SequenceExpression" ||
593 stmt
.type
=== "VariableDeclarator") {
599 stmt
.type
=== "ExpressionStatement" ||
600 stmt
.type
=== "VariableDeclaration") &&
601 stmt
.parent
&& stmt
.parent
.type
=== "Program"
606 * Check indent for function block content
607 * @param {ASTNode} node A BlockStatement node that is inside of a function.
610 function checkIndentInFunctionBlock(node
) {
613 * Search first caller in chain.
616 * Models <- Identifier
625 const calleeNode
= node
.parent
; // FunctionExpression
628 if (calleeNode
.parent
&&
629 (calleeNode
.parent
.type
=== "Property" ||
630 calleeNode
.parent
.type
=== "ArrayExpression")) {
632 // If function is part of array or object, comma can be put at left
633 indent
= getNodeIndent(calleeNode
, false).goodChar
;
636 // If function is standalone, simple calculate indent
637 indent
= getNodeIndent(calleeNode
).goodChar
;
640 if (calleeNode
.parent
.type
=== "CallExpression") {
641 const calleeParent
= calleeNode
.parent
;
643 if (calleeNode
.type
!== "FunctionExpression" && calleeNode
.type
!== "ArrowFunctionExpression") {
644 if (calleeParent
&& calleeParent
.loc
.start
.line
< node
.loc
.start
.line
) {
645 indent
= getNodeIndent(calleeParent
).goodChar
;
648 if (isArgBeforeCalleeNodeMultiline(calleeNode
) &&
649 calleeParent
.callee
.loc
.start
.line
=== calleeParent
.callee
.loc
.end
.line
&&
650 !isNodeFirstInLine(calleeNode
)) {
651 indent
= getNodeIndent(calleeParent
).goodChar
;
657 * function body indent should be indent + indent size, unless this
658 * is a FunctionDeclaration, FunctionExpression, or outer IIFE and the corresponding options are enabled.
660 let functionOffset
= indentSize
;
662 if (options
.outerIIFEBody
!== null && isOuterIIFE(calleeNode
)) {
663 functionOffset
= options
.outerIIFEBody
* indentSize
;
664 } else if (calleeNode
.type
=== "FunctionExpression") {
665 functionOffset
= options
.FunctionExpression
.body
* indentSize
;
666 } else if (calleeNode
.type
=== "FunctionDeclaration") {
667 functionOffset
= options
.FunctionDeclaration
.body
* indentSize
;
669 indent
+= functionOffset
;
671 // check if the node is inside a variable
672 const parentVarNode
= getVariableDeclaratorNode(node
);
674 if (parentVarNode
&& isNodeInVarOnTop(node
, parentVarNode
)) {
675 indent
+= indentSize
* options
.VariableDeclarator
[parentVarNode
.parent
.kind
];
678 if (node
.body
.length
> 0) {
679 checkNodesIndent(node
.body
, indent
);
682 checkLastNodeLineIndent(node
, indent
- functionOffset
);
687 * Checks if the given node starts and ends on the same line
688 * @param {ASTNode} node The node to check
689 * @returns {boolean} Whether or not the block starts and ends on the same line.
691 function isSingleLineNode(node
) {
692 const lastToken
= sourceCode
.getLastToken(node
),
693 startLine
= node
.loc
.start
.line
,
694 endLine
= lastToken
.loc
.end
.line
;
696 return startLine
=== endLine
;
700 * Check indent for array block content or object block content
701 * @param {ASTNode} node node to examine
704 function checkIndentInArrayOrObjectBlock(node
) {
707 if (isSingleLineNode(node
)) {
711 let elements
= (node
.type
=== "ArrayExpression") ? node
.elements
: node
.properties
;
713 // filter out empty elements example would be [ , 2] so remove first element as espree considers it as null
714 elements
= elements
.filter(elem
=> elem
!== null);
718 const parentVarNode
= getVariableDeclaratorNode(node
);
720 // TODO - come up with a better strategy in future
721 if (isNodeFirstInLine(node
)) {
722 const parent
= node
.parent
;
724 nodeIndent
= getNodeIndent(parent
).goodChar
;
725 if (!parentVarNode
|| parentVarNode
.loc
.start
.line
!== node
.loc
.start
.line
) {
726 if (parent
.type
!== "VariableDeclarator" || parentVarNode
=== parentVarNode
.parent
.declarations
[0]) {
727 if (parent
.type
=== "VariableDeclarator" && parentVarNode
.loc
.start
.line
=== parent
.loc
.start
.line
) {
728 nodeIndent
+= (indentSize
* options
.VariableDeclarator
[parentVarNode
.parent
.kind
]);
729 } else if (parent
.type
=== "ObjectExpression" || parent
.type
=== "ArrayExpression") {
730 const parentElements
= node
.parent
.type
=== "ObjectExpression" ? node
.parent
.properties
: node
.parent
.elements
;
732 if (parentElements
[0] &&
733 parentElements
[0].loc
.start
.line
=== parent
.loc
.start
.line
&&
734 parentElements
[0].loc
.end
.line
!== parent
.loc
.start
.line
) {
737 * If the first element of the array spans multiple lines, don't increase the expected indentation of the rest.
744 * the second object is not indented.
746 } else if (typeof options
[parent
.type
] === "number") {
747 nodeIndent
+= options
[parent
.type
] * indentSize
;
749 nodeIndent
= parentElements
[0].loc
.start
.column
;
751 } else if (parent
.type
=== "CallExpression" || parent
.type
=== "NewExpression") {
752 if (typeof options
.CallExpression
.arguments
=== "number") {
753 nodeIndent
+= options
.CallExpression
.arguments
* indentSize
;
754 } else if (options
.CallExpression
.arguments
=== "first") {
755 if (parent
.arguments
.indexOf(node
) !== -1) {
756 nodeIndent
= parent
.arguments
[0].loc
.start
.column
;
759 nodeIndent
+= indentSize
;
761 } else if (parent
.type
=== "LogicalExpression" || parent
.type
=== "ArrowFunctionExpression") {
762 nodeIndent
+= indentSize
;
767 checkFirstNodeLineIndent(node
, nodeIndent
);
769 nodeIndent
= getNodeIndent(node
).goodChar
;
772 if (options
[node
.type
] === "first") {
773 elementsIndent
= elements
.length
? elements
[0].loc
.start
.column
: 0; // If there are no elements, elementsIndent doesn't matter.
775 elementsIndent
= nodeIndent
+ indentSize
* options
[node
.type
];
779 * Check if the node is a multiple variable declaration; if so, then
780 * make sure indentation takes that into account.
782 if (isNodeInVarOnTop(node
, parentVarNode
)) {
783 elementsIndent
+= indentSize
* options
.VariableDeclarator
[parentVarNode
.parent
.kind
];
786 checkNodesIndent(elements
, elementsIndent
);
788 if (elements
.length
> 0) {
790 // Skip last block line check if last item in same line
791 if (elements
[elements
.length
- 1].loc
.end
.line
=== node
.loc
.end
.line
) {
796 checkLastNodeLineIndent(node
, nodeIndent
+
797 (isNodeInVarOnTop(node
, parentVarNode
) ? options
.VariableDeclarator
[parentVarNode
.parent
.kind
] * indentSize
: 0));
801 * Check if the node or node body is a BlockStatement or not
802 * @param {ASTNode} node node to test
803 * @returns {boolean} True if it or its body is a block statement
805 function isNodeBodyBlock(node
) {
806 return node
.type
=== "BlockStatement" || node
.type
=== "ClassBody" || (node
.body
&& node
.body
.type
=== "BlockStatement") ||
807 (node
.consequent
&& node
.consequent
.type
=== "BlockStatement");
811 * Check indentation for blocks
812 * @param {ASTNode} node node to check
815 function blockIndentationCheck(node
) {
817 // Skip inline blocks
818 if (isSingleLineNode(node
)) {
823 node
.parent
.type
=== "FunctionExpression" ||
824 node
.parent
.type
=== "FunctionDeclaration" ||
825 node
.parent
.type
=== "ArrowFunctionExpression")
827 checkIndentInFunctionBlock(node
);
832 let nodesToCheck
= [];
835 * For this statements we should check indent from statement beginning,
836 * not from the beginning of the block.
838 const statementsWithProperties
= [
839 "IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration", "TryStatement"
842 if (node
.parent
&& statementsWithProperties
.indexOf(node
.parent
.type
) !== -1 && isNodeBodyBlock(node
)) {
843 indent
= getNodeIndent(node
.parent
).goodChar
;
844 } else if (node
.parent
&& node
.parent
.type
=== "CatchClause") {
845 indent
= getNodeIndent(node
.parent
.parent
).goodChar
;
847 indent
= getNodeIndent(node
).goodChar
;
850 if (node
.type
=== "IfStatement" && node
.consequent
.type
!== "BlockStatement") {
851 nodesToCheck
= [node
.consequent
];
852 } else if (Array
.isArray(node
.body
)) {
853 nodesToCheck
= node
.body
;
855 nodesToCheck
= [node
.body
];
858 if (nodesToCheck
.length
> 0) {
859 checkNodesIndent(nodesToCheck
, indent
+ indentSize
);
862 if (node
.type
=== "BlockStatement") {
863 checkLastNodeLineIndent(node
, indent
);
868 * Filter out the elements which are on the same line of each other or the node.
869 * basically have only 1 elements from each line except the variable declaration line.
870 * @param {ASTNode} node Variable declaration node
871 * @returns {ASTNode[]} Filtered elements
873 function filterOutSameLineVars(node
) {
874 return node
.declarations
.reduce((finalCollection
, elem
) => {
875 const lastElem
= finalCollection
[finalCollection
.length
- 1];
877 if ((elem
.loc
.start
.line
!== node
.loc
.start
.line
&& !lastElem
) ||
878 (lastElem
&& lastElem
.loc
.start
.line
!== elem
.loc
.start
.line
)) {
879 finalCollection
.push(elem
);
882 return finalCollection
;
887 * Check indentation for variable declarations
888 * @param {ASTNode} node node to examine
891 function checkIndentInVariableDeclarations(node
) {
892 const elements
= filterOutSameLineVars(node
);
893 const nodeIndent
= getNodeIndent(node
).goodChar
;
894 const lastElement
= elements
[elements
.length
- 1];
896 const elementsIndent
= nodeIndent
+ indentSize
* options
.VariableDeclarator
[node
.kind
];
898 checkNodesIndent(elements
, elementsIndent
);
900 // Only check the last line if there is any token after the last item
901 if (sourceCode
.getLastToken(node
).loc
.end
.line
<= lastElement
.loc
.end
.line
) {
905 const tokenBeforeLastElement
= sourceCode
.getTokenBefore(lastElement
);
907 if (tokenBeforeLastElement
.value
=== ",") {
909 // Special case for comma-first syntax where the semicolon is indented
910 checkLastNodeLineIndent(node
, getNodeIndent(tokenBeforeLastElement
).goodChar
);
912 checkLastNodeLineIndent(node
, elementsIndent
- indentSize
);
917 * Check and decide whether to check for indentation for blockless nodes
918 * Scenarios are for or while statements without braces around them
919 * @param {ASTNode} node node to examine
922 function blockLessNodes(node
) {
923 if (node
.body
.type
!== "BlockStatement") {
924 blockIndentationCheck(node
);
929 * Returns the expected indentation for the case statement
930 * @param {ASTNode} node node to examine
931 * @param {int} [providedSwitchIndent] indent for switch statement
932 * @returns {int} indent size
934 function expectedCaseIndent(node
, providedSwitchIndent
) {
935 const switchNode
= (node
.type
=== "SwitchStatement") ? node
: node
.parent
;
936 const switchIndent
= typeof providedSwitchIndent
=== "undefined"
937 ? getNodeIndent(switchNode
).goodChar
938 : providedSwitchIndent
;
941 if (caseIndentStore
[switchNode
.loc
.start
.line
]) {
942 return caseIndentStore
[switchNode
.loc
.start
.line
];
945 if (switchNode
.cases
.length
> 0 && options
.SwitchCase
=== 0) {
946 caseIndent
= switchIndent
;
948 caseIndent
= switchIndent
+ (indentSize
* options
.SwitchCase
);
951 caseIndentStore
[switchNode
.loc
.start
.line
] = caseIndent
;
957 * Checks whether a return statement is wrapped in ()
958 * @param {ASTNode} node node to examine
959 * @returns {boolean} the result
961 function isWrappedInParenthesis(node
) {
962 const regex
= /^return\s*?\(\s*?\);*?/u;
964 const statementWithoutArgument
= sourceCode
.getText(node
).replace(
965 sourceCode
.getText(node
.argument
), ""
968 return regex
.test(statementWithoutArgument
);
973 if (node
.body
.length
> 0) {
975 // Root nodes should have no indent
976 checkNodesIndent(node
.body
, getNodeIndent(node
).goodChar
);
980 ClassBody
: blockIndentationCheck
,
982 BlockStatement
: blockIndentationCheck
,
984 WhileStatement
: blockLessNodes
,
986 ForStatement
: blockLessNodes
,
988 ForInStatement
: blockLessNodes
,
990 ForOfStatement
: blockLessNodes
,
992 DoWhileStatement
: blockLessNodes
,
995 if (node
.consequent
.type
!== "BlockStatement" && node
.consequent
.loc
.start
.line
> node
.loc
.start
.line
) {
996 blockIndentationCheck(node
);
1000 VariableDeclaration(node
) {
1001 if (node
.declarations
[node
.declarations
.length
- 1].loc
.start
.line
> node
.declarations
[0].loc
.start
.line
) {
1002 checkIndentInVariableDeclarations(node
);
1006 ObjectExpression(node
) {
1007 checkIndentInArrayOrObjectBlock(node
);
1010 ArrayExpression(node
) {
1011 checkIndentInArrayOrObjectBlock(node
);
1014 MemberExpression(node
) {
1016 if (typeof options
.MemberExpression
=== "undefined") {
1020 if (isSingleLineNode(node
)) {
1025 * The typical layout of variable declarations and assignments
1026 * alter the expectation of correct indentation. Skip them.
1027 * TODO: Add appropriate configuration options for variable
1028 * declarations and assignments.
1030 if (getParentNodeByType(node
, "VariableDeclarator", ["FunctionExpression", "ArrowFunctionExpression"])) {
1034 if (getParentNodeByType(node
, "AssignmentExpression", ["FunctionExpression"])) {
1038 const propertyIndent
= getNodeIndent(node
).goodChar
+ indentSize
* options
.MemberExpression
;
1040 const checkNodes
= [node
.property
];
1042 const dot
= sourceCode
.getTokenBefore(node
.property
);
1044 if (dot
.type
=== "Punctuator" && dot
.value
=== ".") {
1045 checkNodes
.push(dot
);
1048 checkNodesIndent(checkNodes
, propertyIndent
);
1051 SwitchStatement(node
) {
1053 // Switch is not a 'BlockStatement'
1054 const switchIndent
= getNodeIndent(node
).goodChar
;
1055 const caseIndent
= expectedCaseIndent(node
, switchIndent
);
1057 checkNodesIndent(node
.cases
, caseIndent
);
1060 checkLastNodeLineIndent(node
, switchIndent
);
1065 // Skip inline cases
1066 if (isSingleLineNode(node
)) {
1069 const caseIndent
= expectedCaseIndent(node
);
1071 checkNodesIndent(node
.consequent
, caseIndent
+ indentSize
);
1074 FunctionDeclaration(node
) {
1075 if (isSingleLineNode(node
)) {
1078 if (options
.FunctionDeclaration
.parameters
=== "first" && node
.params
.length
) {
1079 checkNodesIndent(node
.params
.slice(1), node
.params
[0].loc
.start
.column
);
1080 } else if (options
.FunctionDeclaration
.parameters
!== null) {
1081 checkNodesIndent(node
.params
, getNodeIndent(node
).goodChar
+ indentSize
* options
.FunctionDeclaration
.parameters
);
1085 FunctionExpression(node
) {
1086 if (isSingleLineNode(node
)) {
1089 if (options
.FunctionExpression
.parameters
=== "first" && node
.params
.length
) {
1090 checkNodesIndent(node
.params
.slice(1), node
.params
[0].loc
.start
.column
);
1091 } else if (options
.FunctionExpression
.parameters
!== null) {
1092 checkNodesIndent(node
.params
, getNodeIndent(node
).goodChar
+ indentSize
* options
.FunctionExpression
.parameters
);
1096 ReturnStatement(node
) {
1097 if (isSingleLineNode(node
)) {
1101 const firstLineIndent
= getNodeIndent(node
).goodChar
;
1103 // in case if return statement is wrapped in parenthesis
1104 if (isWrappedInParenthesis(node
)) {
1105 checkLastReturnStatementLineIndent(node
, firstLineIndent
);
1107 checkNodeIndent(node
, firstLineIndent
);
1111 CallExpression(node
) {
1112 if (isSingleLineNode(node
)) {
1115 if (options
.CallExpression
.arguments
=== "first" && node
.arguments
.length
) {
1116 checkNodesIndent(node
.arguments
.slice(1), node
.arguments
[0].loc
.start
.column
);
1117 } else if (options
.CallExpression
.arguments
!== null) {
1118 checkNodesIndent(node
.arguments
, getNodeIndent(node
).goodChar
+ indentSize
* options
.CallExpression
.arguments
);