streams.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * Base class for input streams.
  3. * Defines which methods are expected for any stream implementations.
  4. */
  5. export class ParserStream {
  6. value_at (index) { throw new Error(`${this.constructor.name}.value_at() not implemented`); }
  7. look () { throw new Error(`${this.constructor.name}.look() not implemented`); }
  8. next () { throw new Error(`${this.constructor.name}.next() not implemented`); }
  9. fork () { throw new Error(`${this.constructor.name}.fork() not implemented`); }
  10. join () { throw new Error(`${this.constructor.name}.join() not implemented`); }
  11. is_eof () {
  12. return this.look().done;
  13. }
  14. }
  15. /**
  16. * ParserStream that takes a string, and processes it character by character.
  17. */
  18. export class StringStream extends ParserStream {
  19. constructor (str, startIndex = 0) {
  20. super();
  21. this.str = str;
  22. this.i = startIndex;
  23. }
  24. value_at (index) {
  25. if ( index >= this.str.length ) {
  26. return { done: true, value: undefined };
  27. }
  28. return { done: false, value: this.str[index] };
  29. }
  30. look () {
  31. return this.value_at(this.i);
  32. }
  33. next () {
  34. const result = this.value_at(this.i);
  35. this.i++;
  36. return result;
  37. }
  38. fork () {
  39. return new StringStream(this.str, this.i);
  40. }
  41. join (forked) {
  42. this.i = forked.i;
  43. }
  44. }