2024-08-09 12:04:48 +00:00
|
|
|
/**
|
|
|
|
* @fileoverview Rule to flag labels that are the same as an identifier
|
|
|
|
* @author Ian Christian Myers
|
|
|
|
*/
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
// Requirements
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
const astUtils = require("./utils/ast-utils");
|
|
|
|
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
// Rule Definition
|
|
|
|
//------------------------------------------------------------------------------
|
|
|
|
|
2024-08-21 06:34:30 +00:00
|
|
|
/** @type {import('../shared/types').Rule} */
|
2024-08-09 12:04:48 +00:00
|
|
|
module.exports = {
|
|
|
|
meta: {
|
|
|
|
type: "suggestion",
|
|
|
|
|
|
|
|
docs: {
|
2024-08-21 06:34:30 +00:00
|
|
|
description: "Disallow labels that share a name with a variable",
|
2024-08-09 12:04:48 +00:00
|
|
|
recommended: false,
|
2024-08-21 06:34:30 +00:00
|
|
|
url: "https://eslint.org/docs/latest/rules/no-label-var"
|
2024-08-09 12:04:48 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
schema: [],
|
|
|
|
|
|
|
|
messages: {
|
|
|
|
identifierClashWithLabel: "Found identifier with same name as label."
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
create(context) {
|
2024-08-21 06:34:30 +00:00
|
|
|
const sourceCode = context.sourceCode;
|
2024-08-09 12:04:48 +00:00
|
|
|
|
|
|
|
//--------------------------------------------------------------------------
|
|
|
|
// Helpers
|
|
|
|
//--------------------------------------------------------------------------
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Check if the identifier is present inside current scope
|
|
|
|
* @param {Object} scope current scope
|
|
|
|
* @param {string} name To evaluate
|
|
|
|
* @returns {boolean} True if its present
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
function findIdentifier(scope, name) {
|
|
|
|
return astUtils.getVariableByName(scope, name) !== null;
|
|
|
|
}
|
|
|
|
|
|
|
|
//--------------------------------------------------------------------------
|
|
|
|
// Public API
|
|
|
|
//--------------------------------------------------------------------------
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
|
|
|
LabeledStatement(node) {
|
|
|
|
|
|
|
|
// Fetch the innermost scope.
|
2024-08-21 06:34:30 +00:00
|
|
|
const scope = sourceCode.getScope(node);
|
2024-08-09 12:04:48 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Recursively find the identifier walking up the scope, starting
|
|
|
|
* with the innermost scope.
|
|
|
|
*/
|
|
|
|
if (findIdentifier(scope, node.label.name)) {
|
|
|
|
context.report({
|
|
|
|
node,
|
|
|
|
messageId: "identifierClashWithLabel"
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
}
|
|
|
|
};
|