reject-multiple-getters-calls.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. */
  6. "use strict";
  7. const helpers = require("../helpers");
  8. function findStatement(node) {
  9. while (node && node.type !== "ExpressionStatement") {
  10. node = node.parent;
  11. }
  12. return node;
  13. }
  14. function isIdentifier(node, id) {
  15. return node && node.type === "Identifier" && node.name === id;
  16. }
  17. module.exports = {
  18. meta: {
  19. docs: {
  20. url:
  21. "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/reject-multiple-getters-calls.html",
  22. },
  23. messages: {
  24. rejectMultipleCalls:
  25. "ChromeUtils.defineESModuleGetters is already called for {{target}} in the same context. Please merge those calls",
  26. },
  27. type: "suggestion",
  28. },
  29. create(context) {
  30. const parentToTargets = new Map();
  31. return {
  32. CallExpression(node) {
  33. let callee = node.callee;
  34. if (
  35. callee.type === "MemberExpression" &&
  36. isIdentifier(callee.object, "ChromeUtils") &&
  37. isIdentifier(callee.property, "defineESModuleGetters")
  38. ) {
  39. const stmt = findStatement(node);
  40. if (!stmt) {
  41. return;
  42. }
  43. let target;
  44. try {
  45. target = helpers.getASTSource(node.arguments[0]);
  46. } catch (e) {
  47. return;
  48. }
  49. const parent = stmt.parent;
  50. let targets;
  51. if (parentToTargets.has(parent)) {
  52. targets = parentToTargets.get(parent);
  53. } else {
  54. targets = new Set();
  55. parentToTargets.set(parent, targets);
  56. }
  57. if (targets.has(target)) {
  58. context.report({
  59. node,
  60. messageId: "rejectMultipleCalls",
  61. data: { target },
  62. });
  63. }
  64. targets.add(target);
  65. }
  66. },
  67. };
  68. },
  69. };