forinRule.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use strict";
  2. var __extends = (this && this.__extends) || function (d, b) {
  3. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4. function __() { this.constructor = d; }
  5. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  6. };
  7. var ts = require("typescript");
  8. var Lint = require("../lint");
  9. var Rule = (function (_super) {
  10. __extends(Rule, _super);
  11. function Rule() {
  12. _super.apply(this, arguments);
  13. }
  14. Rule.prototype.apply = function (sourceFile) {
  15. return this.applyWithWalker(new ForInWalker(sourceFile, this.getOptions()));
  16. };
  17. Rule.FAILURE_STRING = "for (... in ...) statements must be filtered with an if statement";
  18. return Rule;
  19. }(Lint.Rules.AbstractRule));
  20. exports.Rule = Rule;
  21. var ForInWalker = (function (_super) {
  22. __extends(ForInWalker, _super);
  23. function ForInWalker() {
  24. _super.apply(this, arguments);
  25. }
  26. ForInWalker.prototype.visitForInStatement = function (node) {
  27. this.handleForInStatement(node);
  28. _super.prototype.visitForInStatement.call(this, node);
  29. };
  30. ForInWalker.prototype.handleForInStatement = function (node) {
  31. var statement = node.statement;
  32. var statementKind = node.statement.kind;
  33. if (statementKind === ts.SyntaxKind.IfStatement) {
  34. return;
  35. }
  36. if (statementKind === ts.SyntaxKind.Block) {
  37. var blockNode = statement;
  38. var blockStatements = blockNode.statements;
  39. if (blockStatements.length >= 1) {
  40. var firstBlockStatement = blockStatements[0];
  41. if (firstBlockStatement.kind === ts.SyntaxKind.IfStatement) {
  42. if (blockStatements.length === 1) {
  43. return;
  44. }
  45. var ifStatement = firstBlockStatement.thenStatement;
  46. if (nodeIsContinue(ifStatement)) {
  47. return;
  48. }
  49. }
  50. }
  51. }
  52. var failure = this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING);
  53. this.addFailure(failure);
  54. };
  55. return ForInWalker;
  56. }(Lint.RuleWalker));
  57. function nodeIsContinue(node) {
  58. var kind = node.kind;
  59. if (kind === ts.SyntaxKind.ContinueStatement) {
  60. return true;
  61. }
  62. if (kind === ts.SyntaxKind.Block) {
  63. var blockStatements = node.statements;
  64. if (blockStatements.length === 1 && blockStatements[0].kind === ts.SyntaxKind.ContinueStatement) {
  65. return true;
  66. }
  67. }
  68. return false;
  69. }