Permalink
Browse files

Merge pull request #2405 from MorayJ/grammar-arguments

Add examples of passing arguments to grammars
  • Loading branch information...
MorayJ committed Oct 22, 2018
2 parents 178d2e3 + aa36ae4 commit 51f2357b2d0f2aaf74f9ec02b956e2c0109e890f
Showing with 59 additions and 0 deletions.
  1. +59 −0 doc/Language/grammars.pod6
View
@@ -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

0 comments on commit 51f2357

Please sign in to comment.