Function Purity

D has transitive inference of purity (either weak or strong) on templated functions. This is useful in, for instance, safe parallelization.

Does Rust have something similar?

Specifically, Rust functions that read/write shared/global variables inside unsafe blocks cannot be safely parallelized. Is it up to the developer of such functions to not do such mistakes?

As a comparison, in the D case, such functions will be inferred as (memory) @safe but non-pure. IMHO, that is a more precise way of categorizing the behaviour of such a function.

1 Like

See:
https://mail.mozilla.org/pipermail/rust-dev/2013-April/003926.html

Eventually Clippy could learn to detect and even enforce function purity. But it's much better to keep this annotation out of the core language.

2 Likes

Rust does not need purity here. We can parallelize all functions and the type system will keep the shared mutable state in check.

1 Like

I don't think you're following me here; unsafe blocks in Rust can "trick" the compiler into assuming that a function only access state via it's arguments when it, in fact, also read/write global/shared state. I guess @leonardo's comment references this problem.

Even without unsafe, a function could also access thread local variables or statics with interior mutability. This is perfectly memory safe for parallelization, but could still have logic errors around atomicity, and certainly isn't pure.

1 Like

So, how does Rayon solve this? I thought it guaranteed no data-races.

Rayon doesn't solve that, but it's not really a data race, at least as far as memory safety is concerned. You can still have logic errors around read-modify-write, or deadlock mutexes, etc. There's a large discussion in the readme, "Warning: Be wary of atomicity".

2 Likes