feat: implement closure over "this" in methods and fix upvalue closing order

Add support for closing over "this" in function closures defined inside methods by naming the receiver local variable "this" in method compilers. Fix upvalue closing to copy the actual value instead of the stack top, and reorder return handling to close upvalues before storing the result. Add test cases for closure over "this", nested closures, and nested classes.
This commit is contained in:
Bob Nystrom
2013-12-21 23:55:08 +00:00
parent b1243ac532
commit 1a77a43fa0
6 changed files with 75 additions and 18 deletions
+1 -2
View File
@@ -14,6 +14,5 @@
}
}
// TODO: Closing over this.
// TODO: Close over fn/method parameter.
// TODO: Maximum number of closed-over variables (directly and/or indirect).
// TODO: Shadow variable used in closure.
+12
View File
@@ -0,0 +1,12 @@
class Foo {
getClosure {
return fn {
return this.toString
}
}
toString { return "Foo" }
}
var closure = (new Foo).getClosure
io.write(closure.call) // expect: Foo
+22
View File
@@ -0,0 +1,22 @@
class Outer {
method {
io.write(this.toString) // expect: Outer
fn {
io.write(this.toString) // expect: Outer
class Inner {
method {
io.write(this.toString) // expect: Inner
}
toString { return "Inner" }
}
(new Inner).method
}.call
}
toString { return "Outer" }
}
(new Outer).method
+16
View File
@@ -0,0 +1,16 @@
class Foo {
getClosure {
return fn {
return fn {
return fn {
return this.toString
}
}
}
}
toString { return "Foo" }
}
var closure = (new Foo).getClosure
io.write(closure.call.call.call) // expect: Foo