Using abstract syntax tree attributes
Currently, the G
grammar only parses the constructions when an integer value is assigned to a variable:
$x = 100;
Let us see how to add support for the following assignments:
$x = $y;
The rule for parsing constructions like $x = 100
used the following rule:
rule assignment { <variable> '=' <value> { . . . } }
On the right-hand side of the equals sign, we see a value
, which we can replace with a more general item, expression
. In the end, the expression may be any expression that a language understands, such as 10
, $x
, 10 + 3
, or $x + $y
, and more. Let us approach that point step by step. First, introduce the expression
rule. The problem is that we have to return the value of the expression to the action that makes an assignment.
To keep temporary values, Perl 6 grammars offer the attributes of the abstract syntax tree (AST). To save the value, use the $/.make
method. To get it, use the $/.made
or $/.ast
method (they are synonyms):
rule assignment...