no-label-var.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * @fileoverview Rule to flag labels that are the same as an identifier
  3. * @author Ian Christian Myers
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. /** @type {import('../types').Rule.RuleModule} */
  14. module.exports = {
  15. meta: {
  16. type: "suggestion",
  17. docs: {
  18. description: "Disallow labels that share a name with a variable",
  19. recommended: false,
  20. frozen: true,
  21. url: "https://eslint.org/docs/latest/rules/no-label-var",
  22. },
  23. schema: [],
  24. messages: {
  25. identifierClashWithLabel:
  26. "Found identifier with same name as label.",
  27. },
  28. },
  29. create(context) {
  30. const sourceCode = context.sourceCode;
  31. //--------------------------------------------------------------------------
  32. // Helpers
  33. //--------------------------------------------------------------------------
  34. /**
  35. * Check if the identifier is present inside current scope
  36. * @param {Object} scope current scope
  37. * @param {string} name To evaluate
  38. * @returns {boolean} True if its present
  39. * @private
  40. */
  41. function findIdentifier(scope, name) {
  42. return astUtils.getVariableByName(scope, name) !== null;
  43. }
  44. //--------------------------------------------------------------------------
  45. // Public API
  46. //--------------------------------------------------------------------------
  47. return {
  48. LabeledStatement(node) {
  49. // Fetch the innermost scope.
  50. const scope = sourceCode.getScope(node);
  51. /*
  52. * Recursively find the identifier walking up the scope, starting
  53. * with the innermost scope.
  54. */
  55. if (findIdentifier(scope, node.label.name)) {
  56. context.report({
  57. node,
  58. messageId: "identifierClashWithLabel",
  59. });
  60. }
  61. },
  62. };
  63. },
  64. };