blob: 33d0ad9ecd14335370d46039de934569f2726e65 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/**
2 * @fileoverview Rule to flag use of function declaration identifiers as variables.
3 * @author Ian Christian Myers
4 */
5
6"use strict";
7
8const astUtils = require("./utils/ast-utils");
9
10//------------------------------------------------------------------------------
11// Rule Definition
12//------------------------------------------------------------------------------
13
14module.exports = {
15 meta: {
16 type: "problem",
17
18 docs: {
19 description: "disallow reassigning `function` declarations",
20 category: "Possible Errors",
21 recommended: true,
22 url: "https://eslint.org/docs/rules/no-func-assign"
23 },
24
Tim van der Lippe16aca392020-11-13 11:37:13 +000025 schema: [],
26
27 messages: {
28 isAFunction: "'{{name}}' is a function."
29 }
Yang Guo4fd355c2019-09-19 10:59:03 +020030 },
31
32 create(context) {
33
34 /**
35 * Reports a reference if is non initializer and writable.
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010036 * @param {References} references Collection of reference to check.
Yang Guo4fd355c2019-09-19 10:59:03 +020037 * @returns {void}
38 */
39 function checkReference(references) {
40 astUtils.getModifyingReferences(references).forEach(reference => {
Tim van der Lippe16aca392020-11-13 11:37:13 +000041 context.report({
42 node: reference.identifier,
43 messageId: "isAFunction",
44 data: {
45 name: reference.identifier.name
46 }
47 });
Yang Guo4fd355c2019-09-19 10:59:03 +020048 });
49 }
50
51 /**
52 * Finds and reports references that are non initializer and writable.
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010053 * @param {Variable} variable A variable to check.
Yang Guo4fd355c2019-09-19 10:59:03 +020054 * @returns {void}
55 */
56 function checkVariable(variable) {
57 if (variable.defs[0].type === "FunctionName") {
58 checkReference(variable.references);
59 }
60 }
61
62 /**
63 * Checks parameters of a given function node.
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010064 * @param {ASTNode} node A function node to check.
Yang Guo4fd355c2019-09-19 10:59:03 +020065 * @returns {void}
66 */
67 function checkForFunction(node) {
68 context.getDeclaredVariables(node).forEach(checkVariable);
69 }
70
71 return {
72 FunctionDeclaration: checkForFunction,
73 FunctionExpression: checkForFunction
74 };
75 }
76};