no-unused-labels.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * @fileoverview Rule to disallow unused labels.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. /** @type {import('../shared/types').Rule} */
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "Disallow unused labels",
  15. recommended: true,
  16. url: "https://eslint.org/docs/rules/no-unused-labels"
  17. },
  18. schema: [],
  19. fixable: "code",
  20. messages: {
  21. unused: "'{{name}}:' is defined but never used."
  22. }
  23. },
  24. create(context) {
  25. const sourceCode = context.getSourceCode();
  26. let scopeInfo = null;
  27. /**
  28. * Adds a scope info to the stack.
  29. * @param {ASTNode} node A node to add. This is a LabeledStatement.
  30. * @returns {void}
  31. */
  32. function enterLabeledScope(node) {
  33. scopeInfo = {
  34. label: node.label.name,
  35. used: false,
  36. upper: scopeInfo
  37. };
  38. }
  39. /**
  40. * Removes the top of the stack.
  41. * At the same time, this reports the label if it's never used.
  42. * @param {ASTNode} node A node to report. This is a LabeledStatement.
  43. * @returns {void}
  44. */
  45. function exitLabeledScope(node) {
  46. if (!scopeInfo.used) {
  47. context.report({
  48. node: node.label,
  49. messageId: "unused",
  50. data: node.label,
  51. fix(fixer) {
  52. /*
  53. * Only perform a fix if there are no comments between the label and the body. This will be the case
  54. * when there is exactly one token/comment (the ":") between the label and the body.
  55. */
  56. if (sourceCode.getTokenAfter(node.label, { includeComments: true }) ===
  57. sourceCode.getTokenBefore(node.body, { includeComments: true })) {
  58. return fixer.removeRange([node.range[0], node.body.range[0]]);
  59. }
  60. return null;
  61. }
  62. });
  63. }
  64. scopeInfo = scopeInfo.upper;
  65. }
  66. /**
  67. * Marks the label of a given node as used.
  68. * @param {ASTNode} node A node to mark. This is a BreakStatement or
  69. * ContinueStatement.
  70. * @returns {void}
  71. */
  72. function markAsUsed(node) {
  73. if (!node.label) {
  74. return;
  75. }
  76. const label = node.label.name;
  77. let info = scopeInfo;
  78. while (info) {
  79. if (info.label === label) {
  80. info.used = true;
  81. break;
  82. }
  83. info = info.upper;
  84. }
  85. }
  86. return {
  87. LabeledStatement: enterLabeledScope,
  88. "LabeledStatement:exit": exitLabeledScope,
  89. BreakStatement: markAsUsed,
  90. ContinueStatement: markAsUsed
  91. };
  92. }
  93. };