Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong behavior when evaluating closure #14

Open
Undefined01 opened this issue Dec 1, 2024 · 0 comments
Open

Wrong behavior when evaluating closure #14

Undefined01 opened this issue Dec 1, 2024 · 0 comments

Comments

@Undefined01
Copy link

Undefined01 commented Dec 1, 2024

The current implementation of closures is producing incorrect results when executing closure-related code. Here's an example:

(define add
  (lambda (a) 
    (lambda (b) 
      (+ a b))))

(println ((add 1) 2))
(println ((add 3) 4))

(define add5 (add 5))
(println (add5 1))
(println (add5 2))
(define add7 (add 7))
(println (add7 1))
(println (add7 2))
(println (add5 1))
(println (add5 2))
(println (add7 1))
(println (add7 2))

It prints 3 5 2 3 2 2 3 2 3. It seems that all the inner lambda calls are incorrectly reusing the argument 1 (the argument of the first call to add), which is not expected.

I am new to Truffle, but I find that this is possibly related to LambdaNode. The LambdaNode captures the virtualFrame on the first call to getMumblerFunction, and then the lambda function is returned with this virtual frame. However, the virtual frame may change during subsequent calls to getMumblerFunction, leading to incorrect behavior.

So I just remove the scopeSet flag in LambdaNode.java:

  @Specialization
  public Object getMumblerFunction(VirtualFrame virtualFrame) {
-   MumblerFunction function = this.getFunction();
+   MumblerFunction function = new MumblerFunction(this.getFunction().callTarget);
-   if (!isScopeSet()) {
-     CompilerDirectives.transferToInterpreterAndInvalidate();
-     function.setLexicalScope(virtualFrame.materialize());
-     this.scopeSet = true;
-   }
+   function.setLexicalScope(virtualFrame.materialize());
    return function;
  }

It gives the correct output 3 7 6 7 8 9 6 7 8 9. Is this the correct way to implement closure? Or is there a better way to implement closure for better performance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant