UNPKG

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