noUnsafeAnyRule.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright 2017 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 Rule = /** @class */ (function (_super) {
  24. tslib_1.__extends(Rule, _super);
  25. function Rule() {
  26. return _super !== null && _super.apply(this, arguments) || this;
  27. }
  28. Rule.prototype.applyWithProgram = function (sourceFile, program) {
  29. return this.applyWithWalker(new NoUnsafeAnyWalker(sourceFile, this.ruleName, program.getTypeChecker()));
  30. };
  31. /* tslint:disable:object-literal-sort-keys */
  32. Rule.metadata = {
  33. ruleName: "no-unsafe-any",
  34. description: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Warns when using an expression of type 'any' in a dynamic way.\n Uses are only allowed if they would work for `{} | null | undefined`.\n Type casts and tests are allowed.\n Expressions that work on all values (such as `\"\" + x`) are allowed."], ["\n Warns when using an expression of type 'any' in a dynamic way.\n Uses are only allowed if they would work for \\`{} | null | undefined\\`.\n Type casts and tests are allowed.\n Expressions that work on all values (such as \\`\"\" + x\\`) are allowed."]))),
  35. optionsDescription: "Not configurable.",
  36. options: null,
  37. optionExamples: [true],
  38. type: "functionality",
  39. typescriptOnly: true,
  40. requiresTypeInfo: true,
  41. };
  42. /* tslint:enable:object-literal-sort-keys */
  43. Rule.FAILURE_STRING = "Unsafe use of expression of type 'any'.";
  44. return Rule;
  45. }(Lint.Rules.TypedRule));
  46. exports.Rule = Rule;
  47. var NoUnsafeAnyWalker = /** @class */ (function (_super) {
  48. tslib_1.__extends(NoUnsafeAnyWalker, _super);
  49. function NoUnsafeAnyWalker(sourceFile, ruleName, checker) {
  50. var _this = _super.call(this, sourceFile, ruleName, undefined) || this;
  51. _this.checker = checker;
  52. /** Wraps `visitNode` with the correct `this` binding and discards the return value to prevent `forEachChild` from returning early */
  53. _this.visitNodeCallback = function (node) { return void _this.visitNode(node); };
  54. return _this;
  55. }
  56. NoUnsafeAnyWalker.prototype.walk = function (sourceFile) {
  57. if (sourceFile.isDeclarationFile) {
  58. return; // Not possible in a declaration file.
  59. }
  60. sourceFile.statements.forEach(this.visitNodeCallback);
  61. };
  62. NoUnsafeAnyWalker.prototype.visitNode = function (node, anyOk) {
  63. switch (node.kind) {
  64. case ts.SyntaxKind.ParenthesizedExpression:
  65. // Don't warn on a parenthesized expression, warn on its contents.
  66. return this.visitNode(node.expression, anyOk);
  67. case ts.SyntaxKind.LabeledStatement:
  68. // Ignore label
  69. return this.visitNode(node.statement);
  70. // ignore labels
  71. case ts.SyntaxKind.BreakStatement:
  72. case ts.SyntaxKind.ContinueStatement:
  73. // Ignore types
  74. case ts.SyntaxKind.InterfaceDeclaration:
  75. case ts.SyntaxKind.TypeAliasDeclaration:
  76. case ts.SyntaxKind.TypeParameter:
  77. case ts.SyntaxKind.IndexSignature:
  78. // Ignore imports
  79. case ts.SyntaxKind.ImportEqualsDeclaration:
  80. case ts.SyntaxKind.ImportDeclaration:
  81. case ts.SyntaxKind.ExportDeclaration:
  82. case ts.SyntaxKind.ExportAssignment:
  83. return false;
  84. case ts.SyntaxKind.ThisKeyword:
  85. case ts.SyntaxKind.Identifier:
  86. return anyOk ? false : this.check(node);
  87. // Recurse through these, but ignore the immediate child because it is allowed to be 'any'.
  88. case ts.SyntaxKind.DeleteExpression:
  89. case ts.SyntaxKind.ExpressionStatement:
  90. case ts.SyntaxKind.TypeAssertionExpression:
  91. case ts.SyntaxKind.AsExpression:
  92. case ts.SyntaxKind.TemplateSpan: // Allow stringification (works on all values). Note: tagged templates handled differently.
  93. case ts.SyntaxKind.ThrowStatement:
  94. case ts.SyntaxKind.TypeOfExpression:
  95. case ts.SyntaxKind.VoidExpression:
  96. return this.visitNode(node.expression, true);
  97. case ts.SyntaxKind.PropertyAssignment: {
  98. var _a = node, name = _a.name, initializer = _a.initializer;
  99. this.visitNode(name, /*anyOk*/ true);
  100. if (tsutils_1.isReassignmentTarget(node.parent)) {
  101. return this.visitNode(initializer, true);
  102. }
  103. return this.checkContextualType(initializer, true);
  104. }
  105. case ts.SyntaxKind.ShorthandPropertyAssignment: {
  106. var _b = node, name = _b.name, objectAssignmentInitializer = _b.objectAssignmentInitializer;
  107. if (objectAssignmentInitializer !== undefined) {
  108. return this.checkContextualType(objectAssignmentInitializer);
  109. }
  110. return this.checkContextualType(name, true);
  111. }
  112. case ts.SyntaxKind.PropertyDeclaration: {
  113. var _c = node, name = _c.name, initializer = _c.initializer;
  114. this.visitNode(name, true);
  115. return initializer !== undefined &&
  116. this.visitNode(initializer, isPropertyAny(node, this.checker));
  117. }
  118. case ts.SyntaxKind.SpreadAssignment:
  119. return this.visitNode(node.expression,
  120. // allow any in object spread, but not in object rest
  121. !tsutils_1.isReassignmentTarget(node.parent));
  122. case ts.SyntaxKind.ComputedPropertyName:
  123. return this.visitNode(node.expression, true);
  124. case ts.SyntaxKind.TaggedTemplateExpression: {
  125. var _d = node, tag = _d.tag, template = _d.template;
  126. if (template.kind === ts.SyntaxKind.TemplateExpression) {
  127. for (var _i = 0, _e = template.templateSpans; _i < _e.length; _i++) {
  128. var expression = _e[_i].expression;
  129. this.checkContextualType(expression);
  130. }
  131. }
  132. // Also check the template expression itself
  133. if (this.visitNode(tag)) {
  134. return true;
  135. }
  136. return anyOk ? false : this.check(node);
  137. }
  138. case ts.SyntaxKind.CallExpression:
  139. case ts.SyntaxKind.NewExpression: {
  140. var _f = node, expression = _f.expression, args = _f.arguments;
  141. if (args !== undefined) {
  142. for (var _g = 0, args_1 = args; _g < args_1.length; _g++) {
  143. var arg = args_1[_g];
  144. this.checkContextualType(arg);
  145. }
  146. }
  147. if (this.visitNode(expression)) {
  148. return true;
  149. }
  150. // Also check the call expression itself
  151. return anyOk ? false : this.check(node);
  152. }
  153. case ts.SyntaxKind.PropertyAccessExpression:
  154. // Don't warn for right hand side; this is redundant if we warn for the access itself.
  155. if (this.visitNode(node.expression)) {
  156. return true;
  157. }
  158. return anyOk ? false : this.check(node);
  159. case ts.SyntaxKind.ElementAccessExpression: {
  160. var _h = node, expression = _h.expression, argumentExpression = _h.argumentExpression;
  161. if (argumentExpression !== undefined) {
  162. this.visitNode(argumentExpression, true);
  163. }
  164. if (this.visitNode(expression)) {
  165. return true;
  166. }
  167. return anyOk ? false : this.check(node);
  168. }
  169. case ts.SyntaxKind.ReturnStatement: {
  170. var expression = node.expression;
  171. return expression !== undefined && this.checkContextualType(expression, true);
  172. }
  173. case ts.SyntaxKind.SwitchStatement: {
  174. var _j = node, expression = _j.expression, clauses = _j.caseBlock.clauses;
  175. // Allow `switch (x) {}` where `x` is any
  176. this.visitNode(expression, /*anyOk*/ true);
  177. for (var _k = 0, clauses_1 = clauses; _k < clauses_1.length; _k++) {
  178. var clause = clauses_1[_k];
  179. if (clause.kind === ts.SyntaxKind.CaseClause) {
  180. // Allow `case x:` where `x` is any
  181. this.visitNode(clause.expression, /*anyOk*/ true);
  182. }
  183. for (var _l = 0, _m = clause.statements; _l < _m.length; _l++) {
  184. var statement = _m[_l];
  185. this.visitNode(statement);
  186. }
  187. }
  188. return false;
  189. }
  190. case ts.SyntaxKind.ModuleDeclaration: {
  191. // In `declare global { ... }`, don't mark `global` as unsafe any.
  192. var body = node.body;
  193. return body !== undefined && this.visitNode(body);
  194. }
  195. case ts.SyntaxKind.IfStatement: {
  196. var _o = node, expression = _o.expression, thenStatement = _o.thenStatement, elseStatement = _o.elseStatement;
  197. this.visitNode(expression, true); // allow truthyness check
  198. this.visitNode(thenStatement);
  199. return elseStatement !== undefined && this.visitNode(elseStatement);
  200. }
  201. case ts.SyntaxKind.PrefixUnaryExpression: {
  202. var _p = node, operator = _p.operator, operand = _p.operand;
  203. this.visitNode(operand, operator === ts.SyntaxKind.ExclamationToken); // allow falsyness check
  204. return false;
  205. }
  206. case ts.SyntaxKind.ForStatement: {
  207. var _q = node, initializer = _q.initializer, condition = _q.condition, incrementor = _q.incrementor, statement = _q.statement;
  208. if (initializer !== undefined) {
  209. this.visitNode(initializer, true);
  210. }
  211. if (condition !== undefined) {
  212. this.visitNode(condition, true);
  213. } // allow truthyness check
  214. if (incrementor !== undefined) {
  215. this.visitNode(incrementor, true);
  216. }
  217. return this.visitNode(statement);
  218. }
  219. case ts.SyntaxKind.DoStatement:
  220. case ts.SyntaxKind.WhileStatement:
  221. this.visitNode(node.expression, true);
  222. return this.visitNode(node.statement);
  223. case ts.SyntaxKind.ConditionalExpression: {
  224. var _r = node, condition = _r.condition, whenTrue = _r.whenTrue, whenFalse = _r.whenFalse;
  225. this.visitNode(condition, true);
  226. var left = this.visitNode(whenTrue, anyOk);
  227. return this.visitNode(whenFalse, anyOk) || left;
  228. }
  229. case ts.SyntaxKind.VariableDeclaration:
  230. case ts.SyntaxKind.Parameter:
  231. return this.checkVariableOrParameterDeclaration(node);
  232. case ts.SyntaxKind.BinaryExpression:
  233. return this.checkBinaryExpression(node, anyOk);
  234. case ts.SyntaxKind.AwaitExpression:
  235. this.visitNode(node.expression);
  236. return anyOk ? false : this.check(node);
  237. case ts.SyntaxKind.YieldExpression:
  238. return this.checkYieldExpression(node, anyOk);
  239. case ts.SyntaxKind.ClassExpression:
  240. case ts.SyntaxKind.ClassDeclaration:
  241. this.checkClassLikeDeclaration(node);
  242. return false;
  243. case ts.SyntaxKind.ArrayLiteralExpression: {
  244. for (var _s = 0, _t = node.elements; _s < _t.length; _s++) {
  245. var element = _t[_s];
  246. this.checkContextualType(element, true);
  247. }
  248. return false;
  249. }
  250. case ts.SyntaxKind.JsxExpression:
  251. return node.expression !== undefined &&
  252. this.checkContextualType(node.expression);
  253. }
  254. if (tsutils_1.isTypeNodeKind(node.kind) || tsutils_1.isTokenKind(node.kind)) {
  255. return false;
  256. }
  257. return ts.forEachChild(node, this.visitNodeCallback);
  258. };
  259. NoUnsafeAnyWalker.prototype.check = function (node) {
  260. if (!isNodeAny(node, this.checker)) {
  261. return false;
  262. }
  263. this.addFailureAtNode(node, Rule.FAILURE_STRING);
  264. return true;
  265. };
  266. NoUnsafeAnyWalker.prototype.checkContextualType = function (node, allowIfNoContextualType) {
  267. var type = this.checker.getContextualType(node);
  268. return this.visitNode(node, type === undefined && allowIfNoContextualType || isAny(type));
  269. };
  270. // Allow `const x = foo;` and `const x: any = foo`, but not `const x: Foo = foo;`.
  271. NoUnsafeAnyWalker.prototype.checkVariableOrParameterDeclaration = function (_a) {
  272. var name = _a.name, type = _a.type, initializer = _a.initializer;
  273. this.checkBindingName(name);
  274. // Always allow the LHS to be `any`. Just don't allow RHS to be `any` when LHS isn't.
  275. return initializer !== undefined &&
  276. this.visitNode(initializer,
  277. /*anyOk*/
  278. name.kind === ts.SyntaxKind.Identifier && (type === undefined || type.kind === ts.SyntaxKind.AnyKeyword) ||
  279. type !== undefined && type.kind === ts.SyntaxKind.AnyKeyword);
  280. };
  281. NoUnsafeAnyWalker.prototype.checkBinaryExpression = function (node, anyOk) {
  282. var allowAnyLeft = false;
  283. var allowAnyRight = false;
  284. switch (node.operatorToken.kind) {
  285. case ts.SyntaxKind.ExclamationEqualsEqualsToken:
  286. case ts.SyntaxKind.ExclamationEqualsToken:
  287. case ts.SyntaxKind.EqualsEqualsEqualsToken:
  288. case ts.SyntaxKind.EqualsEqualsToken:
  289. case ts.SyntaxKind.CommaToken: // Allow `any, any`
  290. case ts.SyntaxKind.BarBarToken: // Allow `any || any`
  291. case ts.SyntaxKind.AmpersandAmpersandToken:// Allow `any && any`
  292. allowAnyLeft = allowAnyRight = true;
  293. break;
  294. case ts.SyntaxKind.InstanceOfKeyword:// Allow test
  295. allowAnyLeft = true;
  296. break;
  297. case ts.SyntaxKind.EqualsToken:
  298. // Allow assignment if the lhs is also *any*.
  299. allowAnyLeft = true;
  300. allowAnyRight = isNodeAny(node.left, this.checker);
  301. break;
  302. case ts.SyntaxKind.PlusToken: // Allow implicit stringification
  303. case ts.SyntaxKind.PlusEqualsToken:
  304. allowAnyLeft = allowAnyRight = isStringLike(node.left, this.checker)
  305. || (isStringLike(node.right, this.checker) && node.operatorToken.kind === ts.SyntaxKind.PlusToken);
  306. }
  307. this.visitNode(node.left, allowAnyLeft);
  308. this.visitNode(node.right, allowAnyRight);
  309. return anyOk ? false : this.check(node);
  310. };
  311. NoUnsafeAnyWalker.prototype.checkYieldExpression = function (node, anyOk) {
  312. if (node.expression !== undefined) {
  313. this.checkContextualType(node.expression, true);
  314. }
  315. if (anyOk) {
  316. return false;
  317. }
  318. this.addFailureAtNode(node, Rule.FAILURE_STRING);
  319. return true;
  320. };
  321. NoUnsafeAnyWalker.prototype.checkClassLikeDeclaration = function (node) {
  322. if (node.decorators !== undefined) {
  323. node.decorators.forEach(this.visitNodeCallback);
  324. }
  325. if (node.heritageClauses !== undefined) {
  326. node.heritageClauses.forEach(this.visitNodeCallback);
  327. }
  328. return node.members.forEach(this.visitNodeCallback);
  329. };
  330. NoUnsafeAnyWalker.prototype.checkBindingName = function (node) {
  331. if (node.kind !== ts.SyntaxKind.Identifier) {
  332. if (isNodeAny(node, this.checker)) {
  333. this.addFailureAtNode(node, Rule.FAILURE_STRING);
  334. }
  335. for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
  336. var element = _a[_i];
  337. if (element.kind !== ts.SyntaxKind.OmittedExpression) {
  338. if (element.propertyName !== undefined && element.propertyName.kind === ts.SyntaxKind.ComputedPropertyName) {
  339. this.visitNode(element.propertyName.expression);
  340. }
  341. this.checkBindingName(element.name);
  342. if (element.initializer !== undefined) {
  343. this.checkContextualType(element.initializer);
  344. }
  345. }
  346. }
  347. }
  348. };
  349. return NoUnsafeAnyWalker;
  350. }(Lint.AbstractWalker));
  351. /** Check if property has no type annotation in this class and the base class */
  352. function isPropertyAny(node, checker) {
  353. if (!isNodeAny(node.name, checker) || node.name.kind === ts.SyntaxKind.ComputedPropertyName) {
  354. return false;
  355. }
  356. for (var _i = 0, _a = checker.getBaseTypes(checker.getTypeAtLocation(node.parent)); _i < _a.length; _i++) {
  357. var base = _a[_i];
  358. var prop = base.getProperty(node.name.text);
  359. if (prop !== undefined && prop.declarations !== undefined) {
  360. return isAny(checker.getTypeOfSymbolAtLocation(prop, prop.declarations[0]));
  361. }
  362. }
  363. return true;
  364. }
  365. function isNodeAny(node, checker) {
  366. var symbol = checker.getSymbolAtLocation(node);
  367. if (symbol !== undefined && tsutils_1.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias)) {
  368. symbol = checker.getAliasedSymbol(symbol);
  369. }
  370. if (symbol !== undefined) {
  371. // NamespaceModule is a type-only namespace without runtime value, its type is 'any' when used as 'ns.Type' -> avoid error
  372. if (tsutils_1.isSymbolFlagSet(symbol, ts.SymbolFlags.NamespaceModule)) {
  373. return false;
  374. }
  375. if (tsutils_1.isSymbolFlagSet(symbol, ts.SymbolFlags.Type)) {
  376. return isAny(checker.getDeclaredTypeOfSymbol(symbol));
  377. }
  378. }
  379. return isAny(checker.getTypeAtLocation(node));
  380. }
  381. function isStringLike(expr, checker) {
  382. return tsutils_1.isTypeFlagSet(checker.getTypeAtLocation(expr), ts.TypeFlags.StringLike);
  383. }
  384. function isAny(type) {
  385. return type !== undefined && tsutils_1.isTypeFlagSet(type, ts.TypeFlags.Any);
  386. }
  387. var templateObject_1;