indent.js 72 KB

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