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.

no-else-return.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /**
  2. * @fileoverview Rule to flag `else` after a `return` in `if`
  3. * @author Ian Christian Myers
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. const FixTracker = require("./utils/fix-tracker");
  11. //------------------------------------------------------------------------------
  12. // Rule Definition
  13. //------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. type: "suggestion",
  17. docs: {
  18. description: "disallow `else` blocks after `return` statements in `if` statements",
  19. category: "Best Practices",
  20. recommended: false,
  21. url: "https://eslint.org/docs/rules/no-else-return"
  22. },
  23. schema: [{
  24. type: "object",
  25. properties: {
  26. allowElseIf: {
  27. type: "boolean",
  28. default: true
  29. }
  30. },
  31. additionalProperties: false
  32. }],
  33. fixable: "code",
  34. messages: {
  35. unexpected: "Unnecessary 'else' after 'return'."
  36. }
  37. },
  38. create(context) {
  39. //--------------------------------------------------------------------------
  40. // Helpers
  41. //--------------------------------------------------------------------------
  42. /**
  43. * Checks whether the given names can be safely used to declare block-scoped variables
  44. * in the given scope. Name collisions can produce redeclaration syntax errors,
  45. * or silently change references and modify behavior of the original code.
  46. *
  47. * This is not a generic function. In particular, it is assumed that the scope is a function scope or
  48. * a function's inner scope, and that the names can be valid identifiers in the given scope.
  49. * @param {string[]} names Array of variable names.
  50. * @param {eslint-scope.Scope} scope Function scope or a function's inner scope.
  51. * @returns {boolean} True if all names can be safely declared, false otherwise.
  52. */
  53. function isSafeToDeclare(names, scope) {
  54. if (names.length === 0) {
  55. return true;
  56. }
  57. const functionScope = scope.variableScope;
  58. /*
  59. * If this is a function scope, scope.variables will contain parameters, implicit variables such as "arguments",
  60. * all function-scoped variables ('var'), and block-scoped variables defined in the scope.
  61. * If this is an inner scope, scope.variables will contain block-scoped variables defined in the scope.
  62. *
  63. * Redeclaring any of these would cause a syntax error, except for the implicit variables.
  64. */
  65. const declaredVariables = scope.variables.filter(({ defs }) => defs.length > 0);
  66. if (declaredVariables.some(({ name }) => names.includes(name))) {
  67. return false;
  68. }
  69. // Redeclaring a catch variable would also cause a syntax error.
  70. if (scope !== functionScope && scope.upper.type === "catch") {
  71. if (scope.upper.variables.some(({ name }) => names.includes(name))) {
  72. return false;
  73. }
  74. }
  75. /*
  76. * Redeclaring an implicit variable, such as "arguments", would not cause a syntax error.
  77. * However, if the variable was used, declaring a new one with the same name would change references
  78. * and modify behavior.
  79. */
  80. const usedImplicitVariables = scope.variables.filter(({ defs, references }) =>
  81. defs.length === 0 && references.length > 0);
  82. if (usedImplicitVariables.some(({ name }) => names.includes(name))) {
  83. return false;
  84. }
  85. /*
  86. * Declaring a variable with a name that was already used to reference a variable from an upper scope
  87. * would change references and modify behavior.
  88. */
  89. if (scope.through.some(t => names.includes(t.identifier.name))) {
  90. return false;
  91. }
  92. /*
  93. * If the scope is an inner scope (not the function scope), an uninitialized `var` variable declared inside
  94. * the scope node (directly or in one of its descendants) is neither declared nor 'through' in the scope.
  95. *
  96. * For example, this would be a syntax error "Identifier 'a' has already been declared":
  97. * function foo() { if (bar) { let a; if (baz) { var a; } } }
  98. */
  99. if (scope !== functionScope) {
  100. const scopeNodeRange = scope.block.range;
  101. const variablesToCheck = functionScope.variables.filter(({ name }) => names.includes(name));
  102. if (variablesToCheck.some(v => v.defs.some(({ node: { range } }) =>
  103. scopeNodeRange[0] <= range[0] && range[1] <= scopeNodeRange[1]))) {
  104. return false;
  105. }
  106. }
  107. return true;
  108. }
  109. /**
  110. * Checks whether the removal of `else` and its braces is safe from variable name collisions.
  111. * @param {Node} node The 'else' node.
  112. * @param {eslint-scope.Scope} scope The scope in which the node and the whole 'if' statement is.
  113. * @returns {boolean} True if it is safe, false otherwise.
  114. */
  115. function isSafeFromNameCollisions(node, scope) {
  116. if (node.type === "FunctionDeclaration") {
  117. // Conditional function declaration. Scope and hoisting are unpredictable, different engines work differently.
  118. return false;
  119. }
  120. if (node.type !== "BlockStatement") {
  121. return true;
  122. }
  123. const elseBlockScope = scope.childScopes.find(({ block }) => block === node);
  124. if (!elseBlockScope) {
  125. // ecmaVersion < 6, `else` block statement cannot have its own scope, no possible collisions.
  126. return true;
  127. }
  128. /*
  129. * elseBlockScope is supposed to merge into its upper scope. elseBlockScope.variables array contains
  130. * only block-scoped variables (such as let and const variables or class and function declarations)
  131. * defined directly in the elseBlockScope. These are exactly the only names that could cause collisions.
  132. */
  133. const namesToCheck = elseBlockScope.variables.map(({ name }) => name);
  134. return isSafeToDeclare(namesToCheck, scope);
  135. }
  136. /**
  137. * Display the context report if rule is violated
  138. * @param {Node} node The 'else' node
  139. * @returns {void}
  140. */
  141. function displayReport(node) {
  142. const currentScope = context.getScope();
  143. context.report({
  144. node,
  145. messageId: "unexpected",
  146. fix: fixer => {
  147. if (!isSafeFromNameCollisions(node, currentScope)) {
  148. return null;
  149. }
  150. const sourceCode = context.getSourceCode();
  151. const startToken = sourceCode.getFirstToken(node);
  152. const elseToken = sourceCode.getTokenBefore(startToken);
  153. const source = sourceCode.getText(node);
  154. const lastIfToken = sourceCode.getTokenBefore(elseToken);
  155. let fixedSource, firstTokenOfElseBlock;
  156. if (startToken.type === "Punctuator" && startToken.value === "{") {
  157. firstTokenOfElseBlock = sourceCode.getTokenAfter(startToken);
  158. } else {
  159. firstTokenOfElseBlock = startToken;
  160. }
  161. /*
  162. * If the if block does not have curly braces and does not end in a semicolon
  163. * and the else block starts with (, [, /, +, ` or -, then it is not
  164. * safe to remove the else keyword, because ASI will not add a semicolon
  165. * after the if block
  166. */
  167. const ifBlockMaybeUnsafe = node.parent.consequent.type !== "BlockStatement" && lastIfToken.value !== ";";
  168. const elseBlockUnsafe = /^[([/+`-]/u.test(firstTokenOfElseBlock.value);
  169. if (ifBlockMaybeUnsafe && elseBlockUnsafe) {
  170. return null;
  171. }
  172. const endToken = sourceCode.getLastToken(node);
  173. const lastTokenOfElseBlock = sourceCode.getTokenBefore(endToken);
  174. if (lastTokenOfElseBlock.value !== ";") {
  175. const nextToken = sourceCode.getTokenAfter(endToken);
  176. const nextTokenUnsafe = nextToken && /^[([/+`-]/u.test(nextToken.value);
  177. const nextTokenOnSameLine = nextToken && nextToken.loc.start.line === lastTokenOfElseBlock.loc.start.line;
  178. /*
  179. * If the else block contents does not end in a semicolon,
  180. * and the else block starts with (, [, /, +, ` or -, then it is not
  181. * safe to remove the else block, because ASI will not add a semicolon
  182. * after the remaining else block contents
  183. */
  184. if (nextTokenUnsafe || (nextTokenOnSameLine && nextToken.value !== "}")) {
  185. return null;
  186. }
  187. }
  188. if (startToken.type === "Punctuator" && startToken.value === "{") {
  189. fixedSource = source.slice(1, -1);
  190. } else {
  191. fixedSource = source;
  192. }
  193. /*
  194. * Extend the replacement range to include the entire
  195. * function to avoid conflicting with no-useless-return.
  196. * https://github.com/eslint/eslint/issues/8026
  197. *
  198. * Also, to avoid name collisions between two else blocks.
  199. */
  200. return new FixTracker(fixer, sourceCode)
  201. .retainEnclosingFunction(node)
  202. .replaceTextRange([elseToken.range[0], node.range[1]], fixedSource);
  203. }
  204. });
  205. }
  206. /**
  207. * Check to see if the node is a ReturnStatement
  208. * @param {Node} node The node being evaluated
  209. * @returns {boolean} True if node is a return
  210. */
  211. function checkForReturn(node) {
  212. return node.type === "ReturnStatement";
  213. }
  214. /**
  215. * Naive return checking, does not iterate through the whole
  216. * BlockStatement because we make the assumption that the ReturnStatement
  217. * will be the last node in the body of the BlockStatement.
  218. * @param {Node} node The consequent/alternate node
  219. * @returns {boolean} True if it has a return
  220. */
  221. function naiveHasReturn(node) {
  222. if (node.type === "BlockStatement") {
  223. const body = node.body,
  224. lastChildNode = body[body.length - 1];
  225. return lastChildNode && checkForReturn(lastChildNode);
  226. }
  227. return checkForReturn(node);
  228. }
  229. /**
  230. * Check to see if the node is valid for evaluation,
  231. * meaning it has an else.
  232. * @param {Node} node The node being evaluated
  233. * @returns {boolean} True if the node is valid
  234. */
  235. function hasElse(node) {
  236. return node.alternate && node.consequent;
  237. }
  238. /**
  239. * If the consequent is an IfStatement, check to see if it has an else
  240. * and both its consequent and alternate path return, meaning this is
  241. * a nested case of rule violation. If-Else not considered currently.
  242. * @param {Node} node The consequent node
  243. * @returns {boolean} True if this is a nested rule violation
  244. */
  245. function checkForIf(node) {
  246. return node.type === "IfStatement" && hasElse(node) &&
  247. naiveHasReturn(node.alternate) && naiveHasReturn(node.consequent);
  248. }
  249. /**
  250. * Check the consequent/body node to make sure it is not
  251. * a ReturnStatement or an IfStatement that returns on both
  252. * code paths.
  253. * @param {Node} node The consequent or body node
  254. * @returns {boolean} `true` if it is a Return/If node that always returns.
  255. */
  256. function checkForReturnOrIf(node) {
  257. return checkForReturn(node) || checkForIf(node);
  258. }
  259. /**
  260. * Check whether a node returns in every codepath.
  261. * @param {Node} node The node to be checked
  262. * @returns {boolean} `true` if it returns on every codepath.
  263. */
  264. function alwaysReturns(node) {
  265. if (node.type === "BlockStatement") {
  266. // If we have a BlockStatement, check each consequent body node.
  267. return node.body.some(checkForReturnOrIf);
  268. }
  269. /*
  270. * If not a block statement, make sure the consequent isn't a
  271. * ReturnStatement or an IfStatement with returns on both paths.
  272. */
  273. return checkForReturnOrIf(node);
  274. }
  275. /**
  276. * Check the if statement, but don't catch else-if blocks.
  277. * @returns {void}
  278. * @param {Node} node The node for the if statement to check
  279. * @private
  280. */
  281. function checkIfWithoutElse(node) {
  282. const parent = node.parent;
  283. /*
  284. * Fixing this would require splitting one statement into two, so no error should
  285. * be reported if this node is in a position where only one statement is allowed.
  286. */
  287. if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) {
  288. return;
  289. }
  290. const consequents = [];
  291. let alternate;
  292. for (let currentNode = node; currentNode.type === "IfStatement"; currentNode = currentNode.alternate) {
  293. if (!currentNode.alternate) {
  294. return;
  295. }
  296. consequents.push(currentNode.consequent);
  297. alternate = currentNode.alternate;
  298. }
  299. if (consequents.every(alwaysReturns)) {
  300. displayReport(alternate);
  301. }
  302. }
  303. /**
  304. * Check the if statement
  305. * @returns {void}
  306. * @param {Node} node The node for the if statement to check
  307. * @private
  308. */
  309. function checkIfWithElse(node) {
  310. const parent = node.parent;
  311. /*
  312. * Fixing this would require splitting one statement into two, so no error should
  313. * be reported if this node is in a position where only one statement is allowed.
  314. */
  315. if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) {
  316. return;
  317. }
  318. const alternate = node.alternate;
  319. if (alternate && alwaysReturns(node.consequent)) {
  320. displayReport(alternate);
  321. }
  322. }
  323. const allowElseIf = !(context.options[0] && context.options[0].allowElseIf === false);
  324. //--------------------------------------------------------------------------
  325. // Public API
  326. //--------------------------------------------------------------------------
  327. return {
  328. "IfStatement:exit": allowElseIf ? checkIfWithoutElse : checkIfWithElse
  329. };
  330. }
  331. };