Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
[Yapsi] implemented sub declarations
  • Loading branch information
Carl Masak committed Mar 6, 2011
1 parent 28889de commit 6d95f69
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
32 changes: 25 additions & 7 deletions lib/Yapsi.pm
Expand Up @@ -48,7 +48,11 @@ grammar Yapsi::Perl6::Grammar {
token lvalue { <declaration> || <variable> || <increment> }
token value { <variable> || <literal> || <declaration> || <saycall>
|| <increment> }
rule declaration { $<declarator>=['my'|'our'] <variable> }
rule declaration {
<subdecl>
|| $<declarator>=['my'|'our'] [<subdecl> || <variable>]
}
rule subdecl { 'sub' $<subname>=[\w+] <block> }

token variable { '$' \w+ }
token literal { \d+ }
Expand Down Expand Up @@ -164,8 +168,10 @@ class Yapsi::Perl6::Actions {
my @vars;
my &find-declarations = sub ($m, $key) {
if $key eq "declaration" {
push @vars, { :name(~$m<variable>),
:our($m<declarator> eq 'our') };
my $name = $m<variable> ?? ~$m<variable>
!! '&' ~ $m<subdecl><subname>;
my $our = $m<declarator> eq 'our';
push @vars, { :$name, :$our };
}
};

Expand Down Expand Up @@ -254,11 +260,23 @@ class Yapsi::Perl6::Actions {
# .variable and .block methods.

method declaration($/) {
if %!vars{~$<variable>} eq 'declaration?' {
%!vars{~$<variable>} = @blockstack[*-1].name;
}
if $<variable> {
if %!vars{~$<variable>} eq 'declaration?' {
%!vars{~$<variable>} = @blockstack[*-1].name;
}

make $<variable>.ast;
make $<variable>.ast;
}
else { # subdecl
my $name = '&' ~ $<subdecl><subname>;
%!vars{$name} = @blockstack[*-1].name;
my $bind = FUTURE::Bind.new();
$bind.children.push(
FUTURE::Var.new(:$name),
$<subdecl><block>.ast
);
make $bind;
}
}

method variable($/) {
Expand Down
4 changes: 4 additions & 0 deletions t/compiler.t
Expand Up @@ -38,6 +38,9 @@ my @programs-that-compile =
'my $a; $a()',
'{ say 42 }()',
'my $a = 1; { say my $a = 2 }', # declare+use in block is fine
'sub foo {}',
'my sub foo {}',
'our sub foo {}',
;

sub escape($string) { $string.subst("\n", "\\n", :g) }
Expand Down Expand Up @@ -71,6 +74,7 @@ my @programs-that-don't-compile = # '
'unless {}' => 'could not parse',
'unless a {}' => 'could not parse',
'my $a = 1; { say $a; my $a = 2 }' => 'reference to outer variable',
'sub foo' => 'could not parse',
;

for @programs-that-don't-compile -> $pair { # '
Expand Down

0 comments on commit 6d95f69

Please sign in to comment.