trace<R> function
- @useResult
- Parser<
R> root, { - void output(
- TraceEvent event
- bool predicate(
- Parser parser
Returns a transformed Parser that, when used to read input, prints a trace of all activated parsers and their respective parse results.
For example, the snippet
final parser = letter() & word().star();
trace(parser).parse('f1');
produces the following output:
SequenceParser<dynamic>
SingleCharacterParser[letter expected]
Success<String>[1:2]: f
PossessiveRepeatingParser<String>[0..*]
SingleCharacterParser[letter or digit expected]
Success<String>[1:3]: 1
SingleCharacterParser[letter or digit expected]
Failure[1:3]: letter or digit expected
Success<List<String>>[1:3]: [1]
Success<List<dynamic>>[1:3]: [f, [1]]
Indentation signifies the activation of a parser object. Reverse indentation signifies the returning of a parse result either with a success or failure context.
The optional output callback can be used to continuously receive
TraceEvent objects with current enter and exit data.
Implementation
@useResult
Parser<R> trace<R>(
Parser<R> root, {
void Function(TraceEvent event) output = print,
bool Function(Parser parser)? predicate,
}) {
TraceEvent? parent;
return transformParser(root, <P>(parser) {
if (predicate == null || predicate(parser)) {
return parser.callCC((continuation, context) {
final currentParent = parent;
output(parent = _TraceEvent(currentParent, parser, context));
// Parsers and user callbacks are assumed not to throw during parsing.
final result = continuation(context);
output(_TraceEvent(currentParent, parser, context, result));
parent = currentParent;
return result;
});
} else {
return parser;
}
});
}