Autoclosures (via swift)

Can you do RAII with monads?

I'm a bit confused exactly what you are asking about. As I envision it, do-notation->closures and closures->Thorin->Mir are disjoint parts of the pipeline, and thus independent problems. Perhaps I wasn't so clear on that.

For example, here is some do-notation. ? is generalized to "bind-current-continuation", something only valid in do notation.

let x = do {
   loop { 
       let x = monadic_action()?;
        if !is_ok(x) {
            break Monad::return(None);
        }
       normal_action();
    }
};

This gets desugared to

let x = {
    let edge0 = |()| monadic_action().bind(edge1);
    let edge1 = |temp0| {
        let x = temp0;
        if !is_ok(x) { 
            drop(x); 
            Monad::return(None) 
        } else {
            normal_action();
            drop(x);
            Monad::return(()).bind(edge0)
        }
    }; 
    edge0(())
};

So yes we do no need to elaborate drops since scopes are mangled, but since neither normal_action nor drop is monadic, we don't need need to introduce more binds/closures. only ? and "native control flow" have a monadic meaning. Furthermore, had the user written closures to begin with, their would be no need to introduce drops at this stage, because the closures scopes are still there (they would instead be made explicit during the lowering to thorin).

From here on, we do a CPS transform more like what you wrote, but that's for Thorin. Furthermore, from here on "Monad" is just another trait and not special in anyway, closures are all optimized alike. I suppose do notation, and the extra Thorin stage, can be opted into orthogonally too, but of course without a lot of inlining the above closures have no hope of passing the borrow checker.


For anyone not familiar with thorins, monads, etc, the crucial aspect is ? and control flow is only "magical" inside the do { .. }. This allows users to opt into "things not acting like they normally do", so as to prevent the exception safety problems @nikomatsakis mentioned.

1 Like