blob: d2b4109fa339647c18c156c2b35dfefe936ff4ba [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
25 schema: []
26 },
27
28 create(context) {
29
30 /**
31 * Reports a reference if is non initializer and writable.
32 * @param {References} references - Collection of reference to check.
33 * @returns {void}
34 */
35 function checkReference(references) {
36 astUtils.getModifyingReferences(references).forEach(reference => {
37 context.report({ node: reference.identifier, message: "'{{name}}' is a function.", data: { name: reference.identifier.name } });
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 /**
53 * Checks parameters of a given function node.
54 * @param {ASTNode} node - A function node to check.
55 * @returns {void}
56 */
57 function checkForFunction(node) {
58 context.getDeclaredVariables(node).forEach(checkVariable);
59 }
60
61 return {
62 FunctionDeclaration: checkForFunction,
63 FunctionExpression: checkForFunction
64 };
65 }
66};