Repository navigation
Tracking issue for a minimal subset of RFC 911, const fn #53555
Description
Activity
Centril commented on Aug 21, 2018
Some concerns noted over at #24111:
- design (const fn tracking issue (RFC 911) #24111 (comment))
- priority (const fn tracking issue (RFC 911) #24111 (comment))
- runtime-pointer-addresses (const fn tracking issue (RFC 911) #24111 (comment))
- everything-const (const fn tracking issue (RFC 911) #24111 (comment))
parallel-const-traitsresolved by const fn tracking issue (RFC 911) #24111 (comment)
runtime-pointer-addresses (#24111 (comment))
does not apply here, because we neither stabilize union field accesses which could be used to transmute between any pointer and an integer, nor do we stabilize casting *const T to usize.
priority (#24111 (comment))
The 2018 edition takes precedence over this feature. Since it has been minimized to a very small surface area which will be enforced by a feature whitelist, it seems plausible that we can get everyone on board to at least stabilize it shortly after the 2018 edition has been released.
design (#24111 (comment))
everything-const (#24111 (comment))
Since we are punting on (almost) all design issues by using a minimal scheme, the only design question left is whether we want to start attaching the const keyword to many functions.
Alternate designs:
- infer the constness (deemed not feasible right now and a semver footgun)
- inverting the system by marking functions as
notconst(massive breaking change) - using a
#[const]attribute
Wrt the "everything function is getting const attached to it" worry: The current design is entirely forward compatible with allowing const mod, const impl to allow marking entire code regions as const. Although that seems like it could benefit from the attribute, as you could write #![const] at the top of the crate root and have everything be const.
because we neither stabilize union field accesses which could be used to transmute between any pointer and an integer
We do not? I see you sneakily added that to the first post.^^
These are already stable for const. Why not allow them in const fn?
Why not allow the in const fn?
@oli-obk added that part, but I think about it like this: given union field accesses, you can perform &[mut] T -> usize and so you may violate our plans for CTFE correctness per your blog post. Now, we can say that the operation *(const/mut) T -> usize is UB in const fn, but I would like to wait with that because:
- It gives us more time to develop our story around the rules of
unsafewithinconst fn. - We need to make sure that our teaching material is up to the task so that users will not do
&T -> usizeand think that's OK.
All in all, I think that if we are more conservative here and punt on this, we can ship a more minimal const fn faster.
I see. I don't like these inconsistencies but oh well. Looks like qualify_consts will be cleaned up... another time.^^
In terms of teaching, again we have the same problem for const... I thought the sanity check might help (unlike a const fn, a const has a very simple "observable behavior" so we can actually test for these things statically) but it seems it does not complain about
union Trans { x: &'static i32, y: usize }
const BAR : usize = unsafe { Trans { x: &0 }.y };First, a nit:
const fns with type parameters with bounds (including where clauses) (lifetimes are OK) either on themselves or on the scope they are contained within (e.g. impls and such...)
Presumably something like T: Sized is ok -- or, more to the point, const fn foo<T>(t: T) -> T { t }...? So is it just that Sized trait is allowed?
But, more generally, I think that this proposal does a good job of outlining the surface area of the language to be stabilized, but I'd like to see a better outline of what the implications are regarding the "const system in general".
One key question here is the interaction of const fn and promotion, I think, since that is the main place where we can find ourselves in tricky questions (e.g., even something like const fn foo(a: u32, b: u32) -> { a + b } can be problematic if a call to it is promoted). Can someone (e.g., @oli-obk) write out the conditions in which calls to const fn can currently be promoted, if any? I don't recall. =)
I think by now I am mostly bought into the general framing from Ralf's blog post, but I'd like to also know if there are alternative approaches that we are ruling out by stabilizing const fn.
It seems like one of the key bits that I could imagine being controversial was the idea that a const fn could do things that we cannot statically guarantee are valid (e.g., in unsafe code) but that we could still promote calls to that const fn. If we wind up hitting errors at compilation time, that is then a violation of the const fn declaration analogous to hitting UB at runtime. As I said, I think I am mostly bought into this framing, but I would like to clarify if we are losing room to maneuever here in any way.
To expand a bit on something:
Presumably something like
T: Sizedis ok -- or, more to the point, const fn foo(t: T) -> T { t }...? So is it just thatSizedtrait is allowed?
I had initially considered suggesting that we allow auto traits as well, but I do not think this is a good idea. For one thing, unlike Sized ,auto traits may have custom impls, and that might constrain us in ways that we do not want. e.g., you can have
unsafe impl<T: Display> Send for Foo<T> { }Now, if you have a const fn foo<U: Send>(...) where U = Foo<T>, and we accept it, we will therefore be saying that T: Display is provable in a const context. But if we wanted to change how trait resolution works in a const context to consider only impls that are marked const or some such thing, that could be problematic.
Since Sized does not permit custom impls, we don't have this problem. Similarly, we could permit lifetime bounds (T: 'a).
68 remaining items
But we could still write a function that takes two fn ptrs and compares them? It couldn't be called (currently), but we should rule out the binop as well.
@RalfJung Attempting to define
const fn cmp(x: fn(), y: fn()) -> bool {
x == y
}with #![feature(min_const_fn)] gives "error: function pointers in const fn are unstable".
If we have that in a test, I am happy :)
However, I'd like to see a test ensuring that
const FOO: NonZeroU8 = unsafe { NonZeroU8::new_unchecked(0) };is caught by the sanity check. Currently nightly accepts that constant without complaining.
@RalfJung , it would appear that post-#54835 nightly still accepts this code without warning. Did you intend for this code not to work?
Nightly on the playground gives me
error[E0080]: this constant likely exhibits undefined behavior
--> src/main.rs:3:1
|
3 | const FOO: NonZeroU8 = unsafe { NonZeroU8::new_unchecked(0) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 0, but expected something greater or equal to 1
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior
And there's tests as well: https://github.com/rust-lang/rust/blob/master/src/test/ui/consts/const-eval/ub-nonnull.rs
This can been fixed with #54762
Any change we can get this into beta? I'd really love to do some 2018 edition proving and cleanup of some embedded crates but without min_const_fn available on beta, realistic checks are somewhat limited.
It will be in the next beta. Until then you could just use nightly without any feature gates
@oli-obk That's what I'm doing at the moment but I thought the point of the beta was to test Edition features and nightly might behave differently. I guess I'm looking forward then to trying the next beta and everything working fine just like on nighty. ;)
Documentation was done in rust-lang/reference#440. Since everything is done, I'll close this out.
@oli-obk > It will be in the next beta. Until then you could just use nightly without any feature gates
# rustc +beta --version
rustc 1.30.0-beta.15 (590121930 2018-10-12)
# cargo +beta build --release
...
error[E0658]: const fn is unstable (see issue #53555)
--> /Users/egger/OSS/bare-metal/src/lib.rs:22:5
|
22 | / pub const unsafe fn new(address: usize) -> Self {
23 | | Peripheral {
24 | | address: address as *mut T,
25 | | }
26 | | }
| |_____^
@therealprof "the next beta" means the 1.31 one, which will arrive some time around the time 1.30 stable ships(Oct 25).
This is a tracking issue for the RFC "Const functions and inherent methods" (rust-lang/rfcs#911).
This issue only tracks a minimal subset of the proposal in 911 that we are (hopefully) comfortable with stabilizing. To opt into the minimal subset, use
#![feature(min_const_fn)]. To use the more expansive feature set, you can continue using#![feature(const_fn)]and other associated feature gates.The minimal set will not include items from the following (incomplete) list:
const fns with type parameters with bounds (includingwhereclauses) in scope (including from the parent e.g.impl) other than: lifetimes,Sized, or (the "un"-bound)?SizedThis restriction exists because we are not sure about our story around what bounds mean in a
const fncontext. See RFC: const bounds and methods rfcs#2237,const fnand generics const-eval#1, and https://github.com/Centril/rfc-effects/ for a discussion on this.const fns with argument types or return types that containfnpointers,dyn Trait, orimpl Trait.This is checked recursively.
The restriction ensures that you may not reach a value of these types by any means.
This restriction exists for the same reasons as in 1.
const fns with any operations on floating-point numbers. This is achieved by making any floating-point operation not beconstinsideconst fn.This restriction exists because we are not sure about the story wrt. determinism, achieving the same results on compile-time / run-time (including other machines) and floating points.
using a
const fncall in a pattern, e.g.;anything else that is not currently in
const_fnor constantsusizecast (e.g.*const/mut T -> usize).if/if let/match.loop/while.letand destructuring.union field access.
code requiring
unsafeblocks.Exhaustive list of features supported in
const fnwith#![feature(min_const_fn)]:type parameters where the parameters have any of the following as part of their bounds (either on
whereor directly on the parameters):SizedThis means that
<T: 'a + ?Sized>and<T: 'b + Sized>+<T>are all permitted.Note that
?Sizedis the absence of a constraint when bounds have been fully elaboratedwhich includes adding implicit
Sizedbounds.This entails that permitting
Sized+ lifetimes allows the above examples.This rule also applies to type parameters of items that contain
const fns.arithmetic operators on integers
boolean operators (except for
&&and||which are banned since they are short-circuiting).any kind of aggregate constructor (array,
struct,enum, tuple, ...)calls to other
const fns (methods and functions)index operations on arrays and slices
field accesses on structs and tuples
reading from constants (but not statics, not even taking a reference to a static)
&and*(only dereferencing of references, not raw pointers)casts except for raw pointer to
usizecastsconst unsafe fnis allowed, but the body must consist of safe operations onlyThe bar for stabilizing
const fns in libcore/liballoc/libstd will be that they are writable in stable user code (unless they are wrappers for intrinsics, i.e.size_ofandalign_of). This means that they must work withmin_const_fn.Things to be done before stabilizing:
min_const_fnfeature gate. (Implement themin_const_fnfeature gate #53604)Unresolved questions:
None.
Vocabulary: