Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 1 | /** |
| 2 | * @fileoverview A rule to disallow modifying variables that are declared using `const` |
| 3 | * @author Toru Nagashima |
| 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 `const` variables", |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 20 | recommended: true, |
| 21 | url: "https://eslint.org/docs/rules/no-const-assign" |
| 22 | }, |
| 23 | |
| 24 | schema: [], |
| 25 | |
| 26 | messages: { |
| 27 | const: "'{{name}}' is constant." |
| 28 | } |
| 29 | }, |
| 30 | |
| 31 | create(context) { |
| 32 | |
| 33 | /** |
| 34 | * Finds and reports references that are non initializer and writable. |
Tim van der Lippe | c8f6ffd | 2020-04-06 13:42:00 +0100 | [diff] [blame] | 35 | * @param {Variable} variable A variable to check. |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 36 | * @returns {void} |
| 37 | */ |
| 38 | function checkVariable(variable) { |
| 39 | astUtils.getModifyingReferences(variable.references).forEach(reference => { |
| 40 | context.report({ node: reference.identifier, messageId: "const", data: { name: reference.identifier.name } }); |
| 41 | }); |
| 42 | } |
| 43 | |
| 44 | return { |
| 45 | VariableDeclaration(node) { |
| 46 | if (node.kind === "const") { |
| 47 | context.getDeclaredVariables(node).forEach(checkVariable); |
| 48 | } |
| 49 | } |
| 50 | }; |
| 51 | |
| 52 | } |
| 53 | }; |