blob: 6ca1b6107a86bd4edab1851cab6e99e01d5b2f65 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/**
2 * @fileoverview A rule to disallow modifying variables that are declared using `const`
3 * @author Toru Nagashima
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 `const` variables",
Yang Guo4fd355c2019-09-19 10:59:03 +020020 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 Lippec8f6ffd2020-04-06 13:42:00 +010035 * @param {Variable} variable A variable to check.
Yang Guo4fd355c2019-09-19 10:59:03 +020036 * @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};