# Parse forest from an ambiguous grammar

Parser-generators like nearleyjs can return a parse forest instead of a parse tree.

Since not all input may result in a parse forest (eg, the input may exercise only a non-ambiguous subset of the grammar), how do you programmatically choose the 'correct' parse tree from the forest?

One option is to always choose the first element from the array of parse-trees returned.

Another option is to flag the returning of a parse-forest (instead of a single tree) as an error. But then, this would defy the whole point of having Earley-like parsers that allow parsing of ambiguous grammars!

Also, since only some input may result in a parse-forest (instead of a single parse-tree), how do you rule out surprises in a live/Production environment? Assumption: For non-trivial or non-trivially long grammars, it's not humanly possible to create tests that cover all inputs.

• It sounds like you approach the question from the wrong end. Why do you parse at all (i.e. what's the exact problem are you trying to solve)? this would defy the whole point of having Earley-like parsers that allow parsing of ambiguous grammars! - it doesn't matter what's the point of Earley-like parsers. The only thing that matters whether your selected approach solves your problem. In other words, how do you programmatically choose the 'correct' parse tree is entirely up to you to define, depending on what you want. Whether you need the entire forest or not depends on your problem.
– user114966
Apr 27 at 3:15