Ohm-Management - Projektarbeit B-ME
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.

curly.js 15KB

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