parse method

  1. @override
ParseResult parse(
  1. String source
)
override

Attempts to parse the source string matching this element.

Returns a ParseResult containing the parsed lexeme and remaining string on success. On failure, returns a failed ParseResult.

Implementation

@override
ParseResult parse(String source) {
  if (min > source.length) {
    return ParseResult(false, source);
  }

  final results = Stack<ParseResult>();

  var remaining = source;
  var count = 0;

  final upper = max;

  while (remaining.isNotEmpty && (upper == null || count < upper)) {
    final result = element.parse(remaining);
    results.push(result);
    if (result.success) {
      count++;
      remaining = result.remaining;
    } else {
      // If the inner element fails but we've met the minimum requirement,
      // we stop repeating and return success.
      if (count >= min) {
        break;
      }
      // Otherwise, the entire repetition fails.
      return ParseResult(false, source, stack: results, element: toString());
    }
  }

  if (count < min) {
    // Didn't get the lower limit of repetitions
    return ParseResult(false, remaining, stack: results, element: toString());
  }
  final String lexeme = source.substring(0, source.length - remaining.length);
  return ParseResult(
    true,
    remaining,
    stack: results,
    lexeme: lexeme,
    element: toString(),
  );
}