Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

indent.js 72KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  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, firstConsequentToken.type === "Punctuator" &&
  1039. options.offsetTernaryExpressions ? 2 : 1);
  1040. /*
  1041. * The alternate and the consequent should usually have the same indentation.
  1042. * If they share part of a line, align the alternate against the first token of the consequent.
  1043. * This allows the alternate to be indented correctly in cases like this:
  1044. * foo ? (
  1045. * bar
  1046. * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo`
  1047. * baz // as a result, `baz` is offset by 1 rather than 2
  1048. * )
  1049. */
  1050. if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) {
  1051. offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0);
  1052. } else {
  1053. /**
  1054. * If the alternate and consequent do not share part of a line, offset the alternate from the first
  1055. * token of the conditional expression. For example:
  1056. * foo ? bar
  1057. * : baz
  1058. *
  1059. * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
  1060. * having no expected indentation.
  1061. */
  1062. offsets.setDesiredOffset(firstAlternateToken, firstToken, firstAlternateToken.type === "Punctuator" &&
  1063. options.offsetTernaryExpressions ? 2 : 1);
  1064. }
  1065. }
  1066. },
  1067. "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement": node => addBlocklessNodeIndent(node.body),
  1068. ExportNamedDeclaration(node) {
  1069. if (node.declaration === null) {
  1070. const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
  1071. // Indent the specifiers in `export {foo, bar, baz}`
  1072. addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, { skip: 1 }), closingCurly, 1);
  1073. if (node.source) {
  1074. // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'`
  1075. offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1);
  1076. }
  1077. }
  1078. },
  1079. ForStatement(node) {
  1080. const forOpeningParen = sourceCode.getFirstToken(node, 1);
  1081. if (node.init) {
  1082. offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1);
  1083. }
  1084. if (node.test) {
  1085. offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1);
  1086. }
  1087. if (node.update) {
  1088. offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1);
  1089. }
  1090. addBlocklessNodeIndent(node.body);
  1091. },
  1092. "FunctionDeclaration, FunctionExpression"(node) {
  1093. const closingParen = sourceCode.getTokenBefore(node.body);
  1094. const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen);
  1095. parameterParens.add(openingParen);
  1096. parameterParens.add(closingParen);
  1097. addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters);
  1098. },
  1099. IfStatement(node) {
  1100. addBlocklessNodeIndent(node.consequent);
  1101. if (node.alternate && node.alternate.type !== "IfStatement") {
  1102. addBlocklessNodeIndent(node.alternate);
  1103. }
  1104. },
  1105. ImportDeclaration(node) {
  1106. if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
  1107. const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);
  1108. const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
  1109. addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration);
  1110. }
  1111. const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from");
  1112. const sourceToken = sourceCode.getLastToken(node, token => token.type === "String");
  1113. const semiToken = sourceCode.getLastToken(node, token => token.type === "Punctuator" && token.value === ";");
  1114. if (fromToken) {
  1115. const end = semiToken && semiToken.range[1] === sourceToken.range[1] ? node.range[1] : sourceToken.range[1];
  1116. offsets.setDesiredOffsets([fromToken.range[0], end], sourceCode.getFirstToken(node), 1);
  1117. }
  1118. },
  1119. ImportExpression(node) {
  1120. const openingParen = sourceCode.getFirstToken(node, 1);
  1121. const closingParen = sourceCode.getLastToken(node);
  1122. parameterParens.add(openingParen);
  1123. parameterParens.add(closingParen);
  1124. offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0);
  1125. addElementListIndent([node.source], openingParen, closingParen, options.CallExpression.arguments);
  1126. },
  1127. "MemberExpression, JSXMemberExpression, MetaProperty"(node) {
  1128. const object = node.type === "MetaProperty" ? node.meta : node.object;
  1129. const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken);
  1130. const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken);
  1131. const objectParenCount = sourceCode.getTokensBetween(object, node.property, { filter: astUtils.isClosingParenToken }).length;
  1132. const firstObjectToken = objectParenCount
  1133. ? sourceCode.getTokenBefore(object, { skip: objectParenCount - 1 })
  1134. : sourceCode.getFirstToken(object);
  1135. const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken);
  1136. const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken;
  1137. if (node.computed) {
  1138. // For computed MemberExpressions, match the closing bracket with the opening bracket.
  1139. offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0);
  1140. offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1);
  1141. }
  1142. /*
  1143. * If the object ends on the same line that the property starts, match against the last token
  1144. * of the object, to ensure that the MemberExpression is not indented.
  1145. *
  1146. * Otherwise, match against the first token of the object, e.g.
  1147. * foo
  1148. * .bar
  1149. * .baz // <-- offset by 1 from `foo`
  1150. */
  1151. const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line
  1152. ? lastObjectToken
  1153. : firstObjectToken;
  1154. if (typeof options.MemberExpression === "number") {
  1155. // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object.
  1156. offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression);
  1157. /*
  1158. * For computed MemberExpressions, match the first token of the property against the opening bracket.
  1159. * Otherwise, match the first token of the property against the object.
  1160. */
  1161. offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression);
  1162. } else {
  1163. // If the MemberExpression option is off, ignore the dot and the first token of the property.
  1164. offsets.ignoreToken(firstNonObjectToken);
  1165. offsets.ignoreToken(secondNonObjectToken);
  1166. // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens.
  1167. offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0);
  1168. offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0);
  1169. }
  1170. },
  1171. NewExpression(node) {
  1172. // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo`
  1173. if (node.arguments.length > 0 ||
  1174. astUtils.isClosingParenToken(sourceCode.getLastToken(node)) &&
  1175. astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) {
  1176. addFunctionCallIndent(node);
  1177. }
  1178. },
  1179. Property(node) {
  1180. if (!node.shorthand && !node.method && node.kind === "init") {
  1181. const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken);
  1182. offsets.ignoreToken(sourceCode.getTokenAfter(colon));
  1183. }
  1184. },
  1185. SwitchStatement(node) {
  1186. const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken);
  1187. const closingCurly = sourceCode.getLastToken(node);
  1188. offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase);
  1189. if (node.cases.length) {
  1190. sourceCode.getTokensBetween(
  1191. node.cases[node.cases.length - 1],
  1192. closingCurly,
  1193. { includeComments: true, filter: astUtils.isCommentToken }
  1194. ).forEach(token => offsets.ignoreToken(token));
  1195. }
  1196. },
  1197. SwitchCase(node) {
  1198. if (!(node.consequent.length === 1 && node.consequent[0].type === "BlockStatement")) {
  1199. const caseKeyword = sourceCode.getFirstToken(node);
  1200. const tokenAfterCurrentCase = sourceCode.getTokenAfter(node);
  1201. offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1);
  1202. }
  1203. },
  1204. TemplateLiteral(node) {
  1205. node.expressions.forEach((expression, index) => {
  1206. const previousQuasi = node.quasis[index];
  1207. const nextQuasi = node.quasis[index + 1];
  1208. const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line
  1209. ? sourceCode.getFirstToken(previousQuasi)
  1210. : null;
  1211. offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1);
  1212. offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0);
  1213. });
  1214. },
  1215. VariableDeclaration(node) {
  1216. let variableIndent = Object.prototype.hasOwnProperty.call(options.VariableDeclarator, node.kind)
  1217. ? options.VariableDeclarator[node.kind]
  1218. : DEFAULT_VARIABLE_INDENT;
  1219. const firstToken = sourceCode.getFirstToken(node),
  1220. lastToken = sourceCode.getLastToken(node);
  1221. if (options.VariableDeclarator[node.kind] === "first") {
  1222. if (node.declarations.length > 1) {
  1223. addElementListIndent(
  1224. node.declarations,
  1225. firstToken,
  1226. lastToken,
  1227. "first"
  1228. );
  1229. return;
  1230. }
  1231. variableIndent = DEFAULT_VARIABLE_INDENT;
  1232. }
  1233. if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) {
  1234. /*
  1235. * VariableDeclarator indentation is a bit different from other forms of indentation, in that the
  1236. * indentation of an opening bracket sometimes won't match that of a closing bracket. For example,
  1237. * the following indentations are correct:
  1238. *
  1239. * var foo = {
  1240. * ok: true
  1241. * };
  1242. *
  1243. * var foo = {
  1244. * ok: true,
  1245. * },
  1246. * bar = 1;
  1247. *
  1248. * Account for when exiting the AST (after indentations have already been set for the nodes in
  1249. * the declaration) by manually increasing the indentation level of the tokens in this declarator
  1250. * on the same line as the start of the declaration, provided that there are declarators that
  1251. * follow this one.
  1252. */
  1253. offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true);
  1254. } else {
  1255. offsets.setDesiredOffsets(node.range, firstToken, variableIndent);
  1256. }
  1257. if (astUtils.isSemicolonToken(lastToken)) {
  1258. offsets.ignoreToken(lastToken);
  1259. }
  1260. },
  1261. VariableDeclarator(node) {
  1262. if (node.init) {
  1263. const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken);
  1264. const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator);
  1265. offsets.ignoreToken(equalOperator);
  1266. offsets.ignoreToken(tokenAfterOperator);
  1267. offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1);
  1268. offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0);
  1269. }
  1270. },
  1271. "JSXAttribute[value]"(node) {
  1272. const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "=");
  1273. offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1);
  1274. },
  1275. JSXElement(node) {
  1276. if (node.closingElement) {
  1277. addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1);
  1278. }
  1279. },
  1280. JSXOpeningElement(node) {
  1281. const firstToken = sourceCode.getFirstToken(node);
  1282. let closingToken;
  1283. if (node.selfClosing) {
  1284. closingToken = sourceCode.getLastToken(node, { skip: 1 });
  1285. offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0);
  1286. } else {
  1287. closingToken = sourceCode.getLastToken(node);
  1288. }
  1289. offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node));
  1290. addElementListIndent(node.attributes, firstToken, closingToken, 1);
  1291. },
  1292. JSXClosingElement(node) {
  1293. const firstToken = sourceCode.getFirstToken(node);
  1294. offsets.setDesiredOffsets(node.name.range, firstToken, 1);
  1295. },
  1296. JSXFragment(node) {
  1297. const firstOpeningToken = sourceCode.getFirstToken(node.openingFragment);
  1298. const firstClosingToken = sourceCode.getFirstToken(node.closingFragment);
  1299. addElementListIndent(node.children, firstOpeningToken, firstClosingToken, 1);
  1300. },
  1301. JSXOpeningFragment(node) {
  1302. const firstToken = sourceCode.getFirstToken(node);
  1303. const closingToken = sourceCode.getLastToken(node);
  1304. offsets.setDesiredOffsets(node.range, firstToken, 1);
  1305. offsets.matchOffsetOf(firstToken, closingToken);
  1306. },
  1307. JSXClosingFragment(node) {
  1308. const firstToken = sourceCode.getFirstToken(node);
  1309. const slashToken = sourceCode.getLastToken(node, { skip: 1 });
  1310. const closingToken = sourceCode.getLastToken(node);
  1311. const tokenToMatch = astUtils.isTokenOnSameLine(slashToken, closingToken) ? slashToken : closingToken;
  1312. offsets.setDesiredOffsets(node.range, firstToken, 1);
  1313. offsets.matchOffsetOf(firstToken, tokenToMatch);
  1314. },
  1315. JSXExpressionContainer(node) {
  1316. const openingCurly = sourceCode.getFirstToken(node);
  1317. const closingCurly = sourceCode.getLastToken(node);
  1318. offsets.setDesiredOffsets(
  1319. [openingCurly.range[1], closingCurly.range[0]],
  1320. openingCurly,
  1321. 1
  1322. );
  1323. },
  1324. JSXSpreadAttribute(node) {
  1325. const openingCurly = sourceCode.getFirstToken(node);
  1326. const closingCurly = sourceCode.getLastToken(node);
  1327. offsets.setDesiredOffsets(
  1328. [openingCurly.range[1], closingCurly.range[0]],
  1329. openingCurly,
  1330. 1
  1331. );
  1332. },
  1333. "*"(node) {
  1334. const firstToken = sourceCode.getFirstToken(node);
  1335. // Ensure that the children of every node are indented at least as much as the first token.
  1336. if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) {
  1337. offsets.setDesiredOffsets(node.range, firstToken, 0);
  1338. }
  1339. }
  1340. };
  1341. const listenerCallQueue = [];
  1342. /*
  1343. * To ignore the indentation of a node:
  1344. * 1. Don't call the node's listener when entering it (if it has a listener)
  1345. * 2. Don't set any offsets against the first token of the node.
  1346. * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets.
  1347. */
  1348. const offsetListeners = {};
  1349. for (const [selector, listener] of Object.entries(baseOffsetListeners)) {
  1350. /*
  1351. * Offset listener calls are deferred until traversal is finished, and are called as
  1352. * part of the final `Program:exit` listener. This is necessary because a node might
  1353. * be matched by multiple selectors.
  1354. *
  1355. * Example: Suppose there is an offset listener for `Identifier`, and the user has
  1356. * specified in configuration that `MemberExpression > Identifier` should be ignored.
  1357. * Due to selector specificity rules, the `Identifier` listener will get called first. However,
  1358. * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener
  1359. * should not have been called at all. Without doing extra selector matching, we don't know
  1360. * whether the Identifier matches the `MemberExpression > Identifier` selector until the
  1361. * `MemberExpression > Identifier` listener is called.
  1362. *
  1363. * To avoid this, the `Identifier` listener isn't called until traversal finishes and all
  1364. * ignored nodes are known.
  1365. */
  1366. offsetListeners[selector] = node => listenerCallQueue.push({ listener, node });
  1367. }
  1368. // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set.
  1369. const ignoredNodes = new Set();
  1370. /**
  1371. * Ignores a node
  1372. * @param {ASTNode} node The node to ignore
  1373. * @returns {void}
  1374. */
  1375. function addToIgnoredNodes(node) {
  1376. ignoredNodes.add(node);
  1377. ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node));
  1378. }
  1379. const ignoredNodeListeners = options.ignoredNodes.reduce(
  1380. (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }),
  1381. {}
  1382. );
  1383. /*
  1384. * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation
  1385. * at the end.
  1386. *
  1387. * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears
  1388. * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored,
  1389. * so those listeners wouldn't be called anyway.
  1390. */
  1391. return Object.assign(
  1392. offsetListeners,
  1393. ignoredNodeListeners,
  1394. {
  1395. "*:exit"(node) {
  1396. // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it.
  1397. if (!KNOWN_NODES.has(node.type)) {
  1398. addToIgnoredNodes(node);
  1399. }
  1400. },
  1401. "Program:exit"() {
  1402. // If ignoreComments option is enabled, ignore all comment tokens.
  1403. if (options.ignoreComments) {
  1404. sourceCode.getAllComments()
  1405. .forEach(comment => offsets.ignoreToken(comment));
  1406. }
  1407. // Invoke the queued offset listeners for the nodes that aren't ignored.
  1408. listenerCallQueue
  1409. .filter(nodeInfo => !ignoredNodes.has(nodeInfo.node))
  1410. .forEach(nodeInfo => nodeInfo.listener(nodeInfo.node));
  1411. // Update the offsets for ignored nodes to prevent their child tokens from being reported.
  1412. ignoredNodes.forEach(ignoreNode);
  1413. addParensIndent(sourceCode.ast.tokens);
  1414. /*
  1415. * Create a Map from (tokenOrComment) => (precedingToken).
  1416. * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly.
  1417. */
  1418. const precedingTokens = sourceCode.ast.comments.reduce((commentMap, comment) => {
  1419. const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
  1420. return commentMap.set(comment, commentMap.has(tokenOrCommentBefore) ? commentMap.get(tokenOrCommentBefore) : tokenOrCommentBefore);
  1421. }, new WeakMap());
  1422. sourceCode.lines.forEach((line, lineIndex) => {
  1423. const lineNumber = lineIndex + 1;
  1424. if (!tokenInfo.firstTokensByLineNumber.has(lineNumber)) {
  1425. // Don't check indentation on blank lines
  1426. return;
  1427. }
  1428. const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(lineNumber);
  1429. if (firstTokenOfLine.loc.start.line !== lineNumber) {
  1430. // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice.
  1431. return;
  1432. }
  1433. if (astUtils.isCommentToken(firstTokenOfLine)) {
  1434. const tokenBefore = precedingTokens.get(firstTokenOfLine);
  1435. const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0];
  1436. const mayAlignWithBefore = tokenBefore && !hasBlankLinesBetween(tokenBefore, firstTokenOfLine);
  1437. const mayAlignWithAfter = tokenAfter && !hasBlankLinesBetween(firstTokenOfLine, tokenAfter);
  1438. /*
  1439. * If a comment precedes a line that begins with a semicolon token, align to that token, i.e.
  1440. *
  1441. * let foo
  1442. * // comment
  1443. * ;(async () => {})()
  1444. */
  1445. if (tokenAfter && astUtils.isSemicolonToken(tokenAfter) && !astUtils.isTokenOnSameLine(firstTokenOfLine, tokenAfter)) {
  1446. offsets.setDesiredOffset(firstTokenOfLine, tokenAfter, 0);
  1447. }
  1448. // If a comment matches the expected indentation of the token immediately before or after, don't report it.
  1449. if (
  1450. mayAlignWithBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) ||
  1451. mayAlignWithAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter))
  1452. ) {
  1453. return;
  1454. }
  1455. }
  1456. // If the token matches the expected indentation, don't report it.
  1457. if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) {
  1458. return;
  1459. }
  1460. // Otherwise, report the token/comment.
  1461. report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine));
  1462. });
  1463. }
  1464. }
  1465. );
  1466. }
  1467. };