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

Tree @master (Download .tar.gz)

OptionalParser.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 OptionalParser<T> implements Parser<T | null> {
  public readonly name: string;
  private p: () => Parser<T>;

  constructor(p: () => Parser<T>) {
    this.p = p;
    this.name = `${p().name}?`;
  }

  public parse(doc: Document, loc: DocumentLocation): ParserValue<T | null> | ParserError {
    const result = this.p().parse(doc, loc);

    if (result instanceof ParserValue) {
      return result;
    }

    return new ParserValue(null, loc);
  }
}