Skip to content

Instantly share code, notes, and snippets.

@0racle
Created September 19, 2019 01:20
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 0racle/a9c80c5006a43ea6e57cc0e7e9eb4bf5 to your computer and use it in GitHub Desktop.
Save 0racle/a9c80c5006a43ea6e57cc0e7e9eb4bf5 to your computer and use it in GitHub Desktop.
Slang::ForElse
use Slang::ForElse;
my @values;
for @values -> $value {
say "Got $value";
}
else {
say "No values :("
}
role ForElse::Grammar {
rule statement_control:sym<for> {
<sym><.kok> {}
<.vetPerl5Syntax>
<xblock(2)> {}
[ 'else' <elseblock=pblock> ]?
}
rule vetPerl5Syntax {
[ <?before 'my'? '$'\w+\s+'(' >
<.typed_panic: 'X::Syntax::P5'> ]?
[ <?before '(' <.EXPR>? ';' <.EXPR>? ';' <.EXPR>? ')' >
<.obs('C-style "for (;;)" loop', '"loop (;;)"')> ]?
}
}
role ForElse::Actions {
use nqp;
use QAST:from<NQP>;
sub lookup(Mu \match, \key) {
nqp::atkey(
nqp::findmethod(match, 'hash')(match),
key
).?ast
}
method statement_control:sym<for> (Mu $match) {
my $forloop := callsame;
if lookup($match, 'elseblock') -> $elseblock {
$match.make:
QAST::Op.new: :op<unless>, $forloop,
QAST::Op.new: :op<call>, $elseblock
}
}
}
sub EXPORT {
$*LANG.define_slang:
"MAIN",
$*LANG.slangs<MAIN> but ForElse::Grammar,
$*LANG.slangs<MAIN-actions> but ForElse::Actions;
return hash();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment