UNPKG

45.5 kBJavaScriptView Raw
1/**
2 * @fileoverview This option sets a specific tab width for your code
3 *
4 * This rule has been ported and modified from nodeca.
5 * @author Vitaly Puzrin
6 * @author Gyandeep Singh
7 */
8
9"use strict";
10
11//------------------------------------------------------------------------------
12// Requirements
13//------------------------------------------------------------------------------
14
15const astUtils = require("./utils/ast-utils");
16
17//------------------------------------------------------------------------------
18// Rule Definition
19//------------------------------------------------------------------------------
20
21/* istanbul ignore next: this rule has known coverage issues, but it's deprecated and shouldn't be updated in the future anyway. */
22module.exports = {
23 meta: {
24 type: "layout",
25
26 docs: {
27 description: "enforce consistent indentation",
28 category: "Stylistic Issues",
29 recommended: false,
30 url: "https://eslint.org/docs/rules/indent-legacy"
31 },
32
33 deprecated: true,
34
35 replacedBy: ["indent"],
36
37 fixable: "whitespace",
38
39 schema: [
40 {
41 oneOf: [
42 {
43 enum: ["tab"]
44 },
45 {
46 type: "integer",
47 minimum: 0
48 }
49 ]
50 },
51 {
52 type: "object",
53 properties: {
54 SwitchCase: {
55 type: "integer",
56 minimum: 0
57 },
58 VariableDeclarator: {
59 oneOf: [
60 {
61 type: "integer",
62 minimum: 0
63 },
64 {
65 type: "object",
66 properties: {
67 var: {
68 type: "integer",
69 minimum: 0
70 },
71 let: {
72 type: "integer",
73 minimum: 0
74 },
75 const: {
76 type: "integer",
77 minimum: 0
78 }
79 }
80 }
81 ]
82 },
83 outerIIFEBody: {
84 type: "integer",
85 minimum: 0
86 },
87 MemberExpression: {
88 type: "integer",
89 minimum: 0
90 },
91 FunctionDeclaration: {
92 type: "object",
93 properties: {
94 parameters: {
95 oneOf: [
96 {
97 type: "integer",
98 minimum: 0
99 },
100 {
101 enum: ["first"]
102 }
103 ]
104 },
105 body: {
106 type: "integer",
107 minimum: 0
108 }
109 }
110 },
111 FunctionExpression: {
112 type: "object",
113 properties: {
114 parameters: {
115 oneOf: [
116 {
117 type: "integer",
118 minimum: 0
119 },
120 {
121 enum: ["first"]
122 }
123 ]
124 },
125 body: {
126 type: "integer",
127 minimum: 0
128 }
129 }
130 },
131 CallExpression: {
132 type: "object",
133 properties: {
134 parameters: {
135 oneOf: [
136 {
137 type: "integer",
138 minimum: 0
139 },
140 {
141 enum: ["first"]
142 }
143 ]
144 }
145 }
146 },
147 ArrayExpression: {
148 oneOf: [
149 {
150 type: "integer",
151 minimum: 0
152 },
153 {
154 enum: ["first"]
155 }
156 ]
157 },
158 ObjectExpression: {
159 oneOf: [
160 {
161 type: "integer",
162 minimum: 0
163 },
164 {
165 enum: ["first"]
166 }
167 ]
168 }
169 },
170 additionalProperties: false
171 }
172 ],
173 messages: {
174 expected: "Expected indentation of {{expected}} but found {{actual}}."
175 }
176 },
177
178 create(context) {
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;
182
183 let indentType = "space";
184 let indentSize = 4;
185 const options = {
186 SwitchCase: 0,
187 VariableDeclarator: {
188 var: DEFAULT_VARIABLE_INDENT,
189 let: DEFAULT_VARIABLE_INDENT,
190 const: DEFAULT_VARIABLE_INDENT
191 },
192 outerIIFEBody: null,
193 FunctionDeclaration: {
194 parameters: DEFAULT_PARAMETER_INDENT,
195 body: DEFAULT_FUNCTION_BODY_INDENT
196 },
197 FunctionExpression: {
198 parameters: DEFAULT_PARAMETER_INDENT,
199 body: DEFAULT_FUNCTION_BODY_INDENT
200 },
201 CallExpression: {
202 arguments: DEFAULT_PARAMETER_INDENT
203 },
204 ArrayExpression: 1,
205 ObjectExpression: 1
206 };
207
208 const sourceCode = context.getSourceCode();
209
210 if (context.options.length) {
211 if (context.options[0] === "tab") {
212 indentSize = 1;
213 indentType = "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";
217 }
218
219 if (context.options[1]) {
220 const opts = context.options[1];
221
222 options.SwitchCase = opts.SwitchCase || 0;
223 const variableDeclaratorRules = opts.VariableDeclarator;
224
225 if (typeof variableDeclaratorRules === "number") {
226 options.VariableDeclarator = {
227 var: variableDeclaratorRules,
228 let: variableDeclaratorRules,
229 const: variableDeclaratorRules
230 };
231 } else if (typeof variableDeclaratorRules === "object") {
232 Object.assign(options.VariableDeclarator, variableDeclaratorRules);
233 }
234
235 if (typeof opts.outerIIFEBody === "number") {
236 options.outerIIFEBody = opts.outerIIFEBody;
237 }
238
239 if (typeof opts.MemberExpression === "number") {
240 options.MemberExpression = opts.MemberExpression;
241 }
242
243 if (typeof opts.FunctionDeclaration === "object") {
244 Object.assign(options.FunctionDeclaration, opts.FunctionDeclaration);
245 }
246
247 if (typeof opts.FunctionExpression === "object") {
248 Object.assign(options.FunctionExpression, opts.FunctionExpression);
249 }
250
251 if (typeof opts.CallExpression === "object") {
252 Object.assign(options.CallExpression, opts.CallExpression);
253 }
254
255 if (typeof opts.ArrayExpression === "number" || typeof opts.ArrayExpression === "string") {
256 options.ArrayExpression = opts.ArrayExpression;
257 }
258
259 if (typeof opts.ObjectExpression === "number" || typeof opts.ObjectExpression === "string") {
260 options.ObjectExpression = opts.ObjectExpression;
261 }
262 }
263 }
264
265 const caseIndentStore = {};
266
267 /**
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
273 */
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"
278 let foundStatement;
279
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) {
283
284 /*
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'
287 */
288 foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`;
289 } else if (actualTabs > 0) {
290 foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`;
291 } else {
292 foundStatement = "0";
293 }
294 return {
295 expected: expectedStatement,
296 actual: foundStatement
297 };
298 }
299
300 /**
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
308 * @returns {void}
309 */
310 function report(node, needed, gottenSpaces, gottenTabs, loc, isLastNodeCheck) {
311 if (gottenSpaces && gottenTabs) {
312
313 // To avoid conflicts with `no-mixed-spaces-and-tabs`, don't report lines that have both spaces and tabs.
314 return;
315 }
316
317 const desiredIndent = (indentType === "space" ? " " : "\t").repeat(needed);
318
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];
322
323 context.report({
324 node,
325 loc,
326 messageId: "expected",
327 data: createErrorMessageData(needed, gottenSpaces, gottenTabs),
328 fix: fixer => fixer.replaceTextRange(textRange, desiredIndent)
329 });
330 }
331
332 /**
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.
339 */
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;
346
347 return {
348 space: spaces,
349 tab: tabs,
350 goodChar: indentType === "space" ? spaces : tabs,
351 badChar: indentType === "space" ? tabs : spaces
352 };
353 }
354
355 /**
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
360 */
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;
365
366 return startLine !== endLine;
367 }
368
369 /**
370 * Check indent for node
371 * @param {ASTNode} node Node to check
372 * @param {int} neededIndent needed indent
373 * @returns {void}
374 */
375 function checkNodeIndent(node, neededIndent) {
376 const actualIndent = getNodeIndent(node, false);
377
378 if (
379 node.type !== "ArrayExpression" &&
380 node.type !== "ObjectExpression" &&
381 (actualIndent.goodChar !== neededIndent || actualIndent.badChar !== 0) &&
382 isNodeFirstInLine(node)
383 ) {
384 report(node, neededIndent, actualIndent.space, actualIndent.tab);
385 }
386
387 if (node.type === "IfStatement" && node.alternate) {
388 const elseToken = sourceCode.getTokenBefore(node.alternate);
389
390 checkNodeIndent(elseToken, neededIndent);
391
392 if (!isNodeFirstInLine(node.alternate)) {
393 checkNodeIndent(node.alternate, neededIndent);
394 }
395 }
396
397 if (node.type === "TryStatement" && node.handler) {
398 const catchToken = sourceCode.getFirstToken(node.handler);
399
400 checkNodeIndent(catchToken, neededIndent);
401 }
402
403 if (node.type === "TryStatement" && node.finalizer) {
404 const finallyToken = sourceCode.getTokenBefore(node.finalizer);
405
406 checkNodeIndent(finallyToken, neededIndent);
407 }
408
409 if (node.type === "DoWhileStatement") {
410 const whileToken = sourceCode.getTokenAfter(node.body);
411
412 checkNodeIndent(whileToken, neededIndent);
413 }
414 }
415
416 /**
417 * Check indent for nodes list
418 * @param {ASTNode[]} nodes list of node objects
419 * @param {int} indent needed indent
420 * @returns {void}
421 */
422 function checkNodesIndent(nodes, indent) {
423 nodes.forEach(node => checkNodeIndent(node, indent));
424 }
425
426 /**
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
430 * @returns {void}
431 */
432 function checkLastNodeLineIndent(node, lastLineIndent) {
433 const lastToken = sourceCode.getLastToken(node);
434 const endIndent = getNodeIndent(lastToken, true);
435
436 if ((endIndent.goodChar !== lastLineIndent || endIndent.badChar !== 0) && isNodeFirstInLine(node, true)) {
437 report(
438 node,
439 lastLineIndent,
440 endIndent.space,
441 endIndent.tab,
442 { line: lastToken.loc.start.line, column: lastToken.loc.start.column },
443 true
444 );
445 }
446 }
447
448 /**
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
453 * @returns {void}
454 */
455 function checkLastReturnStatementLineIndent(node, firstLineIndent) {
456
457 /*
458 * in case if return statement ends with ');' we have traverse back to ')'
459 * otherwise we'll measure indent for ';' and replace ')'
460 */
461 const lastToken = sourceCode.getLastToken(node, astUtils.isClosingParenToken);
462 const textBeforeClosingParenthesis = sourceCode.getText(lastToken, lastToken.loc.start.column).slice(0, -1);
463
464 if (textBeforeClosingParenthesis.trim()) {
465
466 // There are tokens before the closing paren, don't report this case
467 return;
468 }
469
470 const endIndent = getNodeIndent(lastToken, true);
471
472 if (endIndent.goodChar !== firstLineIndent) {
473 report(
474 node,
475 firstLineIndent,
476 endIndent.space,
477 endIndent.tab,
478 { line: lastToken.loc.start.line, column: lastToken.loc.start.column },
479 true
480 );
481 }
482 }
483
484 /**
485 * Check first node line indent is correct
486 * @param {ASTNode} node Node to examine
487 * @param {int} firstLineIndent needed indent
488 * @returns {void}
489 */
490 function checkFirstNodeLineIndent(node, firstLineIndent) {
491 const startIndent = getNodeIndent(node, false);
492
493 if ((startIndent.goodChar !== firstLineIndent || startIndent.badChar !== 0) && isNodeFirstInLine(node)) {
494 report(
495 node,
496 firstLineIndent,
497 startIndent.space,
498 startIndent.tab,
499 { line: node.loc.start.line, column: node.loc.start.column }
500 );
501 }
502 }
503
504 /**
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
511 */
512 function getParentNodeByType(node, type, stopAtList) {
513 let parent = node.parent;
514 const stopAtSet = new Set(stopAtList || ["Program"]);
515
516 while (parent.type !== type && !stopAtSet.has(parent.type) && parent.type !== "Program") {
517 parent = parent.parent;
518 }
519
520 return parent.type === type ? parent : null;
521 }
522
523 /**
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
528 */
529 function getVariableDeclaratorNode(node) {
530 return getParentNodeByType(node, "VariableDeclarator");
531 }
532
533 /**
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
539 */
540 function isNodeInVarOnTop(node, varNode) {
541 return varNode &&
542 varNode.parent.loc.start.line === node.loc.start.line &&
543 varNode.parent.declarations.length > 1;
544 }
545
546 /**
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
551 */
552 function isArgBeforeCalleeNodeMultiline(node) {
553 const parent = node.parent;
554
555 if (parent.arguments.length >= 2 && parent.arguments[1] === node) {
556 return parent.arguments[0].loc.end.line > parent.arguments[0].loc.start.line;
557 }
558
559 return false;
560 }
561
562 /**
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
566 */
567 function isOuterIIFE(node) {
568 const parent = node.parent;
569 let stmt = parent.parent;
570
571 /*
572 * Verify that the node is an IIEF
573 */
574 if (
575 parent.type !== "CallExpression" ||
576 parent.callee !== node) {
577
578 return false;
579 }
580
581 /*
582 * Navigate legal ancestors to determine whether this IIEF is outer
583 */
584 while (
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") {
594
595 stmt = stmt.parent;
596 }
597
598 return ((
599 stmt.type === "ExpressionStatement" ||
600 stmt.type === "VariableDeclaration") &&
601 stmt.parent && stmt.parent.type === "Program"
602 );
603 }
604
605 /**
606 * Check indent for function block content
607 * @param {ASTNode} node A BlockStatement node that is inside of a function.
608 * @returns {void}
609 */
610 function checkIndentInFunctionBlock(node) {
611
612 /*
613 * Search first caller in chain.
614 * Ex.:
615 *
616 * Models <- Identifier
617 * .User
618 * .find()
619 * .exec(function() {
620 * // function body
621 * });
622 *
623 * Looks for 'Models'
624 */
625 const calleeNode = node.parent; // FunctionExpression
626 let indent;
627
628 if (calleeNode.parent &&
629 (calleeNode.parent.type === "Property" ||
630 calleeNode.parent.type === "ArrayExpression")) {
631
632 // If function is part of array or object, comma can be put at left
633 indent = getNodeIndent(calleeNode, false).goodChar;
634 } else {
635
636 // If function is standalone, simple calculate indent
637 indent = getNodeIndent(calleeNode).goodChar;
638 }
639
640 if (calleeNode.parent.type === "CallExpression") {
641 const calleeParent = calleeNode.parent;
642
643 if (calleeNode.type !== "FunctionExpression" && calleeNode.type !== "ArrowFunctionExpression") {
644 if (calleeParent && calleeParent.loc.start.line < node.loc.start.line) {
645 indent = getNodeIndent(calleeParent).goodChar;
646 }
647 } else {
648 if (isArgBeforeCalleeNodeMultiline(calleeNode) &&
649 calleeParent.callee.loc.start.line === calleeParent.callee.loc.end.line &&
650 !isNodeFirstInLine(calleeNode)) {
651 indent = getNodeIndent(calleeParent).goodChar;
652 }
653 }
654 }
655
656 /*
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.
659 */
660 let functionOffset = indentSize;
661
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;
668 }
669 indent += functionOffset;
670
671 // check if the node is inside a variable
672 const parentVarNode = getVariableDeclaratorNode(node);
673
674 if (parentVarNode && isNodeInVarOnTop(node, parentVarNode)) {
675 indent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind];
676 }
677
678 if (node.body.length > 0) {
679 checkNodesIndent(node.body, indent);
680 }
681
682 checkLastNodeLineIndent(node, indent - functionOffset);
683 }
684
685
686 /**
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.
690 */
691 function isSingleLineNode(node) {
692 const lastToken = sourceCode.getLastToken(node),
693 startLine = node.loc.start.line,
694 endLine = lastToken.loc.end.line;
695
696 return startLine === endLine;
697 }
698
699 /**
700 * Check to see if the first element inside an array is an object and on the same line as the node
701 * If the node is not an array then it will return false.
702 * @param {ASTNode} node node to check
703 * @returns {boolean} success/failure
704 */
705 function isFirstArrayElementOnSameLine(node) {
706 if (node.type === "ArrayExpression" && node.elements[0]) {
707 return node.elements[0].loc.start.line === node.loc.start.line && node.elements[0].type === "ObjectExpression";
708 }
709 return false;
710
711 }
712
713 /**
714 * Check indent for array block content or object block content
715 * @param {ASTNode} node node to examine
716 * @returns {void}
717 */
718 function checkIndentInArrayOrObjectBlock(node) {
719
720 // Skip inline
721 if (isSingleLineNode(node)) {
722 return;
723 }
724
725 let elements = (node.type === "ArrayExpression") ? node.elements : node.properties;
726
727 // filter out empty elements example would be [ , 2] so remove first element as espree considers it as null
728 elements = elements.filter(elem => elem !== null);
729
730 let nodeIndent;
731 let elementsIndent;
732 const parentVarNode = getVariableDeclaratorNode(node);
733
734 // TODO - come up with a better strategy in future
735 if (isNodeFirstInLine(node)) {
736 const parent = node.parent;
737
738 nodeIndent = getNodeIndent(parent).goodChar;
739 if (!parentVarNode || parentVarNode.loc.start.line !== node.loc.start.line) {
740 if (parent.type !== "VariableDeclarator" || parentVarNode === parentVarNode.parent.declarations[0]) {
741 if (parent.type === "VariableDeclarator" && parentVarNode.loc.start.line === parent.loc.start.line) {
742 nodeIndent += (indentSize * options.VariableDeclarator[parentVarNode.parent.kind]);
743 } else if (parent.type === "ObjectExpression" || parent.type === "ArrayExpression") {
744 const parentElements = node.parent.type === "ObjectExpression" ? node.parent.properties : node.parent.elements;
745
746 if (parentElements[0] &&
747 parentElements[0].loc.start.line === parent.loc.start.line &&
748 parentElements[0].loc.end.line !== parent.loc.start.line) {
749
750 /*
751 * If the first element of the array spans multiple lines, don't increase the expected indentation of the rest.
752 * e.g. [{
753 * foo: 1
754 * },
755 * {
756 * bar: 1
757 * }]
758 * the second object is not indented.
759 */
760 } else if (typeof options[parent.type] === "number") {
761 nodeIndent += options[parent.type] * indentSize;
762 } else {
763 nodeIndent = parentElements[0].loc.start.column;
764 }
765 } else if (parent.type === "CallExpression" || parent.type === "NewExpression") {
766 if (typeof options.CallExpression.arguments === "number") {
767 nodeIndent += options.CallExpression.arguments * indentSize;
768 } else if (options.CallExpression.arguments === "first") {
769 if (parent.arguments.indexOf(node) !== -1) {
770 nodeIndent = parent.arguments[0].loc.start.column;
771 }
772 } else {
773 nodeIndent += indentSize;
774 }
775 } else if (parent.type === "LogicalExpression" || parent.type === "ArrowFunctionExpression") {
776 nodeIndent += indentSize;
777 }
778 }
779 } else if (!parentVarNode && !isFirstArrayElementOnSameLine(parent) && parent.type !== "MemberExpression" && parent.type !== "ExpressionStatement" && parent.type !== "AssignmentExpression" && parent.type !== "Property") {
780 nodeIndent += indentSize;
781 }
782
783 checkFirstNodeLineIndent(node, nodeIndent);
784 } else {
785 nodeIndent = getNodeIndent(node).goodChar;
786 }
787
788 if (options[node.type] === "first") {
789 elementsIndent = elements.length ? elements[0].loc.start.column : 0; // If there are no elements, elementsIndent doesn't matter.
790 } else {
791 elementsIndent = nodeIndent + indentSize * options[node.type];
792 }
793
794 /*
795 * Check if the node is a multiple variable declaration; if so, then
796 * make sure indentation takes that into account.
797 */
798 if (isNodeInVarOnTop(node, parentVarNode)) {
799 elementsIndent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind];
800 }
801
802 checkNodesIndent(elements, elementsIndent);
803
804 if (elements.length > 0) {
805
806 // Skip last block line check if last item in same line
807 if (elements[elements.length - 1].loc.end.line === node.loc.end.line) {
808 return;
809 }
810 }
811
812 checkLastNodeLineIndent(node, nodeIndent +
813 (isNodeInVarOnTop(node, parentVarNode) ? options.VariableDeclarator[parentVarNode.parent.kind] * indentSize : 0));
814 }
815
816 /**
817 * Check if the node or node body is a BlockStatement or not
818 * @param {ASTNode} node node to test
819 * @returns {boolean} True if it or its body is a block statement
820 */
821 function isNodeBodyBlock(node) {
822 return node.type === "BlockStatement" || node.type === "ClassBody" || (node.body && node.body.type === "BlockStatement") ||
823 (node.consequent && node.consequent.type === "BlockStatement");
824 }
825
826 /**
827 * Check indentation for blocks
828 * @param {ASTNode} node node to check
829 * @returns {void}
830 */
831 function blockIndentationCheck(node) {
832
833 // Skip inline blocks
834 if (isSingleLineNode(node)) {
835 return;
836 }
837
838 if (node.parent && (
839 node.parent.type === "FunctionExpression" ||
840 node.parent.type === "FunctionDeclaration" ||
841 node.parent.type === "ArrowFunctionExpression")
842 ) {
843 checkIndentInFunctionBlock(node);
844 return;
845 }
846
847 let indent;
848 let nodesToCheck = [];
849
850 /*
851 * For this statements we should check indent from statement beginning,
852 * not from the beginning of the block.
853 */
854 const statementsWithProperties = [
855 "IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration", "TryStatement"
856 ];
857
858 if (node.parent && statementsWithProperties.indexOf(node.parent.type) !== -1 && isNodeBodyBlock(node)) {
859 indent = getNodeIndent(node.parent).goodChar;
860 } else if (node.parent && node.parent.type === "CatchClause") {
861 indent = getNodeIndent(node.parent.parent).goodChar;
862 } else {
863 indent = getNodeIndent(node).goodChar;
864 }
865
866 if (node.type === "IfStatement" && node.consequent.type !== "BlockStatement") {
867 nodesToCheck = [node.consequent];
868 } else if (Array.isArray(node.body)) {
869 nodesToCheck = node.body;
870 } else {
871 nodesToCheck = [node.body];
872 }
873
874 if (nodesToCheck.length > 0) {
875 checkNodesIndent(nodesToCheck, indent + indentSize);
876 }
877
878 if (node.type === "BlockStatement") {
879 checkLastNodeLineIndent(node, indent);
880 }
881 }
882
883 /**
884 * Filter out the elements which are on the same line of each other or the node.
885 * basically have only 1 elements from each line except the variable declaration line.
886 * @param {ASTNode} node Variable declaration node
887 * @returns {ASTNode[]} Filtered elements
888 */
889 function filterOutSameLineVars(node) {
890 return node.declarations.reduce((finalCollection, elem) => {
891 const lastElem = finalCollection[finalCollection.length - 1];
892
893 if ((elem.loc.start.line !== node.loc.start.line && !lastElem) ||
894 (lastElem && lastElem.loc.start.line !== elem.loc.start.line)) {
895 finalCollection.push(elem);
896 }
897
898 return finalCollection;
899 }, []);
900 }
901
902 /**
903 * Check indentation for variable declarations
904 * @param {ASTNode} node node to examine
905 * @returns {void}
906 */
907 function checkIndentInVariableDeclarations(node) {
908 const elements = filterOutSameLineVars(node);
909 const nodeIndent = getNodeIndent(node).goodChar;
910 const lastElement = elements[elements.length - 1];
911
912 const elementsIndent = nodeIndent + indentSize * options.VariableDeclarator[node.kind];
913
914 checkNodesIndent(elements, elementsIndent);
915
916 // Only check the last line if there is any token after the last item
917 if (sourceCode.getLastToken(node).loc.end.line <= lastElement.loc.end.line) {
918 return;
919 }
920
921 const tokenBeforeLastElement = sourceCode.getTokenBefore(lastElement);
922
923 if (tokenBeforeLastElement.value === ",") {
924
925 // Special case for comma-first syntax where the semicolon is indented
926 checkLastNodeLineIndent(node, getNodeIndent(tokenBeforeLastElement).goodChar);
927 } else {
928 checkLastNodeLineIndent(node, elementsIndent - indentSize);
929 }
930 }
931
932 /**
933 * Check and decide whether to check for indentation for blockless nodes
934 * Scenarios are for or while statements without braces around them
935 * @param {ASTNode} node node to examine
936 * @returns {void}
937 */
938 function blockLessNodes(node) {
939 if (node.body.type !== "BlockStatement") {
940 blockIndentationCheck(node);
941 }
942 }
943
944 /**
945 * Returns the expected indentation for the case statement
946 * @param {ASTNode} node node to examine
947 * @param {int} [providedSwitchIndent] indent for switch statement
948 * @returns {int} indent size
949 */
950 function expectedCaseIndent(node, providedSwitchIndent) {
951 const switchNode = (node.type === "SwitchStatement") ? node : node.parent;
952 const switchIndent = typeof providedSwitchIndent === "undefined"
953 ? getNodeIndent(switchNode).goodChar
954 : providedSwitchIndent;
955 let caseIndent;
956
957 if (caseIndentStore[switchNode.loc.start.line]) {
958 return caseIndentStore[switchNode.loc.start.line];
959 }
960
961 if (switchNode.cases.length > 0 && options.SwitchCase === 0) {
962 caseIndent = switchIndent;
963 } else {
964 caseIndent = switchIndent + (indentSize * options.SwitchCase);
965 }
966
967 caseIndentStore[switchNode.loc.start.line] = caseIndent;
968 return caseIndent;
969
970 }
971
972 /**
973 * Checks wether a return statement is wrapped in ()
974 * @param {ASTNode} node node to examine
975 * @returns {boolean} the result
976 */
977 function isWrappedInParenthesis(node) {
978 const regex = /^return\s*?\(\s*?\);*?/u;
979
980 const statementWithoutArgument = sourceCode.getText(node).replace(
981 sourceCode.getText(node.argument), ""
982 );
983
984 return regex.test(statementWithoutArgument);
985 }
986
987 return {
988 Program(node) {
989 if (node.body.length > 0) {
990
991 // Root nodes should have no indent
992 checkNodesIndent(node.body, getNodeIndent(node).goodChar);
993 }
994 },
995
996 ClassBody: blockIndentationCheck,
997
998 BlockStatement: blockIndentationCheck,
999
1000 WhileStatement: blockLessNodes,
1001
1002 ForStatement: blockLessNodes,
1003
1004 ForInStatement: blockLessNodes,
1005
1006 ForOfStatement: blockLessNodes,
1007
1008 DoWhileStatement: blockLessNodes,
1009
1010 IfStatement(node) {
1011 if (node.consequent.type !== "BlockStatement" && node.consequent.loc.start.line > node.loc.start.line) {
1012 blockIndentationCheck(node);
1013 }
1014 },
1015
1016 VariableDeclaration(node) {
1017 if (node.declarations[node.declarations.length - 1].loc.start.line > node.declarations[0].loc.start.line) {
1018 checkIndentInVariableDeclarations(node);
1019 }
1020 },
1021
1022 ObjectExpression(node) {
1023 checkIndentInArrayOrObjectBlock(node);
1024 },
1025
1026 ArrayExpression(node) {
1027 checkIndentInArrayOrObjectBlock(node);
1028 },
1029
1030 MemberExpression(node) {
1031
1032 if (typeof options.MemberExpression === "undefined") {
1033 return;
1034 }
1035
1036 if (isSingleLineNode(node)) {
1037 return;
1038 }
1039
1040 /*
1041 * The typical layout of variable declarations and assignments
1042 * alter the expectation of correct indentation. Skip them.
1043 * TODO: Add appropriate configuration options for variable
1044 * declarations and assignments.
1045 */
1046 if (getParentNodeByType(node, "VariableDeclarator", ["FunctionExpression", "ArrowFunctionExpression"])) {
1047 return;
1048 }
1049
1050 if (getParentNodeByType(node, "AssignmentExpression", ["FunctionExpression"])) {
1051 return;
1052 }
1053
1054 const propertyIndent = getNodeIndent(node).goodChar + indentSize * options.MemberExpression;
1055
1056 const checkNodes = [node.property];
1057
1058 const dot = sourceCode.getTokenBefore(node.property);
1059
1060 if (dot.type === "Punctuator" && dot.value === ".") {
1061 checkNodes.push(dot);
1062 }
1063
1064 checkNodesIndent(checkNodes, propertyIndent);
1065 },
1066
1067 SwitchStatement(node) {
1068
1069 // Switch is not a 'BlockStatement'
1070 const switchIndent = getNodeIndent(node).goodChar;
1071 const caseIndent = expectedCaseIndent(node, switchIndent);
1072
1073 checkNodesIndent(node.cases, caseIndent);
1074
1075
1076 checkLastNodeLineIndent(node, switchIndent);
1077 },
1078
1079 SwitchCase(node) {
1080
1081 // Skip inline cases
1082 if (isSingleLineNode(node)) {
1083 return;
1084 }
1085 const caseIndent = expectedCaseIndent(node);
1086
1087 checkNodesIndent(node.consequent, caseIndent + indentSize);
1088 },
1089
1090 FunctionDeclaration(node) {
1091 if (isSingleLineNode(node)) {
1092 return;
1093 }
1094 if (options.FunctionDeclaration.parameters === "first" && node.params.length) {
1095 checkNodesIndent(node.params.slice(1), node.params[0].loc.start.column);
1096 } else if (options.FunctionDeclaration.parameters !== null) {
1097 checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionDeclaration.parameters);
1098 }
1099 },
1100
1101 FunctionExpression(node) {
1102 if (isSingleLineNode(node)) {
1103 return;
1104 }
1105 if (options.FunctionExpression.parameters === "first" && node.params.length) {
1106 checkNodesIndent(node.params.slice(1), node.params[0].loc.start.column);
1107 } else if (options.FunctionExpression.parameters !== null) {
1108 checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionExpression.parameters);
1109 }
1110 },
1111
1112 ReturnStatement(node) {
1113 if (isSingleLineNode(node)) {
1114 return;
1115 }
1116
1117 const firstLineIndent = getNodeIndent(node).goodChar;
1118
1119 // in case if return statement is wrapped in parenthesis
1120 if (isWrappedInParenthesis(node)) {
1121 checkLastReturnStatementLineIndent(node, firstLineIndent);
1122 } else {
1123 checkNodeIndent(node, firstLineIndent);
1124 }
1125 },
1126
1127 CallExpression(node) {
1128 if (isSingleLineNode(node)) {
1129 return;
1130 }
1131 if (options.CallExpression.arguments === "first" && node.arguments.length) {
1132 checkNodesIndent(node.arguments.slice(1), node.arguments[0].loc.start.column);
1133 } else if (options.CallExpression.arguments !== null) {
1134 checkNodesIndent(node.arguments, getNodeIndent(node).goodChar + indentSize * options.CallExpression.arguments);
1135 }
1136 }
1137
1138 };
1139
1140 }
1141};