Skip to content

Commit

Permalink
Rollup merge of rust-lang#67216 - ecstatic-morse:const-loop, r=oli-obk
Browse files Browse the repository at this point in the history
Enable `loop` and `while` in constants behind a feature flag

This PR is an initial implementation of rust-lang#52000. It adds a `const_loop` feature gate, which allows `while` and `loop` expressions through both HIR and MIR const-checkers if enabled. `for` expressions remain forbidden by the HIR const-checker, since they desugar to a call to `IntoIterator::into_iter`, which will be rejected anyways.

`while` loops also require [`#![feature(const_if_match)]`](rust-lang#66507), since they have a conditional built into them. The diagnostics from the HIR const checker will suggest this to the user.

r? @oli-obk
cc @rust-lang/wg-const-eval
  • Loading branch information
Centril authored Dec 14, 2019
2 parents d720440 + faa52d1 commit 0e2fb73
Show file tree
Hide file tree
Showing 26 changed files with 559 additions and 127 deletions.
2 changes: 1 addition & 1 deletion src/librustc_error_codes/error_codes/E0744.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Control-flow expressions are not allowed inside a const context.
At the moment, `if` and `match`, as well as the looping constructs `for`,
`while`, and `loop`, are forbidden inside a `const`, `static`, or `const fn`.

```compile_fail,E0744
```compile_fail,E0658
const _: i32 = {
let mut x = 0;
loop {
Expand Down
14 changes: 14 additions & 0 deletions src/librustc_feature/active.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,17 @@ macro_rules! declare_features {
pub fn walk_feature_fields(&self, mut f: impl FnMut(&str, bool)) {
$(f(stringify!($feature), self.$feature);)+
}

/// Is the given feature enabled?
///
/// Panics if the symbol doesn't correspond to a declared feature.
pub fn enabled(&self, feature: Symbol) -> bool {
match feature {
$( sym::$feature => self.$feature, )*

_ => panic!("`{}` was not listed in `declare_features`", feature),
}
}
}
};
}
Expand Down Expand Up @@ -526,6 +537,9 @@ declare_features! (
/// Allows using `&mut` in constant functions.
(active, const_mut_refs, "1.41.0", Some(57349), None),

/// Allows the use of `loop` and `while` in constants.
(active, const_loop, "1.41.0", Some(52000), None),

// -------------------------------------------------------------------------
// feature-group-end: actual feature gates
// -------------------------------------------------------------------------
Expand Down
4 changes: 4 additions & 0 deletions src/librustc_mir/transform/check_consts/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ impl NonConstOp for LiveDrop {
#[derive(Debug)]
pub struct Loop;
impl NonConstOp for Loop {
fn feature_gate(tcx: TyCtxt<'_>) -> Option<bool> {
Some(tcx.features().const_loop)
}

fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
// This should be caught by the HIR const-checker.
item.tcx.sess.delay_span_bug(
Expand Down
6 changes: 5 additions & 1 deletion src/librustc_mir/transform/qualify_min_const_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,8 +390,12 @@ fn check_terminator(
cleanup: _,
} => check_operand(tcx, cond, span, def_id, body),

| TerminatorKind::FalseUnwind { .. }
if feature_allowed(tcx, def_id, sym::const_loop)
=> Ok(()),

TerminatorKind::FalseUnwind { .. } => {
Err((span, "loops are not allowed in const fn".into()))
},
}
}
}
87 changes: 68 additions & 19 deletions src/librustc_passes/check_const.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ use rustc::hir::map::Map;
use rustc::hir;
use rustc::ty::TyCtxt;
use rustc::ty::query::Providers;
use rustc_feature::Features;
use rustc::session::config::nightly_options;
use syntax::ast::Mutability;
use syntax::feature_gate::feature_err;
use syntax::span_err;
use syntax_pos::{sym, Span};
use syntax_pos::{sym, Span, Symbol};
use rustc_error_codes::*;

use std::fmt;
Expand All @@ -37,18 +37,31 @@ impl NonConstExpr {
}
}

/// Returns `true` if all feature gates required to enable this expression are turned on, or
/// `None` if there is no feature gate corresponding to this expression.
fn is_feature_gate_enabled(self, features: &Features) -> Option<bool> {
fn required_feature_gates(self) -> Option<&'static [Symbol]> {
use hir::MatchSource::*;
match self {
use hir::LoopSource::*;

let gates: &[_] = match self {
| Self::Match(Normal)
| Self::Match(IfDesugar { .. })
| Self::Match(IfLetDesugar { .. })
=> Some(features.const_if_match),
=> &[sym::const_if_match],

_ => None,
}
| Self::Loop(Loop)
=> &[sym::const_loop],

| Self::Loop(While)
| Self::Loop(WhileLet)
| Self::Match(WhileDesugar)
| Self::Match(WhileLetDesugar)
=> &[sym::const_loop, sym::const_if_match],

// A `for` loop's desugaring contains a call to `IntoIterator::into_iter`,
// so they are not yet allowed with `#![feature(const_loop)]`.
_ => return None,
};

Some(gates)
}
}

