Skip to content

Thoughts on compile-time function evaluation and type systems (2018)

ralfj.de
41 pointslkurusa1 comment
On HN

Comments

Now, let us go one level up and look at the const type system. We have seen that comparing raw pointers can raise a CTFE error, so this is actually not a const-safe operation. Similar to casting pointers to integers, we have to make the const type system reject code that compares raw pointers. However, it seems like a shame to not even allow comparing two references for equality, after converting them to raw pointers! After all, references never dangle, so this is a perfectly const-safe operation.
Lucky enough, Rust already has an answer to the need to side-step the type system in controlled ways: unsafe blocks. Comparing raw pointers is not allowed by the const type system because it is not const-safe, but just like we allow run-time-unsafe operations to be performed in unsafe blocks, we can allow const-unsafe operations as well. So, we should be able to write the following:
    const fn ptr_eq<T>(x: &T, y: &T) -> bool {
        unsafe { x as *const _ == y as *const _ }
    }
If this is ever introduced, I hope that one would be able to mark whether an unsafe block is used because a const-safety restriction (like comparing two pointers for equality) or runtime-safety restriction (all other uses of regular, runtime unsafe)

Like this:

    const fn ptr_eq<T>(x: &T, y: &T) -> bool {
        unsafe(const) { x as *const _ == y as *const _ }
    }
edit: this same point was made in the Rust internals thread when the article was written, https://internals.rust-lang.org/t/thoughts-on-compile-time-f...
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.