no-func-assign.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * @fileoverview Rule to flag use of function declaration identifiers as variables.
  3. * @author Ian Christian Myers
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. /** @type {import('../shared/types').Rule} */
  11. module.exports = {
  12. meta: {
  13. type: "problem",
  14. docs: {
  15. description: "Disallow reassigning `function` declarations",
  16. recommended: true,
  17. url: "https://eslint.org/docs/rules/no-func-assign"
  18. },
  19. schema: [],
  20. messages: {
  21. isAFunction: "'{{name}}' is a function."
  22. }
  23. },
  24. create(context) {
  25. /**
  26. * Reports a reference if is non initializer and writable.
  27. * @param {References} references Collection of reference to check.
  28. * @returns {void}
  29. */
  30. function checkReference(references) {
  31. astUtils.getModifyingReferences(references).forEach(reference => {
  32. context.report({
  33. node: reference.identifier,
  34. messageId: "isAFunction",
  35. data: {
  36. name: reference.identifier.name
  37. }
  38. });
  39. });
  40. }
  41. /**
  42. * Finds and reports references that are non initializer and writable.
  43. * @param {Variable} variable A variable to check.
  44. * @returns {void}
  45. */
  46. function checkVariable(variable) {
  47. if (variable.defs[0].type === "FunctionName") {
  48. checkReference(variable.references);
  49. }
  50. }
  51. /**
  52. * Checks parameters of a given function node.
  53. * @param {ASTNode} node A function node to check.
  54. * @returns {void}
  55. */
  56. function checkForFunction(node) {
  57. context.getDeclaredVariables(node).forEach(checkVariable);
  58. }
  59. return {
  60. FunctionDeclaration: checkForFunction,
  61. FunctionExpression: checkForFunction
  62. };
  63. }
  64. };