Skip to content

Instantly share code, notes, and snippets.

@alabamenhu
Created February 4, 2022 05:48
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save alabamenhu/22ec54745fd63e8565e3740216210ce1 to your computer and use it in GitHub Desktop.
Simple Custom Function
sub EXPORT(|) {
role FooGrammarMixin {
rule statement_control:sym<foo> {
<quote-start> # you need to set this to something that will start your custom language
<foo-language> # this will be a token you define elsewhere (or in here, but messier)
<quote-end> # this will finish off your custom language, and pass things on
}
token <quote-start> { '[start]' }
token <quote-end> { '[end]' }
token <foo-language> {
# define your language in regex here
}
}
role FooActionsMixin {
method statement_control:sym<foo> ($/) {
$<foo-language>; # <-- that's the parse tree for your custom language,
# easier to use when RakuAST is available
# The code below creates a QAST node that calls a sub defined later
# With RakuAST, you'd develop the AST via the <foo-language> grammar/actions
# and then just say 'make $/.hash<foo-language>.made' instead of everything
# else below here.
my $block := QAST::Op.new(
:op<call>,
:name<&Slang::Foo::make-function>,
QAST::SVal.new(:value($<foo-language>.Str))
);
$/.'make'($block);
}
}
sub Slang::Foo::make-function(Str $s) {
my &func;
# parse $s here to create a function of some sort.
return &func
}
# This mixes in our roles into the main language,
# making the new tokens and actions available to the parse
$*LANG.define_slang:
'MAIN',
$*LANG.slang_grammar('MAIN').^mixin(FooGrammarMixin),
$*LANG.slang_actions('MAIN').^mixin(FooActionsMixin);
Map.new: '&Slang::Foo::make-function', &Slang::Foo::make-function
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment