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

Tree @master (Download .tar.gz)

CharParser.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 CharParser implements Parser<string> {
  public readonly name: string;
  private ch: string;

  constructor(ch: string) {
    this.ch = ch;
    this.name = `"${ch}"`;
  }

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

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

    if (input.charAt(0) !== this.ch) {
      return new ParserError(`expected ${this.ch}, got ${input}`, loc, null);
    }

    return new ParserValue(this.ch,
      new DocumentLocation(loc.line, loc.char + 1));
  }
}