Skip to content

Parsers final

finalclassParsers

Static factory and combinator namespace for Parser0 and Parser.

All parser construction starts here. The methods fall into several groups:

Properties

hashCode no setter inherited

intgethashCode

The hash code for this object.

A hash code is a single integer which represents the state of the object that affects operator == comparisons.

All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).

If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.

Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.

Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.

If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.

Inherited from Object.

Implementation
dart
external int get hashCode;

runtimeType no setter inherited

TypegetruntimeType

A representation of the runtime type of the object.

Inherited from Object.

Implementation
dart
external Type get runtimeType;

Methods

noSuchMethod() inherited

dynamicnoSuchMethod(Invocationinvocation)

Invoked when a nonexistent method or property is accessed.

A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:

dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time error

This invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).

Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.

A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:

dart
class MockList<T> implements List<T> {
  noSuchMethod(Invocation invocation) {
    log(invocation);
    super.noSuchMethod(invocation); // Will throw.
  }
}
void main() {
  MockList().add(42);
}

This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.

If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.

The default behavior is to throw a NoSuchMethodError.

Inherited from Object.

Implementation
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);

toString() inherited

StringtoString()

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

Inherited from Object.

Implementation
dart
external String toString();

Operators

operator ==() inherited

booloperator ==(Objectother)

The equality operator.

The default behavior for all Objects is to return true if and only if this object and other are the same object.

Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:

  • Total: It must return a boolean for all arguments. It should never throw.

  • Reflexive: For all objects o, o == o must be true.

  • Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

  • Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.

The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.

If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.

Inherited from Object.

Implementation
dart
external bool operator ==(Object other);

Static Properties

anyChar final

finalParser<String>anyChar

A parser that matches any single character of input.

Implementation
dart
static final Parser<String> anyChar = AnyChar();

caret no setter

Parser0<Caret>getcaret

A parser that succeeds with the current Caret (line/column position) without consuming any input.

Implementation
dart
static Parser0<Caret> get caret => GetCaret();

emptyStringParser0 final

finalParser0<String>emptyStringParser0

A Parser0 that always succeeds with the empty string without consuming input.

Implementation
dart
static final Parser0<String> emptyStringParser0 = Pure('');

end no setter

Parser0<Unit>getend

A parser that succeeds (producing Unit) only at the end of input.

Implementation
dart
static Parser0<Unit> get end => EndParser();

index no setter

Parser0<int>getindex

A parser that succeeds with the current byte offset into the input without consuming any input.

Implementation
dart
static Parser0<int> get index => Index();

start no setter

Parser0<Unit>getstart

A parser that succeeds (producing Unit) only at the start of input.

Implementation
dart
static Parser0<Unit> get start => StartParser();

unit final

finalParser0<Unit>unit

A Parser0 that always succeeds with Unit without consuming input.

Implementation
dart
static final Parser0<Unit> unit = pure(Unit());

Static Methods

as()

Parser<B>as<B>(Parser<dynamic>pa,Bb)

Parser variant of as0.

Implementation
dart
static Parser<B> as<B>(Parser<dynamic> pa, B b) {
  final v = pa.voided;

  &#47;&#47; If b is (), such as foo.as(())
  &#47;&#47; we can just return v
  if (b == Unit()) {
    return v as Parser<B>;
  } else {
    return switch (v) {
      &#47;&#47; CharIn is common and cheap, no need to wrap with Void since CharIn
      &#47;&#47; always returns the char even when voided.
      Void(:final parser) => switch (_singleChar(parser)) {
        final String c when b == c => parser as Parser<B>,
        _ => Map(parser, (_) => b),
      },
      final Fail<dynamic> f => f.widen(),
      final FailWith<dynamic> f => f.widen(),
      final voided => Map(voided, (_) => b),
    };
  }
}

as0()

Parser0<B>as0<B>(Parser0<dynamic>pa,Bb)

Returns a parser that succeeds with b whenever pa succeeds.

Implementation
dart
static Parser0<B> as0<B>(Parser0<dynamic> pa, B b) {
  switch (pa) {
    case final Parser<dynamic> p:
      return as(p, b);
    default:
      final voided = pa.voided;

      if (b == Unit()) {
        return voided as Parser0<B>;
      } else if (_alwaysSucceeds(voided)) {
        return pure(b);
      } else {
        return Map0(voided, (_) => b);
      }
  }
}

backtrack()

Parser<A>backtrack<A>(Parser<A>pa)

Parser variant of backtrack0.

Implementation
dart
static Parser<A> backtrack<A>(Parser<A> pa) {
  return switch (pa) {
    final pa when _doesBacktrack(pa) => pa,
    final Void<A> v => Void(Backtrack(v.parser)) as Parser<A>,
    final nbt => Backtrack(nbt),
  };
}

