Repository navigation
Tracking issue for a minimal subset of RFC 911, const fn #53555
Description
Activity
- addedB-RFC-approvedBlocker: Approved by a merged RFC but not yet implemented.Blocker: Approved by a merged RFC but not yet implemented.T-langRelevant to the language teamRelevant to the language teamB-RFC-implementedBlocker: Approved by a merged RFC and implemented but not stabilized.Blocker: Approved by a merged RFC and implemented but not stabilized.C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCCategory: An issue tracking the progress of sth. like the implementation of an RFC
on Aug 21, 2018 Centril commented
on Aug 21, 2018 on Aug 21, 2018 · Hidden as resolvedAuthorshow commentMore actionsSome 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
unionfield accesses which could be used to transmute between any pointer and an integer, nor do we stabilize casting*const Ttousize.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
constkeyword 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
constattached to it" worry: The current design is entirely forward compatible with allowingconst mod,const implto 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.Reacted by Mazdak Farrokhzadbecause 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 inconst 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 -> usizeand so you may violate our plans for CTFE correctness per your blog post. Now, we can say that the operation*(const/mut) T -> usizeis UB inconst 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 fnfaster.- It gives us more time to develop our story around the rules of
I see. I don't like these inconsistencies but oh well. Looks like
qualify_constswill 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 aconst fn, aconsthas a very simple "observable behavior" so we can actually test for these things statically) but it seems it does not complain aboutunion 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: Sizedis ok -- or, more to the point,const fn foo<T>(t: T) -> T { t }...? So is it just thatSizedtrait 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 fnand promotion, I think, since that is the main place where we can find ourselves in tricky questions (e.g., even something likeconst 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 toconst fncan 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 fncould 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 theconst fndeclaration 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.Reacted by Mazdak FarrokhzadTo 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 haveunsafe impl<T: Display> Send for Foo<T> { }
Now, if you have a
const fn foo<U: Send>(...)whereU = Foo<T>, and we accept it, we will therefore be saying thatT: Displayis 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 markedconstor some such thing, that could be problematic.Since
Sizeddoes not permit custom impls, we don't have this problem. Similarly, we could permit lifetime bounds (T: 'a).Reacted by Mazdak Farrokhzad68 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 :)
- added a commit that references this issue
on Oct 7, 2018 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 behaviorAnd 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_fnavailable 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: