noUnusedExpressionRule.js 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright 2014 Palantir Technologies, Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. Object.defineProperty(exports, "__esModule", { value: true });
  19. var tslib_1 = require("tslib");
  20. var tsutils_1 = require("tsutils");
  21. var ts = require("typescript");
  22. var Lint = require("../index");
  23. var ALLOW_FAST_NULL_CHECKS = "allow-fast-null-checks";
  24. var ALLOW_NEW = "allow-new";
  25. var ALLOW_TAGGED_TEMPLATE = "allow-tagged-template";
  26. var Rule = /** @class */ (function (_super) {
  27. tslib_1.__extends(Rule, _super);
  28. function Rule() {
  29. return _super !== null && _super.apply(this, arguments) || this;
  30. }
  31. Rule.prototype.apply = function (sourceFile) {
  32. return this.applyWithFunction(sourceFile, walk, {
  33. allowFastNullChecks: this.ruleArguments.indexOf(ALLOW_FAST_NULL_CHECKS) !== -1,
  34. allowNew: this.ruleArguments.indexOf(ALLOW_NEW) !== -1,
  35. allowTaggedTemplate: this.ruleArguments.indexOf(ALLOW_TAGGED_TEMPLATE) !== -1,
  36. });
  37. };
  38. /* tslint:disable:object-literal-sort-keys */
  39. Rule.metadata = {
  40. ruleName: "no-unused-expression",
  41. description: "Disallows unused expression statements.",
  42. descriptionDetails: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Unused expressions are expression statements which are not assignments or function calls\n (and thus usually no-ops)."], ["\n Unused expressions are expression statements which are not assignments or function calls\n (and thus usually no-ops)."]))),
  43. rationale: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n Detects potential errors where an assignment or function call was intended."], ["\n Detects potential errors where an assignment or function call was intended."]))),
  44. optionsDescription: Lint.Utils.dedent(templateObject_3 || (templateObject_3 = tslib_1.__makeTemplateObject(["\n Two arguments may be optionally provided:\n\n * `", "` allows to use logical operators to perform fast null checks and perform\n method or function calls for side effects (e.g. `e && e.preventDefault()`).\n * `", "` allows 'new' expressions for side effects (e.g. `new ModifyGlobalState();`.\n * `", "` allows tagged templates for side effects (e.g. `this.add\\`foo\\`;`."], ["\n Two arguments may be optionally provided:\n\n * \\`", "\\` allows to use logical operators to perform fast null checks and perform\n method or function calls for side effects (e.g. \\`e && e.preventDefault()\\`).\n * \\`", "\\` allows 'new' expressions for side effects (e.g. \\`new ModifyGlobalState();\\`.\n * \\`", "\\` allows tagged templates for side effects (e.g. \\`this.add\\\\\\`foo\\\\\\`;\\`."])), ALLOW_FAST_NULL_CHECKS, ALLOW_NEW, ALLOW_TAGGED_TEMPLATE),
  45. options: {
  46. type: "array",
  47. items: {
  48. type: "string",
  49. enum: [ALLOW_FAST_NULL_CHECKS, ALLOW_NEW, ALLOW_TAGGED_TEMPLATE],
  50. },
  51. minLength: 0,
  52. maxLength: 3,
  53. },
  54. optionExamples: [true, [true, ALLOW_FAST_NULL_CHECKS]],
  55. type: "functionality",
  56. typescriptOnly: false,
  57. };
  58. /* tslint:enable:object-literal-sort-keys */
  59. Rule.FAILURE_STRING = "unused expression, expected an assignment or function call";
  60. return Rule;
  61. }(Lint.Rules.AbstractRule));
  62. exports.Rule = Rule;
  63. function walk(ctx) {
  64. var checking = false;
  65. var allowFastNullChecks = true;
  66. return ts.forEachChild(ctx.sourceFile, cb);
  67. function cb(node) {
  68. if (checking) {
  69. if (tsutils_1.isParenthesizedExpression(node) || tsutils_1.isVoidExpression(node)) {
  70. return cb(node.expression);
  71. }
  72. else if (tsutils_1.isConditionalExpression(node)) {
  73. noCheck(node.condition, cb);
  74. return both(node.whenTrue, node.whenFalse);
  75. }
  76. else if (tsutils_1.isBinaryExpression(node)) {
  77. switch (node.operatorToken.kind) {
  78. case ts.SyntaxKind.CommaToken:
  79. if (isIndirectEval(node)) {
  80. return false;
  81. }
  82. return both(node.left, node.right);
  83. case ts.SyntaxKind.AmpersandAmpersandToken:
  84. case ts.SyntaxKind.BarBarToken:
  85. if (allowFastNullChecks) {
  86. noCheck(node.left, cb);
  87. return cb(node.right);
  88. }
  89. }
  90. }
  91. noCheck(node, forEachChild);
  92. return isUnusedExpression(node, ctx.options);
  93. }
  94. if (tsutils_1.isExpressionStatement(node)) {
  95. allowFastNullChecks = ctx.options.allowFastNullChecks;
  96. if (!isDirective(node)) {
  97. check(node.expression, node);
  98. }
  99. allowFastNullChecks = true;
  100. return false;
  101. }
  102. else if (tsutils_1.isVoidExpression(node)) {
  103. // allow `void 0` and `void(0)`
  104. if (!isLiteralZero(tsutils_1.isParenthesizedExpression(node.expression) ? node.expression.expression : node.expression)) {
  105. check(node.expression);
  106. }
  107. return false;
  108. }
  109. else if (tsutils_1.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.CommaToken && !isIndirectEval(node)) {
  110. check(node.left);
  111. return cb(node.right);
  112. }
  113. return ts.forEachChild(node, cb);
  114. }
  115. function forEachChild(node) {
  116. return ts.forEachChild(node, cb);
  117. }
  118. function check(node, failNode) {
  119. checking = true;
  120. if (cb(node)) {
  121. ctx.addFailureAtNode(failNode === undefined ? node : failNode, Rule.FAILURE_STRING);
  122. }
  123. checking = false;
  124. }
  125. function noCheck(node, callback) {
  126. var old = allowFastNullChecks;
  127. checking = false;
  128. allowFastNullChecks = true;
  129. callback(node);
  130. allowFastNullChecks = old;
  131. checking = true;
  132. }
  133. function both(one, two) {
  134. if (cb(one)) {
  135. if (cb(two)) {
  136. return true;
  137. }
  138. else {
  139. ctx.addFailureAtNode(one, Rule.FAILURE_STRING);
  140. }
  141. }
  142. else if (cb(two)) {
  143. ctx.addFailureAtNode(two, Rule.FAILURE_STRING);
  144. }
  145. return false;
  146. }
  147. }
  148. function isUnusedExpression(node, options) {
  149. switch (node.kind) {
  150. case ts.SyntaxKind.CallExpression:
  151. case ts.SyntaxKind.YieldExpression:
  152. case ts.SyntaxKind.DeleteExpression:
  153. case ts.SyntaxKind.AwaitExpression:
  154. case ts.SyntaxKind.PostfixUnaryExpression:
  155. return false;
  156. case ts.SyntaxKind.NewExpression:
  157. return !options.allowNew;
  158. case ts.SyntaxKind.TaggedTemplateExpression:
  159. return !options.allowTaggedTemplate;
  160. case ts.SyntaxKind.BinaryExpression:
  161. return !tsutils_1.isAssignmentKind(node.operatorToken.kind);
  162. case ts.SyntaxKind.PrefixUnaryExpression:
  163. return node.operator !== ts.SyntaxKind.PlusPlusToken &&
  164. node.operator !== ts.SyntaxKind.MinusMinusToken;
  165. default:
  166. return true;
  167. }
  168. }
  169. function isLiteralZero(node) {
  170. return tsutils_1.isNumericLiteral(node) && node.text === "0";
  171. }
  172. function isIndirectEval(node) {
  173. return tsutils_1.isIdentifier(node.right) && node.right.text === "eval" &&
  174. isLiteralZero(node.left) &&
  175. node.parent.kind === ts.SyntaxKind.ParenthesizedExpression &&
  176. node.parent.parent.kind === ts.SyntaxKind.CallExpression;
  177. }
  178. function isDirective(node) {
  179. if (node.expression.kind !== ts.SyntaxKind.StringLiteral || !canContainDirective(node.parent)) {
  180. return false;
  181. }
  182. var parent = node.parent;
  183. // check if all previous statements in block are also directives
  184. for (var i = parent.statements.indexOf(node) - 1; i >= 0; --i) {
  185. var statement = parent.statements[i];
  186. if (!tsutils_1.isExpressionStatement(statement) || statement.expression.kind !== ts.SyntaxKind.StringLiteral) {
  187. return false;
  188. }
  189. }
  190. return true;
  191. }
  192. function canContainDirective(node) {
  193. switch (node.kind) {
  194. case ts.SyntaxKind.SourceFile:
  195. case ts.SyntaxKind.ModuleBlock:
  196. return true;
  197. case ts.SyntaxKind.Block:
  198. switch (node.parent.kind) {
  199. case ts.SyntaxKind.ArrowFunction:
  200. case ts.SyntaxKind.FunctionExpression:
  201. case ts.SyntaxKind.FunctionDeclaration:
  202. case ts.SyntaxKind.MethodDeclaration:
  203. case ts.SyntaxKind.Constructor:
  204. case ts.SyntaxKind.GetAccessor:
  205. case ts.SyntaxKind.SetAccessor:
  206. return true;
  207. default:
  208. return false;
  209. }
  210. default:
  211. return false;
  212. }
  213. }
  214. var templateObject_1, templateObject_2, templateObject_3;