So I'm pretty new to JavaCC, I have this in JavaCC for a conditional grammar. I have to implement it in such a way that if the condition is true in the grammar I established, the rest of commands (block()) execute, but if not, just skip this part. How can I do that?
void conditional(): { }
{
< IF > condition() block()
[<ELSE> block()]< FI>
}
There is very little information about your project and the way to approach the question of conditional greately depends on the context.
For instance, if your program is compiling code for a target machine like, say JVM bytecode, you would do something like this:
This assumes that
condition()will generate the code that calculates a boolean value and that that boolean value is then pushed to the stack.generateJumpIfFalse()generates a conditional jump that pops a boolean from the stack and, if false, jumps to a location that is not yet known because the block that follows has not yet been compiled. Forward jumps have to be updated once this location is known.; that's watfixForwardJumpdoes.Now if your program is an interpretor, You want the parser to produce some structure that your java code can then execute.
In the present case, you manipulate two basic kind of structure:
Statements andExpression. They could be the same thing, but the difference is than anExpressionreturns a value when executed, whereasStatementdoes not.In the case of an interpretor, you often want the syntactic methods to return some substructure of the whole input programme; so you would have something like this:
Let's say that
StatementandExpressionare interfaces of the following kind:Class
ConditionalStatementmust of course implement theStatementinterface. It would look like this:Of course, it can get a lot more complicated than that.