shnewto / bnf

Parse BNF grammar definitions
MIT License
256 stars 22 forks source link

2 Questions about Parsing #105

Closed Axiomatic-Mind closed 1 year ago

Axiomatic-Mind commented 1 year ago
  1. Why does Grammar::parse_input have a return type of impl Iterator<Item = ParseTree> and not of Option<ParseTree> or Result<ParseTree, Error>? Is there any circumstance in which Grammar::parse_input could parse to multiple ParseTrees?

  2. I know that I can access the data in a ParseTree by calling ParseTree::rhs_iter to get something of type ParseTreeIter, which implements Iterator<Item = &ParseTreeNode>. I can then iterate through this to get items of type &ParseTreeNode, but how can I get the data out from this? src/lib.rs only publicly exports Grammar and ParseTree from src/grammar.rs, and I cannot construct the variants of the externally private ParseTreeNode necessary to match ParseTreeNodes and access the data stored within.

shnewto commented 1 year ago

Hey @Axiomatic-Mind ๐Ÿ‘‹ as to your first question, whether parse_input returns a list of parse trees or not is mostly up to your grammar, and things like grammars for programming languages usually shouldn't have ambiguous ways to interpret a sentence. But grammars for natural language can be full of ambiguities that can lead to multiple parse trees. My personal favorite example of the kind of sentence that would lead a parser like this to return multiple trees is "Time flies like an arrow". Where we're either talking about the concept of time moving quickly, or something more like a plot line from Doctor Who, i.e. "Time flies like an arrow. Fruit flies like a banana."

As to your second question, it's a great point! ParseTreeNode probably needs to be exposed!

Axiomatic-Mind commented 1 year ago

Thanks! Embarrassingly, I was trying to get that information by calling format!(โ€œ{:?}โ€, foo) on the output of the parse_input function and using regular expressions to parse it. The lengths to which one will go!

shnewto commented 1 year ago

Thanks so much for #106! I've published version 0.4.1 to crates.io now so you should be able to use your changes

CrockAgile commented 1 year ago

Thanks for noticing this issue @Axiomatic-Mind ! totally just an oversight. And double thanks for opening a PR ๐Ÿ™Œ

Axiomatic-Mind commented 1 year ago

My pleasure๐Ÿ‘