git.dumitru.net fructose / master src / tests / parser / combinators / seq.test.ts
master

Tree @master (Download .tar.gz)

seq.test.ts @masterraw · history · blame

import Parser from "../../../parser/Parser";
import ParserError from "../../../parser/ParserError";
import { into, matchChar, seq, zeroOrMore } from "../../../parser/Parsers";
import { doc, loc, val } from "../../utils";

describe("seq combinator", () => {
  const p0: Parser<string[]> = seq([
    () => matchChar("a"),
    () => into<string[], string>(
      () => zeroOrMore(() => matchChar("b")),
      (v) => v.join("")),
    () => matchChar("a")]);

  test("parses sequence equivalent to /ab*a/", () => {
    expect(
      p0.parse(doc("aa"), loc(0, 0)))
    .toEqual(
      val(["a", "", "a"], loc(0, 2)));

    expect(
      p0.parse(doc("aba"), loc(0, 0)))
    .toEqual(
      val(["a", "b", "a"], loc(0, 3)));

    expect(
      p0.parse(doc("abbba"), loc(0, 0)))
    .toEqual(
      val(["a", "bbb", "a"], loc(0, 5)));
  });

  test("returns an error on unexpected input", () => {
    expect(
      p0.parse(doc("a"), loc(0, 0)))
    .toBeInstanceOf(ParserError);

    expect(
      p0.parse(doc("ab"), loc(0, 0)))
    .toBeInstanceOf(ParserError);
  });
});