Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Add examples of passing arguments to grammars
Demonstrate passing arguments to grammars
  • Loading branch information
MorayJ committed Oct 22, 2018
1 parent 178d2e3 commit f273384
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions doc/Language/grammars.pod6
Expand Up @@ -419,6 +419,65 @@ attributes can be accessed in the match returned after parsing if made public:
# OUTPUT: [(Bool) True]
=end code
=head2 Passing arguments into grammars
To pass arguments into a grammar, you can use the named argument of C<:args> on any of the parsing methods of grammar. The arguments passed should be in a C<list>.
=begin code
grammar demonstrate-arguments {
rule TOP ($word) {
"I like" $word
}
}
# Notice the comma after "sweets" when passed to :args to coerce it to a list
say demonstrate-arguments.parse("I like sweets", :args(("sweets",))); # OUTPUT: «「I like sweets」␤»
=end code
Once the arguments are passed in, they can be used in a call to a named regex inside the grammar.
=begin code
grammar demonstrate-arguments-again
rule TOP ($word) {
<phrase-stem><added-word($word)>
}
rule phrase-stem {
"I like"
}
rule added-word($passed-word) {
$passed-word
}
}
say demonstrate-arguments-again.parse("I like vegetables", :args(("vegetables",)));
# OUTPUT: 「I like vegetables」␤»
# OUTPUT: «phrase-stem => 「I like 」␤»
# OUTPUT: «added-word => 「vegetables」␤»
=end code
Alternatively, you can initialise dynamic variables and use any arguments that way within the grammar.
=begin code
grammar demonstrate-arguments-dynamic {
rule TOP ($*word, $*extra) {
<phrase-stem><added-words>
}
rule phrase-stem {
"I like"
}
rule added-words {
$*word $*extra
}
}
say demonstrate-arguments-dynamic.parse("I like everything else", :args(("everything", "else")));
# OUTPUT: «「I like everything else」␤»
# OUTPUT: «phrase-stem => 「I like 」␤»
# OUTPUT: «added-words => 「everything else」␤»
=end code
X<|Actions>
=head1 Action objects
Expand Down

0 comments on commit f273384

Please sign in to comment.