noDuplicateKeyRule.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 NoDuplicateKeyWalker(sourceFile, this.getOptions()));
  16. };
  17. Rule.FAILURE_STRING = "duplicate key '";
  18. return Rule;
  19. }(Lint.Rules.AbstractRule));
  20. exports.Rule = Rule;
  21. var NoDuplicateKeyWalker = (function (_super) {
  22. __extends(NoDuplicateKeyWalker, _super);
  23. function NoDuplicateKeyWalker() {
  24. _super.apply(this, arguments);
  25. this.objectKeysStack = [];
  26. }
  27. NoDuplicateKeyWalker.prototype.visitObjectLiteralExpression = function (node) {
  28. this.objectKeysStack.push(Object.create(null));
  29. _super.prototype.visitObjectLiteralExpression.call(this, node);
  30. this.objectKeysStack.pop();
  31. };
  32. NoDuplicateKeyWalker.prototype.visitPropertyAssignment = function (node) {
  33. var objectKeys = this.objectKeysStack[this.objectKeysStack.length - 1];
  34. var keyNode = node.name;
  35. if (keyNode.kind === ts.SyntaxKind.Identifier) {
  36. var key = keyNode.text;
  37. if (objectKeys[key]) {
  38. var failureString = Rule.FAILURE_STRING + key + "'";
  39. this.addFailure(this.createFailure(keyNode.getStart(), keyNode.getWidth(), failureString));
  40. }
  41. else {
  42. objectKeys[key] = true;
  43. }
  44. }
  45. _super.prototype.visitPropertyAssignment.call(this, node);
  46. };
  47. return NoDuplicateKeyWalker;
  48. }(Lint.RuleWalker));