blob: aa04f337ae0c43f79f064ee66e724f315656ab62 [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",
Yang Guo4fd355c2019-09-19 10:59:03 +020020 recommended: true,
21 url: "https://eslint.org/docs/rules/no-func-assign"
22 },
23
Tim van der Lippe16aca392020-11-13 11:37:13 +000024 schema: [],
25
26 messages: {
27 isAFunction: "'{{name}}' is a function."
28 }
Yang Guo4fd355c2019-09-19 10:59:03 +020029 },
30
31 create(context) {
32
33 /**
34 * Reports a reference if is non initializer and writable.
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010035 * @param {References} references Collection of reference to check.
Yang Guo4fd355c2019-09-19 10:59:03 +020036 * @returns {void}
37 */
38 function checkReference(references) {
39 astUtils.getModifyingReferences(references).forEach(reference => {
Tim van der Lippe16aca392020-11-13 11:37:13 +000040 context.report({
41 node: reference.identifier,
42 messageId: "isAFunction",
43 data: {
44 name: reference.identifier.name
45 }
46 });
Yang Guo4fd355c2019-09-19 10:59:03 +020047 });
48 }
49
50 /**
51 * Finds and reports references that are non initializer and writable.
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010052 * @param {Variable} variable A variable to check.
Yang Guo4fd355c2019-09-19 10:59:03 +020053 * @returns {void}
54 */
55 function checkVariable(variable) {
56 if (variable.defs[0].type === "FunctionName") {
57 checkReference(variable.references);
58 }
59 }
60
61 /**
62 * Checks parameters of a given function node.
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010063 * @param {ASTNode} node A function node to check.
Yang Guo4fd355c2019-09-19 10:59:03 +020064 * @returns {void}
65 */
66 function checkForFunction(node) {
67 context.getDeclaredVariables(node).forEach(checkVariable);
68 }
69
70 return {
71 FunctionDeclaration: checkForFunction,
72 FunctionExpression: checkForFunction
73 };
74 }
75};