no-collapsible-if.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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/S1066
  22. const nodes_1 = require("../utils/nodes");
  23. const locations_1 = require("../utils/locations");
  24. const docs_url_1 = require("../utils/docs-url");
  25. const message = 'Merge this if statement with the nested one.';
  26. const rule = {
  27. meta: {
  28. messages: {
  29. mergeNestedIfStatement: message,
  30. sonarRuntime: '{{sonarRuntimeData}}',
  31. },
  32. type: 'suggestion',
  33. docs: {
  34. description: 'Collapsible "if" statements should be merged',
  35. recommended: 'error',
  36. url: (0, docs_url_1.default)(__filename),
  37. },
  38. schema: [
  39. {
  40. // internal parameter
  41. enum: ['sonar-runtime'],
  42. },
  43. ],
  44. },
  45. create(context) {
  46. return {
  47. IfStatement(node) {
  48. let { consequent } = node;
  49. if ((0, nodes_1.isBlockStatement)(consequent) && consequent.body.length === 1) {
  50. consequent = consequent.body[0];
  51. }
  52. if (isIfStatementWithoutElse(node) && isIfStatementWithoutElse(consequent)) {
  53. const ifKeyword = context.getSourceCode().getFirstToken(consequent);
  54. const enclosingIfKeyword = context.getSourceCode().getFirstToken(node);
  55. if (ifKeyword && enclosingIfKeyword) {
  56. (0, locations_1.report)(context, {
  57. messageId: 'mergeNestedIfStatement',
  58. loc: enclosingIfKeyword.loc,
  59. }, [(0, locations_1.issueLocation)(ifKeyword.loc, ifKeyword.loc, 'Nested "if" statement.')], message);
  60. }
  61. }
  62. },
  63. };
  64. function isIfStatementWithoutElse(node) {
  65. return (0, nodes_1.isIfStatement)(node) && !node.alternate;
  66. }
  67. },
  68. };
  69. module.exports = rule;
  70. //# sourceMappingURL=no-collapsible-if.js.map