Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Implement and test nqp::getlexdyn.
  • Loading branch information
pmurias committed Aug 16, 2015
1 parent 2635c3b commit 9470abb
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/vm/js/QAST/Compiler.nqp
Expand Up @@ -1079,6 +1079,8 @@ class QAST::OperationsJS {
} , :sideffects);
}

add_simple_op('getlexdyn', $T_OBJ, [$T_STR], sub ($name) {"{$*BLOCK.ctx}.lookup_dynamic_from_caller($name)"});

add_simple_op('captureposelems', $T_INT, [$T_OBJ]);
add_simple_op('captureposarg', $T_OBJ, [$T_OBJ, $T_INT]);
add_simple_op('invokewithcapture', $T_OBJ, [$T_OBJ, $T_OBJ], sub ($invokee, $capture) {
Expand Down
13 changes: 13 additions & 0 deletions src/vm/js/nqp-runtime/runtime.js
Expand Up @@ -144,6 +144,19 @@ Ctx.prototype.lookup_dynamic = function(name) {
nqp code usually fallbacks to looking up of global */
};

Ctx.prototype.lookup_dynamic_from_caller = function(name) {
var ctx = this.caller;
while (ctx) {
if (ctx.hasOwnProperty(name)) {
return ctx[name];
}
ctx = ctx.caller;
}
return null;
/* Looking up of a contextual is allowed to fail,
nqp code usually fallbacks to looking up of global */
};

Ctx.prototype.lookup = function(name, value) {
var ctx = this;
while (ctx) {
Expand Down
26 changes: 25 additions & 1 deletion t/nqp/21-contextual.t
Expand Up @@ -2,7 +2,7 @@

# Tests for contextual variables

plan(7);
plan(10);

sub foo() { $*VAR }

Expand All @@ -28,3 +28,27 @@ sub foo() { $*VAR }
}



sub simple_lookup() {
my $foo := nqp::getlexdyn('$*fo' ~ 'o');
ok( $foo eq 'bar', "getting dynamic variable using getlexdyn");
}

{
my $*foo := "bar";
simple_lookup();
}

sub ignore_local() {
my $*foo2;
$*foo2 := "baz";
my $foo := nqp::getlexdyn('$*foo2');
ok( $foo eq 'bar2', "getting dynamic variable using getlexdyn gets the variable from the caller");
ok( nqp::isnull(nqp::getlexdyn("$*no_such")), "nqp::getlexdyn return null for missing variables");
}

{
my $*foo2 := "bar2";
ignore_local();
}

0 comments on commit 9470abb

Please sign in to comment.