no-redundant-boolean.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/S1125
  22. const nodes_1 = require("../utils/nodes");
  23. const docs_url_1 = require("../utils/docs-url");
  24. const rule = {
  25. meta: {
  26. messages: {
  27. removeUnnecessaryBoolean: 'Remove the unnecessary boolean literal.',
  28. },
  29. schema: [],
  30. type: 'suggestion',
  31. docs: {
  32. description: 'Boolean literals should not be redundant',
  33. recommended: 'error',
  34. url: (0, docs_url_1.default)(__filename),
  35. },
  36. },
  37. create(context) {
  38. return {
  39. BinaryExpression(node) {
  40. const expression = node;
  41. if (expression.operator === '==' || expression.operator === '!=') {
  42. checkBooleanLiteral(expression.left);
  43. checkBooleanLiteral(expression.right);
  44. }
  45. },
  46. LogicalExpression(node) {
  47. const expression = node;
  48. checkBooleanLiteral(expression.left);
  49. if (expression.operator === '&&') {
  50. checkBooleanLiteral(expression.right);
  51. }
  52. // ignore `x || true` and `x || false` expressions outside of conditional expressions and `if` statements
  53. const { parent } = node;
  54. if (expression.operator === '||' &&
  55. (((0, nodes_1.isConditionalExpression)(parent) && parent.test === expression) || (0, nodes_1.isIfStatement)(parent))) {
  56. checkBooleanLiteral(expression.right);
  57. }
  58. },
  59. UnaryExpression(node) {
  60. const unaryExpression = node;
  61. if (unaryExpression.operator === '!') {
  62. checkBooleanLiteral(unaryExpression.argument);
  63. }
  64. },
  65. };
  66. function checkBooleanLiteral(expression) {
  67. if ((0, nodes_1.isBooleanLiteral)(expression)) {
  68. context.report({ messageId: 'removeUnnecessaryBoolean', node: expression });
  69. }
  70. }
  71. },
  72. };
  73. module.exports = rule;
  74. //# sourceMappingURL=no-redundant-boolean.js.map