actions Action Objects
Documentation for actions Action Objects, assembled from the following types:
A successful grammar match gives you a parse tree of Match objects, and the deeper that match tree gets, and the more branches in the grammar are, the harder it becomes to navigate the match tree to get the information you are actually interested in.
To avoid the need for diving deep into a match tree, you can supply an actions object. After each successful parse of a named rule in your grammar, it tries to call a method of the same name as the grammar rule, giving it the newly created Match object as a positional argument. If no such method exists, it is skipped.
Here is a contrived example of a grammar and actions in action:
my = TestGrammar.parse('40', actions => TestActions.new);say ; # OUTPUT: «｢40｣␤»say .made; # OUTPUT: «42␤»
An instance of
TestActions is passed as named argument
actions to the parse call, and when token
TOP has matched successfully, it automatically calls method
TOP, passing the match object as an argument.
To make it clear that the argument is a match object, the example uses
$/ as a parameter name to the action method, though that's just a handy convention, nothing intrinsic.
$match would have worked too. (Though using
$/ does give the advantage of providing
$<capture> as a shortcut for
A slightly more involved example follows:
my = KeyValuePairsActions.new;my = KeyValuePairs.parse(for @ ->
This produces the following output:
Key: second Value: bKey: hits Value: 42Key: perl Value: 6
pair, which parsed a pair separated by an equals sign, aliases the two calls to token
identifier to separate capture names to make them available more easily and intuitively. The corresponding action method constructs a Pair object, and uses the
.made property of the sub match objects. So it (like the action method
TOP too) exploits the fact that action methods for submatches are called before those of the calling/outer regex. So action methods are called in post-order.
The action method
TOP simply collects all the objects that were
.made by the multiple matches of the
pair rule, and returns them in a list.
Also note that
KeyValuePairsActions was passed as a type object to method
parse, which was possible because none of the action methods use attributes (which would only be available in an instance).
In other cases, action methods might want to keep state in attributes. Then of course you must pass an instance to method parse.
ws is special: when
:sigspace is enabled (and it is when we are using
rule), it replaces certain whitespace sequences. This is why the spaces around the equals sign in
rule pair work just fine and why the whitespace before closing
} does not gobble up the newlines looked for in