I am writing an interpreter that converts my DSL language into C# which is then compiled and shipped as a standalone executable.
I have successfully managed to handle variable definitions and some basic arithmetic expressions computation.
So far, I did all of this using ANTLR without generating AST trees. I managed to do everything only by embedding action code into the grammar as shown below:
statement
: var_declaration
| if_statement
;
// k = var or k = var.something.somethingelse
var_declaration
:
varType=ID varName=ID ASSIGN r=rvalue
{
if(variablesTable.ContainsKey(varName.Text)){
// Variable ID not defined yet, cannot continue;
ReportError("A local variable '"+varName.Text+"' is already defined");
return;
}
if(r == null){ ReportError ("No r-value specified"); return;}
}
;
if_statement
: 'if' expression s1=statement ('else' s2=statement)?
statement
:...
expression
:...
I am now struggling on how to handle and properly generate code for if and loop statements.
Question
- Do I have to build an AST tree to handle conditional and loop
statements? - I have googled this over and over again without finding clear
tutorials on how this can be done with or without AST trees, do you
know of any good tutorials on this?
Thanks in advance,
It looks like checking for if statements is possible through action code embedded in the grammar but this is the not recommended way of dealing with this as it won’t scale once the grammar grows big.