git.dumitru.net fructose / master src / parser / base / RegexParser.ts
master

Tree @master (Download .tar.gz)

RegexParser.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 RegexParser implements Parser<string> {
  public readonly name: string;
  private r: RegExp;

  constructor(r: RegExp) {
    this.r = r;
    this.name = String(r);
  }

  public parse(doc: Document, loc: DocumentLocation): ParserValue<string> | ParserError {
    const input = doc.getLineFromLocation(loc);

    if (input === null) {
      return new ParserError(`expected ${this.name}, got end of input`, loc, null);
    }

    const match = input.match(this.r);

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

    return new ParserValue(match[0],
      new DocumentLocation(loc.line, loc.char + match[0].length));
  }
}