Question

I'm using Python PLY to parse a specific language. For a grammar like:

IF LPAREN condition RPAREN LBRACE stmtlist RBRACE ELSE LBRACE stmtlist RBRACE

When I know the condition value, say True, then is there a way to stop parsing the stmtlist in the ELSE path?

Thanks,

Was it helpful?

Solution

You will have to continue the parse, because you need to find the end of the block enclosed by the second RBRACE; in other words, you need to parse to find the beginning of the next statement.

That said, when you analyze the results of the parse (to generate code, construct an AST, whatever you need to do), if you can determine that condition always evaluates to true (perhaps it is the expression 1 = 1), then you can suppress generating code for the second stmtlist.

Update:

Your grammar (the syntax of your language) is specified non-procedurally, so there's no place for you to attach conditional logic.

On the other hand, you specify semantic actions to take when a particular syntactic element of your grammar is matched, and you do this procedurally. In PLY, you do this by coding the body of grammar rule function(s). In the grammar rule function that matches the second stmtlist, you can write conditional code to skip over code generation, based on other information you have figured out about the input program (the input to your compiled language processor).

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