Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

indent.js 67KB

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