parser.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. export const adapt_parser = v => v;
  2. export const UNRECOGNIZED = Symbol('unrecognized');
  3. export const INVALID = Symbol('invalid');
  4. export const VALUE = Symbol('value');
  5. /**
  6. * Base class for parsers.
  7. * To implement your own, subclass it and define these methods:
  8. * - _create(): Acts as the constructor
  9. * - _parse(stream): Performs the parsing on the stream, and returns either UNRECOGNIZED, INVALID, or a result object.
  10. */
  11. export class Parser {
  12. result (o) {
  13. if (o.value && o.value.$discard) {
  14. delete o.value;
  15. }
  16. return o;
  17. }
  18. parse (stream) {
  19. let result = this._parse(stream);
  20. if ( typeof result !== 'object' ) {
  21. result = { status: result };
  22. }
  23. return this.result(result);
  24. }
  25. set_symbol_registry (symbol_registry) {
  26. this.symbol_registry = symbol_registry;
  27. }
  28. _create () { throw new Error(`${this.constructor.name}._create() not implemented`); }
  29. _parse (stream) { throw new Error(`${this.constructor.name}._parse() not implemented`); }
  30. }