git.dumitru.net fructose / master src / parser / combinators / AnyOfParser.ts
master

Tree @master (Download .tar.gz)

AnyOfParser.ts @masterraw · history · blame

import Document from "../../Document";
import DocumentLocation from "../../DocumentLocation";
import Parser from "../Parser";
import ParserError from "../ParserError";
import ParserValue from "../ParserValue";

export default class AnyOfParser<T> implements Parser<T> {
  public readonly name: string;
  private ps: Array<() => Parser<T>>;

  constructor(ps: Array<() => Parser<T>>) {
    this.ps = ps;
    this.name = `(${ps.map((o) => o.toString()).join(" | ")})`;
  }

  public parse(doc: Document, loc: DocumentLocation): ParserValue<T> | ParserError {
    for (const option of this.ps) {
      const result = option().parse(doc, loc);

      if (result instanceof ParserValue) {
        return result;
      }
    }

    return new ParserError(`expected: ${this.name}, got something else`, loc, null);
  }
}