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