or method

  1. @useResult
ChoiceParser or(
  1. Parser other, {
  2. FailureJoiner? failureJoiner,
})

Returns a parser that accepts the receiver or other (ordered choice).

Evaluates the receiver first; if it succeeds, its result is returned. If it fails, parsing falls back to other. If called on an existing ChoiceParser, this flattens other into the existing choice rather than nesting choices.

The optional failureJoiner determines which Failure to report when all alternatives fail. Defaults to selectLast, though selectFarthest can sometimes provide more helpful error messages.

Order is significant. Because alternatives are tested sequentially, earlier branches take precedence over later, overlapping ones:

// Evaluates to Object (String or int):
final parser = letter() | digit().map(int.parse);

// In this example, char('a') is unreachable because letter() matches first:
final shadowed = letter() | char('a');

The returned parser has result type dynamic due to Dart's lack of union types (https://github.com/dart-lang/language/issues/1557). For better type safety, prefer ChoiceIterableExtension.toChoiceParser.

Implementation

@useResult
ChoiceParser<dynamic> or(Parser other, {FailureJoiner? failureJoiner}) =>
    switch (this) {
      ChoiceParser(
        children: final children,
        failureJoiner: final thisFailureJoiner,
      ) =>
        [
          ...children,
          other,
        ].toChoiceParser(failureJoiner: failureJoiner ?? thisFailureJoiner),
      _ => [this, other].toChoiceParser(failureJoiner: failureJoiner),
    };