abra-lang icon indicating copy to clipboard operation
abra-lang copied to clipboard

[C-Compiler] Global overshadows "known"-ness of local variables

Open kengorab opened this issue 3 years ago • 0 comments

When compiling to C, the following code doesn't work as expected:

val count = 16
func newCountdown(n: Int): () => Unit {
  var count = n
  func rec() {
    print(count, "")
    if count > 0 {
      count -= 1
      rec()
    } else {
      println()
    }
  }
  rec
}
val countdown = newCountdown(5)
countdown()

The following outputs

16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

when the expected output is

5 4 3 2 1 0

This is because the global count variable is treated as a "known variable" when determining the closed-over variables in the rec() function. If the var count = n line wasn't there, this behavior would be correct since the count variable is a global and we don't need to create an env struct as we do for locals. However, when determining these "known variables", we should walk backwards through the scopes and only treat variables as "known" if they are globals which are not present in any of the intermediate scopes.

kengorab avatar Mar 13 '22 22:03 kengorab