by a1369209993 · 4y ago · 0 comments
Actually it's because approximately every damn compiler framework or textbook assumes that local variables go into and out of scope in a stack/LIFO order. (So if you declare `foo` and then `bar`, `foo` can't go out of scope until `bar` does, even if `foo` was a random temporary and `bar` is needed for the entire rest of the function.) And all the algorithms for working with local variables bake in this assumption, so you have to redesign everything to get back the sane semantics you get for free in assembly.
At least that's my experience with implementing proper local variable scoping; YMMV.
Fortunately, these days languages that are imperative at their core pick up "functional spillover" like that kotlin let seem to solve that nuisance-grade problem of a dangling `foo` temp just fine.
(the kotlin let is basically a list transform applied to a single instance, without all the pointless ceremony of wrapping as an Optional. I wanted to like scala more than kotlin, but I've come to respect kotlin a lot, for striking a balance between "language designer high" and the pragmatic mundane that must never be allowed full reign or else we get another groovy)
Actually, runtime does not use a stack in the relevant sense (on non-toy compilers anyway). It allocates a stack frame on the call stack on a per-function basis, with possibly some other bits to handle variable-length arrays, but the actual local variables are allocated inside the stack frame in mostly the same way they're allocated in registers (but with less spilling). So the same 'undeclare'/register-coloring semantics apply.