indent.js 70 KB

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