Reputation: 11
I want to implement if else conditions in to my language. Currently I have
def p_if_statement(p):
'''if_statement : IF LPAREN condition RPAREN LCURLY statements RCURLY
| IF LPAREN condition RPAREN LCURLY statements RCURLY ELSE LCURLY statements RCURLY'''
print(p[0:10])
I know it is unfinished but I'm having trouble seeing what to do when the if condition is false. Example:
if(False){
a = 5;
print(a);
}
This code will print out 5 and then it will print p[0:10]. It seems like the statements get evaluated before the conditional. Any help would be greatly appreciated
Upvotes: 0
Views: 135
Reputation: 241931
That's correct. When a ply reduction action function executes, all of its components have already executed. Were this not the case, it would be impossible for the argument p
to contain the components' semantic values.
So if you want to incorporate loops and conditionals into the language you are parsing, you will have to abandon the idea of direct evaluation during parsing. Instead, the parse needs to create a description of the parsed text which can subsequently be evaluated (or compiled for later evaluation).
A common form of describing a parsed text is an Abstract Syntax Tree (AST), although many other options exist (and there's no definitive AST, so you have lots of flexibility there, too).
Upvotes: 1