noStringLiteralRule.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 NoStringLiteralWalker(sourceFile, this.getOptions()));
  16. };
  17. Rule.FAILURE_STRING = "object access via string literals is disallowed";
  18. return Rule;
  19. }(Lint.Rules.AbstractRule));
  20. exports.Rule = Rule;
  21. var NoStringLiteralWalker = (function (_super) {
  22. __extends(NoStringLiteralWalker, _super);
  23. function NoStringLiteralWalker() {
  24. _super.apply(this, arguments);
  25. }
  26. NoStringLiteralWalker.prototype.visitElementAccessExpression = function (node) {
  27. var argument = node.argumentExpression;
  28. var accessorText = argument.getText();
  29. if (argument.kind === ts.SyntaxKind.StringLiteral && accessorText.length > 2) {
  30. var unquotedAccessorText = accessorText.substring(1, accessorText.length - 1);
  31. if (isValidIdentifier(unquotedAccessorText)) {
  32. this.addFailure(this.createFailure(argument.getStart(), argument.getWidth(), Rule.FAILURE_STRING));
  33. }
  34. }
  35. _super.prototype.visitElementAccessExpression.call(this, node);
  36. };
  37. return NoStringLiteralWalker;
  38. }(Lint.RuleWalker));
  39. function isValidIdentifier(token) {
  40. var scanner = ts.createScanner(ts.ScriptTarget.ES5, false, ts.LanguageVariant.Standard, token);
  41. scanner.scan();
  42. return scanner.getTokenText() === token && scanner.isIdentifier();
  43. }