[d565449] | 1 | /**
|
---|
| 2 | * @fileoverview Disallow shadowing of NaN, undefined, and Infinity (ES5 section 15.1.1)
|
---|
| 3 | * @author Michael Ficarra
|
---|
| 4 | */
|
---|
| 5 | "use strict";
|
---|
| 6 |
|
---|
| 7 | /**
|
---|
| 8 | * Determines if a variable safely shadows undefined.
|
---|
| 9 | * This is the case when a variable named `undefined` is never assigned to a value (i.e. it always shares the same value
|
---|
| 10 | * as the global).
|
---|
| 11 | * @param {eslintScope.Variable} variable The variable to check
|
---|
| 12 | * @returns {boolean} true if this variable safely shadows `undefined`
|
---|
| 13 | */
|
---|
| 14 | function safelyShadowsUndefined(variable) {
|
---|
| 15 | return variable.name === "undefined" &&
|
---|
| 16 | variable.references.every(ref => !ref.isWrite()) &&
|
---|
| 17 | variable.defs.every(def => def.node.type === "VariableDeclarator" && def.node.init === null);
|
---|
| 18 | }
|
---|
| 19 |
|
---|
| 20 | //------------------------------------------------------------------------------
|
---|
| 21 | // Rule Definition
|
---|
| 22 | //------------------------------------------------------------------------------
|
---|
| 23 |
|
---|
| 24 | /** @type {import('../shared/types').Rule} */
|
---|
| 25 | module.exports = {
|
---|
| 26 | meta: {
|
---|
| 27 | type: "suggestion",
|
---|
| 28 |
|
---|
| 29 | docs: {
|
---|
| 30 | description: "Disallow identifiers from shadowing restricted names",
|
---|
| 31 | recommended: true,
|
---|
| 32 | url: "https://eslint.org/docs/latest/rules/no-shadow-restricted-names"
|
---|
| 33 | },
|
---|
| 34 |
|
---|
| 35 | schema: [],
|
---|
| 36 |
|
---|
| 37 | messages: {
|
---|
| 38 | shadowingRestrictedName: "Shadowing of global property '{{name}}'."
|
---|
| 39 | }
|
---|
| 40 | },
|
---|
| 41 |
|
---|
| 42 | create(context) {
|
---|
| 43 |
|
---|
| 44 |
|
---|
| 45 | const RESTRICTED = new Set(["undefined", "NaN", "Infinity", "arguments", "eval"]);
|
---|
| 46 | const sourceCode = context.sourceCode;
|
---|
| 47 |
|
---|
| 48 | return {
|
---|
| 49 | "VariableDeclaration, :function, CatchClause"(node) {
|
---|
| 50 | for (const variable of sourceCode.getDeclaredVariables(node)) {
|
---|
| 51 | if (variable.defs.length > 0 && RESTRICTED.has(variable.name) && !safelyShadowsUndefined(variable)) {
|
---|
| 52 | context.report({
|
---|
| 53 | node: variable.defs[0].name,
|
---|
| 54 | messageId: "shadowingRestrictedName",
|
---|
| 55 | data: {
|
---|
| 56 | name: variable.name
|
---|
| 57 | }
|
---|
| 58 | });
|
---|
| 59 | }
|
---|
| 60 | }
|
---|
| 61 | }
|
---|
| 62 | };
|
---|
| 63 |
|
---|
| 64 | }
|
---|
| 65 | };
|
---|