petitparser / dart-petitparser

Dynamic parser combinators in Dart.
https://pub.dartlang.org/packages/petitparser
MIT License
457 stars 48 forks source link

Debugging Parsers with References is unsupported #73

Closed adimit closed 4 years ago

adimit commented 4 years ago

Hi, I'm trying to debug a grammar that has several refs everywhere. This is pretty much just how the examples do it, so I figured I'd take the same approach.

Unfortunately, with something like

Parser foo() => letter()
Parser bar() => ref(foo)

I can't just do e.g. trace(bar), as that will tell me that References cannot be copied.

  Unsupported operation: References cannot be copied.
  package:petitparser/src/definition/reference.dart 50:23  Reference.copy
  package:petitparser/src/reflection/transform.dart 18:34  transformParser
  package:petitparser/src/debug/progress.dart 29:10        progress

I guess copying a function reference doesn't make much sense (in Dart.) Is there another way to debug parsers that contain refs? Which I imagine is most of the non-trivial ones. Or am I overlooking something? Thanks!

renggli commented 4 years ago

In your example, trace is trying to transform the grammar before it is built. As a workaround you could build your grammar starting at bar (instead of the default start). Something along these lines:

class MyGrammarDefinition extends GrammarDefinition {
  Parser start() => ref(bar);
  Parser foo() => letter();
  Parser bar() => ref(foo);
}

void main() {
  final grammar = MyGrammarDefinition();
  final bar = grammar.build(start: grammar.bar);
  final traced = trace(bar);

  traced.parse('a');
}
adimit commented 4 years ago

Nice, thanks for your quick reply. I didn't know the grammar definition first had to be built. I guess the step was implicit.