no-label-var.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. module.exports = {
  14. meta: {
  15. type: "suggestion",
  16. docs: {
  17. description: "disallow labels that share a name with a variable",
  18. category: "Variables",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/no-label-var"
  21. },
  22. schema: [],
  23. messages: {
  24. identifierClashWithLabel: "Found identifier with same name as label."
  25. }
  26. },
  27. create(context) {
  28. //--------------------------------------------------------------------------
  29. // Helpers
  30. //--------------------------------------------------------------------------
  31. /**
  32. * Check if the identifier is present inside current scope
  33. * @param {Object} scope current scope
  34. * @param {string} name To evaluate
  35. * @returns {boolean} True if its present
  36. * @private
  37. */
  38. function findIdentifier(scope, name) {
  39. return astUtils.getVariableByName(scope, name) !== null;
  40. }
  41. //--------------------------------------------------------------------------
  42. // Public API
  43. //--------------------------------------------------------------------------
  44. return {
  45. LabeledStatement(node) {
  46. // Fetch the innermost scope.
  47. const scope = context.getScope();
  48. /*
  49. * Recursively find the identifier walking up the scope, starting
  50. * with the innermost scope.
  51. */
  52. if (findIdentifier(scope, node.label.name)) {
  53. context.report({
  54. node,
  55. messageId: "identifierClashWithLabel"
  56. });
  57. }
  58. }
  59. };
  60. }
  61. };