Skip to content

Instantly share code, notes, and snippets.

@sirrobert
Created September 4, 2012 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirrobert/3626130 to your computer and use it in GitHub Desktop.
Save sirrobert/3626130 to your computer and use it in GitHub Desktop.
dynamic roles for grammars
use v6;
grammar G {
proto token TOP { * };
token TOP:sym<a> { 'a' };
};
class GA {
method TOP { say "TOP"; };
method TOP:sym<a> ($/) { say 'a' };
};
sub create ($name, &mtd) {
my $foo = eval "
anon role Add-to-grammar \{
token TOP:sym<$name> \{ '$name' \};
\};
";
my $bar = eval "
anon role add-to-actions \{
method TOP:sym<$name> (\$/) \{ &mtd($/) \};
\};
";
return $foo, $bar;
};
my ($foo, $bar) = create 'b', { say 'b' };
(G but $foo).parse: 'a', :actions(GA.new but $bar);
(G but $foo).parse: 'b', :actions(GA.new but $bar);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment