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 lodash = require("lodash");
  13. const astUtils = require("./utils/ast-utils");
  14. const createTree = require("functional-red-black-tree");
  15. //------------------------------------------------------------------------------
  16. // Rule Definition
  17. //------------------------------------------------------------------------------
  18. const KNOWN_NODES = new Set([
  19. "AssignmentExpression",
  20. "AssignmentPattern",
  21. "ArrayExpression",
  22. "ArrayPattern",
  23. "ArrowFunctionExpression",
  24. "AwaitExpression",
  25. "BlockStatement",
  26. "BinaryExpression",
  27. "BreakStatement",
  28. "CallExpression",
  29. "CatchClause",
  30. "ChainExpression",
  31. "ClassBody",
  32. "ClassDeclaration",
  33. "ClassExpression",
  34. "ConditionalExpression",
  35. "ContinueStatement",
  36. "DoWhileStatement",
  37. "DebuggerStatement",
  38. "EmptyStatement",
  39. "ExperimentalRestProperty",
  40. "ExperimentalSpreadProperty",
  41. "ExpressionStatement",
  42. "ForStatement",
  43. "ForInStatement",
  44. "ForOfStatement",
  45. "FunctionDeclaration",
  46. "FunctionExpression",
  47. "Identifier",
  48. "IfStatement",
  49. "Literal",
  50. "LabeledStatement",
  51. "LogicalExpression",
  52. "MemberExpression",
  53. "MetaProperty",
  54. "MethodDefinition",
  55. "NewExpression",
  56. "ObjectExpression",
  57. "ObjectPattern",
  58. "Program",
  59. "Property",
  60. "RestElement",
  61. "ReturnStatement",
  62. "SequenceExpression",
  63. "SpreadElement",
  64. "Super",
  65. "SwitchCase",
  66. "SwitchStatement",
  67. "TaggedTemplateExpression",
  68. "TemplateElement",
  69. "TemplateLiteral",
  70. "ThisExpression",
  71. "ThrowStatement",
  72. "TryStatement",
  73. "UnaryExpression",
  74. "UpdateExpression",
  75. "VariableDeclaration",
  76. "VariableDeclarator",
  77. "WhileStatement",
  78. "WithStatement",
  79. "YieldExpression",
  80. "JSXFragment",
  81. "JSXOpeningFragment",
  82. "JSXClosingFragment",
  83. "JSXIdentifier",
  84. "JSXNamespacedName",
  85. "JSXMemberExpression",
  86. "JSXEmptyExpression",
  87. "JSXExpressionContainer",
  88. "JSXElement",
  89. "JSXClosingElement",
  90. "JSXOpeningElement",
  91. "JSXAttribute",
  92. "JSXSpreadAttribute",
  93. "JSXText",
  94. "ExportDefaultDeclaration",
  95. "ExportNamedDeclaration",
  96. "ExportAllDeclaration",
  97. "ExportSpecifier",
  98. "ImportDeclaration",
  99. "ImportSpecifier",
  100. "ImportDefaultSpecifier",
  101. "ImportNamespaceSpecifier",
  102. "ImportExpression"
  103. ]);
  104. /*
  105. * General rule strategy:
  106. * 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another
  107. * specified token or to the first column.
  108. * 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a
  109. * BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly
  110. * brace of the BlockStatement.
  111. * 3. After traversing the AST, calculate the expected indentation levels of every token according to the
  112. * OffsetStorage container.
  113. * 4. For each line, compare the expected indentation of the first token to the actual indentation in the file,
  114. * and report the token if the two values are not equal.
  115. */
  116. /**
  117. * A mutable balanced binary search tree that stores (key, value) pairs. The keys are numeric, and must be unique.
  118. * This is intended to be a generic wrapper around a balanced binary search tree library, so that the underlying implementation
  119. * can easily be swapped out.
  120. */
  121. class BinarySearchTree {
  122. /**
  123. * Creates an empty tree
  124. */
  125. constructor() {
  126. this._rbTree = createTree();
  127. }
  128. /**
  129. * Inserts an entry into the tree.
  130. * @param {number} key The entry's key
  131. * @param {*} value The entry's value
  132. * @returns {void}
  133. */
  134. insert(key, value) {
  135. const iterator = this._rbTree.find(key);
  136. if (iterator.valid) {
  137. this._rbTree = iterator.update(value);
  138. } else {
  139. this._rbTree = this._rbTree.insert(key, value);
  140. }
  141. }
  142. /**
  143. * Finds the entry with the largest key less than or equal to the provided key
  144. * @param {number} key The provided key
  145. * @returns {{key: number, value: *}|null} The found entry, or null if no such entry exists.
  146. */
  147. findLe(key) {
  148. const iterator = this._rbTree.le(key);
  149. return iterator && { key: iterator.key, value: iterator.value };
  150. }
  151. /**
  152. * Deletes all of the keys in the interval [start, end)
  153. * @param {number} start The start of the range
  154. * @param {number} end The end of the range
  155. * @returns {void}
  156. */
  157. deleteRange(start, end) {
  158. // Exit without traversing the tree if the range has zero size.
  159. if (start === end) {
  160. return;
  161. }
  162. const iterator = this._rbTree.ge(start);
  163. while (iterator.valid && iterator.key < end) {
  164. this._rbTree = this._rbTree.remove(iterator.key);
  165. iterator.next();
  166. }
  167. }
  168. }
  169. /**
  170. * A helper class to get token-based info related to indentation
  171. */
  172. class TokenInfo {
  173. // eslint-disable-next-line jsdoc/require-description
  174. /**
  175. * @param {SourceCode} sourceCode A SourceCode object
  176. */
  177. constructor(sourceCode) {
  178. this.sourceCode = sourceCode;
  179. this.firstTokensByLineNumber = sourceCode.tokensAndComments.reduce((map, token) => {
  180. if (!map.has(token.loc.start.line)) {
  181. map.set(token.loc.start.line, token);
  182. }
  183. if (!map.has(token.loc.end.line) && sourceCode.text.slice(token.range[1] - token.loc.end.column, token.range[1]).trim()) {
  184. map.set(token.loc.end.line, token);
  185. }
  186. return map;
  187. }, new Map());
  188. }
  189. /**
  190. * Gets the first token on a given token's line
  191. * @param {Token|ASTNode} token a node or token
  192. * @returns {Token} The first token on the given line
  193. */
  194. getFirstTokenOfLine(token) {
  195. return this.firstTokensByLineNumber.get(token.loc.start.line);
  196. }
  197. /**
  198. * Determines whether a token is the first token in its line
  199. * @param {Token} token The token
  200. * @returns {boolean} `true` if the token is the first on its line
  201. */
  202. isFirstTokenOfLine(token) {
  203. return this.getFirstTokenOfLine(token) === token;
  204. }
  205. /**
  206. * Get the actual indent of a token
  207. * @param {Token} token Token to examine. This should be the first token on its line.
  208. * @returns {string} The indentation characters that precede the token
  209. */
  210. getTokenIndent(token) {
  211. return this.sourceCode.text.slice(token.range[0] - token.loc.start.column, token.range[0]);
  212. }
  213. }
  214. /**
  215. * A class to store information on desired offsets of tokens from each other
  216. */
  217. class OffsetStorage {
  218. // eslint-disable-next-line jsdoc/require-description
  219. /**
  220. * @param {TokenInfo} tokenInfo a TokenInfo instance
  221. * @param {number} indentSize The desired size of each indentation level
  222. * @param {string} indentType The indentation character
  223. */
  224. constructor(tokenInfo, indentSize, indentType) {
  225. this._tokenInfo = tokenInfo;
  226. this._indentSize = indentSize;
  227. this._indentType = indentType;
  228. this._tree = new BinarySearchTree();
  229. this._tree.insert(0, { offset: 0, from: null, force: false });
  230. this._lockedFirstTokens = new WeakMap();
  231. this._desiredIndentCache = new WeakMap();
  232. this._ignoredTokens = new WeakSet();
  233. }
  234. _getOffsetDescriptor(token) {
  235. return this._tree.findLe(token.range[0]).value;
  236. }
  237. /**
  238. * Sets the offset column of token B to match the offset column of token A.
  239. * **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In
  240. * most cases, `setDesiredOffset` should be used instead.
  241. * @param {Token} baseToken The first token
  242. * @param {Token} offsetToken The second token, whose offset should be matched to the first token
  243. * @returns {void}
  244. */
  245. matchOffsetOf(baseToken, offsetToken) {
  246. /*
  247. * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to
  248. * the token that it depends on. For example, with the `ArrayExpression: first` option, the first
  249. * token of each element in the array after the first will be mapped to the first token of the first
  250. * element. The desired indentation of each of these tokens is computed based on the desired indentation
  251. * of the "first" element, rather than through the normal offset mechanism.
  252. */
  253. this._lockedFirstTokens.set(offsetToken, baseToken);
  254. }
  255. /**
  256. * Sets the desired offset of a token.
  257. *
  258. * This uses a line-based offset collapsing behavior to handle tokens on the same line.
  259. * For example, consider the following two cases:
  260. *
  261. * (
  262. * [
  263. * bar
  264. * ]
  265. * )
  266. *
  267. * ([
  268. * bar
  269. * ])
  270. *
  271. * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from
  272. * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is
  273. * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces)
  274. * from the start of its line.
  275. *
  276. * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level
  277. * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the
  278. * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented
  279. * by 1 indent level from the start of the line.
  280. *
  281. * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node,
  282. * without needing to check which lines those tokens are on.
  283. *
  284. * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive
  285. * behavior can occur. For example, consider the following cases:
  286. *
  287. * foo(
  288. * ).
  289. * bar(
  290. * baz
  291. * )
  292. *
  293. * foo(
  294. * ).bar(
  295. * baz
  296. * )
  297. *
  298. * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz`
  299. * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz`
  300. * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no
  301. * collapsing would occur).
  302. *
  303. * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and
  304. * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed
  305. * in the second case.
  306. * @param {Token} token The token
  307. * @param {Token} fromToken The token that `token` should be offset from
  308. * @param {number} offset The desired indent level
  309. * @returns {void}
  310. */
  311. setDesiredOffset(token, fromToken, offset) {
  312. return this.setDesiredOffsets(token.range, fromToken, offset);
  313. }
  314. /**
  315. * Sets the desired offset of all tokens in a range
  316. * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens.
  317. * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains
  318. * it). This means that the offset of each token is updated O(AST depth) times.
  319. * It would not be performant to store and update the offsets for each token independently, because the rule would end
  320. * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files.
  321. *
  322. * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following
  323. * list could represent the state of the offset tree at a given point:
  324. *
  325. * * Tokens starting in the interval [0, 15) are aligned with the beginning of the file
  326. * * Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token
  327. * * Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token
  328. * * Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token
  329. * * Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token
  330. *
  331. * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using:
  332. * `setDesiredOffsets([30, 43], fooToken, 1);`
  333. * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied.
  334. * @param {Token} fromToken The token that this is offset from
  335. * @param {number} offset The desired indent level
  336. * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false.
  337. * @returns {void}
  338. */
  339. setDesiredOffsets(range, fromToken, offset, force) {
  340. /*
  341. * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset
  342. * descriptor. The tree for the example above would have the following nodes:
  343. *
  344. * * key: 0, value: { offset: 0, from: null }
  345. * * key: 15, value: { offset: 1, from: barToken }
  346. * * key: 30, value: { offset: 1, from: fooToken }
  347. * * key: 43, value: { offset: 2, from: barToken }
  348. * * key: 820, value: { offset: 1, from: bazToken }
  349. *
  350. * To find the offset descriptor for any given token, one needs to find the node with the largest key
  351. * which is <= token.start. To make this operation fast, the nodes are stored in a balanced binary
  352. * search tree indexed by key.
  353. */
  354. const descriptorToInsert = { offset, from: fromToken, force };
  355. const descriptorAfterRange = this._tree.findLe(range[1]).value;
  356. const fromTokenIsInRange = fromToken && fromToken.range[0] >= range[0] && fromToken.range[1] <= range[1];
  357. const fromTokenDescriptor = fromTokenIsInRange && this._getOffsetDescriptor(fromToken);
  358. // First, remove any existing nodes in the range from the tree.
  359. this._tree.deleteRange(range[0] + 1, range[1]);
  360. // Insert a new node into the tree for this range
  361. this._tree.insert(range[0], descriptorToInsert);
  362. /*
  363. * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously,
  364. * even if it's in the current range.
  365. */
  366. if (fromTokenIsInRange) {
  367. this._tree.insert(fromToken.range[0], fromTokenDescriptor);
  368. this._tree.insert(fromToken.range[1], descriptorToInsert);
  369. }
  370. /*
  371. * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following
  372. * tokens the same as it was before.
  373. */
  374. this._tree.insert(range[1], descriptorAfterRange);
  375. }
  376. /**
  377. * Gets the desired indent of a token
  378. * @param {Token} token The token
  379. * @returns {string} The desired indent of the token
  380. */
  381. getDesiredIndent(token) {
  382. if (!this._desiredIndentCache.has(token)) {
  383. if (this._ignoredTokens.has(token)) {
  384. /*
  385. * If the token is ignored, use the actual indent of the token as the desired indent.
  386. * This ensures that no errors are reported for this token.
  387. */
  388. this._desiredIndentCache.set(
  389. token,
  390. this._tokenInfo.getTokenIndent(token)
  391. );
  392. } else if (this._lockedFirstTokens.has(token)) {
  393. const firstToken = this._lockedFirstTokens.get(token);
  394. this._desiredIndentCache.set(
  395. token,
  396. // (indentation for the first element's line)
  397. this.getDesiredIndent(this._tokenInfo.getFirstTokenOfLine(firstToken)) +
  398. // (space between the start of the first element's line and the first element)
  399. this._indentType.repeat(firstToken.loc.start.column - this._tokenInfo.getFirstTokenOfLine(firstToken).loc.start.column)
  400. );
  401. } else {
  402. const offsetInfo = this._getOffsetDescriptor(token);
  403. const offset = (
  404. offsetInfo.from &&
  405. offsetInfo.from.loc.start.line === token.loc.start.line &&
  406. !/^\s*?\n/u.test(token.value) &&
  407. !offsetInfo.force
  408. ) ? 0 : offsetInfo.offset * this._indentSize;
  409. this._desiredIndentCache.set(
  410. token,
  411. (offsetInfo.from ? this.getDesiredIndent(offsetInfo.from) : "") + this._indentType.repeat(offset)
  412. );
  413. }
  414. }
  415. return this._desiredIndentCache.get(token);
  416. }
  417. /**
  418. * Ignores a token, preventing it from being reported.
  419. * @param {Token} token The token
  420. * @returns {void}
  421. */
  422. ignoreToken(token) {
  423. if (this._tokenInfo.isFirstTokenOfLine(token)) {
  424. this._ignoredTokens.add(token);
  425. }
  426. }
  427. /**
  428. * Gets the first token that the given token's indentation is dependent on
  429. * @param {Token} token The token
  430. * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level
  431. */
  432. getFirstDependency(token) {
  433. return this._getOffsetDescriptor(token).from;
  434. }
  435. }
  436. const ELEMENT_LIST_SCHEMA = {
  437. oneOf: [
  438. {
  439. type: "integer",
  440. minimum: 0
  441. },
  442. {
  443. enum: ["first", "off"]
  444. }
  445. ]
  446. };
  447. module.exports = {
  448. meta: {
  449. type: "layout",
  450. docs: {
  451. description: "enforce consistent indentation",
  452. category: "Stylistic Issues",
  453. recommended: false,
  454. url: "https://eslint.org/docs/rules/indent"
  455. },
  456. fixable: "whitespace",
  457. schema: [
  458. {
  459. oneOf: [
  460. {
  461. enum: ["tab"]
  462. },
  463. {
  464. type: "integer",
  465. minimum: 0
  466. }
  467. ]
  468. },
  469. {
  470. type: "object",
  471. properties: {
  472. SwitchCase: {
  473. type: "integer",
  474. minimum: 0,
  475. default: 0
  476. },
  477. VariableDeclarator: {
  478. oneOf: [
  479. ELEMENT_LIST_SCHEMA,
  480. {
  481. type: "object",
  482. properties: {
  483. var: ELEMENT_LIST_SCHEMA,
  484. let: ELEMENT_LIST_SCHEMA,
  485. const: ELEMENT_LIST_SCHEMA
  486. },
  487. additionalProperties: false
  488. }
  489. ]
  490. },
  491. outerIIFEBody: {
  492. oneOf: [
  493. {
  494. type: "integer",
  495. minimum: 0
  496. },
  497. {
  498. enum: ["off"]
  499. }
  500. ]
  501. },
  502. MemberExpression: {
  503. oneOf: [
  504. {
  505. type: "integer",
  506. minimum: 0
  507. },
  508. {
  509. enum: ["off"]
  510. }
  511. ]
  512. },
  513. FunctionDeclaration: {
  514. type: "object",
  515. properties: {
  516. parameters: ELEMENT_LIST_SCHEMA,
  517. body: {
  518. type: "integer",
  519. minimum: 0
  520. }
  521. },
  522. additionalProperties: false
  523. },
  524. FunctionExpression: {
  525. type: "object",
  526. properties: {
  527. parameters: ELEMENT_LIST_SCHEMA,
  528. body: {
  529. type: "integer",
  530. minimum: 0
  531. }
  532. },
  533. additionalProperties: false
  534. },
  535. CallExpression: {
  536. type: "object",
  537. properties: {
  538. arguments: ELEMENT_LIST_SCHEMA
  539. },
  540. additionalProperties: false
  541. },
  542. ArrayExpression: ELEMENT_LIST_SCHEMA,
  543. ObjectExpression: ELEMENT_LIST_SCHEMA,
  544. ImportDeclaration: ELEMENT_LIST_SCHEMA,
  545. flatTernaryExpressions: {
  546. type: "boolean",
  547. default: false
  548. },
  549. offsetTernaryExpressions: {
  550. type: "boolean",
  551. default: false
  552. },
  553. ignoredNodes: {
  554. type: "array",
  555. items: {
  556. type: "string",
  557. not: {
  558. pattern: ":exit$"
  559. }
  560. }
  561. },
  562. ignoreComments: {
  563. type: "boolean",
  564. default: false
  565. }
  566. },
  567. additionalProperties: false
  568. }
  569. ],
  570. messages: {
  571. wrongIndentation: "Expected indentation of {{expected}} but found {{actual}}."
  572. }
  573. },
  574. create(context) {
  575. const DEFAULT_VARIABLE_INDENT = 1;
  576. const DEFAULT_PARAMETER_INDENT = 1;
  577. const DEFAULT_FUNCTION_BODY_INDENT = 1;
  578. let indentType = "space";
  579. let indentSize = 4;
  580. const options = {
  581. SwitchCase: 0,
  582. VariableDeclarator: {
  583. var: DEFAULT_VARIABLE_INDENT,
  584. let: DEFAULT_VARIABLE_INDENT,
  585. const: DEFAULT_VARIABLE_INDENT
  586. },
  587. outerIIFEBody: 1,
  588. FunctionDeclaration: {
  589. parameters: DEFAULT_PARAMETER_INDENT,
  590. body: DEFAULT_FUNCTION_BODY_INDENT
  591. },
  592. FunctionExpression: {
  593. parameters: DEFAULT_PARAMETER_INDENT,
  594. body: DEFAULT_FUNCTION_BODY_INDENT
  595. },
  596. CallExpression: {
  597. arguments: DEFAULT_PARAMETER_INDENT
  598. },
  599. MemberExpression: 1,
  600. ArrayExpression: 1,
  601. ObjectExpression: 1,
  602. ImportDeclaration: 1,
  603. flatTernaryExpressions: false,
  604. ignoredNodes: [],
  605. ignoreComments: false
  606. };
  607. if (context.options.length) {
  608. if (context.options[0] === "tab") {
  609. indentSize = 1;
  610. indentType = "tab";
  611. } else {
  612. indentSize = context.options[0];
  613. indentType = "space";
  614. }
  615. if (context.options[1]) {
  616. Object.assign(options, context.options[1]);
  617. if (typeof options.VariableDeclarator === "number" || options.VariableDeclarator === "first") {
  618. options.VariableDeclarator = {
  619. var: options.VariableDeclarator,
  620. let: options.VariableDeclarator,
  621. const: options.VariableDeclarator
  622. };
  623. }
  624. }
  625. }
  626. const sourceCode = context.getSourceCode();
  627. const tokenInfo = new TokenInfo(sourceCode);
  628. const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t");
  629. const parameterParens = new WeakSet();
  630. /**
  631. * Creates an error message for a line, given the expected/actual indentation.
  632. * @param {int} expectedAmount The expected amount of indentation characters for this line
  633. * @param {int} actualSpaces The actual number of indentation spaces that were found on this line
  634. * @param {int} actualTabs The actual number of indentation tabs that were found on this line
  635. * @returns {string} An error message for this line
  636. */
  637. function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) {
  638. const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs"
  639. const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space"
  640. const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs"
  641. let foundStatement;
  642. if (actualSpaces > 0) {
  643. /*
  644. * Abbreviate the message if the expected indentation is also spaces.
  645. * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
  646. */
  647. foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`;
  648. } else if (actualTabs > 0) {
  649. foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`;
  650. } else {
  651. foundStatement = "0";
  652. }
  653. return {
  654. expected: expectedStatement,
  655. actual: foundStatement
  656. };
  657. }
  658. /**
  659. * Reports a given indent violation
  660. * @param {Token} token Token violating the indent rule
  661. * @param {string} neededIndent Expected indentation string
  662. * @returns {void}
  663. */
  664. function report(token, neededIndent) {
  665. const actualIndent = Array.from(tokenInfo.getTokenIndent(token));
  666. const numSpaces = actualIndent.filter(char => char === " ").length;
  667. const numTabs = actualIndent.filter(char => char === "\t").length;
  668. context.report({
  669. node: token,
  670. messageId: "wrongIndentation",
  671. data: createErrorMessageData(neededIndent.length, numSpaces, numTabs),
  672. loc: {
  673. start: { line: token.loc.start.line, column: 0 },
  674. end: { line: token.loc.start.line, column: token.loc.start.column }
  675. },
  676. fix(fixer) {
  677. const range = [token.range[0] - token.loc.start.column, token.range[0]];
  678. const newText = neededIndent;
  679. return fixer.replaceTextRange(range, newText);
  680. }
  681. });
  682. }
  683. /**
  684. * Checks if a token's indentation is correct
  685. * @param {Token} token Token to examine
  686. * @param {string} desiredIndent Desired indentation of the string
  687. * @returns {boolean} `true` if the token's indentation is correct
  688. */
  689. function validateTokenIndent(token, desiredIndent) {
  690. const indentation = tokenInfo.getTokenIndent(token);
  691. return indentation === desiredIndent ||
  692. // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
  693. indentation.includes(" ") && indentation.includes("\t");
  694. }
  695. /**
  696. * Check to see if the node is a file level IIFE
  697. * @param {ASTNode} node The function node to check.
  698. * @returns {boolean} True if the node is the outer IIFE
  699. */
  700. function isOuterIIFE(node) {
  701. /*
  702. * Verify that the node is an IIFE
  703. */
  704. if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) {
  705. return false;
  706. }
  707. /*
  708. * Navigate legal ancestors to determine whether this IIFE is outer.
  709. * A "legal ancestor" is an expression or statement that causes the function to get executed immediately.
  710. * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator.
  711. */
  712. let statement = node.parent && node.parent.parent;
  713. while (
  714. statement.type === "UnaryExpression" && ["!", "~", "+", "-"].indexOf(statement.operator) > -1 ||
  715. statement.type === "AssignmentExpression" ||
  716. statement.type === "LogicalExpression" ||
  717. statement.type === "SequenceExpression" ||
  718. statement.type === "VariableDeclarator"
  719. ) {
  720. statement = statement.parent;
  721. }
  722. return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program";
  723. }
  724. /**
  725. * Counts the number of linebreaks that follow the last non-whitespace character in a string
  726. * @param {string} string The string to check
  727. * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character,
  728. * or the total number of linebreaks if the string is all whitespace.
  729. */
  730. function countTrailingLinebreaks(string) {
  731. const trailingWhitespace = string.match(/\s*$/u)[0];
  732. const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher());
  733. return linebreakMatches === null ? 0 : linebreakMatches.length;
  734. }
  735. /**
  736. * Check indentation for lists of elements (arrays, objects, function params)
  737. * @param {ASTNode[]} elements List of elements that should be offset
  738. * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '['
  739. * @param {Token} endToken The end token of the list, e.g. ']'
  740. * @param {number|string} offset The amount that the elements should be offset
  741. * @returns {void}
  742. */
  743. function addElementListIndent(elements, startToken, endToken, offset) {
  744. /**
  745. * Gets the first token of a given element, including surrounding parentheses.
  746. * @param {ASTNode} element A node in the `elements` list
  747. * @returns {Token} The first token of this element
  748. */
  749. function getFirstToken(element) {
  750. let token = sourceCode.getTokenBefore(element);
  751. while (astUtils.isOpeningParenToken(token) && token !== startToken) {
  752. token = sourceCode.getTokenBefore(token);
  753. }
  754. return sourceCode.getTokenAfter(token);
  755. }
  756. // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden)
  757. offsets.setDesiredOffsets(
  758. [startToken.range[1], endToken.range[0]],
  759. startToken,
  760. typeof offset === "number" ? offset : 1
  761. );
  762. offsets.setDesiredOffset(endToken, startToken, 0);
  763. // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level.
  764. if (offset === "first" && elements.length && !elements[0]) {
  765. return;
  766. }
  767. elements.forEach((element, index) => {
  768. if (!element) {
  769. // Skip holes in arrays
  770. return;
  771. }
  772. if (offset === "off") {
  773. // Ignore the first token of every element if the "off" option is used
  774. offsets.ignoreToken(getFirstToken(element));
  775. }
  776. // Offset the following elements correctly relative to the first element
  777. if (index === 0) {
  778. return;
  779. }
  780. if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) {
  781. offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element));
  782. } else {
  783. const previousElement = elements[index - 1];
  784. const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement);
  785. const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement);
  786. if (
  787. previousElement &&
  788. previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line
  789. ) {
  790. offsets.setDesiredOffsets(
  791. [previousElement.range[1], element.range[1]],
  792. firstTokenOfPreviousElement,
  793. 0
  794. );
  795. }
  796. }
  797. });
  798. }
  799. /**
  800. * Check and decide whether to check for indentation for blockless nodes
  801. * Scenarios are for or while statements without braces around them
  802. * @param {ASTNode} node node to examine
  803. * @returns {void}
  804. */
  805. function addBlocklessNodeIndent(node) {
  806. if (node.type !== "BlockStatement") {
  807. const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken);
  808. let firstBodyToken = sourceCode.getFirstToken(node);
  809. let lastBodyToken = sourceCode.getLastToken(node);
  810. while (
  811. astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) &&
  812. astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken))
  813. ) {
  814. firstBodyToken = sourceCode.getTokenBefore(firstBodyToken);
  815. lastBodyToken = sourceCode.getTokenAfter(lastBodyToken);
  816. }
  817. offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
  818. /*
  819. * For blockless nodes with semicolon-first style, don't indent the semicolon.
  820. * e.g.
  821. * if (foo) bar()
  822. * ; [1, 2, 3].map(foo)
  823. */
  824. const lastToken = sourceCode.getLastToken(node);
  825. if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) {
  826. offsets.setDesiredOffset(lastToken, lastParentToken, 0);
  827. }
  828. }
  829. }
  830. /**
  831. * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`)
  832. * @param {ASTNode} node A CallExpression or NewExpression node
  833. * @returns {void}
  834. */
  835. function addFunctionCallIndent(node) {
  836. let openingParen;
  837. if (node.arguments.length) {
  838. openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken);
  839. } else {
  840. openingParen = sourceCode.getLastToken(node, 1);
  841. }
  842. const closingParen = sourceCode.getLastToken(node);
  843. parameterParens.add(openingParen);
  844. parameterParens.add(closingParen);
  845. /*
  846. * If `?.` token exists, set desired offset for that.
  847. * This logic is copied from `MemberExpression`'s.
  848. */
  849. if (node.optional) {
  850. const dotToken = sourceCode.getTokenAfter(node.callee, astUtils.isQuestionDotToken);
  851. const calleeParenCount = sourceCode.getTokensBetween(node.callee, dotToken, { filter: astUtils.isClosingParenToken }).length;
  852. const firstTokenOfCallee = calleeParenCount
  853. ? sourceCode.getTokenBefore(node.callee, { skip: calleeParenCount - 1 })
  854. : sourceCode.getFirstToken(node.callee);
  855. const lastTokenOfCallee = sourceCode.getTokenBefore(dotToken);
  856. const offsetBase = lastTokenOfCallee.loc.end.line === openingParen.loc.start.line
  857. ? lastTokenOfCallee
  858. : firstTokenOfCallee;
  859. offsets.setDesiredOffset(dotToken, offsetBase, 1);
  860. }
  861. const offsetAfterToken = node.callee.type === "TaggedTemplateExpression" ? sourceCode.getFirstToken(node.callee.quasi) : openingParen;
  862. const offsetToken = sourceCode.getTokenBefore(offsetAfterToken);
  863. offsets.setDesiredOffset(openingParen, offsetToken, 0);
  864. addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments);
  865. }
  866. /**
  867. * Checks the indentation of parenthesized values, given a list of tokens in a program
  868. * @param {Token[]} tokens A list of tokens
  869. * @returns {void}
  870. */
  871. function addParensIndent(tokens) {
  872. const parenStack = [];
  873. const parenPairs = [];
  874. tokens.forEach(nextToken => {
  875. // Accumulate a list of parenthesis pairs
  876. if (astUtils.isOpeningParenToken(nextToken)) {
  877. parenStack.push(nextToken);
  878. } else if (astUtils.isClosingParenToken(nextToken)) {
  879. parenPairs.unshift({ left: parenStack.pop(), right: nextToken });
  880. }
  881. });
  882. parenPairs.forEach(pair => {
  883. const leftParen = pair.left;
  884. const rightParen = pair.right;
  885. // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.
  886. if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) {
  887. const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen));
  888. parenthesizedTokens.forEach(token => {
  889. if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) {
  890. offsets.setDesiredOffset(token, leftParen, 1);
  891. }
  892. });
  893. }
  894. offsets.setDesiredOffset(rightParen, leftParen, 0);
  895. });
  896. }
  897. /**
  898. * Ignore all tokens within an unknown node whose offset do not depend
  899. * on another token's offset within the unknown node
  900. * @param {ASTNode} node Unknown Node
  901. * @returns {void}
  902. */
  903. function ignoreNode(node) {
  904. const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true }));
  905. unknownNodeTokens.forEach(token => {
  906. if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) {
  907. const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token);
  908. if (token === firstTokenOfLine) {
  909. offsets.ignoreToken(token);
  910. } else {
  911. offsets.setDesiredOffset(token, firstTokenOfLine, 0);
  912. }
  913. }
  914. });
  915. }
  916. /**
  917. * Check whether the given token is on the first line of a statement.
  918. * @param {Token} token The token to check.
  919. * @param {ASTNode} leafNode The expression node that the token belongs directly.
  920. * @returns {boolean} `true` if the token is on the first line of a statement.
  921. */
  922. function isOnFirstLineOfStatement(token, leafNode) {
  923. let node = leafNode;
  924. while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) {
  925. node = node.parent;
  926. }
  927. node = node.parent;
  928. return !node || node.loc.start.line === token.loc.start.line;
  929. }
  930. /**
  931. * Check whether there are any blank (whitespace-only) lines between
  932. * two tokens on separate lines.
  933. * @param {Token} firstToken The first token.
  934. * @param {Token} secondToken The second token.
  935. * @returns {boolean} `true` if the tokens are on separate lines and
  936. * there exists a blank line between them, `false` otherwise.
  937. */
  938. function hasBlankLinesBetween(firstToken, secondToken) {
  939. const firstTokenLine = firstToken.loc.end.line;
  940. const secondTokenLine = secondToken.loc.start.line;
  941. if (firstTokenLine === secondTokenLine || firstTokenLine === secondTokenLine - 1) {
  942. return false;
  943. }
  944. for (let line = firstTokenLine + 1; line < secondTokenLine; ++line) {
  945. if (!tokenInfo.firstTokensByLineNumber.has(line)) {
  946. return true;
  947. }
  948. }
  949. return false;
  950. }
  951. const ignoredNodeFirstTokens = new Set();
  952. const baseOffsetListeners = {
  953. "ArrayExpression, ArrayPattern"(node) {
  954. const openingBracket = sourceCode.getFirstToken(node);
  955. const closingBracket = sourceCode.getTokenAfter(lodash.findLast(node.elements) || openingBracket, astUtils.isClosingBracketToken);
  956. addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression);
  957. },
  958. "ObjectExpression, ObjectPattern"(node) {
  959. const openingCurly = sourceCode.getFirstToken(node);
  960. const closingCurly = sourceCode.getTokenAfter(
  961. node.properties.length ? node.properties[node.properties.length - 1] : openingCurly,
  962. astUtils.isClosingBraceToken
  963. );
  964. addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression);
  965. },
  966. ArrowFunctionExpression(node) {
  967. const maybeOpeningParen = sourceCode.getFirstToken(node, { skip: node.async ? 1 : 0 });
  968. if (astUtils.isOpeningParenToken(maybeOpeningParen)) {
  969. const openingParen = maybeOpeningParen;
  970. const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken);
  971. parameterParens.add(openingParen);
  972. parameterParens.add(closingParen);
  973. addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters);
  974. }
  975. addBlocklessNodeIndent(node.body);
  976. },
  977. AssignmentExpression(node) {
  978. const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
  979. offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1);
  980. offsets.ignoreToken(operator);
  981. offsets.ignoreToken(sourceCode.getTokenAfter(operator));
  982. },
  983. "BinaryExpression, LogicalExpression"(node) {
  984. const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
  985. /*
  986. * For backwards compatibility, don't check BinaryExpression indents, e.g.
  987. * var foo = bar &&
  988. * baz;
  989. */
  990. const tokenAfterOperator = sourceCode.getTokenAfter(operator);
  991. offsets.ignoreToken(operator);
  992. offsets.ignoreToken(tokenAfterOperator);
  993. offsets.setDesiredOffset(tokenAfterOperator, operator, 0);
  994. },
  995. "BlockStatement, ClassBody"(node) {
  996. let blockIndentLevel;
  997. if (node.parent && isOuterIIFE(node.parent)) {
  998. blockIndentLevel = options.outerIIFEBody;
  999. } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) {
  1000. blockIndentLevel = options.FunctionExpression.body;
  1001. } else if (node.parent && node.parent.type === "FunctionDeclaration") {
  1002. blockIndentLevel = options.FunctionDeclaration.body;
  1003. } else {
  1004. blockIndentLevel = 1;
  1005. }
  1006. /*
  1007. * For blocks that aren't lone statements, ensure that the opening curly brace
  1008. * is aligned with the parent.
  1009. */
  1010. if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
  1011. offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0);
  1012. }
  1013. addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel);
  1014. },
  1015. CallExpression: addFunctionCallIndent,
  1016. "ClassDeclaration[superClass], ClassExpression[superClass]"(node) {
  1017. const classToken = sourceCode.getFirstToken(node);
  1018. const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken);
  1019. offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1);
  1020. },
  1021. ConditionalExpression(node) {
  1022. const firstToken = sourceCode.getFirstToken(node);
  1023. // `flatTernaryExpressions` option is for the following style:
  1024. // var a =
  1025. // foo > 0 ? bar :
  1026. // foo < 0 ? baz :
  1027. // /*else*/ qiz ;
  1028. if (!options.flatTernaryExpressions ||
  1029. !astUtils.isTokenOnSameLine(node.test, node.consequent) ||
  1030. isOnFirstLineOfStatement(firstToken, node)
  1031. ) {
  1032. const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?");
  1033. const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":");
  1034. const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken);
  1035. const lastConsequentToken = sourceCode.getTokenBefore(colonToken);
  1036. const firstAlternateToken = sourceCode.getTokenAfter(colonToken);
  1037. offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
  1038. offsets.setDesiredOffset(colonToken, firstToken, 1);
  1039. offsets.setDesiredOffset(firstConsequentToken, firstToken,
  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 = lodash.mapValues(
  1351. 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. listener =>
  1369. node =>
  1370. listenerCallQueue.push({ listener, node })
  1371. );
  1372. // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set.
  1373. const ignoredNodes = new Set();
  1374. /**
  1375. * Ignores a node
  1376. * @param {ASTNode} node The node to ignore
  1377. * @returns {void}
  1378. */
  1379. function addToIgnoredNodes(node) {
  1380. ignoredNodes.add(node);
  1381. ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node));
  1382. }
  1383. const ignoredNodeListeners = options.ignoredNodes.reduce(
  1384. (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }),
  1385. {}
  1386. );
  1387. /*
  1388. * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation
  1389. * at the end.
  1390. *
  1391. * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears
  1392. * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored,
  1393. * so those listeners wouldn't be called anyway.
  1394. */
  1395. return Object.assign(
  1396. offsetListeners,
  1397. ignoredNodeListeners,
  1398. {
  1399. "*:exit"(node) {
  1400. // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it.
  1401. if (!KNOWN_NODES.has(node.type)) {
  1402. addToIgnoredNodes(node);
  1403. }
  1404. },
  1405. "Program:exit"() {
  1406. // If ignoreComments option is enabled, ignore all comment tokens.
  1407. if (options.ignoreComments) {
  1408. sourceCode.getAllComments()
  1409. .forEach(comment => offsets.ignoreToken(comment));
  1410. }
  1411. // Invoke the queued offset listeners for the nodes that aren't ignored.
  1412. listenerCallQueue
  1413. .filter(nodeInfo => !ignoredNodes.has(nodeInfo.node))
  1414. .forEach(nodeInfo => nodeInfo.listener(nodeInfo.node));
  1415. // Update the offsets for ignored nodes to prevent their child tokens from being reported.
  1416. ignoredNodes.forEach(ignoreNode);
  1417. addParensIndent(sourceCode.ast.tokens);
  1418. /*
  1419. * Create a Map from (tokenOrComment) => (precedingToken).
  1420. * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly.
  1421. */
  1422. const precedingTokens = sourceCode.ast.comments.reduce((commentMap, comment) => {
  1423. const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
  1424. return commentMap.set(comment, commentMap.has(tokenOrCommentBefore) ? commentMap.get(tokenOrCommentBefore) : tokenOrCommentBefore);
  1425. }, new WeakMap());
  1426. sourceCode.lines.forEach((line, lineIndex) => {
  1427. const lineNumber = lineIndex + 1;
  1428. if (!tokenInfo.firstTokensByLineNumber.has(lineNumber)) {
  1429. // Don't check indentation on blank lines
  1430. return;
  1431. }
  1432. const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(lineNumber);
  1433. if (firstTokenOfLine.loc.start.line !== lineNumber) {
  1434. // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice.
  1435. return;
  1436. }
  1437. if (astUtils.isCommentToken(firstTokenOfLine)) {
  1438. const tokenBefore = precedingTokens.get(firstTokenOfLine);
  1439. const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0];
  1440. const mayAlignWithBefore = tokenBefore && !hasBlankLinesBetween(tokenBefore, firstTokenOfLine);
  1441. const mayAlignWithAfter = tokenAfter && !hasBlankLinesBetween(firstTokenOfLine, tokenAfter);
  1442. /*
  1443. * If a comment precedes a line that begins with a semicolon token, align to that token, i.e.
  1444. *
  1445. * let foo
  1446. * // comment
  1447. * ;(async () => {})()
  1448. */
  1449. if (tokenAfter && astUtils.isSemicolonToken(tokenAfter) && !astUtils.isTokenOnSameLine(firstTokenOfLine, tokenAfter)) {
  1450. offsets.setDesiredOffset(firstTokenOfLine, tokenAfter, 0);
  1451. }
  1452. // If a comment matches the expected indentation of the token immediately before or after, don't report it.
  1453. if (
  1454. mayAlignWithBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) ||
  1455. mayAlignWithAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter))
  1456. ) {
  1457. return;
  1458. }
  1459. }
  1460. // If the token matches the expected indentation, don't report it.
  1461. if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) {
  1462. return;
  1463. }
  1464. // Otherwise, report the token/comment.
  1465. report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine));
  1466. });
  1467. }
  1468. }
  1469. );
  1470. }
  1471. };