no-identical-conditions.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use strict";
  2. /*
  3. * eslint-plugin-sonarjs
  4. * Copyright (C) 2018-2021 SonarSource SA
  5. * mailto:info AT sonarsource DOT com
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 3 of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with this program; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. */
  21. // https://sonarsource.github.io/rspec/#/rspec/S1862
  22. const nodes_1 = require("../utils/nodes");
  23. const equivalence_1 = require("../utils/equivalence");
  24. const locations_1 = require("../utils/locations");
  25. const docs_url_1 = require("../utils/docs-url");
  26. const message = 'This branch duplicates the one on line {{line}}';
  27. const rule = {
  28. meta: {
  29. messages: {
  30. duplicatedBranch: message,
  31. sonarRuntime: '{{sonarRuntimeData}}',
  32. },
  33. type: 'problem',
  34. docs: {
  35. description: 'Related "if/else if" statements should not have the same condition',
  36. recommended: 'error',
  37. url: (0, docs_url_1.default)(__filename),
  38. },
  39. schema: [
  40. {
  41. // internal parameter
  42. enum: ['sonar-runtime'],
  43. },
  44. ],
  45. },
  46. create(context) {
  47. return {
  48. IfStatement(node) {
  49. const ifStmt = node;
  50. const condition = ifStmt.test;
  51. let statement = ifStmt.alternate;
  52. while (statement) {
  53. if ((0, nodes_1.isIfStatement)(statement)) {
  54. if ((0, equivalence_1.areEquivalent)(condition, statement.test, context.getSourceCode())) {
  55. const line = ifStmt.loc && ifStmt.loc.start.line;
  56. if (line && condition.loc) {
  57. (0, locations_1.report)(context, {
  58. messageId: 'duplicatedBranch',
  59. data: {
  60. line,
  61. },
  62. node: statement.test,
  63. }, [(0, locations_1.issueLocation)(condition.loc, condition.loc, 'Original')], message);
  64. }
  65. }
  66. statement = statement.alternate;
  67. }
  68. else {
  69. break;
  70. }
  71. }
  72. },
  73. };
  74. },
  75. };
  76. module.exports = rule;
  77. //# sourceMappingURL=no-identical-conditions.js.map