elseif-without-else.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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/S126
  22. const docs_url_1 = require("../utils/docs-url");
  23. const rule = {
  24. meta: {
  25. messages: {
  26. addMissingElseClause: 'Add the missing "else" clause.',
  27. },
  28. schema: [],
  29. type: 'suggestion',
  30. docs: {
  31. description: '"if ... else if" constructs should end with "else" clauses',
  32. recommended: false,
  33. url: (0, docs_url_1.default)(__filename),
  34. },
  35. },
  36. create(context) {
  37. return {
  38. IfStatement: (node) => {
  39. const ifstmt = node;
  40. if (isElseIf(ifstmt) && !ifstmt.alternate) {
  41. const sourceCode = context.getSourceCode();
  42. const elseKeyword = sourceCode.getTokenBefore(node, token => token.type === 'Keyword' && token.value === 'else');
  43. const ifKeyword = sourceCode.getFirstToken(node, token => token.type === 'Keyword' && token.value === 'if');
  44. context.report({
  45. messageId: 'addMissingElseClause',
  46. loc: {
  47. start: elseKeyword.loc.start,
  48. end: ifKeyword.loc.end,
  49. },
  50. });
  51. }
  52. },
  53. };
  54. },
  55. };
  56. function isElseIf(node) {
  57. const { parent } = node;
  58. return (parent === null || parent === void 0 ? void 0 : parent.type) === 'IfStatement' && parent.alternate === node;
  59. }
  60. module.exports = rule;
  61. //# sourceMappingURL=elseif-without-else.js.map