项目原始demo,不改动
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

no-inner-declarations.js 2.6 KiB

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