util.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. "use strict";
  2. var _types = require("../tokenizer/types");
  3. var _index = require("./index");
  4. var _index2 = _interopRequireDefault(_index);
  5. var _whitespace = require("../util/whitespace");
  6. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7. var pp = _index2.default.prototype;
  8. // ## Parser utilities
  9. // TODO
  10. pp.addExtra = function (node, key, val) {
  11. if (!node) return;
  12. var extra = node.extra = node.extra || {};
  13. extra[key] = val;
  14. };
  15. // TODO
  16. pp.isRelational = function (op) {
  17. return this.match(_types.types.relational) && this.state.value === op;
  18. };
  19. // TODO
  20. pp.expectRelational = function (op) {
  21. if (this.isRelational(op)) {
  22. this.next();
  23. } else {
  24. this.unexpected();
  25. }
  26. };
  27. // Tests whether parsed token is a contextual keyword.
  28. pp.isContextual = function (name) {
  29. return this.match(_types.types.name) && this.state.value === name;
  30. };
  31. // Consumes contextual keyword if possible.
  32. pp.eatContextual = function (name) {
  33. return this.state.value === name && this.eat(_types.types.name);
  34. };
  35. // Asserts that following token is given contextual keyword.
  36. pp.expectContextual = function (name, message) {
  37. if (!this.eatContextual(name)) this.unexpected(null, message);
  38. };
  39. // Test whether a semicolon can be inserted at the current position.
  40. pp.canInsertSemicolon = function () {
  41. return this.match(_types.types.eof) || this.match(_types.types.braceR) || _whitespace.lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  42. };
  43. // TODO
  44. pp.isLineTerminator = function () {
  45. return this.eat(_types.types.semi) || this.canInsertSemicolon();
  46. };
  47. // Consume a semicolon, or, failing that, see if we are allowed to
  48. // pretend that there is a semicolon at this position.
  49. pp.semicolon = function () {
  50. if (!this.isLineTerminator()) this.unexpected();
  51. };
  52. // Expect a token of a given type. If found, consume it, otherwise,
  53. // raise an unexpected token error at given pos.
  54. pp.expect = function (type, pos) {
  55. return this.eat(type) || this.unexpected(pos);
  56. };
  57. // Raise an unexpected token error.
  58. pp.unexpected = function (pos) {
  59. var message = arguments.length <= 1 || arguments[1] === undefined ? "Unexpected token" : arguments[1];
  60. this.raise(pos != null ? pos : this.state.start, message);
  61. };