optimize<R> function

  1. @useResult
Parser<R> optimize<R>(
  1. Parser<R> parser, {
  2. ReplaceParser? callback,
  3. List<OptimizeRule>? rules,
})

Returns an in-place optimized version of the parser.

Implementation

@useResult
Parser<R> optimize<R>(Parser<R> parser,
    {ReplaceParser<dynamic>? 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;
}