Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 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 | module.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. |
Tim van der Lippe | c8f6ffd | 2020-04-06 13:42:00 +0100 | [diff] [blame^] | 32 | * @param {References} references Collection of reference to check. |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 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. |
Tim van der Lippe | c8f6ffd | 2020-04-06 13:42:00 +0100 | [diff] [blame^] | 43 | * @param {Variable} variable A variable to check. |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 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. |
Tim van der Lippe | c8f6ffd | 2020-04-06 13:42:00 +0100 | [diff] [blame^] | 54 | * @param {ASTNode} node A function node to check. |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 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 | }; |