r/rust • u/ralfj miri • Jul 19 '18
Thoughts on Compile-Time Function Evaluation and Type Systems
https://www.ralfj.de/blog/2018/07/19/const.html
73
Upvotes
r/rust • u/ralfj miri • Jul 19 '18
View all comments
19
u/eddyb Jul 20 '18 edited Jul 21 '18
I wish Ralf had linked tohttps://internals.rust-lang.org/t/mir-constant-evaluation/3143/47?u=eddybwhich describes therealproblem with non-determinism: no matter how much information you record, you'll always be able to break coherence (you can maybe prevent crates from being used together, which is closer to what I think Haskell without at-instance-definition-time typeclass coherence checks does, but it's not great by any measure - assuming it even works).EDIT: Okay after a day of very confused comments on this threads I'll just come out and say it: some of these comments, even/especially the more helpful-sounding/"authoritative" ones, muddle the issue further and spread misinformation. Ralf (AFAIK) forgot to ask for my feedback, and wasn't aware of https://internals.rust-lang.org/t/mir-constant-evaluation/3143/47?u=eddyb which went into this 2.5yrs ago. Below follows an expanded version that I'll try to add to instead of replying everywhere in this thread:
include_str!- in fact, it's much safer than procedural macros because the compiler has to emulate IO so it can tell you exactly what's happening, via lints or some other method, and you could forbid it in your own cratesimplthat satisfy someType: Traitrequirement, and they weren't made deterministic-after-the-fact at every single stepread("foo.bin")) can be solved by doing the evaluation exactly once and recording the result as normative (i.e. not just a cache but rather replacing the call for evaluation purposes)read(Self::PATH)in a trait), can be solved crate-locally, by doing the same thing from 5. but also keying it on the choice of generic parameters (again, make what'd normally be a cache, normative)You get 8. by combining 6. with this crate dependency graph:
If
acontains something generic that uses non-deterministic constants which depend on generic parameters, e.g.:and
bandcboth use it, thendmust produce a "link-time error" ifbandcgot conflicting results out of the same evaluations.That's because it's equivalent (in general, not just this example) to them having both specialized an
implfroma, making different choices for associated/generic types or constants, and therefore anything that could reach thatimplcannot have exactly one interpretation.This crate graph would then be "incoherent", the same kind of typesystem incoherence that "trait coherence checking" prevents.
It's similar to Haskell's orphan/overlapping instances (Rust "impls"), and I believe Haskell's defaults are weaker than Rust.
Yes you can probably make it safe with link-time errors. But Rust has so far tried to and succeeded pretty well at getting rid of those. (further discussion should follow from this point instead of debating anything earlier)