objectLiteralSortKeysRule.js 2.3 KB

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