keyword-spacing.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. /**
  2. * @fileoverview Rule to enforce spacing before and after keywords.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils"),
  10. keywords = require("./utils/keywords");
  11. //------------------------------------------------------------------------------
  12. // Constants
  13. //------------------------------------------------------------------------------
  14. const PREV_TOKEN = /^[)\]}>]$/u;
  15. const NEXT_TOKEN = /^(?:[([{<~!]|\+\+?|--?)$/u;
  16. const PREV_TOKEN_M = /^[)\]}>*]$/u;
  17. const NEXT_TOKEN_M = /^[{*]$/u;
  18. const TEMPLATE_OPEN_PAREN = /\$\{$/u;
  19. const TEMPLATE_CLOSE_PAREN = /^\}/u;
  20. const CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template|PrivateIdentifier)$/u;
  21. const KEYS = keywords.concat(["as", "async", "await", "from", "get", "let", "of", "set", "yield"]);
  22. // check duplications.
  23. (function() {
  24. KEYS.sort();
  25. for (let i = 1; i < KEYS.length; ++i) {
  26. if (KEYS[i] === KEYS[i - 1]) {
  27. throw new Error(`Duplication was found in the keyword list: ${KEYS[i]}`);
  28. }
  29. }
  30. }());
  31. //------------------------------------------------------------------------------
  32. // Helpers
  33. //------------------------------------------------------------------------------
  34. /**
  35. * Checks whether or not a given token is a "Template" token ends with "${".
  36. * @param {Token} token A token to check.
  37. * @returns {boolean} `true` if the token is a "Template" token ends with "${".
  38. */
  39. function isOpenParenOfTemplate(token) {
  40. return token.type === "Template" && TEMPLATE_OPEN_PAREN.test(token.value);
  41. }
  42. /**
  43. * Checks whether or not a given token is a "Template" token starts with "}".
  44. * @param {Token} token A token to check.
  45. * @returns {boolean} `true` if the token is a "Template" token starts with "}".
  46. */
  47. function isCloseParenOfTemplate(token) {
  48. return token.type === "Template" && TEMPLATE_CLOSE_PAREN.test(token.value);
  49. }
  50. //------------------------------------------------------------------------------
  51. // Rule Definition
  52. //------------------------------------------------------------------------------
  53. /** @type {import('../shared/types').Rule} */
  54. module.exports = {
  55. meta: {
  56. type: "layout",
  57. docs: {
  58. description: "Enforce consistent spacing before and after keywords",
  59. recommended: false,
  60. url: "https://eslint.org/docs/rules/keyword-spacing"
  61. },
  62. fixable: "whitespace",
  63. schema: [
  64. {
  65. type: "object",
  66. properties: {
  67. before: { type: "boolean", default: true },
  68. after: { type: "boolean", default: true },
  69. overrides: {
  70. type: "object",
  71. properties: KEYS.reduce((retv, key) => {
  72. retv[key] = {
  73. type: "object",
  74. properties: {
  75. before: { type: "boolean" },
  76. after: { type: "boolean" }
  77. },
  78. additionalProperties: false
  79. };
  80. return retv;
  81. }, {}),
  82. additionalProperties: false
  83. }
  84. },
  85. additionalProperties: false
  86. }
  87. ],
  88. messages: {
  89. expectedBefore: "Expected space(s) before \"{{value}}\".",
  90. expectedAfter: "Expected space(s) after \"{{value}}\".",
  91. unexpectedBefore: "Unexpected space(s) before \"{{value}}\".",
  92. unexpectedAfter: "Unexpected space(s) after \"{{value}}\"."
  93. }
  94. },
  95. create(context) {
  96. const sourceCode = context.getSourceCode();
  97. const tokensToIgnore = new WeakSet();
  98. /**
  99. * Reports a given token if there are not space(s) before the token.
  100. * @param {Token} token A token to report.
  101. * @param {RegExp} pattern A pattern of the previous token to check.
  102. * @returns {void}
  103. */
  104. function expectSpaceBefore(token, pattern) {
  105. const prevToken = sourceCode.getTokenBefore(token);
  106. if (prevToken &&
  107. (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) &&
  108. !isOpenParenOfTemplate(prevToken) &&
  109. !tokensToIgnore.has(prevToken) &&
  110. astUtils.isTokenOnSameLine(prevToken, token) &&
  111. !sourceCode.isSpaceBetweenTokens(prevToken, token)
  112. ) {
  113. context.report({
  114. loc: token.loc,
  115. messageId: "expectedBefore",
  116. data: token,
  117. fix(fixer) {
  118. return fixer.insertTextBefore(token, " ");
  119. }
  120. });
  121. }
  122. }
  123. /**
  124. * Reports a given token if there are space(s) before the token.
  125. * @param {Token} token A token to report.
  126. * @param {RegExp} pattern A pattern of the previous token to check.
  127. * @returns {void}
  128. */
  129. function unexpectSpaceBefore(token, pattern) {
  130. const prevToken = sourceCode.getTokenBefore(token);
  131. if (prevToken &&
  132. (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) &&
  133. !isOpenParenOfTemplate(prevToken) &&
  134. !tokensToIgnore.has(prevToken) &&
  135. astUtils.isTokenOnSameLine(prevToken, token) &&
  136. sourceCode.isSpaceBetweenTokens(prevToken, token)
  137. ) {
  138. context.report({
  139. loc: { start: prevToken.loc.end, end: token.loc.start },
  140. messageId: "unexpectedBefore",
  141. data: token,
  142. fix(fixer) {
  143. return fixer.removeRange([prevToken.range[1], token.range[0]]);
  144. }
  145. });
  146. }
  147. }
  148. /**
  149. * Reports a given token if there are not space(s) after the token.
  150. * @param {Token} token A token to report.
  151. * @param {RegExp} pattern A pattern of the next token to check.
  152. * @returns {void}
  153. */
  154. function expectSpaceAfter(token, pattern) {
  155. const nextToken = sourceCode.getTokenAfter(token);
  156. if (nextToken &&
  157. (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) &&
  158. !isCloseParenOfTemplate(nextToken) &&
  159. !tokensToIgnore.has(nextToken) &&
  160. astUtils.isTokenOnSameLine(token, nextToken) &&
  161. !sourceCode.isSpaceBetweenTokens(token, nextToken)
  162. ) {
  163. context.report({
  164. loc: token.loc,
  165. messageId: "expectedAfter",
  166. data: token,
  167. fix(fixer) {
  168. return fixer.insertTextAfter(token, " ");
  169. }
  170. });
  171. }
  172. }
  173. /**
  174. * Reports a given token if there are space(s) after the token.
  175. * @param {Token} token A token to report.
  176. * @param {RegExp} pattern A pattern of the next token to check.
  177. * @returns {void}
  178. */
  179. function unexpectSpaceAfter(token, pattern) {
  180. const nextToken = sourceCode.getTokenAfter(token);
  181. if (nextToken &&
  182. (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) &&
  183. !isCloseParenOfTemplate(nextToken) &&
  184. !tokensToIgnore.has(nextToken) &&
  185. astUtils.isTokenOnSameLine(token, nextToken) &&
  186. sourceCode.isSpaceBetweenTokens(token, nextToken)
  187. ) {
  188. context.report({
  189. loc: { start: token.loc.end, end: nextToken.loc.start },
  190. messageId: "unexpectedAfter",
  191. data: token,
  192. fix(fixer) {
  193. return fixer.removeRange([token.range[1], nextToken.range[0]]);
  194. }
  195. });
  196. }
  197. }
  198. /**
  199. * Parses the option object and determines check methods for each keyword.
  200. * @param {Object|undefined} options The option object to parse.
  201. * @returns {Object} - Normalized option object.
  202. * Keys are keywords (there are for every keyword).
  203. * Values are instances of `{"before": function, "after": function}`.
  204. */
  205. function parseOptions(options = {}) {
  206. const before = options.before !== false;
  207. const after = options.after !== false;
  208. const defaultValue = {
  209. before: before ? expectSpaceBefore : unexpectSpaceBefore,
  210. after: after ? expectSpaceAfter : unexpectSpaceAfter
  211. };
  212. const overrides = (options && options.overrides) || {};
  213. const retv = Object.create(null);
  214. for (let i = 0; i < KEYS.length; ++i) {
  215. const key = KEYS[i];
  216. const override = overrides[key];
  217. if (override) {
  218. const thisBefore = ("before" in override) ? override.before : before;
  219. const thisAfter = ("after" in override) ? override.after : after;
  220. retv[key] = {
  221. before: thisBefore ? expectSpaceBefore : unexpectSpaceBefore,
  222. after: thisAfter ? expectSpaceAfter : unexpectSpaceAfter
  223. };
  224. } else {
  225. retv[key] = defaultValue;
  226. }
  227. }
  228. return retv;
  229. }
  230. const checkMethodMap = parseOptions(context.options[0]);
  231. /**
  232. * Reports a given token if usage of spacing followed by the token is
  233. * invalid.
  234. * @param {Token} token A token to report.
  235. * @param {RegExp} [pattern] Optional. A pattern of the previous
  236. * token to check.
  237. * @returns {void}
  238. */
  239. function checkSpacingBefore(token, pattern) {
  240. checkMethodMap[token.value].before(token, pattern || PREV_TOKEN);
  241. }
  242. /**
  243. * Reports a given token if usage of spacing preceded by the token is
  244. * invalid.
  245. * @param {Token} token A token to report.
  246. * @param {RegExp} [pattern] Optional. A pattern of the next
  247. * token to check.
  248. * @returns {void}
  249. */
  250. function checkSpacingAfter(token, pattern) {
  251. checkMethodMap[token.value].after(token, pattern || NEXT_TOKEN);
  252. }
  253. /**
  254. * Reports a given token if usage of spacing around the token is invalid.
  255. * @param {Token} token A token to report.
  256. * @returns {void}
  257. */
  258. function checkSpacingAround(token) {
  259. checkSpacingBefore(token);
  260. checkSpacingAfter(token);
  261. }
  262. /**
  263. * Reports the first token of a given node if the first token is a keyword
  264. * and usage of spacing around the token is invalid.
  265. * @param {ASTNode|null} node A node to report.
  266. * @returns {void}
  267. */
  268. function checkSpacingAroundFirstToken(node) {
  269. const firstToken = node && sourceCode.getFirstToken(node);
  270. if (firstToken && firstToken.type === "Keyword") {
  271. checkSpacingAround(firstToken);
  272. }
  273. }
  274. /**
  275. * Reports the first token of a given node if the first token is a keyword
  276. * and usage of spacing followed by the token is invalid.
  277. *
  278. * This is used for unary operators (e.g. `typeof`), `function`, and `super`.
  279. * Other rules are handling usage of spacing preceded by those keywords.
  280. * @param {ASTNode|null} node A node to report.
  281. * @returns {void}
  282. */
  283. function checkSpacingBeforeFirstToken(node) {
  284. const firstToken = node && sourceCode.getFirstToken(node);
  285. if (firstToken && firstToken.type === "Keyword") {
  286. checkSpacingBefore(firstToken);
  287. }
  288. }
  289. /**
  290. * Reports the previous token of a given node if the token is a keyword and
  291. * usage of spacing around the token is invalid.
  292. * @param {ASTNode|null} node A node to report.
  293. * @returns {void}
  294. */
  295. function checkSpacingAroundTokenBefore(node) {
  296. if (node) {
  297. const token = sourceCode.getTokenBefore(node, astUtils.isKeywordToken);
  298. checkSpacingAround(token);
  299. }
  300. }
  301. /**
  302. * Reports `async` or `function` keywords of a given node if usage of
  303. * spacing around those keywords is invalid.
  304. * @param {ASTNode} node A node to report.
  305. * @returns {void}
  306. */
  307. function checkSpacingForFunction(node) {
  308. const firstToken = node && sourceCode.getFirstToken(node);
  309. if (firstToken &&
  310. ((firstToken.type === "Keyword" && firstToken.value === "function") ||
  311. firstToken.value === "async")
  312. ) {
  313. checkSpacingBefore(firstToken);
  314. }
  315. }
  316. /**
  317. * Reports `class` and `extends` keywords of a given node if usage of
  318. * spacing around those keywords is invalid.
  319. * @param {ASTNode} node A node to report.
  320. * @returns {void}
  321. */
  322. function checkSpacingForClass(node) {
  323. checkSpacingAroundFirstToken(node);
  324. checkSpacingAroundTokenBefore(node.superClass);
  325. }
  326. /**
  327. * Reports `if` and `else` keywords of a given node if usage of spacing
  328. * around those keywords is invalid.
  329. * @param {ASTNode} node A node to report.
  330. * @returns {void}
  331. */
  332. function checkSpacingForIfStatement(node) {
  333. checkSpacingAroundFirstToken(node);
  334. checkSpacingAroundTokenBefore(node.alternate);
  335. }
  336. /**
  337. * Reports `try`, `catch`, and `finally` keywords of a given node if usage
  338. * of spacing around those keywords is invalid.
  339. * @param {ASTNode} node A node to report.
  340. * @returns {void}
  341. */
  342. function checkSpacingForTryStatement(node) {
  343. checkSpacingAroundFirstToken(node);
  344. checkSpacingAroundFirstToken(node.handler);
  345. checkSpacingAroundTokenBefore(node.finalizer);
  346. }
  347. /**
  348. * Reports `do` and `while` keywords of a given node if usage of spacing
  349. * around those keywords is invalid.
  350. * @param {ASTNode} node A node to report.
  351. * @returns {void}
  352. */
  353. function checkSpacingForDoWhileStatement(node) {
  354. checkSpacingAroundFirstToken(node);
  355. checkSpacingAroundTokenBefore(node.test);
  356. }
  357. /**
  358. * Reports `for` and `in` keywords of a given node if usage of spacing
  359. * around those keywords is invalid.
  360. * @param {ASTNode} node A node to report.
  361. * @returns {void}
  362. */
  363. function checkSpacingForForInStatement(node) {
  364. checkSpacingAroundFirstToken(node);
  365. const inToken = sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken);
  366. const previousToken = sourceCode.getTokenBefore(inToken);
  367. if (previousToken.type !== "PrivateIdentifier") {
  368. checkSpacingBefore(inToken);
  369. }
  370. checkSpacingAfter(inToken);
  371. }
  372. /**
  373. * Reports `for` and `of` keywords of a given node if usage of spacing
  374. * around those keywords is invalid.
  375. * @param {ASTNode} node A node to report.
  376. * @returns {void}
  377. */
  378. function checkSpacingForForOfStatement(node) {
  379. if (node.await) {
  380. checkSpacingBefore(sourceCode.getFirstToken(node, 0));
  381. checkSpacingAfter(sourceCode.getFirstToken(node, 1));
  382. } else {
  383. checkSpacingAroundFirstToken(node);
  384. }
  385. const ofToken = sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken);
  386. const previousToken = sourceCode.getTokenBefore(ofToken);
  387. if (previousToken.type !== "PrivateIdentifier") {
  388. checkSpacingBefore(ofToken);
  389. }
  390. checkSpacingAfter(ofToken);
  391. }
  392. /**
  393. * Reports `import`, `export`, `as`, and `from` keywords of a given node if
  394. * usage of spacing around those keywords is invalid.
  395. *
  396. * This rule handles the `*` token in module declarations.
  397. *
  398. * import*as A from "./a"; /*error Expected space(s) after "import".
  399. * error Expected space(s) before "as".
  400. * @param {ASTNode} node A node to report.
  401. * @returns {void}
  402. */
  403. function checkSpacingForModuleDeclaration(node) {
  404. const firstToken = sourceCode.getFirstToken(node);
  405. checkSpacingBefore(firstToken, PREV_TOKEN_M);
  406. checkSpacingAfter(firstToken, NEXT_TOKEN_M);
  407. if (node.type === "ExportDefaultDeclaration") {
  408. checkSpacingAround(sourceCode.getTokenAfter(firstToken));
  409. }
  410. if (node.type === "ExportAllDeclaration" && node.exported) {
  411. const asToken = sourceCode.getTokenBefore(node.exported);
  412. checkSpacingBefore(asToken, PREV_TOKEN_M);
  413. checkSpacingAfter(asToken, NEXT_TOKEN_M);
  414. }
  415. if (node.source) {
  416. const fromToken = sourceCode.getTokenBefore(node.source);
  417. checkSpacingBefore(fromToken, PREV_TOKEN_M);
  418. checkSpacingAfter(fromToken, NEXT_TOKEN_M);
  419. }
  420. }
  421. /**
  422. * Reports `as` keyword of a given node if usage of spacing around this
  423. * keyword is invalid.
  424. * @param {ASTNode} node An `ImportSpecifier` node to check.
  425. * @returns {void}
  426. */
  427. function checkSpacingForImportSpecifier(node) {
  428. if (node.imported.range[0] !== node.local.range[0]) {
  429. const asToken = sourceCode.getTokenBefore(node.local);
  430. checkSpacingBefore(asToken, PREV_TOKEN_M);
  431. }
  432. }
  433. /**
  434. * Reports `as` keyword of a given node if usage of spacing around this
  435. * keyword is invalid.
  436. * @param {ASTNode} node An `ExportSpecifier` node to check.
  437. * @returns {void}
  438. */
  439. function checkSpacingForExportSpecifier(node) {
  440. if (node.local.range[0] !== node.exported.range[0]) {
  441. const asToken = sourceCode.getTokenBefore(node.exported);
  442. checkSpacingBefore(asToken, PREV_TOKEN_M);
  443. checkSpacingAfter(asToken, NEXT_TOKEN_M);
  444. }
  445. }
  446. /**
  447. * Reports `as` keyword of a given node if usage of spacing around this
  448. * keyword is invalid.
  449. * @param {ASTNode} node A node to report.
  450. * @returns {void}
  451. */
  452. function checkSpacingForImportNamespaceSpecifier(node) {
  453. const asToken = sourceCode.getFirstToken(node, 1);
  454. checkSpacingBefore(asToken, PREV_TOKEN_M);
  455. }
  456. /**
  457. * Reports `static`, `get`, and `set` keywords of a given node if usage of
  458. * spacing around those keywords is invalid.
  459. * @param {ASTNode} node A node to report.
  460. * @throws {Error} If unable to find token get, set, or async beside method name.
  461. * @returns {void}
  462. */
  463. function checkSpacingForProperty(node) {
  464. if (node.static) {
  465. checkSpacingAroundFirstToken(node);
  466. }
  467. if (node.kind === "get" ||
  468. node.kind === "set" ||
  469. (
  470. (node.method || node.type === "MethodDefinition") &&
  471. node.value.async
  472. )
  473. ) {
  474. const token = sourceCode.getTokenBefore(
  475. node.key,
  476. tok => {
  477. switch (tok.value) {
  478. case "get":
  479. case "set":
  480. case "async":
  481. return true;
  482. default:
  483. return false;
  484. }
  485. }
  486. );
  487. if (!token) {
  488. throw new Error("Failed to find token get, set, or async beside method name");
  489. }
  490. checkSpacingAround(token);
  491. }
  492. }
  493. /**
  494. * Reports `await` keyword of a given node if usage of spacing before
  495. * this keyword is invalid.
  496. * @param {ASTNode} node A node to report.
  497. * @returns {void}
  498. */
  499. function checkSpacingForAwaitExpression(node) {
  500. checkSpacingBefore(sourceCode.getFirstToken(node));
  501. }
  502. return {
  503. // Statements
  504. DebuggerStatement: checkSpacingAroundFirstToken,
  505. WithStatement: checkSpacingAroundFirstToken,
  506. // Statements - Control flow
  507. BreakStatement: checkSpacingAroundFirstToken,
  508. ContinueStatement: checkSpacingAroundFirstToken,
  509. ReturnStatement: checkSpacingAroundFirstToken,
  510. ThrowStatement: checkSpacingAroundFirstToken,
  511. TryStatement: checkSpacingForTryStatement,
  512. // Statements - Choice
  513. IfStatement: checkSpacingForIfStatement,
  514. SwitchStatement: checkSpacingAroundFirstToken,
  515. SwitchCase: checkSpacingAroundFirstToken,
  516. // Statements - Loops
  517. DoWhileStatement: checkSpacingForDoWhileStatement,
  518. ForInStatement: checkSpacingForForInStatement,
  519. ForOfStatement: checkSpacingForForOfStatement,
  520. ForStatement: checkSpacingAroundFirstToken,
  521. WhileStatement: checkSpacingAroundFirstToken,
  522. // Statements - Declarations
  523. ClassDeclaration: checkSpacingForClass,
  524. ExportNamedDeclaration: checkSpacingForModuleDeclaration,
  525. ExportDefaultDeclaration: checkSpacingForModuleDeclaration,
  526. ExportAllDeclaration: checkSpacingForModuleDeclaration,
  527. FunctionDeclaration: checkSpacingForFunction,
  528. ImportDeclaration: checkSpacingForModuleDeclaration,
  529. VariableDeclaration: checkSpacingAroundFirstToken,
  530. // Expressions
  531. ArrowFunctionExpression: checkSpacingForFunction,
  532. AwaitExpression: checkSpacingForAwaitExpression,
  533. ClassExpression: checkSpacingForClass,
  534. FunctionExpression: checkSpacingForFunction,
  535. NewExpression: checkSpacingBeforeFirstToken,
  536. Super: checkSpacingBeforeFirstToken,
  537. ThisExpression: checkSpacingBeforeFirstToken,
  538. UnaryExpression: checkSpacingBeforeFirstToken,
  539. YieldExpression: checkSpacingBeforeFirstToken,
  540. // Others
  541. ImportSpecifier: checkSpacingForImportSpecifier,
  542. ExportSpecifier: checkSpacingForExportSpecifier,
  543. ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier,
  544. MethodDefinition: checkSpacingForProperty,
  545. PropertyDefinition: checkSpacingForProperty,
  546. StaticBlock: checkSpacingAroundFirstToken,
  547. Property: checkSpacingForProperty,
  548. // To avoid conflicts with `space-infix-ops`, e.g. `a > this.b`
  549. "BinaryExpression[operator='>']"(node) {
  550. const operatorToken = sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken);
  551. tokensToIgnore.add(operatorToken);
  552. }
  553. };
  554. }
  555. };