indent.js 77 KB

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