1 | /**
|
2 | * @fileoverview This option sets a specific tab width for your code
|
3 | *
|
4 | * @author Teddy Katz
|
5 | * @author Vitaly Puzrin
|
6 | * @author Gyandeep Singh
|
7 | */
|
8 |
|
9 | ;
|
10 |
|
11 | //------------------------------------------------------------------------------
|
12 | // Requirements
|
13 | //------------------------------------------------------------------------------
|
14 |
|
15 | const lodash = require("lodash");
|
16 | const astUtils = require("../ast-utils");
|
17 | const createTree = require("functional-red-black-tree");
|
18 |
|
19 | //------------------------------------------------------------------------------
|
20 | // Rule Definition
|
21 | //------------------------------------------------------------------------------
|
22 |
|
23 | const KNOWN_NODES = new Set([
|
24 | "AssignmentExpression",
|
25 | "AssignmentPattern",
|
26 | "ArrayExpression",
|
27 | "ArrayPattern",
|
28 | "ArrowFunctionExpression",
|
29 | "AwaitExpression",
|
30 | "BlockStatement",
|
31 | "BinaryExpression",
|
32 | "BreakStatement",
|
33 | "CallExpression",
|
34 | "CatchClause",
|
35 | "ClassBody",
|
36 | "ClassDeclaration",
|
37 | "ClassExpression",
|
38 | "ConditionalExpression",
|
39 | "ContinueStatement",
|
40 | "DoWhileStatement",
|
41 | "DebuggerStatement",
|
42 | "EmptyStatement",
|
43 | "ExperimentalRestProperty",
|
44 | "ExperimentalSpreadProperty",
|
45 | "ExpressionStatement",
|
46 | "ForStatement",
|
47 | "ForInStatement",
|
48 | "ForOfStatement",
|
49 | "FunctionDeclaration",
|
50 | "FunctionExpression",
|
51 | "Identifier",
|
52 | "IfStatement",
|
53 | "Literal",
|
54 | "LabeledStatement",
|
55 | "LogicalExpression",
|
56 | "MemberExpression",
|
57 | "MetaProperty",
|
58 | "MethodDefinition",
|
59 | "NewExpression",
|
60 | "ObjectExpression",
|
61 | "ObjectPattern",
|
62 | "Program",
|
63 | "Property",
|
64 | "RestElement",
|
65 | "ReturnStatement",
|
66 | "SequenceExpression",
|
67 | "SpreadElement",
|
68 | "Super",
|
69 | "SwitchCase",
|
70 | "SwitchStatement",
|
71 | "TaggedTemplateExpression",
|
72 | "TemplateElement",
|
73 | "TemplateLiteral",
|
74 | "ThisExpression",
|
75 | "ThrowStatement",
|
76 | "TryStatement",
|
77 | "UnaryExpression",
|
78 | "UpdateExpression",
|
79 | "VariableDeclaration",
|
80 | "VariableDeclarator",
|
81 | "WhileStatement",
|
82 | "WithStatement",
|
83 | "YieldExpression",
|
84 | "JSXIdentifier",
|
85 | "JSXNamespacedName",
|
86 | "JSXMemberExpression",
|
87 | "JSXEmptyExpression",
|
88 | "JSXExpressionContainer",
|
89 | "JSXElement",
|
90 | "JSXClosingElement",
|
91 | "JSXOpeningElement",
|
92 | "JSXAttribute",
|
93 | "JSXSpreadAttribute",
|
94 | "JSXText",
|
95 | "ExportDefaultDeclaration",
|
96 | "ExportNamedDeclaration",
|
97 | "ExportAllDeclaration",
|
98 | "ExportSpecifier",
|
99 | "ImportDeclaration",
|
100 | "ImportSpecifier",
|
101 | "ImportDefaultSpecifier",
|
102 | "ImportNamespaceSpecifier"
|
103 | ]);
|
104 |
|
105 | /*
|
106 | * General rule strategy:
|
107 | * 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another
|
108 | * specified token or to the first column.
|
109 | * 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a
|
110 | * BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly
|
111 | * brace of the BlockStatement.
|
112 | * 3. After traversing the AST, calculate the expected indentation levels of every token according to the
|
113 | * OffsetStorage container.
|
114 | * 4. For each line, compare the expected indentation of the first token to the actual indentation in the file,
|
115 | * and report the token if the two values are not equal.
|
116 | */
|
117 |
|
118 |
|
119 | /**
|
120 | * A mutable balanced binary search tree that stores (key, value) pairs. The keys are numeric, and must be unique.
|
121 | * This is intended to be a generic wrapper around a balanced binary search tree library, so that the underlying implementation
|
122 | * can easily be swapped out.
|
123 | */
|
124 | class BinarySearchTree {
|
125 |
|
126 | /**
|
127 | * Creates an empty tree
|
128 | */
|
129 | constructor() {
|
130 | this._rbTree = createTree();
|
131 | }
|
132 |
|
133 | /**
|
134 | * Inserts an entry into the tree.
|
135 | * @param {number} key The entry's key
|
136 | * @param {*} value The entry's value
|
137 | * @returns {void}
|
138 | */
|
139 | insert(key, value) {
|
140 | const iterator = this._rbTree.find(key);
|
141 |
|
142 | if (iterator.valid) {
|
143 | this._rbTree = iterator.update(value);
|
144 | } else {
|
145 | this._rbTree = this._rbTree.insert(key, value);
|
146 | }
|
147 | }
|
148 |
|
149 | /**
|
150 | * Finds the entry with the largest key less than or equal to the provided key
|
151 | * @param {number} key The provided key
|
152 | * @returns {{key: number, value: *}|null} The found entry, or null if no such entry exists.
|
153 | */
|
154 | findLe(key) {
|
155 | const iterator = this._rbTree.le(key);
|
156 |
|
157 | return iterator && { key: iterator.key, value: iterator.value };
|
158 | }
|
159 |
|
160 | /**
|
161 | * Deletes all of the keys in the interval [start, end)
|
162 | * @param {number} start The start of the range
|
163 | * @param {number} end The end of the range
|
164 | * @returns {void}
|
165 | */
|
166 | deleteRange(start, end) {
|
167 |
|
168 | // Exit without traversing the tree if the range has zero size.
|
169 | if (start === end) {
|
170 | return;
|
171 | }
|
172 | const iterator = this._rbTree.ge(start);
|
173 |
|
174 | while (iterator.valid && iterator.key < end) {
|
175 | this._rbTree = this._rbTree.remove(iterator.key);
|
176 | iterator.next();
|
177 | }
|
178 | }
|
179 | }
|
180 |
|
181 | /**
|
182 | * A helper class to get token-based info related to indentation
|
183 | */
|
184 | class TokenInfo {
|
185 |
|
186 | /**
|
187 | * @param {SourceCode} sourceCode A SourceCode object
|
188 | */
|
189 | constructor(sourceCode) {
|
190 | this.sourceCode = sourceCode;
|
191 | this.firstTokensByLineNumber = sourceCode.tokensAndComments.reduce((map, token) => {
|
192 | if (!map.has(token.loc.start.line)) {
|
193 | map.set(token.loc.start.line, token);
|
194 | }
|
195 | if (!map.has(token.loc.end.line) && sourceCode.text.slice(token.range[1] - token.loc.end.column, token.range[1]).trim()) {
|
196 | map.set(token.loc.end.line, token);
|
197 | }
|
198 | return map;
|
199 | }, new Map());
|
200 | }
|
201 |
|
202 | /**
|
203 | * Gets the first token on a given token's line
|
204 | * @param {Token|ASTNode} token a node or token
|
205 | * @returns {Token} The first token on the given line
|
206 | */
|
207 | getFirstTokenOfLine(token) {
|
208 | return this.firstTokensByLineNumber.get(token.loc.start.line);
|
209 | }
|
210 |
|
211 | /**
|
212 | * Determines whether a token is the first token in its line
|
213 | * @param {Token} token The token
|
214 | * @returns {boolean} `true` if the token is the first on its line
|
215 | */
|
216 | isFirstTokenOfLine(token) {
|
217 | return this.getFirstTokenOfLine(token) === token;
|
218 | }
|
219 |
|
220 | /**
|
221 | * Get the actual indent of a token
|
222 | * @param {Token} token Token to examine. This should be the first token on its line.
|
223 | * @returns {string} The indentation characters that precede the token
|
224 | */
|
225 | getTokenIndent(token) {
|
226 | return this.sourceCode.text.slice(token.range[0] - token.loc.start.column, token.range[0]);
|
227 | }
|
228 | }
|
229 |
|
230 | /**
|
231 | * A class to store information on desired offsets of tokens from each other
|
232 | */
|
233 | class OffsetStorage {
|
234 |
|
235 | /**
|
236 | * @param {TokenInfo} tokenInfo a TokenInfo instance
|
237 | * @param {number} indentSize The desired size of each indentation level
|
238 | * @param {string} indentType The indentation character
|
239 | */
|
240 | constructor(tokenInfo, indentSize, indentType) {
|
241 | this._tokenInfo = tokenInfo;
|
242 | this._indentSize = indentSize;
|
243 | this._indentType = indentType;
|
244 |
|
245 | this._tree = new BinarySearchTree();
|
246 | this._tree.insert(0, { offset: 0, from: null, force: false });
|
247 |
|
248 | this._lockedFirstTokens = new WeakMap();
|
249 | this._desiredIndentCache = new WeakMap();
|
250 | this._ignoredTokens = new WeakSet();
|
251 | }
|
252 |
|
253 | _getOffsetDescriptor(token) {
|
254 | return this._tree.findLe(token.range[0]).value;
|
255 | }
|
256 |
|
257 | /**
|
258 | * Sets the offset column of token B to match the offset column of token A.
|
259 | * **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In
|
260 | * most cases, `setDesiredOffset` should be used instead.
|
261 | * @param {Token} baseToken The first token
|
262 | * @param {Token} offsetToken The second token, whose offset should be matched to the first token
|
263 | * @returns {void}
|
264 | */
|
265 | matchOffsetOf(baseToken, offsetToken) {
|
266 |
|
267 | /*
|
268 | * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to
|
269 | * the token that it depends on. For example, with the `ArrayExpression: first` option, the first
|
270 | * token of each element in the array after the first will be mapped to the first token of the first
|
271 | * element. The desired indentation of each of these tokens is computed based on the desired indentation
|
272 | * of the "first" element, rather than through the normal offset mechanism.
|
273 | */
|
274 | this._lockedFirstTokens.set(offsetToken, baseToken);
|
275 | }
|
276 |
|
277 | /**
|
278 | * Sets the desired offset of a token.
|
279 | *
|
280 | * This uses a line-based offset collapsing behavior to handle tokens on the same line.
|
281 | * For example, consider the following two cases:
|
282 | *
|
283 | * (
|
284 | * [
|
285 | * bar
|
286 | * ]
|
287 | * )
|
288 | *
|
289 | * ([
|
290 | * bar
|
291 | * ])
|
292 | *
|
293 | * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from
|
294 | * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is
|
295 | * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces)
|
296 | * from the start of its line.
|
297 | *
|
298 | * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level
|
299 | * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the
|
300 | * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented
|
301 | * by 1 indent level from the start of the line.
|
302 | *
|
303 | * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node,
|
304 | * without needing to check which lines those tokens are on.
|
305 | *
|
306 | * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive
|
307 | * behavior can occur. For example, consider the following cases:
|
308 | *
|
309 | * foo(
|
310 | * ).
|
311 | * bar(
|
312 | * baz
|
313 | * )
|
314 | *
|
315 | * foo(
|
316 | * ).bar(
|
317 | * baz
|
318 | * )
|
319 | *
|
320 | * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz`
|
321 | * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz`
|
322 | * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no
|
323 | * collapsing would occur).
|
324 | *
|
325 | * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and
|
326 | * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed
|
327 | * in the second case.
|
328 | *
|
329 | * @param {Token} token The token
|
330 | * @param {Token} fromToken The token that `token` should be offset from
|
331 | * @param {number} offset The desired indent level
|
332 | * @returns {void}
|
333 | */
|
334 | setDesiredOffset(token, fromToken, offset) {
|
335 | return this.setDesiredOffsets(token.range, fromToken, offset);
|
336 | }
|
337 |
|
338 | /**
|
339 | * Sets the desired offset of all tokens in a range
|
340 | * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens.
|
341 | * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains
|
342 | * it). This means that the offset of each token is updated O(AST depth) times.
|
343 | * It would not be performant to store and update the offsets for each token independently, because the rule would end
|
344 | * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files.
|
345 | *
|
346 | * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following
|
347 | * list could represent the state of the offset tree at a given point:
|
348 | *
|
349 | * * Tokens starting in the interval [0, 15) are aligned with the beginning of the file
|
350 | * * Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token
|
351 | * * Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token
|
352 | * * Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token
|
353 | * * Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token
|
354 | *
|
355 | * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using:
|
356 | * `setDesiredOffsets([30, 43], fooToken, 1);`
|
357 | *
|
358 | * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied.
|
359 | * @param {Token} fromToken The token that this is offset from
|
360 | * @param {number} offset The desired indent level
|
361 | * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false.
|
362 | * @returns {void}
|
363 | */
|
364 | setDesiredOffsets(range, fromToken, offset, force) {
|
365 |
|
366 | /*
|
367 | * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset
|
368 | * descriptor. The tree for the example above would have the following nodes:
|
369 | *
|
370 | * * key: 0, value: { offset: 0, from: null }
|
371 | * * key: 15, value: { offset: 1, from: barToken }
|
372 | * * key: 30, value: { offset: 1, from: fooToken }
|
373 | * * key: 43, value: { offset: 2, from: barToken }
|
374 | * * key: 820, value: { offset: 1, from: bazToken }
|
375 | *
|
376 | * To find the offset descriptor for any given token, one needs to find the node with the largest key
|
377 | * which is <= token.start. To make this operation fast, the nodes are stored in a balanced binary
|
378 | * search tree indexed by key.
|
379 | */
|
380 |
|
381 | const descriptorToInsert = { offset, from: fromToken, force };
|
382 |
|
383 | const descriptorAfterRange = this._tree.findLe(range[1]).value;
|
384 |
|
385 | const fromTokenIsInRange = fromToken && fromToken.range[0] >= range[0] && fromToken.range[1] <= range[1];
|
386 | const fromTokenDescriptor = fromTokenIsInRange && this._getOffsetDescriptor(fromToken);
|
387 |
|
388 | // First, remove any existing nodes in the range from the tree.
|
389 | this._tree.deleteRange(range[0] + 1, range[1]);
|
390 |
|
391 | // Insert a new node into the tree for this range
|
392 | this._tree.insert(range[0], descriptorToInsert);
|
393 |
|
394 | /*
|
395 | * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously,
|
396 | * even if it's in the current range.
|
397 | */
|
398 | if (fromTokenIsInRange) {
|
399 | this._tree.insert(fromToken.range[0], fromTokenDescriptor);
|
400 | this._tree.insert(fromToken.range[1], descriptorToInsert);
|
401 | }
|
402 |
|
403 | /*
|
404 | * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following
|
405 | * tokens the same as it was before.
|
406 | */
|
407 | this._tree.insert(range[1], descriptorAfterRange);
|
408 | }
|
409 |
|
410 | /**
|
411 | * Gets the desired indent of a token
|
412 | * @param {Token} token The token
|
413 | * @returns {string} The desired indent of the token
|
414 | */
|
415 | getDesiredIndent(token) {
|
416 | if (!this._desiredIndentCache.has(token)) {
|
417 |
|
418 | if (this._ignoredTokens.has(token)) {
|
419 |
|
420 | /*
|
421 | * If the token is ignored, use the actual indent of the token as the desired indent.
|
422 | * This ensures that no errors are reported for this token.
|
423 | */
|
424 | this._desiredIndentCache.set(
|
425 | token,
|
426 | this._tokenInfo.getTokenIndent(token)
|
427 | );
|
428 | } else if (this._lockedFirstTokens.has(token)) {
|
429 | const firstToken = this._lockedFirstTokens.get(token);
|
430 |
|
431 | this._desiredIndentCache.set(
|
432 | token,
|
433 |
|
434 | // (indentation for the first element's line)
|
435 | this.getDesiredIndent(this._tokenInfo.getFirstTokenOfLine(firstToken)) +
|
436 |
|
437 | // (space between the start of the first element's line and the first element)
|
438 | this._indentType.repeat(firstToken.loc.start.column - this._tokenInfo.getFirstTokenOfLine(firstToken).loc.start.column)
|
439 | );
|
440 | } else {
|
441 | const offsetInfo = this._getOffsetDescriptor(token);
|
442 | const offset = (
|
443 | offsetInfo.from &&
|
444 | offsetInfo.from.loc.start.line === token.loc.start.line &&
|
445 | !/^\s*?\n/.test(token.value) &&
|
446 | !offsetInfo.force
|
447 | ) ? 0 : offsetInfo.offset * this._indentSize;
|
448 |
|
449 | this._desiredIndentCache.set(
|
450 | token,
|
451 | (offsetInfo.from ? this.getDesiredIndent(offsetInfo.from) : "") + this._indentType.repeat(offset)
|
452 | );
|
453 | }
|
454 | }
|
455 | return this._desiredIndentCache.get(token);
|
456 | }
|
457 |
|
458 | /**
|
459 | * Ignores a token, preventing it from being reported.
|
460 | * @param {Token} token The token
|
461 | * @returns {void}
|
462 | */
|
463 | ignoreToken(token) {
|
464 | if (this._tokenInfo.isFirstTokenOfLine(token)) {
|
465 | this._ignoredTokens.add(token);
|
466 | }
|
467 | }
|
468 |
|
469 | /**
|
470 | * Gets the first token that the given token's indentation is dependent on
|
471 | * @param {Token} token The token
|
472 | * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level
|
473 | */
|
474 | getFirstDependency(token) {
|
475 | return this._getOffsetDescriptor(token).from;
|
476 | }
|
477 | }
|
478 |
|
479 | const ELEMENT_LIST_SCHEMA = {
|
480 | oneOf: [
|
481 | {
|
482 | type: "integer",
|
483 | minimum: 0
|
484 | },
|
485 | {
|
486 | enum: ["first", "off"]
|
487 | }
|
488 | ]
|
489 | };
|
490 |
|
491 | module.exports = {
|
492 | meta: {
|
493 | docs: {
|
494 | description: "enforce consistent indentation",
|
495 | category: "Stylistic Issues",
|
496 | recommended: false,
|
497 | url: "https://eslint.org/docs/rules/indent"
|
498 | },
|
499 |
|
500 | fixable: "whitespace",
|
501 |
|
502 | schema: [
|
503 | {
|
504 | oneOf: [
|
505 | {
|
506 | enum: ["tab"]
|
507 | },
|
508 | {
|
509 | type: "integer",
|
510 | minimum: 0
|
511 | }
|
512 | ]
|
513 | },
|
514 | {
|
515 | type: "object",
|
516 | properties: {
|
517 | SwitchCase: {
|
518 | type: "integer",
|
519 | minimum: 0
|
520 | },
|
521 | VariableDeclarator: {
|
522 | oneOf: [
|
523 | {
|
524 | type: "integer",
|
525 | minimum: 0
|
526 | },
|
527 | {
|
528 | type: "object",
|
529 | properties: {
|
530 | var: {
|
531 | type: "integer",
|
532 | minimum: 0
|
533 | },
|
534 | let: {
|
535 | type: "integer",
|
536 | minimum: 0
|
537 | },
|
538 | const: {
|
539 | type: "integer",
|
540 | minimum: 0
|
541 | }
|
542 | },
|
543 | additionalProperties: false
|
544 | }
|
545 | ]
|
546 | },
|
547 | outerIIFEBody: {
|
548 | type: "integer",
|
549 | minimum: 0
|
550 | },
|
551 | MemberExpression: {
|
552 | oneOf: [
|
553 | {
|
554 | type: "integer",
|
555 | minimum: 0
|
556 | },
|
557 | {
|
558 | enum: ["off"]
|
559 | }
|
560 | ]
|
561 | },
|
562 | FunctionDeclaration: {
|
563 | type: "object",
|
564 | properties: {
|
565 | parameters: ELEMENT_LIST_SCHEMA,
|
566 | body: {
|
567 | type: "integer",
|
568 | minimum: 0
|
569 | }
|
570 | },
|
571 | additionalProperties: false
|
572 | },
|
573 | FunctionExpression: {
|
574 | type: "object",
|
575 | properties: {
|
576 | parameters: ELEMENT_LIST_SCHEMA,
|
577 | body: {
|
578 | type: "integer",
|
579 | minimum: 0
|
580 | }
|
581 | },
|
582 | additionalProperties: false
|
583 | },
|
584 | CallExpression: {
|
585 | type: "object",
|
586 | properties: {
|
587 | arguments: ELEMENT_LIST_SCHEMA
|
588 | },
|
589 | additionalProperties: false
|
590 | },
|
591 | ArrayExpression: ELEMENT_LIST_SCHEMA,
|
592 | ObjectExpression: ELEMENT_LIST_SCHEMA,
|
593 | ImportDeclaration: ELEMENT_LIST_SCHEMA,
|
594 | flatTernaryExpressions: {
|
595 | type: "boolean"
|
596 | },
|
597 | ignoredNodes: {
|
598 | type: "array",
|
599 | items: {
|
600 | type: "string",
|
601 | not: {
|
602 | pattern: ":exit$"
|
603 | }
|
604 | }
|
605 | },
|
606 | ignoreComments: {
|
607 | type: "boolean"
|
608 | }
|
609 | },
|
610 | additionalProperties: false
|
611 | }
|
612 | ]
|
613 | },
|
614 |
|
615 | create(context) {
|
616 | const DEFAULT_VARIABLE_INDENT = 1;
|
617 | const DEFAULT_PARAMETER_INDENT = 1;
|
618 | const DEFAULT_FUNCTION_BODY_INDENT = 1;
|
619 |
|
620 | let indentType = "space";
|
621 | let indentSize = 4;
|
622 | const options = {
|
623 | SwitchCase: 0,
|
624 | VariableDeclarator: {
|
625 | var: DEFAULT_VARIABLE_INDENT,
|
626 | let: DEFAULT_VARIABLE_INDENT,
|
627 | const: DEFAULT_VARIABLE_INDENT
|
628 | },
|
629 | outerIIFEBody: 1,
|
630 | FunctionDeclaration: {
|
631 | parameters: DEFAULT_PARAMETER_INDENT,
|
632 | body: DEFAULT_FUNCTION_BODY_INDENT
|
633 | },
|
634 | FunctionExpression: {
|
635 | parameters: DEFAULT_PARAMETER_INDENT,
|
636 | body: DEFAULT_FUNCTION_BODY_INDENT
|
637 | },
|
638 | CallExpression: {
|
639 | arguments: DEFAULT_PARAMETER_INDENT
|
640 | },
|
641 | MemberExpression: 1,
|
642 | ArrayExpression: 1,
|
643 | ObjectExpression: 1,
|
644 | ImportDeclaration: 1,
|
645 | flatTernaryExpressions: false,
|
646 | ignoredNodes: [],
|
647 | ignoreComments: false
|
648 | };
|
649 |
|
650 | if (context.options.length) {
|
651 | if (context.options[0] === "tab") {
|
652 | indentSize = 1;
|
653 | indentType = "tab";
|
654 | } else {
|
655 | indentSize = context.options[0];
|
656 | indentType = "space";
|
657 | }
|
658 |
|
659 | if (context.options[1]) {
|
660 | lodash.merge(options, context.options[1]);
|
661 |
|
662 | if (typeof options.VariableDeclarator === "number") {
|
663 | options.VariableDeclarator = {
|
664 | var: options.VariableDeclarator,
|
665 | let: options.VariableDeclarator,
|
666 | const: options.VariableDeclarator
|
667 | };
|
668 | }
|
669 | }
|
670 | }
|
671 |
|
672 | const sourceCode = context.getSourceCode();
|
673 | const tokenInfo = new TokenInfo(sourceCode);
|
674 | const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t");
|
675 | const parameterParens = new WeakSet();
|
676 |
|
677 | /**
|
678 | * Creates an error message for a line, given the expected/actual indentation.
|
679 | * @param {int} expectedAmount The expected amount of indentation characters for this line
|
680 | * @param {int} actualSpaces The actual number of indentation spaces that were found on this line
|
681 | * @param {int} actualTabs The actual number of indentation tabs that were found on this line
|
682 | * @returns {string} An error message for this line
|
683 | */
|
684 | function createErrorMessage(expectedAmount, actualSpaces, actualTabs) {
|
685 | const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs"
|
686 | const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space"
|
687 | const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs"
|
688 | let foundStatement;
|
689 |
|
690 | if (actualSpaces > 0) {
|
691 |
|
692 | /*
|
693 | * Abbreviate the message if the expected indentation is also spaces.
|
694 | * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
|
695 | */
|
696 | foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`;
|
697 | } else if (actualTabs > 0) {
|
698 | foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`;
|
699 | } else {
|
700 | foundStatement = "0";
|
701 | }
|
702 |
|
703 | return `Expected indentation of ${expectedStatement} but found ${foundStatement}.`;
|
704 | }
|
705 |
|
706 | /**
|
707 | * Reports a given indent violation
|
708 | * @param {Token} token Token violating the indent rule
|
709 | * @param {string} neededIndent Expected indentation string
|
710 | * @returns {void}
|
711 | */
|
712 | function report(token, neededIndent) {
|
713 | const actualIndent = Array.from(tokenInfo.getTokenIndent(token));
|
714 | const numSpaces = actualIndent.filter(char => char === " ").length;
|
715 | const numTabs = actualIndent.filter(char => char === "\t").length;
|
716 |
|
717 | context.report({
|
718 | node: token,
|
719 | message: createErrorMessage(neededIndent.length, numSpaces, numTabs),
|
720 | loc: {
|
721 | start: { line: token.loc.start.line, column: 0 },
|
722 | end: { line: token.loc.start.line, column: token.loc.start.column }
|
723 | },
|
724 | fix(fixer) {
|
725 | const range = [token.range[0] - token.loc.start.column, token.range[0]];
|
726 | const newText = neededIndent;
|
727 |
|
728 | return fixer.replaceTextRange(range, newText);
|
729 | }
|
730 | });
|
731 | }
|
732 |
|
733 | /**
|
734 | * Checks if a token's indentation is correct
|
735 | * @param {Token} token Token to examine
|
736 | * @param {string} desiredIndent Desired indentation of the string
|
737 | * @returns {boolean} `true` if the token's indentation is correct
|
738 | */
|
739 | function validateTokenIndent(token, desiredIndent) {
|
740 | const indentation = tokenInfo.getTokenIndent(token);
|
741 |
|
742 | return indentation === desiredIndent ||
|
743 |
|
744 | // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
|
745 | indentation.includes(" ") && indentation.includes("\t");
|
746 | }
|
747 |
|
748 | /**
|
749 | * Check to see if the node is a file level IIFE
|
750 | * @param {ASTNode} node The function node to check.
|
751 | * @returns {boolean} True if the node is the outer IIFE
|
752 | */
|
753 | function isOuterIIFE(node) {
|
754 |
|
755 | /*
|
756 | * Verify that the node is an IIFE
|
757 | */
|
758 | if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) {
|
759 | return false;
|
760 | }
|
761 |
|
762 | /*
|
763 | * Navigate legal ancestors to determine whether this IIFE is outer.
|
764 | * A "legal ancestor" is an expression or statement that causes the function to get executed immediately.
|
765 | * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator.
|
766 | */
|
767 | let statement = node.parent && node.parent.parent;
|
768 |
|
769 | while (
|
770 | statement.type === "UnaryExpression" && ["!", "~", "+", "-"].indexOf(statement.operator) > -1 ||
|
771 | statement.type === "AssignmentExpression" ||
|
772 | statement.type === "LogicalExpression" ||
|
773 | statement.type === "SequenceExpression" ||
|
774 | statement.type === "VariableDeclarator"
|
775 | ) {
|
776 | statement = statement.parent;
|
777 | }
|
778 |
|
779 | return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program";
|
780 | }
|
781 |
|
782 | /**
|
783 | * Counts the number of linebreaks that follow the last non-whitespace character in a string
|
784 | * @param {string} string The string to check
|
785 | * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character,
|
786 | * or the total number of linebreaks if the string is all whitespace.
|
787 | */
|
788 | function countTrailingLinebreaks(string) {
|
789 | const trailingWhitespace = string.match(/\s*$/)[0];
|
790 | const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher());
|
791 |
|
792 | return linebreakMatches === null ? 0 : linebreakMatches.length;
|
793 | }
|
794 |
|
795 | /**
|
796 | * Check indentation for lists of elements (arrays, objects, function params)
|
797 | * @param {ASTNode[]} elements List of elements that should be offset
|
798 | * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '['
|
799 | * @param {Token} endToken The end token of the list, e.g. ']'
|
800 | * @param {number|string} offset The amount that the elements should be offset
|
801 | * @returns {void}
|
802 | */
|
803 | function addElementListIndent(elements, startToken, endToken, offset) {
|
804 |
|
805 | /**
|
806 | * Gets the first token of a given element, including surrounding parentheses.
|
807 | * @param {ASTNode} element A node in the `elements` list
|
808 | * @returns {Token} The first token of this element
|
809 | */
|
810 | function getFirstToken(element) {
|
811 | let token = sourceCode.getTokenBefore(element);
|
812 |
|
813 | while (astUtils.isOpeningParenToken(token) && token !== startToken) {
|
814 | token = sourceCode.getTokenBefore(token);
|
815 | }
|
816 | return sourceCode.getTokenAfter(token);
|
817 | }
|
818 |
|
819 | // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden)
|
820 | offsets.setDesiredOffsets(
|
821 | [startToken.range[1], endToken.range[0]],
|
822 | startToken,
|
823 | typeof offset === "number" ? offset : 1
|
824 | );
|
825 | offsets.setDesiredOffset(endToken, startToken, 0);
|
826 |
|
827 | // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level.
|
828 | if (offset === "first" && elements.length && !elements[0]) {
|
829 | return;
|
830 | }
|
831 | elements.forEach((element, index) => {
|
832 | if (!element) {
|
833 |
|
834 | // Skip holes in arrays
|
835 | return;
|
836 | }
|
837 | if (offset === "off") {
|
838 |
|
839 | // Ignore the first token of every element if the "off" option is used
|
840 | offsets.ignoreToken(getFirstToken(element));
|
841 | }
|
842 |
|
843 | // Offset the following elements correctly relative to the first element
|
844 | if (index === 0) {
|
845 | return;
|
846 | }
|
847 | if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) {
|
848 | offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element));
|
849 | } else {
|
850 | const previousElement = elements[index - 1];
|
851 | const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement);
|
852 | const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement);
|
853 |
|
854 | if (
|
855 | previousElement &&
|
856 | previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line
|
857 | ) {
|
858 | offsets.setDesiredOffsets(element.range, firstTokenOfPreviousElement, 0);
|
859 | }
|
860 | }
|
861 | });
|
862 | }
|
863 |
|
864 | /**
|
865 | * Check and decide whether to check for indentation for blockless nodes
|
866 | * Scenarios are for or while statements without braces around them
|
867 | * @param {ASTNode} node node to examine
|
868 | * @returns {void}
|
869 | */
|
870 | function addBlocklessNodeIndent(node) {
|
871 | if (node.type !== "BlockStatement") {
|
872 | const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken);
|
873 |
|
874 | let firstBodyToken = sourceCode.getFirstToken(node);
|
875 | let lastBodyToken = sourceCode.getLastToken(node);
|
876 |
|
877 | while (
|
878 | astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) &&
|
879 | astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken))
|
880 | ) {
|
881 | firstBodyToken = sourceCode.getTokenBefore(firstBodyToken);
|
882 | lastBodyToken = sourceCode.getTokenAfter(lastBodyToken);
|
883 | }
|
884 |
|
885 | offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
|
886 |
|
887 | /*
|
888 | * For blockless nodes with semicolon-first style, don't indent the semicolon.
|
889 | * e.g.
|
890 | * if (foo) bar()
|
891 | * ; [1, 2, 3].map(foo)
|
892 | */
|
893 | const lastToken = sourceCode.getLastToken(node);
|
894 |
|
895 | if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) {
|
896 | offsets.setDesiredOffset(lastToken, lastParentToken, 0);
|
897 | }
|
898 | }
|
899 | }
|
900 |
|
901 | /**
|
902 | * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`)
|
903 | * @param {ASTNode} node A CallExpression or NewExpression node
|
904 | * @returns {void}
|
905 | */
|
906 | function addFunctionCallIndent(node) {
|
907 | let openingParen;
|
908 |
|
909 | if (node.arguments.length) {
|
910 | openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken);
|
911 | } else {
|
912 | openingParen = sourceCode.getLastToken(node, 1);
|
913 | }
|
914 | const closingParen = sourceCode.getLastToken(node);
|
915 |
|
916 | parameterParens.add(openingParen);
|
917 | parameterParens.add(closingParen);
|
918 | offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0);
|
919 |
|
920 | addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments);
|
921 | }
|
922 |
|
923 | /**
|
924 | * Checks the indentation of parenthesized values, given a list of tokens in a program
|
925 | * @param {Token[]} tokens A list of tokens
|
926 | * @returns {void}
|
927 | */
|
928 | function addParensIndent(tokens) {
|
929 | const parenStack = [];
|
930 | const parenPairs = [];
|
931 |
|
932 | tokens.forEach(nextToken => {
|
933 |
|
934 | // Accumulate a list of parenthesis pairs
|
935 | if (astUtils.isOpeningParenToken(nextToken)) {
|
936 | parenStack.push(nextToken);
|
937 | } else if (astUtils.isClosingParenToken(nextToken)) {
|
938 | parenPairs.unshift({ left: parenStack.pop(), right: nextToken });
|
939 | }
|
940 | });
|
941 |
|
942 | parenPairs.forEach(pair => {
|
943 | const leftParen = pair.left;
|
944 | const rightParen = pair.right;
|
945 |
|
946 | // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.
|
947 | if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) {
|
948 | const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen));
|
949 |
|
950 | parenthesizedTokens.forEach(token => {
|
951 | if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) {
|
952 | offsets.setDesiredOffset(token, leftParen, 1);
|
953 | }
|
954 | });
|
955 | }
|
956 |
|
957 | offsets.setDesiredOffset(rightParen, leftParen, 0);
|
958 | });
|
959 | }
|
960 |
|
961 | /**
|
962 | * Ignore all tokens within an unknown node whose offset do not depend
|
963 | * on another token's offset within the unknown node
|
964 | * @param {ASTNode} node Unknown Node
|
965 | * @returns {void}
|
966 | */
|
967 | function ignoreNode(node) {
|
968 | const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true }));
|
969 |
|
970 | unknownNodeTokens.forEach(token => {
|
971 | if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) {
|
972 | const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token);
|
973 |
|
974 | if (token === firstTokenOfLine) {
|
975 | offsets.ignoreToken(token);
|
976 | } else {
|
977 | offsets.setDesiredOffset(token, firstTokenOfLine, 0);
|
978 | }
|
979 | }
|
980 | });
|
981 | }
|
982 |
|
983 | /**
|
984 | * Check whether the given token is on the first line of a statement.
|
985 | * @param {Token} token The token to check.
|
986 | * @param {ASTNode} leafNode The expression node that the token belongs directly.
|
987 | * @returns {boolean} `true` if the token is on the first line of a statement.
|
988 | */
|
989 | function isOnFirstLineOfStatement(token, leafNode) {
|
990 | let node = leafNode;
|
991 |
|
992 | while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) {
|
993 | node = node.parent;
|
994 | }
|
995 | node = node.parent;
|
996 |
|
997 | return !node || node.loc.start.line === token.loc.start.line;
|
998 | }
|
999 |
|
1000 | const ignoredNodeFirstTokens = new Set();
|
1001 |
|
1002 | const baseOffsetListeners = {
|
1003 | "ArrayExpression, ArrayPattern"(node) {
|
1004 | const openingBracket = sourceCode.getFirstToken(node);
|
1005 | const closingBracket = sourceCode.getTokenAfter(lodash.findLast(node.elements) || openingBracket, astUtils.isClosingBracketToken);
|
1006 |
|
1007 | addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression);
|
1008 | },
|
1009 |
|
1010 | "ObjectExpression, ObjectPattern"(node) {
|
1011 | const openingCurly = sourceCode.getFirstToken(node);
|
1012 | const closingCurly = sourceCode.getTokenAfter(
|
1013 | node.properties.length ? node.properties[node.properties.length - 1] : openingCurly,
|
1014 | astUtils.isClosingBraceToken
|
1015 | );
|
1016 |
|
1017 | addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression);
|
1018 | },
|
1019 |
|
1020 | ArrowFunctionExpression(node) {
|
1021 | const firstToken = sourceCode.getFirstToken(node);
|
1022 |
|
1023 | if (astUtils.isOpeningParenToken(firstToken)) {
|
1024 | const openingParen = firstToken;
|
1025 | const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken);
|
1026 |
|
1027 | parameterParens.add(openingParen);
|
1028 | parameterParens.add(closingParen);
|
1029 | addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters);
|
1030 | }
|
1031 | addBlocklessNodeIndent(node.body);
|
1032 | },
|
1033 |
|
1034 | AssignmentExpression(node) {
|
1035 | const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
|
1036 |
|
1037 | offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1);
|
1038 | offsets.ignoreToken(operator);
|
1039 | offsets.ignoreToken(sourceCode.getTokenAfter(operator));
|
1040 | },
|
1041 |
|
1042 | "BinaryExpression, LogicalExpression"(node) {
|
1043 | const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
|
1044 |
|
1045 | /*
|
1046 | * For backwards compatibility, don't check BinaryExpression indents, e.g.
|
1047 | * var foo = bar &&
|
1048 | * baz;
|
1049 | */
|
1050 |
|
1051 | const tokenAfterOperator = sourceCode.getTokenAfter(operator);
|
1052 |
|
1053 | offsets.ignoreToken(operator);
|
1054 | offsets.ignoreToken(tokenAfterOperator);
|
1055 | offsets.setDesiredOffset(tokenAfterOperator, operator, 0);
|
1056 | },
|
1057 |
|
1058 | "BlockStatement, ClassBody"(node) {
|
1059 |
|
1060 | let blockIndentLevel;
|
1061 |
|
1062 | if (node.parent && isOuterIIFE(node.parent)) {
|
1063 | blockIndentLevel = options.outerIIFEBody;
|
1064 | } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) {
|
1065 | blockIndentLevel = options.FunctionExpression.body;
|
1066 | } else if (node.parent && node.parent.type === "FunctionDeclaration") {
|
1067 | blockIndentLevel = options.FunctionDeclaration.body;
|
1068 | } else {
|
1069 | blockIndentLevel = 1;
|
1070 | }
|
1071 |
|
1072 | /*
|
1073 | * For blocks that aren't lone statements, ensure that the opening curly brace
|
1074 | * is aligned with the parent.
|
1075 | */
|
1076 | if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
|
1077 | offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0);
|
1078 | }
|
1079 | addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel);
|
1080 | },
|
1081 |
|
1082 | CallExpression: addFunctionCallIndent,
|
1083 |
|
1084 |
|
1085 | "ClassDeclaration[superClass], ClassExpression[superClass]"(node) {
|
1086 | const classToken = sourceCode.getFirstToken(node);
|
1087 | const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken);
|
1088 |
|
1089 | offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1);
|
1090 | },
|
1091 |
|
1092 | ConditionalExpression(node) {
|
1093 | const firstToken = sourceCode.getFirstToken(node);
|
1094 |
|
1095 | // `flatTernaryExpressions` option is for the following style:
|
1096 | // var a =
|
1097 | // foo > 0 ? bar :
|
1098 | // foo < 0 ? baz :
|
1099 | // /*else*/ qiz ;
|
1100 | if (!options.flatTernaryExpressions ||
|
1101 | !astUtils.isTokenOnSameLine(node.test, node.consequent) ||
|
1102 | isOnFirstLineOfStatement(firstToken, node)
|
1103 | ) {
|
1104 | const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?");
|
1105 | const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":");
|
1106 |
|
1107 | const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken);
|
1108 | const lastConsequentToken = sourceCode.getTokenBefore(colonToken);
|
1109 | const firstAlternateToken = sourceCode.getTokenAfter(colonToken);
|
1110 |
|
1111 | offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
|
1112 | offsets.setDesiredOffset(colonToken, firstToken, 1);
|
1113 |
|
1114 | offsets.setDesiredOffset(firstConsequentToken, firstToken, 1);
|
1115 |
|
1116 | /*
|
1117 | * The alternate and the consequent should usually have the same indentation.
|
1118 | * If they share part of a line, align the alternate against the first token of the consequent.
|
1119 | * This allows the alternate to be indented correctly in cases like this:
|
1120 | * foo ? (
|
1121 | * bar
|
1122 | * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo`
|
1123 | * baz // as a result, `baz` is offset by 1 rather than 2
|
1124 | * )
|
1125 | */
|
1126 | if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) {
|
1127 | offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0);
|
1128 | } else {
|
1129 |
|
1130 | /**
|
1131 | * If the alternate and consequent do not share part of a line, offset the alternate from the first
|
1132 | * token of the conditional expression. For example:
|
1133 | * foo ? bar
|
1134 | * : baz
|
1135 | *
|
1136 | * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
|
1137 | * having no expected indentation.
|
1138 | */
|
1139 | offsets.setDesiredOffset(firstAlternateToken, firstToken, 1);
|
1140 | }
|
1141 | }
|
1142 | },
|
1143 |
|
1144 | "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement": node => addBlocklessNodeIndent(node.body),
|
1145 |
|
1146 | ExportNamedDeclaration(node) {
|
1147 | if (node.declaration === null) {
|
1148 | const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
|
1149 |
|
1150 | // Indent the specifiers in `export {foo, bar, baz}`
|
1151 | addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, { skip: 1 }), closingCurly, 1);
|
1152 |
|
1153 | if (node.source) {
|
1154 |
|
1155 | // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'`
|
1156 | offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1);
|
1157 | }
|
1158 | }
|
1159 | },
|
1160 |
|
1161 | ForStatement(node) {
|
1162 | const forOpeningParen = sourceCode.getFirstToken(node, 1);
|
1163 |
|
1164 | if (node.init) {
|
1165 | offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1);
|
1166 | }
|
1167 | if (node.test) {
|
1168 | offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1);
|
1169 | }
|
1170 | if (node.update) {
|
1171 | offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1);
|
1172 | }
|
1173 | addBlocklessNodeIndent(node.body);
|
1174 | },
|
1175 |
|
1176 | "FunctionDeclaration, FunctionExpression"(node) {
|
1177 | const closingParen = sourceCode.getTokenBefore(node.body);
|
1178 | const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen);
|
1179 |
|
1180 | parameterParens.add(openingParen);
|
1181 | parameterParens.add(closingParen);
|
1182 | addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters);
|
1183 | },
|
1184 |
|
1185 | IfStatement(node) {
|
1186 | addBlocklessNodeIndent(node.consequent);
|
1187 | if (node.alternate && node.alternate.type !== "IfStatement") {
|
1188 | addBlocklessNodeIndent(node.alternate);
|
1189 | }
|
1190 | },
|
1191 |
|
1192 | ImportDeclaration(node) {
|
1193 | if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
|
1194 | const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);
|
1195 | const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
|
1196 |
|
1197 | addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration);
|
1198 | }
|
1199 |
|
1200 | const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from");
|
1201 |
|
1202 | if (fromToken) {
|
1203 | offsets.setDesiredOffsets([fromToken.range[0], node.range[1]], sourceCode.getFirstToken(node), 1);
|
1204 | }
|
1205 | },
|
1206 |
|
1207 | "MemberExpression, JSXMemberExpression, MetaProperty"(node) {
|
1208 | const object = node.type === "MetaProperty" ? node.meta : node.object;
|
1209 | const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken);
|
1210 | const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken);
|
1211 |
|
1212 | const objectParenCount = sourceCode.getTokensBetween(object, node.property, { filter: astUtils.isClosingParenToken }).length;
|
1213 | const firstObjectToken = objectParenCount
|
1214 | ? sourceCode.getTokenBefore(object, { skip: objectParenCount - 1 })
|
1215 | : sourceCode.getFirstToken(object);
|
1216 | const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken);
|
1217 | const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken;
|
1218 |
|
1219 | if (node.computed) {
|
1220 |
|
1221 | // For computed MemberExpressions, match the closing bracket with the opening bracket.
|
1222 | offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0);
|
1223 | offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1);
|
1224 | }
|
1225 |
|
1226 | /*
|
1227 | * If the object ends on the same line that the property starts, match against the last token
|
1228 | * of the object, to ensure that the MemberExpression is not indented.
|
1229 | *
|
1230 | * Otherwise, match against the first token of the object, e.g.
|
1231 | * foo
|
1232 | * .bar
|
1233 | * .baz // <-- offset by 1 from `foo`
|
1234 | */
|
1235 | const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line
|
1236 | ? lastObjectToken
|
1237 | : firstObjectToken;
|
1238 |
|
1239 | if (typeof options.MemberExpression === "number") {
|
1240 |
|
1241 | // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object.
|
1242 | offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression);
|
1243 |
|
1244 | /*
|
1245 | * For computed MemberExpressions, match the first token of the property against the opening bracket.
|
1246 | * Otherwise, match the first token of the property against the object.
|
1247 | */
|
1248 | offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression);
|
1249 | } else {
|
1250 |
|
1251 | // If the MemberExpression option is off, ignore the dot and the first token of the property.
|
1252 | offsets.ignoreToken(firstNonObjectToken);
|
1253 | offsets.ignoreToken(secondNonObjectToken);
|
1254 |
|
1255 | // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens.
|
1256 | offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0);
|
1257 | offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0);
|
1258 | }
|
1259 | },
|
1260 |
|
1261 | NewExpression(node) {
|
1262 |
|
1263 | // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo`
|
1264 | if (node.arguments.length > 0 ||
|
1265 | astUtils.isClosingParenToken(sourceCode.getLastToken(node)) &&
|
1266 | astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) {
|
1267 | addFunctionCallIndent(node);
|
1268 | }
|
1269 | },
|
1270 |
|
1271 | Property(node) {
|
1272 | if (!node.shorthand && !node.method && node.kind === "init") {
|
1273 | const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken);
|
1274 |
|
1275 | offsets.ignoreToken(sourceCode.getTokenAfter(colon));
|
1276 | }
|
1277 | },
|
1278 |
|
1279 | SwitchStatement(node) {
|
1280 | const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken);
|
1281 | const closingCurly = sourceCode.getLastToken(node);
|
1282 |
|
1283 | offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase);
|
1284 |
|
1285 | if (node.cases.length) {
|
1286 | sourceCode.getTokensBetween(
|
1287 | node.cases[node.cases.length - 1],
|
1288 | closingCurly,
|
1289 | { includeComments: true, filter: astUtils.isCommentToken }
|
1290 | ).forEach(token => offsets.ignoreToken(token));
|
1291 | }
|
1292 | },
|
1293 |
|
1294 | SwitchCase(node) {
|
1295 | if (!(node.consequent.length === 1 && node.consequent[0].type === "BlockStatement")) {
|
1296 | const caseKeyword = sourceCode.getFirstToken(node);
|
1297 | const tokenAfterCurrentCase = sourceCode.getTokenAfter(node);
|
1298 |
|
1299 | offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1);
|
1300 | }
|
1301 | },
|
1302 |
|
1303 | TemplateLiteral(node) {
|
1304 | node.expressions.forEach((expression, index) => {
|
1305 | const previousQuasi = node.quasis[index];
|
1306 | const nextQuasi = node.quasis[index + 1];
|
1307 | const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line ? sourceCode.getFirstToken(previousQuasi) : null;
|
1308 |
|
1309 | offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1);
|
1310 | offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0);
|
1311 | });
|
1312 | },
|
1313 |
|
1314 | VariableDeclaration(node) {
|
1315 | const variableIndent = options.VariableDeclarator.hasOwnProperty(node.kind) ? options.VariableDeclarator[node.kind] : DEFAULT_VARIABLE_INDENT;
|
1316 |
|
1317 | if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) {
|
1318 |
|
1319 | /*
|
1320 | * VariableDeclarator indentation is a bit different from other forms of indentation, in that the
|
1321 | * indentation of an opening bracket sometimes won't match that of a closing bracket. For example,
|
1322 | * the following indentations are correct:
|
1323 | *
|
1324 | * var foo = {
|
1325 | * ok: true
|
1326 | * };
|
1327 | *
|
1328 | * var foo = {
|
1329 | * ok: true,
|
1330 | * },
|
1331 | * bar = 1;
|
1332 | *
|
1333 | * Account for when exiting the AST (after indentations have already been set for the nodes in
|
1334 | * the declaration) by manually increasing the indentation level of the tokens in this declarator
|
1335 | * on the same line as the start of the declaration, provided that there are declarators that
|
1336 | * follow this one.
|
1337 | */
|
1338 | const firstToken = sourceCode.getFirstToken(node);
|
1339 |
|
1340 | offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true);
|
1341 | } else {
|
1342 | offsets.setDesiredOffsets(node.range, sourceCode.getFirstToken(node), variableIndent);
|
1343 | }
|
1344 | const lastToken = sourceCode.getLastToken(node);
|
1345 |
|
1346 | if (astUtils.isSemicolonToken(lastToken)) {
|
1347 | offsets.ignoreToken(lastToken);
|
1348 | }
|
1349 | },
|
1350 |
|
1351 | VariableDeclarator(node) {
|
1352 | if (node.init) {
|
1353 | const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken);
|
1354 | const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator);
|
1355 |
|
1356 | offsets.ignoreToken(equalOperator);
|
1357 | offsets.ignoreToken(tokenAfterOperator);
|
1358 | offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1);
|
1359 | offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0);
|
1360 | }
|
1361 | },
|
1362 |
|
1363 | "JSXAttribute[value]"(node) {
|
1364 | const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "=");
|
1365 |
|
1366 | offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1);
|
1367 | },
|
1368 |
|
1369 | JSXElement(node) {
|
1370 | if (node.closingElement) {
|
1371 | addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1);
|
1372 | }
|
1373 | },
|
1374 |
|
1375 | JSXOpeningElement(node) {
|
1376 | const firstToken = sourceCode.getFirstToken(node);
|
1377 | let closingToken;
|
1378 |
|
1379 | if (node.selfClosing) {
|
1380 | closingToken = sourceCode.getLastToken(node, { skip: 1 });
|
1381 | offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0);
|
1382 | } else {
|
1383 | closingToken = sourceCode.getLastToken(node);
|
1384 | }
|
1385 | offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node));
|
1386 | addElementListIndent(node.attributes, firstToken, closingToken, 1);
|
1387 | },
|
1388 |
|
1389 | JSXClosingElement(node) {
|
1390 | const firstToken = sourceCode.getFirstToken(node);
|
1391 |
|
1392 | offsets.setDesiredOffsets(node.name.range, firstToken, 1);
|
1393 | },
|
1394 |
|
1395 | JSXExpressionContainer(node) {
|
1396 | const openingCurly = sourceCode.getFirstToken(node);
|
1397 | const closingCurly = sourceCode.getLastToken(node);
|
1398 |
|
1399 | offsets.setDesiredOffsets(
|
1400 | [openingCurly.range[1], closingCurly.range[0]],
|
1401 | openingCurly,
|
1402 | 1
|
1403 | );
|
1404 | },
|
1405 |
|
1406 | "*"(node) {
|
1407 | const firstToken = sourceCode.getFirstToken(node);
|
1408 |
|
1409 | // Ensure that the children of every node are indented at least as much as the first token.
|
1410 | if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) {
|
1411 | offsets.setDesiredOffsets(node.range, firstToken, 0);
|
1412 | }
|
1413 | }
|
1414 | };
|
1415 |
|
1416 | const listenerCallQueue = [];
|
1417 |
|
1418 | /*
|
1419 | * To ignore the indentation of a node:
|
1420 | * 1. Don't call the node's listener when entering it (if it has a listener)
|
1421 | * 2. Don't set any offsets against the first token of the node.
|
1422 | * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets.
|
1423 | */
|
1424 | const offsetListeners = lodash.mapValues(
|
1425 | baseOffsetListeners,
|
1426 |
|
1427 | /*
|
1428 | * Offset listener calls are deferred until traversal is finished, and are called as
|
1429 | * part of the final `Program:exit` listener. This is necessary because a node might
|
1430 | * be matched by multiple selectors.
|
1431 | *
|
1432 | * Example: Suppose there is an offset listener for `Identifier`, and the user has
|
1433 | * specified in configuration that `MemberExpression > Identifier` should be ignored.
|
1434 | * Due to selector specificity rules, the `Identifier` listener will get called first. However,
|
1435 | * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener
|
1436 | * should not have been called at all. Without doing extra selector matching, we don't know
|
1437 | * whether the Identifier matches the `MemberExpression > Identifier` selector until the
|
1438 | * `MemberExpression > Identifier` listener is called.
|
1439 | *
|
1440 | * To avoid this, the `Identifier` listener isn't called until traversal finishes and all
|
1441 | * ignored nodes are known.
|
1442 | */
|
1443 | listener =>
|
1444 | node =>
|
1445 | listenerCallQueue.push({ listener, node })
|
1446 | );
|
1447 |
|
1448 | // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set.
|
1449 | const ignoredNodes = new Set();
|
1450 |
|
1451 | /**
|
1452 | * Ignores a node
|
1453 | * @param {ASTNode} node The node to ignore
|
1454 | * @returns {void}
|
1455 | */
|
1456 | function addToIgnoredNodes(node) {
|
1457 | ignoredNodes.add(node);
|
1458 | ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node));
|
1459 | }
|
1460 |
|
1461 | const ignoredNodeListeners = options.ignoredNodes.reduce(
|
1462 | (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }),
|
1463 | {}
|
1464 | );
|
1465 |
|
1466 | /*
|
1467 | * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation
|
1468 | * at the end.
|
1469 | *
|
1470 | * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears
|
1471 | * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored,
|
1472 | * so those listeners wouldn't be called anyway.
|
1473 | */
|
1474 | return Object.assign(
|
1475 | offsetListeners,
|
1476 | ignoredNodeListeners,
|
1477 | {
|
1478 | "*:exit"(node) {
|
1479 |
|
1480 | // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it.
|
1481 | if (!KNOWN_NODES.has(node.type)) {
|
1482 | addToIgnoredNodes(node);
|
1483 | }
|
1484 | },
|
1485 | "Program:exit"() {
|
1486 |
|
1487 | // If ignoreComments option is enabled, ignore all comment tokens.
|
1488 | if (options.ignoreComments) {
|
1489 | sourceCode.getAllComments()
|
1490 | .forEach(comment => offsets.ignoreToken(comment));
|
1491 | }
|
1492 |
|
1493 | // Invoke the queued offset listeners for the nodes that aren't ignored.
|
1494 | listenerCallQueue
|
1495 | .filter(nodeInfo => !ignoredNodes.has(nodeInfo.node))
|
1496 | .forEach(nodeInfo => nodeInfo.listener(nodeInfo.node));
|
1497 |
|
1498 | // Update the offsets for ignored nodes to prevent their child tokens from being reported.
|
1499 | ignoredNodes.forEach(ignoreNode);
|
1500 |
|
1501 | addParensIndent(sourceCode.ast.tokens);
|
1502 |
|
1503 | /*
|
1504 | * Create a Map from (tokenOrComment) => (precedingToken).
|
1505 | * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly.
|
1506 | */
|
1507 | const precedingTokens = sourceCode.ast.comments.reduce((commentMap, comment) => {
|
1508 | const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
|
1509 |
|
1510 | return commentMap.set(comment, commentMap.has(tokenOrCommentBefore) ? commentMap.get(tokenOrCommentBefore) : tokenOrCommentBefore);
|
1511 | }, new WeakMap());
|
1512 |
|
1513 | sourceCode.lines.forEach((line, lineIndex) => {
|
1514 | const lineNumber = lineIndex + 1;
|
1515 |
|
1516 | if (!tokenInfo.firstTokensByLineNumber.has(lineNumber)) {
|
1517 |
|
1518 | // Don't check indentation on blank lines
|
1519 | return;
|
1520 | }
|
1521 |
|
1522 | const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(lineNumber);
|
1523 |
|
1524 | if (firstTokenOfLine.loc.start.line !== lineNumber) {
|
1525 |
|
1526 | // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice.
|
1527 | return;
|
1528 | }
|
1529 |
|
1530 | // If the token matches the expected expected indentation, don't report it.
|
1531 | if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) {
|
1532 | return;
|
1533 | }
|
1534 |
|
1535 | if (astUtils.isCommentToken(firstTokenOfLine)) {
|
1536 | const tokenBefore = precedingTokens.get(firstTokenOfLine);
|
1537 | const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0];
|
1538 |
|
1539 | // If a comment matches the expected indentation of the token immediately before or after, don't report it.
|
1540 | if (
|
1541 | tokenBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) ||
|
1542 | tokenAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter))
|
1543 | ) {
|
1544 | return;
|
1545 | }
|
1546 | }
|
1547 |
|
1548 | // Otherwise, report the token/comment.
|
1549 | report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine));
|
1550 | });
|
1551 | }
|
1552 | }
|
1553 | );
|
1554 | }
|
1555 | };
|