A bare scope block (`do:`) — worth adding?

Hi all,

In Mojo there’s no way to introduce a standalone scope - something like C’s bare { ... }. I keep wanting this for two common cases:

  1. Limiting the visibility of temporaries. In a long function I often compute a bunch of intermediate values (e.g. series coefficients) that are only needed for a few lines. A scope keeps them from leaking into the rest of the function and prevents accidental reuse.
  2. Controlling destruction timing. A scope forces vars to be destroyed at a well-defined point rather than at end of function.

The current workarounds all have problems:

  • if True: - works, but the compiler recognizes the constant condition and emits an “unreachable code” warning. The warning is correct behavior for real code, which makes it a poor idiom for intentional scoping.
  • try: ... finally: pass - compiles and creates a scope, but it’s semantically misleading: readers will reasonably assume error handling is involved. Using an error-handling construct purely for scoping obscures intent.
  • Nested def - creates a scope but adds call machinery and capture semantics; overkill.

So: would a bare block statement be a good addition? Something like:

var x = compute_header()  
do: 
    var tmp1 = expensive_intermediate()  
    var tmp2 = another_intermediate(tmp1)  
    x = combine(x, tmp2)  

# tmp1, tmp2 no longer visible here

Thanks!

Controlling destruction timing. A scope forces vars to be destroyed at a well-defined point rather than at end of function.

Mojo has ASAP destruction, so values are destroyed after their last use.

I don’t really have opinions on adding scopes like this so I’ll leave that be.

Ah, you’re right @owenhilyard - thanks for the correction. Old habits die hard; I was still thinking in terms of scope-bound RAII…

With ASAP destruction covering the timing argument, the remaining case is name hygiene alone—which still has precedent: Rust’s bare { } blocks and Swift’s do { } exist exactly for that, and readers recognize the idiom. Whether it earns new syntax is a judgement call, but it might be worth first asking whether the if True: unreachable warning could be suppressed (or a sanctioned scoping idiom documented), since that would capture most of the benefit without adding surface area.