Expand Down Expand Up @@ -120,11 +133,15 @@ impl<'tcx> CheckConstVisitor<'tcx> {

/// Emits an error when an unsupported expression is found in a const context.
fn const_check_violated(&self, expr: NonConstExpr, span: Span) {
match expr.is_feature_gate_enabled(self.tcx.features()) {
let features = self.tcx.features();
let required_gates = expr.required_feature_gates();
match required_gates {
// Don't emit an error if the user has enabled the requisite feature gates.
Some(true) => return,
Some(gates) if gates.iter().all(|&g| features.enabled(g)) => return,

// Users of `-Zunleash-the-miri-inside-of-you` must use feature gates when possible.
// `-Zunleash-the-miri-inside-of-you` only works for expressions that don't have a
// corresponding feature gate. This encourages nightly users to use feature gates when
// possible.
None if self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you => {
self.tcx.sess.span_warn(span, "skipping const checks");
return;
Expand All @@ -135,15 +152,47 @@ impl<'tcx> CheckConstVisitor<'tcx> {

let const_kind = self.const_kind
.expect("`const_check_violated` may only be called inside a const context");

let msg = format!("`{}` is not allowed in a `{}`", expr.name(), const_kind);
match expr {
| NonConstExpr::Match(hir::MatchSource::Normal)
| NonConstExpr::Match(hir::MatchSource::IfDesugar { .. })
| NonConstExpr::Match(hir::MatchSource::IfLetDesugar { .. })
=> feature_err(&self.tcx.sess.parse_sess, sym::const_if_match, span, &msg).emit(),

_ => span_err!(self.tcx.sess, span, E0744, "{}", msg),
let required_gates = required_gates.unwrap_or(&[]);
let missing_gates: Vec<_> = required_gates
.iter()
.copied()
.filter(|&g| !features.enabled(g))
.collect();

match missing_gates.as_slice() {
&[] => span_err!(self.tcx.sess, span, E0744, "{}", msg),

// If the user enabled `#![feature(const_loop)]` but not `#![feature(const_if_match)]`,
// explain why their `while` loop is being rejected.
&[gate @ sym::const_if_match] if required_gates.contains(&sym::const_loop) => {
feature_err(&self.tcx.sess.parse_sess, gate, span, &msg)
.note("`#![feature(const_loop)]` alone is not sufficient, \
since this loop expression contains an implicit conditional")
.emit();
}

&[missing_primary, ref missing_secondary @ ..] => {
let mut err = feature_err(&self.tcx.sess.parse_sess, missing_primary, span, &msg);

// If multiple feature gates would be required to enable this expression, include
// them as help messages. Don't emit a separate error for each missing feature gate.
//
// FIXME(ecstaticmorse): Maybe this could be incorporated into `feature_err`? This
// is a pretty narrow case, however.
if nightly_options::is_nightly_build() {
for gate in missing_secondary {
let note = format!(
"add `#![feature({})]` to the crate attributes to enable",
gate,
);
err.help(&note);
}
}

err.emit();
}
}
}

Expand Down
1 change: 1 addition & 0 deletions src/librustc_passes/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#![feature(in_band_lifetimes)]
#![feature(nll)]
#![feature(slice_patterns)]

#![recursion_limit="256"]

Expand Down
1 change: 1 addition & 0 deletions src/libsyntax_pos/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ symbols! {
const_indexing,
const_in_array_repeat_expressions,
const_let,
const_loop,
const_mut_refs,
const_panic,
const_raw_ptr_deref,
Expand Down
7 changes: 5 additions & 2 deletions src/test/ui/closures/issue-52437.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ error: invalid label name `'static`
LL | [(); &(&'static: loop { |x| {}; }) as *const _ as usize]
| ^^^^^^^

error[E0744]: `loop` is not allowed in a `const`
error[E0658]: `loop` is not allowed in a `const`
--> $DIR/issue-52437.rs:2:13
|
LL | [(); &(&'static: loop { |x| {}; }) as *const _ as usize]
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: for more information, see https://github.com/rust-lang/rust/issues/52000
= help: add `#![feature(const_loop)]` to the crate attributes to enable

error[E0282]: type annotations needed
--> $DIR/issue-52437.rs:2:30
Expand All @@ -18,5 +21,5 @@ LL | [(); &(&'static: loop { |x| {}; }) as *const _ as usize]

error: aborting due to 3 previous errors

Some errors have detailed explanations: E0282, E0744.
Some errors have detailed explanations: E0282, E0658.
For more information about an error, try `rustc --explain E0282`.
8 changes: 6 additions & 2 deletions src/test/ui/consts/const-eval/infinite_loop.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0744]: `while` is not allowed in a `const`
error[E0658]: `while` is not allowed in a `const`
--> $DIR/infinite_loop.rs:7:9
|
LL | / while n != 0 {
Expand All @@ -8,6 +8,10 @@ LL | |
LL | |
LL | | }
| |_________^
|
= note: for more information, see https://github.com/rust-lang/rust/issues/52000
= help: add `#![feature(const_loop)]` to the crate attributes to enable
= help: add `#![feature(const_if_match)]` to the crate attributes to enable

error[E0658]: `if` is not allowed in a `const`
--> $DIR/infinite_loop.rs:9:17
Expand Down Expand Up @@ -39,5 +43,5 @@ LL | n = if n % 2 == 0 { n/2 } else { 3*n + 1 };

error: aborting due to 3 previous errors

Some errors have detailed explanations: E0080, E0658, E0744.
Some errors have detailed explanations: E0080, E0658.
For more information about an error, try `rustc --explain E0080`.
7 changes: 5 additions & 2 deletions src/test/ui/consts/const-eval/issue-52442.stderr
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
error[E0744]: `loop` is not allowed in a `const`
error[E0658]: `loop` is not allowed in a `const`
--> $DIR/issue-52442.rs:2:14
|
LL | [(); { &loop { break } as *const _ as usize } ];
| ^^^^^^^^^^^^^^
|
= note: for more information, see https://github.com/rust-lang/rust/issues/52000
= help: add `#![feature(const_loop)]` to the crate attributes to enable

error[E0658]: casting pointers to integers in constants is unstable
--> $DIR/issue-52442.rs:2:13
Expand All @@ -21,5 +24,5 @@ LL | [(); { &loop { break } as *const _ as usize } ];

error: aborting due to 3 previous errors

Some errors have detailed explanations: E0080, E0658, E0744.
Some errors have detailed explanations: E0080, E0658.
For more information about an error, try `rustc --explain E0080`.
8 changes: 6 additions & 2 deletions src/test/ui/consts/const-eval/issue-52475.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0744]: `while` is not allowed in a `const`
error[E0658]: `while` is not allowed in a `const`
--> $DIR/issue-52475.rs:6:9
|
LL | / while n < 5 {
Expand All @@ -7,6 +7,10 @@ LL | | n = (n + 1) % 5;
LL | | x = &0; // Materialize a new AllocId
LL | | }
| |_________^
|
= note: for more information, see https://github.com/rust-lang/rust/issues/52000
= help: add `#![feature(const_loop)]` to the crate attributes to enable
= help: add `#![feature(const_if_match)]` to the crate attributes to enable

warning: Constant evaluating a complex constant, this might take some time
--> $DIR/issue-52475.rs:2:18
Expand All @@ -29,5 +33,5 @@ LL | n = (n + 1) % 5;

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0080, E0744.
Some errors have detailed explanations: E0080, E0658.
For more information about an error, try `rustc --explain E0080`.
12 changes: 9 additions & 3 deletions src/test/ui/consts/const-eval/issue-62272.stderr
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
error[E0744]: `loop` is not allowed in a `const`
error[E0658]: `loop` is not allowed in a `const`
--> $DIR/issue-62272.rs:7:17
|
LL | const FOO: () = loop { break; };
| ^^^^^^^^^^^^^^^
|
= note: for more information, see https://github.com/rust-lang/rust/issues/52000
= help: add `#![feature(const_loop)]` to the crate attributes to enable

error[E0744]: `loop` is not allowed in a `const`
error[E0658]: `loop` is not allowed in a `const`
--> $DIR/issue-62272.rs:10:20
|
LL | [FOO; { let x; loop { x = 5; break; } x }];
| ^^^^^^^^^^^^^^^^^^^^^^
|
= note: for more information, see https://github.com/rust-lang/rust/issues/52000
= help: add `#![feature(const_loop)]` to the crate attributes to enable

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0744`.
For more information about this error, try `rustc --explain E0658`.
8 changes: 6 additions & 2 deletions src/test/ui/consts/const-labeled-break.stderr
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
error[E0744]: `while` is not allowed in a `const`
error[E0658]: `while` is not allowed in a `const`
--> $DIR/const-labeled-break.rs:10:19
|
LL | const CRASH: () = 'a: while break 'a {};
| ^^^^^^^^^^^^^^^^^^^^^
|
= note: for more information, see https://github.com/rust-lang/rust/issues/52000
= help: add `#![feature(const_loop)]` to the crate attributes to enable
= help: add `#![feature(const_if_match)]` to the crate attributes to enable

error: aborting due to previous error

For more information about this error, try `rustc --explain E0744`.
For more information about this error, try `rustc --explain E0658`.
Loading

0 comments on commit 0e2fb73

Please sign in to comment.