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

Emit outside of escape scope #513

Open
elliottslaughter opened this issue Oct 6, 2021 · 0 comments
Open

Emit outside of escape scope #513

elliottslaughter opened this issue Oct 6, 2021 · 0 comments

Comments

@elliottslaughter
Copy link
Member

This is one of the dark corners of the escape/emit support in Terra: they are lexically scoped, but strange things can happen because you can capture closures and then run them afterwards.

local c = terralib.includec("stdio.h")

local h = {}

function g()
  h.x()
end

terra main()
  var x = 1
  escape
    function h.x() emit quote c.printf("%d\n", x) end end
    emit quote
      x = x + 20
      escape
        g()
      end
    end
  end
  x = x + 300
  escape
    emit quote
      x = x + 4000
      escape
        g()
      end
    end
  end
end
-- g()
main:printpretty()
main()

This produces the output:

scape_containment5.t:9: terra main() : {}
cape_containment5.t:10:     var x : int32 = 1
cape_containment5.t:12:     printf("%d\n", x)
cape_containment5.t:14:     x = x + 20
cape_containment5.t:20:     x = x + 300
cape_containment5.t:12:     printf("%d\n", x)
cape_containment5.t:23:     x = x + 4000
scape_containment5.t:9: end
1
321

A couple of notes:

  • The ordering of the first printf and x = x + 20 prove that emit is lexically scoped. If it were dynamically scoped, the lines would be reversed (and the output would be 21 instead of 1).
  • The ordering of the second printf is kind of bizarre. It seems that the semantics of escape are to place the code at the bottom of whatever function contains the escape, rather than being inside the escape itself. Therefore, when we capture the h.x closure and run it later, we get the second printf after the statement x = x + 300, which occurs after the escape where h.x was defined in the first place.
  • The indirection through g is just to prove that we can do this with arbitrary data structures and arbitrary code indirection; i.e., this could be any number of levels deep in the stack.

I don't know if it's worth it, but should we try to tighten up this behavior at all, either disallowing the use of h.x once the associated escape has executed, or fixing it so the output appears in the right place?

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