no-catch-shadow.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier
  3. * @author Ian Christian Myers
  4. * @deprecated in ESLint v5.1.0
  5. */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Requirements
  9. //------------------------------------------------------------------------------
  10. const astUtils = require("./utils/ast-utils");
  11. //------------------------------------------------------------------------------
  12. // Rule Definition
  13. //------------------------------------------------------------------------------
  14. /** @type {import('../types').Rule.RuleModule} */
  15. module.exports = {
  16. meta: {
  17. type: "suggestion",
  18. docs: {
  19. description:
  20. "Disallow `catch` clause parameters from shadowing variables in the outer scope",
  21. recommended: false,
  22. url: "https://eslint.org/docs/latest/rules/no-catch-shadow",
  23. },
  24. deprecated: {
  25. message: "This rule was renamed.",
  26. url: "https://eslint.org/blog/2018/07/eslint-v5.1.0-released/",
  27. deprecatedSince: "5.1.0",
  28. availableUntil: "11.0.0",
  29. replacedBy: [
  30. {
  31. rule: {
  32. name: "no-shadow",
  33. url: "https://eslint.org/docs/rules/no-shadow",
  34. },
  35. },
  36. ],
  37. },
  38. schema: [],
  39. messages: {
  40. mutable:
  41. "Value of '{{name}}' may be overwritten in IE 8 and earlier.",
  42. },
  43. },
  44. create(context) {
  45. const sourceCode = context.sourceCode;
  46. //--------------------------------------------------------------------------
  47. // Helpers
  48. //--------------------------------------------------------------------------
  49. /**
  50. * Check if the parameters are been shadowed
  51. * @param {Object} scope current scope
  52. * @param {string} name parameter name
  53. * @returns {boolean} True is its been shadowed
  54. */
  55. function paramIsShadowing(scope, name) {
  56. return astUtils.getVariableByName(scope, name) !== null;
  57. }
  58. //--------------------------------------------------------------------------
  59. // Public API
  60. //--------------------------------------------------------------------------
  61. return {
  62. "CatchClause[param!=null]"(node) {
  63. let scope = sourceCode.getScope(node);
  64. /*
  65. * When ecmaVersion >= 6, CatchClause creates its own scope
  66. * so start from one upper scope to exclude the current node
  67. */
  68. if (scope.block === node) {
  69. scope = scope.upper;
  70. }
  71. if (paramIsShadowing(scope, node.param.name)) {
  72. context.report({
  73. node,
  74. messageId: "mutable",
  75. data: { name: node.param.name },
  76. });
  77. }
  78. },
  79. };
  80. },
  81. };