I have written grammar for a language (sample code below)
//this is a procedure
procedure main()
$i := 0
begin
if ($i = 0)
$i := 10
loop while ($i != 0)
print($i)
$i := $i - 1
end loop
end if
end procedure
The tree grammar for which is
@members {
private Map<String, Integer> variablesTable = new HashMap<String, Integer>();
}
procedure
: ^('procedure' IDENTIFIER assignment_expression* 'begin' statement+)
;
statement
: assignment_expression | selection_statement
;
assignment_expression
: ^(':=' IDENTIFIER e=expression)
{ variablesTable.put($IDENTIFIER.text, e); }
;
expression returns [int result]
: ^('+' op1=expression op2=expression) { result = op1 + op2; }
/* removed similar lines */
| IDENTIFIER { result = variablesTable.get($IDENTIFIER.text); }
| INTEGER { result = Integer.parseInt($INTEGER.text); }
;
equality_expression returns [boolean truth]
: ^('=' op1=expression op2=expression) { truth = op1 == op2; }
| ^('!=' op1=expression op2=expression) { truth = op1 != op2; }
;
selection_statement
: ^('if' e=equality_expression block1=statement+ ('else' block2=statement+)? )
{
if (e) {
//What do I put here?
}
}
;
While I can evaluate expressions, print messages etc., I am not able figure out how to change execution (interpretation) of program.
Like in above code, for if-else, how can I execute if-block in case predicate is true, and skip to else (if it is there)?
Same goes for loop, how can I evaluate loop-predicate at the end of loop?
Thanks!
Embedding code inside the tree grammar is only suitable for very simple languages (calculators and such). Embedding it will (IMO) result in an incomprehensible mess of mixed grammar rules, programming logic and rule-parameters and rule-return values. Pretty much every rule will then need at least a
booleanvalue keeping track if the (sub) rules of it needed to be executed or not (is it inside theif– orelseblock?).When interpreting a language consisting of
if– andwhile-statements, simple as it may be, I recommend creating custom trees/nodes and evaluate those.I’ve written a blog series that shows how to do just that: http://bkiers.blogspot.com/2011/03/creating-your-own-programming-language.html