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

Tree @master (Download .tar.gz)

IntoParser.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 IntoParser<F, T> implements Parser<T> {
  public readonly name: string;
  private from: () => Parser<F>;
  private transformer: (from: F) => T;

  constructor(from: () => Parser<F>, transformer: (from: F) => T) {
    this.from = from;
    this.transformer = transformer;
    this.name = from.name;
  }

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

    if (result instanceof ParserValue) {
      return new ParserValue(this.transformer(result.value), result.location);
    }

    if (result instanceof ParserError) {
      return result;
    }

    return new ParserError("something went wrong", loc, null);
  }
}