ooc-lang / rock

:ocean: self-hosted ooc compiler that generates c99
http://ooc-lang.org/
MIT License
404 stars 40 forks source link

Double closures = wrong byref closure capture #882

Closed fasterthanlime closed 9 years ago

fasterthanlime commented 9 years ago

Sample:

Gift: cover {
  msg: String
  pad: Int
}

please: func (f: Func) { f() }

main: func {
  g := ("One", 0)

  please(||
    g = ("Two", 0)
    please(||
      g = ("Three", 0)
    )
  )

  g msg println()
}

Expected behaviour

Print "Three"

Current behavior

Print "Two" and writes to a random memory location.. which is really really bad. C compiler only emits a warning (Gift* vs Gift**)

Explanation

Each closure is a struct of thunk (address of the actual C function) and context (optional pointer to context struct).

When calling closures, context needs to be created (on the stack). If a variable is assigned to in a closure, it's captured "by reference", which means we pass the address to the closure instead of the value.

Currently, when creating context, variables that are captured byref are always passed with &someVariable, even if they're in a closure that has itself captured them byref. That means the inner closure gets the address of the pointer to the address of the actual variable. Hence the random memory write.

davidhesselbom commented 9 years ago

Nice, need to see if this fixes #864.

fasterthanlime commented 9 years ago

Hey @davidhesselbom! Hmm no, looks like a different issue but it shouldn't be a hard fix.

Sorry about being the worst maintainer ever in the history of open source projects btw, just doing some selfish bugfixes because our engine for Jaakan is written in ooc.

fasterthanlime commented 9 years ago

@davidhesselbom well that wasn't hard at all :) props to @zhaihj for finding the erroneous comparison.