/Slang basics.rakumod Secret
Created
February 4, 2022 05:48
Star
You must be signed in to star a gist
Simple Custom Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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