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.

no-inner-declarations.js 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * @fileoverview Rule to enforce declarations in program or function body root.
  3. * @author Brandon Mills
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "problem",
  12. docs: {
  13. description: "disallow variable or `function` declarations in nested blocks",
  14. category: "Possible Errors",
  15. recommended: true,
  16. url: "https://eslint.org/docs/rules/no-inner-declarations"
  17. },
  18. schema: [
  19. {
  20. enum: ["functions", "both"]
  21. }
  22. ]
  23. },
  24. create(context) {
  25. /**
  26. * Find the nearest Program or Function ancestor node.
  27. * @returns {Object} Ancestor's type and distance from node.
  28. */
  29. function nearestBody() {
  30. const ancestors = context.getAncestors();
  31. let ancestor = ancestors.pop(),
  32. generation = 1;
  33. while (ancestor && ["Program", "FunctionDeclaration",
  34. "FunctionExpression", "ArrowFunctionExpression"
  35. ].indexOf(ancestor.type) < 0) {
  36. generation += 1;
  37. ancestor = ancestors.pop();
  38. }
  39. return {
  40. // Type of containing ancestor
  41. type: ancestor.type,
  42. // Separation between ancestor and node
  43. distance: generation
  44. };
  45. }
  46. /**
  47. * Ensure that a given node is at a program or function body's root.
  48. * @param {ASTNode} node Declaration node to check.
  49. * @returns {void}
  50. */
  51. function check(node) {
  52. const body = nearestBody(),
  53. valid = ((body.type === "Program" && body.distance === 1) ||
  54. body.distance === 2);
  55. if (!valid) {
  56. context.report({
  57. node,
  58. message: "Move {{type}} declaration to {{body}} root.",
  59. data: {
  60. type: (node.type === "FunctionDeclaration" ? "function" : "variable"),
  61. body: (body.type === "Program" ? "program" : "function body")
  62. }
  63. });
  64. }
  65. }
  66. return {
  67. FunctionDeclaration: check,
  68. VariableDeclaration(node) {
  69. if (context.options[0] === "both" && node.kind === "var") {
  70. check(node);
  71. }
  72. }
  73. };
  74. }
  75. };