Question

I currently have the following grammar below:

COMPONENT = HEADER BODY
BODY = ELEMENT+
ELEMENT = EXPRESSION | DECLARATION | DESCRIPTION | NAME

I would like to assert that the body must have one of each of the ELEMENT in any order. Currently I am checking this after parsing, I am however curious if it's possible to express this in the grammar using Parser Combinators particularly guards

I tried doing further research regarding this, but nothing seems to come up.

Was it helpful?

Solution

Yes, it is possible. You simply write down all the valid permutations. This gets out of hand, fast.

It isn't worth the trouble to express in the grammar, because in essence you are trying to establish a constraint across the syntax, and grammars are really best at expressing context-free constraints.

Better to parse with grammar rules simply allowing all of the possibles clauses as options, and build your semantic pass (you will have one anyway) to check the additional constraints.

OTHER TIPS

When writing a grammar, you should move as many constraints as possible to the semantic pass instead of the syntactic pass. This greatly improves the ability of the parser to recover from errors during parsing, and allows you to fully control the manner and wording used when reporting the error to users. For the case of permutations, the increased flexibility in the parser will likely reduce the size of the parsing tables as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top