backtrack0()

Parser0<B>backtrack0<A>(Parser0<A>pa)

Wraps pa so that the input offset is always restored on failure, enabling orElse to catch failures even after partial consumption.

Implementation
dart
static Parser0<A> backtrack0<A>(Parser0<A> pa) {
  return switch (pa) {
    final Parser<A> p1 => backtrack(p1),
    final pa when _doesBacktrack(pa) => pa,
    &#47;&#47; flow analysis doesn't narrow A -> Unit
    final Void0<A> v0 => Void0(Backtrack0(v0.parser)) as Parser0<A>,
    final nbt => Backtrack0(nbt),
  };
}

char()

Parser<Unit>char(Stringchar)

A parser that matches exactly the single character char and discards the result.

Common single characters are cached to reduce allocations.

Implementation
dart
static Parser<Unit> char(String char) {
  final cidx = Char.fromString(char).codeUnit - 32;

  if (0 <= cidx && cidx < _charArray.length) {
    return _charArray[cidx];
  } else {
    return _charImpl(char);
  }
}

charIn()

Parser<String>charIn(RIterableOnce<String>cs)

A parser that matches any single character contained in cs and returns the matched character.

Implementation
dart
static Parser<String> charIn(RIterableOnce<String> cs) {
  switch (cs) {
    default:
      final ary = cs.toList()..sort((a, b) => a.compareTo(b));

      final ranges = _rangesFor(ary);

      if (ranges.size == 1 && ranges.head.bounds == (Char.MinValue, Char.MaxValue)) {
        return anyChar;
      } else {
        return CharIn(BitSet.bitSetFor(ary), ranges);
      }
  }
}

charInRange()

Parser<String>charInRange(Stringstart,Stringend)

A parser that matches any single character whose code unit falls in the inclusive range [start, end].

Implementation
dart
static Parser<String> charInRange(String start, String end) {
  return CharIn.fromRanges(nel(CharsRange((Char.fromString(start), Char.fromString(end)))));
}

charInString()

Parser<String>charInString(Stringstr)

A parser that matches any single character that appears in str.

Implementation
dart
static Parser<String> charInString(String str) => charIn(str.split('').toIList());

charsWhile()

Parser<String>charsWhile(boolFunction(Char)predicate)

Scans forward while predicate holds on successive characters, returning the matched substring. Fails if no characters match. Equivalent to charIn(set).rep().string but avoids per-character virtual dispatch.

Implementation
dart
static Parser<String> charsWhile(bool Function(Char) predicate) => CharsWhile(predicate);

charsWhile0()

Parser0<String>charsWhile0(boolFunction(Char)predicate)

Like charsWhile but succeeds with an empty string when nothing matches.

Implementation
dart
static Parser0<String> charsWhile0(bool Function(Char) predicate) => CharsWhile0(predicate);

charWhere()

Parser<String>charWhere(boolFunction(Char)p)

A parser that matches any single character for which p returns true.

Implementation
dart
static Parser<String> charWhere(Function1<Char, bool> p) =>
    anyChar.filter((s) => p(Char.fromString(s)));

defer()

Parser<A>defer<A>(Parser<A>Function()pa)

Creates a Parser whose construction is deferred until first use.

See defer0 for details.

Implementation
dart
static Parser<A> defer<A>(Function0<Parser<A>> pa) => Defer(pa);

defer0()

Parser0<A>defer0<A>(Parser0<A>Function()pa)

Creates a Parser0 whose construction is deferred until first use.

Use this to break circular references in recursive grammars. Prefer recursive when the recursion is self-contained.

Implementation
dart
static Parser0<A> defer0<A>(Function0<Parser0<A>> pa) => Defer0(pa);

eitherOr()

Parser<Either<A,B>>eitherOr<A, B>(Parser<B>first,Parser<A>second,);

Parser variant of eitherOr0.

Implementation
dart
static Parser<Either<A, B>> eitherOr<A, B>(
  Parser<B> first,
  Parser<A> second,
) => oneOf(ilist([first.map((a) => Right(a)), second.map((b) => Left(b))]));

eitherOr0()

Parser0<Either<A,B>>eitherOr0<A, B>(Parser0<B>first,Parser0<A>second,);

Tries first; on success returns Right. Falls back to second and returns Left.

Implementation
dart
static Parser0<Either<A, B>> eitherOr0<A, B>(
  Parser0<B> first,
  Parser0<A> second,
) => oneOf0(ilist([first.map((a) => Right(a)), second.map((b) => Left(b))]));

fail()

Parser<A>fail<A>()

