no-catch-shadow.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. module.exports = {
  15. meta: {
  16. type: "suggestion",
  17. docs: {
  18. description: "disallow `catch` clause parameters from shadowing variables in the outer scope",
  19. category: "Variables",
  20. recommended: false,
  21. url: "https://eslint.org/docs/rules/no-catch-shadow"
  22. },
  23. replacedBy: ["no-shadow"],
  24. deprecated: true,
  25. schema: [],
  26. messages: {
  27. mutable: "Value of '{{name}}' may be overwritten in IE 8 and earlier."
  28. }
  29. },
  30. create(context) {
  31. //--------------------------------------------------------------------------
  32. // Helpers
  33. //--------------------------------------------------------------------------
  34. /**
  35. * Check if the parameters are been shadowed
  36. * @param {Object} scope current scope
  37. * @param {string} name parameter name
  38. * @returns {boolean} True is its been shadowed
  39. */
  40. function paramIsShadowing(scope, name) {
  41. return astUtils.getVariableByName(scope, name) !== null;
  42. }
  43. //--------------------------------------------------------------------------
  44. // Public API
  45. //--------------------------------------------------------------------------
  46. return {
  47. "CatchClause[param!=null]"(node) {
  48. let scope = context.getScope();
  49. /*
  50. * When ecmaVersion >= 6, CatchClause creates its own scope
  51. * so start from one upper scope to exclude the current node
  52. */
  53. if (scope.block === node) {
  54. scope = scope.upper;
  55. }
  56. if (paramIsShadowing(scope, node.param.name)) {
  57. context.report({ node, messageId: "mutable", data: { name: node.param.name } });
  58. }
  59. }
  60. };
  61. }
  62. };