UNPKG

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