Skip to content

Instantly share code, notes, and snippets.

@lucs
Created January 25, 2019 21:45
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 lucs/0f64cd5448ccfb8a94d18285bea34f7e to your computer and use it in GitHub Desktop.
Save lucs/0f64cd5448ccfb8a94d18285bea34f7e to your computer and use it in GitHub Desktop.
grammar Goo {
rule TOP { <Foo>+ }
rule Foo { 'foo' <Num> <Bar>+ }
rule Bar { 'bar' <Num>+ }
rule Num { \d+ }
}
class GooActions {
method Bar ($/) {
say "This Bar is contained in a Foo whose Num is ???";
}
}
Goo.new.parse(
'foo 111 bar 2 3 bar 4 foo 222 bar 5 6',
:actions(GooActions.new)
);
#`(
How can I get the Bar action method to see its Foo container
rule's Num, to have this printed?:
This Bar is contained in a Foo whose Num is 111
This Bar is contained in a Foo whose Num is 111
This Bar is contained in a Foo whose Num is 222
)
@moritz
Copy link

moritz commented Jan 25, 2019

You can use a dynamic variable to propagate the desired information down into the nested rules:

grammar Goo {
    rule TOP { <Foo>+ }
    rule Foo { :my $*FOO; 'foo' <Num> { $*FOO = $<Num> } <Bar>+ }
    rule Bar { 'bar' <Num>+ }
    rule Num { \d+ }
}

class GooActions {
    method Bar ($/) {
        say "This Bar is contained in a Foo whose Num is $*FOO";
    }
}

Goo.new.parse(
    'foo 111 bar 2 3 bar 4 foo 222 bar 5 6',
    :actions(GooActions.new)
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment