optimize<R> function
- @useResult
- Parser<
R> parser, { - ReplaceParser? callback,
- List<
OptimizeRule> ? rules,
Returns an in-place optimized version of the parser.
Implementation
@useResult
Parser<R> optimize<R>(Parser<R> parser,
{ReplaceParser? callback, List<OptimizeRule>? rules}) {
final analyzer = Analyzer(parser);
final selectedRules = rules ?? allOptimizerRules;
final replacements = <Parser, Parser>{};
for (final parser in analyzer.parsers) {
parser.captureResultGeneric(<R>(parser) {
for (final rule in selectedRules) {
rule.run<R>(analyzer, parser, (a, b) {
if (callback != null) callback(a, b);
replacements[a] = b;
});
}
});
}
if (replacements.isNotEmpty) {
for (final parser in analyzer.parsers) {
for (final replacement in replacements.entries) {
parser.replace(replacement.key, replacement.value);
}
}
return replacements[parser] as Parser<R>? ?? parser;
}
return parser;
}