A parser that always fails without consuming input or recording a message.

Implementation
dart
static Parser<A> fail<A>() => Fail();

failWith()

Parser<A>failWith<A>(Stringmessage)

A parser that always fails with message as the error text, without consuming input.

Implementation
dart
static Parser<A> failWith<A>(String message) => FailWith(message);

flatMap0()

Parser0<B>flatMap0<A, B>(Parser0<A>pa,Parser0<B>Function(A)f,);

Sequences pa with a function f that selects the next parser based on the result. The return type is Parser0.

Implementation
dart
static Parser0<B> flatMap0<A, B>(
  Parser0<A> pa,
  Function1<A, Parser0<B>> f,
) => switch (pa) {
  final Parser<A> p => flatMap10(p, f),
  _ => _hasKnownResult(pa).fold(
    () => FlatMap0(pa, f),
    (a) => pa.productR(f(a)),
  ),
};

flatMap01()

Parser<B>flatMap01<A, B>(Parser0<A>pa,Parser<B>Function(A)f,);

Like flatMap0 but f must return a Parser, so the overall result is a Parser (guaranteed to consume input when f's parser runs).

Implementation
dart
static Parser<B> flatMap01<A, B>(
  Parser0<A> pa,
  Function1<A, Parser<B>> f,
) => switch (pa) {
  final Parser<A> p1 => flatMap10(p1, f),
  _ => _hasKnownResult(pa).fold(
    () => FlatMap(pa, f),
    (a) => pa.with1.productR(f(a)),
  ),
};

flatMap10()

Parser<B>flatMap10<A, B>(Parser<A>pa,Parser0<B>Function(A)f,);

Like flatMap0 but pa is a Parser, so the overall result is a Parser (pa itself guarantees consumption).

Implementation
dart
static Parser<B> flatMap10<A, B>(
  Parser<A> pa,
  Function1<A, Parser0<B>> f,
) => switch (pa) {
  final Fail<dynamic> f => f.widen(),
  final FailWith<dynamic> f => f.widen(),
  _ => _hasKnownResult(pa).fold(
    () => FlatMap(pa, f),
    (a) => pa.productR(f(a)),
  ),
};

fromCharMap()

Parser<A>fromCharMap<A>(IMap<String,A>charMap)

A parser that matches any key in charMap (each key must be a single character) and returns the associated value.

Implementation
dart
static Parser<A> fromCharMap<A>(IMap<String, A> charMap) =>
    charIn(charMap.keys).map((key) => charMap[key]);

fromStringMap()

Parser<A>fromStringMap<A>(IMap<String,A>charMap)

A Parser that matches any key in charMap as a string literal and returns the associated value. All keys must be non-empty.

Implementation
dart
static Parser<A> fromStringMap<A>(IMap<String, A> charMap) =>
    stringIn(charMap.keys).map((key) => charMap[key]);

fromStringMap0()

Parser0<A>fromStringMap0<A>(IMap<String,A>charMap)

A Parser0 that matches any key in charMap as a string literal and returns the associated value. Empty string keys are supported.

Implementation
dart
static Parser0<A> fromStringMap0<A>(IMap<String, A> charMap) =>
    stringIn0(charMap.keys).map((key) => charMap[key]);

ignoreCase()

Parser<Unit>ignoreCase(Stringstr)

A Parser that matches str case-insensitively and produces Unit.

Implementation
dart
static Parser<Unit> ignoreCase(String str) => IgnoreCase(str.toLowerCase());

ignoreCase0()

Parser0<Unit>ignoreCase0(Stringstr)

A Parser0 that matches str case-insensitively. Succeeds with Unit if str is empty.

Implementation
dart
static Parser0<Unit> ignoreCase0(String str) => str.isEmpty ? unit : ignoreCase(str);

ignoreCaseChar()

Parser<String>ignoreCaseChar(Stringchar)

A parser that matches char regardless of case and returns the matched character.

Implementation
dart
static Parser<String> ignoreCaseChar(String char) =>
    charIn([char.toLowerCase(), char.toUpperCase()].toIList());

ignoreCaseCharIn()

Parser<String>ignoreCaseCharIn(RIterableOnce<String>chars)

A parser that matches any character in chars regardless of case.

Implementation
dart
static Parser<String> ignoreCaseCharIn(RIterableOnce<String> chars) =>
    charIn(chars.flatMap((c) => ilist([c.toLowerCase(), c.toUpperCase()])));

ignoreCaseCharInRange()

Parser<String>ignoreCaseCharInRange(Stringstart,Stringend)

A parser that matches any character whose lower- or upper-case form falls in the inclusive range [start, end].

Implementation
dart
static Parser<String> ignoreCaseCharInRange(String start, String end) {
  final lowerStart = Char.fromString(start.toLowerCase());
  final lowerEnd = Char.fromString(end.toLowerCase());
  final upperStart = Char.fromString(start.toUpperCase());
  final upperEnd = Char.fromString(end.toUpperCase());

  if (lowerStart == upperStart && lowerEnd == upperEnd) {
    return charInRange(start, end);
  } else {
    return CharIn.fromRanges(
      NonEmptyIList(
        CharsRange((lowerStart, lowerEnd)),
        ilist([CharsRange((upperStart, upperEnd))]),
      ),
    );
  }
}

ignoreCaseCharInString()

Parser<String>ignoreCaseCharInString(Stringstr)

A parser that matches any character in str regardless of case.

Implementation
dart
static Parser<String> ignoreCaseCharInString(String str) =>
    ignoreCaseCharIn(str.split('').toIList());

length()

Parser<String>length(intlen)

A Parser that consumes exactly len characters and returns them as a string. len must be positive.

Implementation
dart
static Parser<String> length(int len) => Length(len);

length0()

Parser0<String>length0(intlen)

A Parser0 that consumes exactly len characters and returns them as a string. When len is 0 it always succeeds with the empty string.

Implementation
dart
static Parser0<String> length0(int len) => len > 0 ? length(len) : emptyStringParser0;

map()

Parser<B>map<A, B>(Parser<A>p,BFunction(A)f)

Transforms the value produced by p with f. Returns Parser.

Implementation
dart
static Parser<B> map<A, B>(Parser<A> p, Function1<A, B> f) {
  return _hasKnownResult(p).fold(
    () {
      return switch (p) {
        final Fail<dynamic> f => f.widen(),
        final FailWith<dynamic> f => f.widen(),
        Map<dynamic, dynamic>() => (p as Map<dynamic, A>).andThen(f),
        _ => Map(p, f),
      };
    },
    (a) => p.as(f(a)),
  );
}

map0()

Parser0<B>map0<A, B>(Parser0<A>p,BFunction(A)f)

Transforms the value produced by p with f. Returns Parser0.

Implementation
dart
static Parser0<B> map0<A, B>(Parser0<A> p, Function1<A, B> f) {
  return switch (p) {
    final Parser<A> p1 => map(p1, f),
    _ => _hasKnownResult(p).fold(
      () {
        return switch (p) {
          final Fail<dynamic> f => f.widen(),
          final FailWith<dynamic> f => f.widen(),
          Map0<dynamic, dynamic>() => (p as Map0<dynamic, A>).andThen(f),
          _ => Map0(p, f),
        };
      },
      (a) => p.as(f(a)),
    ),
  };
}

not()

Parser0<Unit>not(Parser0<dynamic>pa)

Returns a parser that succeeds (producing Unit) only when pa would fail at the current position, and fails when pa would succeed. Consumes no input in either case.

Implementation
dart
static Parser0<Unit> not(Parser0<dynamic> pa) {
  return switch (voided0(pa)) {
    final Fail<dynamic> _ || FailWith<dynamic> _ => unit,
    final u when _alwaysSucceeds(u) => Fail(),
    final notFail => Not(notFail),
  };
}

oneOf()

Parser<A>oneOf<A>(IList<Parser<A>>ps)

Parser variant of oneOf0.

Implementation
dart
static Parser<A> oneOf<A>(IList<Parser<A>> ps) {
  final res = _oneOfInternal(ps);
  return _hasKnownResult(res).fold(() => res, (a) => res.as(a));
}

oneOf0()

Parser0<A>oneOf0<A>(IList<Parser0<A>>ps)

Tries each parser in ps in order, returning the result of the first one that succeeds. A parser is only tried when the preceding one fails without consuming input (committed failures propagate immediately).

Implementation
dart
static Parser0<A> oneOf0<A>(IList<Parser0<A>> ps) {
  final res = _oneOf0Internal(ps);
  return _hasKnownResult(res).fold(() => res, (a) => res.as(a));
}

peek()

Parser0<Unit>peek(Parser0<dynamic>pa)

Returns a parser that succeeds when pa would succeed but consumes no input.

Implementation
dart
static Parser0<Unit> peek(Parser0<dynamic> pa) {
  return switch (pa) {
    final Peek peek => peek,
    final s when _alwaysSucceeds(s) => unit,
    final notPeek => Peek(voided0(notPeek)),
  };
}

product0()

Parser0<Record>product0<A, B>(Parser0<A>first,Parser0<B>second)

Runs first then second, returning both results as a tuple.

Implementation
dart
static Parser0<(A, B)> product0<A, B>(
  Parser0<A> first,
  Parser0<B> second,
) => switch (first) {
  final Parser<A> f1 => product10(f1, second),
  Pure<A>(:final a) => map0(second, (b) => (a, b)),
  _ => switch (second) {
    final Parser<B> s1 => product01(first, s1),
    Pure<B>(a: final pureB) => map0(first, (x) => (x, pureB)),
    _ => Prod0(first, second),
  },
};

product01()

Parser<Record>product01<A, B>(Parser0<A>first,Parser<B>second)

Like product0 but second is a Parser, so the result is a Parser.

Implementation
dart
static Parser<(A, B)> product01<A, B>(
  Parser0<A> first,
  Parser<B> second,
) => switch (first) {
  final Parser<A> p1 => product10(p1, second),
  Pure<A>(:final a) => map(second, (b) => (a, b)),
  _ => Prod(first, second),
};

product10()

Parser<Record>product10<A, B>(Parser<A>first,Parser0<B>second)

Like product0 but first is a Parser, so the result is a Parser.

Implementation
dart
static Parser<(A, B)> product10<A, B>(
  Parser<A> first,
  Parser0<B> second,
) => switch (first) {
  final Fail<dynamic> f => f.widen(),
  final FailWith<dynamic> f => f.widen(),
  _ => switch (second) {
    Pure<B>(a: final pureB) => map(first, (x) => (x, pureB)),
    _ => Prod(first, second),
  },
};

pure()

Parser0<B>pure<A>(Aa)

A Parser0 that always succeeds with a without consuming any input.

Implementation
dart
static Parser0<A> pure<A>(A a) => Pure(a);

recursive()

Parser<A>recursive<A>(Parser<A>Function(Parser<A>)f)

Creates a self-referential Parser for recursive grammars.

f receives a reference to the parser being constructed and must return the fully built parser. The reference is safe to use only inside other deferred combinators (e.g. as an argument to defer).

Example:

dart
final expr = Parsers.recursive<int>((self) =>
  digits | char('(').productR(self).productL(char(')')));
Implementation
dart
static Parser<A> recursive<A>(Function1<Parser<A>, Parser<A>> f) {
  late Parser<A> result;
  &#47;&#47; ignore: join_return_with_assignment
  result = f(defer(() => result));
  return result;
}

repAs()

Parser<B>repAs<A, B>(Parser<A>p1,Accumulator<A,B>acc,intmin, {int?max,});

Repeats p1 at least min times, accumulating with acc. Pass max to cap repetitions.

Implementation
dart
static Parser<B> repAs<A, B>(
  Parser<A> p1,
  Accumulator<A, B> acc,
  int min, {
  int? max,
}) {
  if (max == null) {
    assert(min >= 1, 'min should be >= 1, was $min');
    return Rep(p1, min, Integer.maxValue, acc);
  } else if (min == max) {
    return repExactlyAs(p1, min, acc);
  } else {
    assert(max > min, 'max should be >= min, but $max < $min');
    return Rep(p1, min, max - 1, acc);
  }
}

repAs0()

Parser0<B>repAs0<A, B>(Parser<A>p1,Accumulator0<A,B>acc, {int?max,});

Repeats p1 zero or more times, accumulating with acc. Pass max to cap repetitions.

Implementation
dart
static Parser0<B> repAs0<A, B>(
  Parser<A> p1,
  Accumulator0<A, B> acc, {
  int? max,
}) {
  if (max == null) {
    return OneOf0(
      ilist([
        Rep(p1, 1, Integer.maxValue, acc),
        pure(acc.newAppender().finish()),
      ]),
    );
  } else {
    assert(max >= 0, 'max should be >= 0, was $max');

    final empty = acc.newAppender().finish();

    if (max == 0) {
      return pure(empty);
    } else {
      &#47;&#47; 0 or more items
      return OneOf0(
        ilist([
          Rep(p1, 1, max - 1, acc),
          pure(empty),
        ]),
      );
    }
  }
}

repExactlyAs()

Parser<B>repExactlyAs<A, B>(Parser<A>p,inttimes,Accumulator<A,B>acc,);

Repeats p exactly times times, accumulating with acc.

Implementation
dart
static Parser<B> repExactlyAs<A, B>(
  Parser<A> p,
  int times,
  Accumulator<A, B> acc,
) {
  if (times == 1) {
    return p.map((a) => acc.newAppender(a).finish());
  } else {
    assert(times > 1, 'times should be >= 1, was $times');
    return Rep(p, times, times - 1, acc);
  }
}

repSep()

Parser<NonEmptyIList<A>>repSep<A>(Parser<A>p1,Parser0<dynamic>sep, {intmin=1,int?max,});

Repeats p1 separated by sep, collecting one or more results into a NonEmptyIList. Pass min/max to control the number of elements.

Implementation
dart
static Parser<NonEmptyIList<A>> repSep<A>(
  Parser<A> p1,
  Parser0<dynamic> sep, {
  int min = 1,
  int? max,
}) {
  if (min < 0) throw ArgumentError('min must be > 0, found: $min');

  if (max == null && min == 1) {
    &#47;&#47; Fast path: direct loop avoids the OneOf0+SoftProd+Void combinator chain.
    return RepSep(p1, sep);
  } else {
    if (max == null) {
      final rest = sep.voided.with1.soft.productR(p1).rep0(min: min - 1);
      return p1.product(rest).map((tup) => NonEmptyIList(tup.$1, tup.$2));
    } else {
      if (max < min) throw ArgumentError('max must be greater than min, found: $max < $min');

      if ((min == 1) && (max == 1)) {
        return p1.map((a) => nel(a));
      } else {
        final rest = sep.voided.with1.soft.productR(p1).rep0(min: min - 1, max: max - 1);
        return p1.product(rest).map((tup) => NonEmptyIList(tup.$1, tup.$2));
      }
    }
  }
}

repSep0()

Parser0<IList<A>>repSep0<A>(Parser<A>p1,Parser0<dynamic>sep, {intmin=0,int?max,});

Repeats p1 separated by sep, collecting zero or more results into an IList. Pass min/max to control the number of elements.

Implementation
dart
static Parser0<IList<A>> repSep0<A>(
  Parser<A> p1,
  Parser0<dynamic> sep, {
  int min = 0,
  int? max,
}) {
  if (max == null) {
    if (min == 0) {
      return repSep(p1, sep).opt.map(
        (nelOpt) => nelOpt.fold(
          () => nil(),
          (nel) => nel.toIList(),
        ),
      );
    } else {
      return repSep(p1, sep, min: min).map((nel) => nel.toIList());
    }
  } else {
    if (min == 0) {
      if (max == 0) {
        return pure(nil());
      } else {
        return repSep(p1, sep, max: max).opt.map(
          (nelOpt) => nelOpt.fold(
            () => nil(),
            (nel) => nel.toIList(),
          ),
        );
      }
    } else {
      return repSep(p1, sep, min: min, max: max).map((nel) => nel.toIList());
    }
  }
}

repUntil()

Parser<NonEmptyIList<A>>repUntil<A>(Parser<A>p,Parser0<dynamic>end,);

Repeats p one or more times, stopping as soon as end matches.

Implementation
dart
static Parser<NonEmptyIList<A>> repUntil<A>(
  Parser<A> p,
  Parser0<dynamic> end,
) => not(end).with1.productR(p).rep();

repUntil0()

Parser0<IList<A>>repUntil0<A>(Parser<A>p,Parser0<dynamic>end)

Repeats p zero or more times, stopping as soon as end matches.

Implementation
dart
static Parser0<IList<A>> repUntil0<A>(
  Parser<A> p,
  Parser0<dynamic> end,
) => not(end).with1.productR(p).rep0();

repUntilAs()

Parser<B>repUntilAs<A, B>(Parser<A>p,Parser0<dynamic>end,Accumulator<A,B>acc,);

Repeats p one or more times until end matches, accumulating with acc.

Implementation
dart
static Parser<B> repUntilAs<A, B>(
  Parser<A> p,
  Parser0<dynamic> end,
  Accumulator<A, B> acc,
) => not(end).with1.productR(p).repAs(acc);

repUntilAs0()

Parser0<B>repUntilAs0<A, B>(Parser<A>p,Parser0<dynamic>end,Accumulator0<A,B>acc,);

Repeats p zero or more times until end matches, accumulating with acc.

Implementation
dart
static Parser0<B> repUntilAs0<A, B>(
  Parser<A> p,
  Parser0<dynamic> end,
  Accumulator0<A, B> acc,
) => not(end).with1.productR(p).repAs0(acc);

select()

Parser<B>select<A, B>(Parser<Either<A,B>>p,Parser0<BFunction(A)>fn,);

Parser variant of select0.

Implementation
dart
static Parser<B> select<A, B>(
  Parser<Either<A, B>> p,
  Parser0<Function1<A, B>> fn,
) => _hasKnownResult(p).fold(
  () => Select(p, fn).map(
    (either) => either.fold(
      (tup) => tup.$2(tup.$1),
      (b) => b,
    ),
  ),
  (either) => either.fold(
    (a) => p.productR(fn.map((f) => f(a))),
    (b) => p.as(b),
  ),
);

select0()

Parser0<B>select0<A, B>(Parser0<Either<A,B>>p,Parser0<BFunction(A)>fn,);

Selective functor combinator: if p returns Left(a), runs fn to obtain a function and applies it to a; if p returns Right(b), returns b without running fn.

Implementation
dart
static Parser0<B> select0<A, B>(
  Parser0<Either<A, B>> p,
  Parser0<Function1<A, B>> fn,
) => _hasKnownResult(p).fold(
  () => Select0(p, fn).map(
    (either) => either.fold(
      (tup) => tup.$2(tup.$1),
      (b) => b,
    ),
  ),
  (either) => either.fold(
    (a) => p.productR(fn.map((f) => f(a))),
    (b) => p.as(b),
  ),
);

softProduct0()

Parser0<Record>softProduct0<A, B>(Parser0<A>first,Parser0<B>second)

Like product0 but a failure in second backtracks to before first ran, so the combined failure can be caught by oneOf0 / orElse.

Implementation
dart
static Parser0<(A, B)> softProduct0<A, B>(
  Parser0<A> first,
  Parser0<B> second,
) => switch (first) {
  final Parser<A> f1 => softProduct10(f1, second),
  Pure<A>(:final a) => map0(second, (b) => (a, b)),
  _ => switch (second) {
    final Parser<B> s1 => softProduct01(first, s1),
    Pure<B>(a: final pureB) => map0(first, (x) => (x, pureB)),
    _ => SoftProd0(first, second),
  },
};

softProduct01()

Parser<Record>softProduct01<A, B>(Parser0<A>first,Parser<B>second)

Like softProduct0 but second is a Parser, so the result is a Parser.

Implementation
dart
static Parser<(A, B)> softProduct01<A, B>(
  Parser0<A> first,
  Parser<B> second,
) => switch (first) {
  final Fail<dynamic> f => f.widen(),
  final FailWith<dynamic> f => f.widen(),
  Pure<A>(:final a) => map(second, (b) => (a, b)),
  _ => SoftProd(first, second),
};

softProduct10()

Parser<Record>softProduct10<A, B>(Parser<A>first,Parser0<B>second)

Like softProduct0 but first is a Parser, so the result is a Parser.

Implementation
dart
static Parser<(A, B)> softProduct10<A, B>(
  Parser<A> first,
  Parser0<B> second,
) => switch (first) {
  final Fail<dynamic> f => f.widen(),
  final FailWith<dynamic> f => f.widen(),
  _ => switch (second) {
    Pure<B>(a: final pureB) => map(first, (x) => (x, pureB)),
    _ => SoftProd(first, second),
  },
};

string()

Parser<Unit>string(Stringstr)

A Parser that matches str exactly and produces Unit.

Implementation
dart
static Parser<Unit> string(String str) => Str(str);

string0()

Parser0<Unit>string0(Stringstr)

A Parser0 that matches str exactly, producing Unit. Succeeds immediately (without consuming input) when str is empty.

Implementation
dart
static Parser0<Unit> string0(String str) => str.isEmpty ? unit : Str(str);

stringIn()

Parser<String>stringIn(RIterable<String>strings)

A Parser that matches any of the given non-empty strings and returns the matched string. Uses a trie internally for efficient longest-match dispatch.

Implementation
dart
static Parser<String> stringIn(RIterable<String> strings) {
  final distinct = strings.toIList().distinct();

  if (distinct.isEmpty) {
    return fail();
  } else if (distinct.size == 1) {
    return string(distinct[0]).string;
  } else {
    return StringIn(SplayTreeSet.from(distinct.toList(), (a, b) => a.compareTo(b)));
  }
}

stringIn0()

Parser0<String>stringIn0(RIterable<String>strings)

A Parser0 that matches any of the given strings and returns the matched string. Empty strings are supported and result in an immediate success fallback.

Implementation
dart
static Parser0<String> stringIn0(RIterable<String> strings) {
  if (strings.exists((s) => s.isEmpty)) {
    return Parsers.oneOf0(
      ilist([
        stringIn(strings.filter((str) => str.nonEmpty)),
        emptyStringParser0,
      ]),
    );
  } else {
    return stringIn(strings);
  }
}

stringP()

Parser<String>stringP(Parser<dynamic>pa)

Returns a parser that produces the substring matched by pa instead of pa's original value. Parser variant.

Implementation
dart
static Parser<String> stringP(Parser<dynamic> pa) {
  return switch (pa) {
    final str when _matchesString(str) => str as Parser<String>,
    _ => switch (_unmap(pa)) {
      final StringIn si => si,
      final Length len => len,
      final Str strP => strP.as(strP.message),
      final Fail<dynamic> f => f.widen(),
      final FailWith<dynamic> f => f.widen(),
      final notStr => StringP(notStr),
    },
  };
}

stringP0()

Parser0<String>stringP0(Parser0<dynamic>pa)

Returns a parser that produces the substring matched by pa instead of pa's original value. Parser0 variant.

Implementation
dart
static Parser0<String> stringP0(Parser0<dynamic> pa) {
  return switch (pa) {
    final Parser<dynamic> s1 => stringP(s1),
    final str when _matchesString(str) => str as Parser0<String>,
    _ => switch (_unmap0(pa)) {
      final Pure<dynamic> _ || Index _ || GetCaret _ => emptyStringParser0,
      final nonEmpty => StringP0(nonEmpty),
    },
  };
}

until()

Parser<String>until(Parser0<dynamic>p)

Consumes one or more characters, stopping just before p would match, and returns the consumed substring.

Implementation
dart
static Parser<String> until(Parser0<dynamic> p) => repUntil(anyChar, p).string;

until0()

Parser0<String>until0(Parser0<dynamic>p)

Consumes zero or more characters, stopping just before p would match, and returns the consumed substring.

Implementation
dart
static Parser0<String> until0(Parser0<dynamic> p) => repUntil0(anyChar, p).string;

voided()

Parser<Unit>voided(Parser<dynamic>pa)

Returns a parser that runs pa and discards the result, producing Unit. Parser variant.

Implementation
dart
static Parser<Unit> voided(Parser<dynamic> pa) {
  return switch (pa) {
    final Void<dynamic> v => v,
    _ => switch (_unmap(pa)) {
      final Fail<dynamic> f => f.widen(),
      final FailWith<dynamic> f => f.widen(),
      final notVoid when _isVoided(notVoid) => notVoid as Parser<Unit>,
      final notVoid => Void(notVoid),
    },
  };
}

voided0()

Parser0<Unit>voided0(Parser0<dynamic>pa)

Returns a parser that runs pa and discards the result, producing Unit. Parser0 variant.

Implementation
dart
static Parser0<Unit> voided0(Parser0<dynamic> pa) {
  switch (pa) {
    case final Parser<dynamic> p1:
      return voided(p1);
    case final Void0<dynamic> v:
      return v;
    default:
      if (_alwaysSucceeds(pa)) {
        return unit;
      } else {
        final unmapped = _unmap0(pa);

        if (_isVoided(unmapped)) {
          return unmapped as Parser0<Unit>;
        } else {
          return Void0(unmapped);
        }
      }
  }
}

withContext()

Parser<A>withContext<A>(Parser<A>p,Stringctx)

Attaches context label ctx to any error produced by p. Parser variant.

Implementation
dart
static Parser<A> withContext<A>(Parser<A> p, String ctx) {
  return switch (p) {
    final Void<A> v => Void(withContext(v.parser, ctx)) as Parser<A>,
    _ => WithContextP(ctx, p),
  };
}

withContext0()

Parser0<A>withContext0<A>(Parser0<A>p0,Stringctx)

Attaches context label ctx to any error produced by p0, making failure messages easier to diagnose. Parser0 variant.

Implementation
dart
static Parser0<A> withContext0<A>(Parser0<A> p0, String ctx) {
  return switch (p0) {
    final Void0<A> v0 => Void0(withContext0(v0.parser, ctx)) as Parser0<A>,
    _ when _alwaysSucceeds(p0) => p0,
    _ => WithContextP0(ctx, p0),
  };
}

withString()

Parser<Record>withString<A>(Parser<A>pa)

Returns a parser that produces both the parsed value and the substring consumed by pa. Parser variant.

Implementation
dart
static Parser<(A, String)> withString<A>(Parser<A> pa) {
  return switch (pa) {
    final Fail<dynamic> f => f.widen(),
    final FailWith<dynamic> f => f.widen(),
    _ when _matchesString(pa) => (pa as Parser<String>).map((s) => (s, s)) as Parser<(A, String)>,
    final notFail => WithStringP(notFail),
  };
}

withString0()

Parser0<Record>withString0<A>(Parser0<A>pa)

Returns a parser that produces both the parsed value and the substring consumed by pa. Parser0 variant.

Implementation
dart
static Parser0<(A, String)> withString0<A>(Parser0<A> pa) {
  return switch (pa) {
    final Parser<A> p1 => withString(p1),
    _ when _alwaysSucceeds(pa) => map0(pa, (a) => (a, '')),
    _ when _matchesString(pa) =>
      (pa as Parser0<String>).map((s) => (s, s)) as Parser0<(A, String)>,
    final not1 => WithStringP0(not1),
  };
}