项目原始demo,不改动
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
このリポジトリはアーカイブされています。 ファイルの閲覧とクローンは可能ですが、プッシュや、課題・プルリクエストのオープンはできません。
 
 
 
 

381 行
16 KiB

  1. /**
  2. * @fileoverview Rule to flag statements without curly braces
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. module.exports = {
  14. meta: {
  15. docs: {
  16. description: "enforce consistent brace style for all control statements",
  17. category: "Best Practices",
  18. recommended: false,
  19. url: "https://eslint.org/docs/rules/curly"
  20. },
  21. schema: {
  22. anyOf: [
  23. {
  24. type: "array",
  25. items: [
  26. {
  27. enum: ["all"]
  28. }
  29. ],
  30. minItems: 0,
  31. maxItems: 1
  32. },
  33. {
  34. type: "array",
  35. items: [
  36. {
  37. enum: ["multi", "multi-line", "multi-or-nest"]
  38. },
  39. {
  40. enum: ["consistent"]
  41. }
  42. ],
  43. minItems: 0,
  44. maxItems: 2
  45. }
  46. ]
  47. },
  48. fixable: "code",
  49. messages: {
  50. missingCurlyAfter: "Expected { after '{{name}}'.",
  51. missingCurlyAfterCondition: "Expected { after '{{name}}' condition.",
  52. unexpectedCurlyAfter: "Unnecessary { after '{{name}}'.",
  53. unexpectedCurlyAfterCondition: "Unnecessary { after '{{name}}' condition."
  54. }
  55. },
  56. create(context) {
  57. const multiOnly = (context.options[0] === "multi");
  58. const multiLine = (context.options[0] === "multi-line");
  59. const multiOrNest = (context.options[0] === "multi-or-nest");
  60. const consistent = (context.options[1] === "consistent");
  61. const sourceCode = context.getSourceCode();
  62. //--------------------------------------------------------------------------
  63. // Helpers
  64. //--------------------------------------------------------------------------
  65. /**
  66. * Determines if a given node is a one-liner that's on the same line as it's preceding code.
  67. * @param {ASTNode} node The node to check.
  68. * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code.
  69. * @private
  70. */
  71. function isCollapsedOneLiner(node) {
  72. const before = sourceCode.getTokenBefore(node);
  73. const last = sourceCode.getLastToken(node);
  74. const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last;
  75. return before.loc.start.line === lastExcludingSemicolon.loc.end.line;
  76. }
  77. /**
  78. * Determines if a given node is a one-liner.
  79. * @param {ASTNode} node The node to check.
  80. * @returns {boolean} True if the node is a one-liner.
  81. * @private
  82. */
  83. function isOneLiner(node) {
  84. const first = sourceCode.getFirstToken(node),
  85. last = sourceCode.getLastToken(node);
  86. return first.loc.start.line === last.loc.end.line;
  87. }
  88. /**
  89. * Checks if the given token is an `else` token or not.
  90. *
  91. * @param {Token} token - The token to check.
  92. * @returns {boolean} `true` if the token is an `else` token.
  93. */
  94. function isElseKeywordToken(token) {
  95. return token.value === "else" && token.type === "Keyword";
  96. }
  97. /**
  98. * Gets the `else` keyword token of a given `IfStatement` node.
  99. * @param {ASTNode} node - A `IfStatement` node to get.
  100. * @returns {Token} The `else` keyword token.
  101. */
  102. function getElseKeyword(node) {
  103. return node.alternate && sourceCode.getFirstTokenBetween(node.consequent, node.alternate, isElseKeywordToken);
  104. }
  105. /**
  106. * Checks a given IfStatement node requires braces of the consequent chunk.
  107. * This returns `true` when below:
  108. *
  109. * 1. The given node has the `alternate` node.
  110. * 2. There is a `IfStatement` which doesn't have `alternate` node in the
  111. * trailing statement chain of the `consequent` node.
  112. *
  113. * @param {ASTNode} node - A IfStatement node to check.
  114. * @returns {boolean} `true` if the node requires braces of the consequent chunk.
  115. */
  116. function requiresBraceOfConsequent(node) {
  117. if (node.alternate && node.consequent.type === "BlockStatement") {
  118. if (node.consequent.body.length >= 2) {
  119. return true;
  120. }
  121. for (
  122. let currentNode = node.consequent.body[0];
  123. currentNode;
  124. currentNode = astUtils.getTrailingStatement(currentNode)
  125. ) {
  126. if (currentNode.type === "IfStatement" && !currentNode.alternate) {
  127. return true;
  128. }
  129. }
  130. }
  131. return false;
  132. }
  133. /**
  134. * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError.
  135. * @param {Token} closingBracket The } token
  136. * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block.
  137. */
  138. function needsSemicolon(closingBracket) {
  139. const tokenBefore = sourceCode.getTokenBefore(closingBracket);
  140. const tokenAfter = sourceCode.getTokenAfter(closingBracket);
  141. const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
  142. if (astUtils.isSemicolonToken(tokenBefore)) {
  143. // If the last statement already has a semicolon, don't add another one.
  144. return false;
  145. }
  146. if (!tokenAfter) {
  147. // If there are no statements after this block, there is no need to add a semicolon.
  148. return false;
  149. }
  150. if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") {
  151. /*
  152. * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression),
  153. * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause
  154. * a SyntaxError if it was followed by `else`.
  155. */
  156. return false;
  157. }
  158. if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) {
  159. // If the next token is on the same line, insert a semicolon.
  160. return true;
  161. }
  162. if (/^[([/`+-]/.test(tokenAfter.value)) {
  163. // If the next token starts with a character that would disrupt ASI, insert a semicolon.
  164. return true;
  165. }
  166. if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) {
  167. // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI.
  168. return true;
  169. }
  170. // Otherwise, do not insert a semicolon.
  171. return false;
  172. }
  173. /**
  174. * Prepares to check the body of a node to see if it's a block statement.
  175. * @param {ASTNode} node The node to report if there's a problem.
  176. * @param {ASTNode} body The body node to check for blocks.
  177. * @param {string} name The name to report if there's a problem.
  178. * @param {{ condition: boolean }} opts Options to pass to the report functions
  179. * @returns {Object} a prepared check object, with "actual", "expected", "check" properties.
  180. * "actual" will be `true` or `false` whether the body is already a block statement.
  181. * "expected" will be `true` or `false` if the body should be a block statement or not, or
  182. * `null` if it doesn't matter, depending on the rule options. It can be modified to change
  183. * the final behavior of "check".
  184. * "check" will be a function reporting appropriate problems depending on the other
  185. * properties.
  186. */
  187. function prepareCheck(node, body, name, opts) {
  188. const hasBlock = (body.type === "BlockStatement");
  189. let expected = null;
  190. if (node.type === "IfStatement" && node.consequent === body && requiresBraceOfConsequent(node)) {
  191. expected = true;
  192. } else if (multiOnly) {
  193. if (hasBlock && body.body.length === 1) {
  194. expected = false;
  195. }
  196. } else if (multiLine) {
  197. if (!isCollapsedOneLiner(body)) {
  198. expected = true;
  199. }
  200. } else if (multiOrNest) {
  201. if (hasBlock && body.body.length === 1 && isOneLiner(body.body[0])) {
  202. const leadingComments = sourceCode.getCommentsBefore(body.body[0]);
  203. expected = leadingComments.length > 0;
  204. } else if (!isOneLiner(body)) {
  205. expected = true;
  206. }
  207. } else {
  208. expected = true;
  209. }
  210. return {
  211. actual: hasBlock,
  212. expected,
  213. check() {
  214. if (this.expected !== null && this.expected !== this.actual) {
  215. if (this.expected) {
  216. context.report({
  217. node,
  218. loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
  219. messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter",
  220. data: {
  221. name
  222. },
  223. fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`)
  224. });
  225. } else {
  226. context.report({
  227. node,
  228. loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
  229. messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter",
  230. data: {
  231. name
  232. },
  233. fix(fixer) {
  234. /*
  235. * `do while` expressions sometimes need a space to be inserted after `do`.
  236. * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)`
  237. */
  238. const needsPrecedingSpace = node.type === "DoWhileStatement" &&
  239. sourceCode.getTokenBefore(body).range[1] === body.range[0] &&
  240. !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 }));
  241. const openingBracket = sourceCode.getFirstToken(body);
  242. const closingBracket = sourceCode.getLastToken(body);
  243. const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket);
  244. if (needsSemicolon(closingBracket)) {
  245. /*
  246. * If removing braces would cause a SyntaxError due to multiple statements on the same line (or
  247. * change the semantics of the code due to ASI), don't perform a fix.
  248. */
  249. return null;
  250. }
  251. const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) +
  252. sourceCode.getText(lastTokenInBlock) +
  253. sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]);
  254. return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText);
  255. }
  256. });
  257. }
  258. }
  259. }
  260. };
  261. }
  262. /**
  263. * Prepares to check the bodies of a "if", "else if" and "else" chain.
  264. * @param {ASTNode} node The first IfStatement node of the chain.
  265. * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more
  266. * information.
  267. */
  268. function prepareIfChecks(node) {
  269. const preparedChecks = [];
  270. for (let currentNode = node; currentNode; currentNode = currentNode.alternate) {
  271. preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true }));
  272. if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") {
  273. preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else"));
  274. break;
  275. }
  276. }
  277. if (consistent) {
  278. /*
  279. * If any node should have or already have braces, make sure they
  280. * all have braces.
  281. * If all nodes shouldn't have braces, make sure they don't.
  282. */
  283. const expected = preparedChecks.some(preparedCheck => {
  284. if (preparedCheck.expected !== null) {
  285. return preparedCheck.expected;
  286. }
  287. return preparedCheck.actual;
  288. });
  289. preparedChecks.forEach(preparedCheck => {
  290. preparedCheck.expected = expected;
  291. });
  292. }
  293. return preparedChecks;
  294. }
  295. //--------------------------------------------------------------------------
  296. // Public
  297. //--------------------------------------------------------------------------
  298. return {
  299. IfStatement(node) {
  300. if (node.parent.type !== "IfStatement") {
  301. prepareIfChecks(node).forEach(preparedCheck => {
  302. preparedCheck.check();
  303. });
  304. }
  305. },
  306. WhileStatement(node) {
  307. prepareCheck(node, node.body, "while", { condition: true }).check();
  308. },
  309. DoWhileStatement(node) {
  310. prepareCheck(node, node.body, "do").check();
  311. },
  312. ForStatement(node) {
  313. prepareCheck(node, node.body, "for", { condition: true }).check();
  314. },
  315. ForInStatement(node) {
  316. prepareCheck(node, node.body, "for-in").check();
  317. },
  318. ForOfStatement(node) {
  319. prepareCheck(node, node.body, "for-of").check();
  320. }
  321. };
  322. }
  323. };