]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_passes/src/check_const.rs
New upstream version 1.70.0+dfsg1
[rustc.git] / compiler / rustc_passes / src / check_const.rs
CommitLineData
60c5eb7d
XL
1//! This pass checks HIR bodies that may be evaluated at compile-time (e.g., `const`, `static`,
2//! `const fn`) for structured control flow (e.g. `if`, `while`), which is forbidden in a const
3//! context.
4//!
5//! By the time the MIR const-checker runs, these high-level constructs have been lowered to
6//! control-flow primitives (e.g., `Goto`, `SwitchInt`), making it tough to properly attribute
7//! errors. We still look for those primitives in the MIR const-checker to ensure nothing slips
8//! through, but errors for structured control flow in a `const` should be emitted here.
9
f035d41b 10use rustc_attr as attr;
dfeec247 11use rustc_hir as hir;
f035d41b 12use rustc_hir::def_id::LocalDefId;
5099ac24
FG
13use rustc_hir::intravisit::{self, Visitor};
14use rustc_middle::hir::nested_filter;
ba9703b0
XL
15use rustc_middle::ty::query::Providers;
16use rustc_middle::ty::TyCtxt;
ba9703b0 17use rustc_session::parse::feature_err;
dfeec247 18use rustc_span::{sym, Span, Symbol};
60c5eb7d 19
9ffffee4 20use crate::errors::{ExprNotAllowedInContext, SkippingConstChecks};
2b03887a 21
60c5eb7d
XL
22/// An expression that is not *always* legal in a const context.
23#[derive(Clone, Copy)]
24enum NonConstExpr {
25 Loop(hir::LoopSource),
26 Match(hir::MatchSource),
27}
28
29impl NonConstExpr {
dfeec247 30 fn name(self) -> String {
60c5eb7d 31 match self {
dfeec247
XL
32 Self::Loop(src) => format!("`{}`", src.name()),
33 Self::Match(src) => format!("`{}`", src.name()),
60c5eb7d
XL
34 }
35 }
36
37 fn required_feature_gates(self) -> Option<&'static [Symbol]> {
60c5eb7d 38 use hir::LoopSource::*;
dfeec247 39 use hir::MatchSource::*;
60c5eb7d
XL
40
41 let gates: &[_] = match self {
94222f64 42 Self::Match(AwaitDesugar) => {
f035d41b 43 return None;
ba9703b0 44 }
60c5eb7d 45
94222f64
XL
46 Self::Loop(ForLoop) | Self::Match(ForLoopDesugar) => &[sym::const_for],
47
48 Self::Match(TryDesugar) => &[sym::const_try],
fc512014 49
f035d41b 50 // All other expressions are allowed.
9ffffee4 51 Self::Loop(Loop | While) | Self::Match(Normal | FormatArgs) => &[],
60c5eb7d
XL
52 };
53
54 Some(gates)
55 }
56}
57
f035d41b 58fn check_mod_const_bodies(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
60c5eb7d 59 let mut vis = CheckConstVisitor::new(tcx);
064997fb 60 tcx.hir().visit_item_likes_in_module(module_def_id, &mut vis);
60c5eb7d
XL
61}
62
f035d41b 63pub(crate) fn provide(providers: &mut Providers) {
dfeec247 64 *providers = Providers { check_mod_const_bodies, ..*providers };
60c5eb7d
XL
65}
66
67#[derive(Copy, Clone)]
68struct CheckConstVisitor<'tcx> {
69 tcx: TyCtxt<'tcx>,
f9f354fc 70 const_kind: Option<hir::ConstContext>,
f035d41b 71 def_id: Option<LocalDefId>,
60c5eb7d
XL
72}
73
74impl<'tcx> CheckConstVisitor<'tcx> {
75 fn new(tcx: TyCtxt<'tcx>) -> Self {
f035d41b 76 CheckConstVisitor { tcx, const_kind: None, def_id: None }
60c5eb7d
XL
77 }
78
79 /// Emits an error when an unsupported expression is found in a const context.
80 fn const_check_violated(&self, expr: NonConstExpr, span: Span) {
f035d41b
XL
81 let Self { tcx, def_id, const_kind } = *self;
82
83 let features = tcx.features();
60c5eb7d 84 let required_gates = expr.required_feature_gates();
f035d41b
XL
85
86 let is_feature_allowed = |feature_gate| {
87 // All features require that the corresponding gate be enabled,
29967ef6 88 // even if the function has `#[rustc_allow_const_fn_unstable(the_gate)]`.
f035d41b
XL
89 if !tcx.features().enabled(feature_gate) {
90 return false;
91 }
92
93 // If `def_id` is `None`, we don't need to consider stability attributes.
94 let def_id = match def_id {
04454e1e 95 Some(x) => x,
f035d41b
XL
96 None => return true,
97 };
98
3c0e092e
XL
99 // If the function belongs to a trait, then it must enable the const_trait_impl
100 // feature to use that trait function (with a const default body).
064997fb 101 if tcx.trait_of_item(def_id.to_def_id()).is_some() {
3c0e092e
XL
102 return true;
103 }
104
f035d41b
XL
105 // If this crate is not using stability attributes, or this function is not claiming to be a
106 // stable `const fn`, that is all that is required.
353b0b11 107 if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
f035d41b
XL
108 return true;
109 }
110
111 // However, we cannot allow stable `const fn`s to use unstable features without an explicit
29967ef6 112 // opt-in via `rustc_allow_const_fn_unstable`.
04454e1e
FG
113 let attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(def_id));
114 attr::rustc_allow_const_fn_unstable(&tcx.sess, attrs).any(|name| name == feature_gate)
f035d41b
XL
115 };
116
60c5eb7d
XL
117 match required_gates {
118 // Don't emit an error if the user has enabled the requisite feature gates.
f035d41b 119 Some(gates) if gates.iter().copied().all(is_feature_allowed) => return,
60c5eb7d
XL
120
121 // `-Zunleash-the-miri-inside-of-you` only works for expressions that don't have a
122 // corresponding feature gate. This encourages nightly users to use feature gates when
123 // possible.
064997fb 124 None if tcx.sess.opts.unstable_opts.unleash_the_miri_inside_of_you => {
9ffffee4 125 tcx.sess.emit_warning(SkippingConstChecks { span });
60c5eb7d
XL
126 return;
127 }
128
129 _ => {}
130 }
131
f035d41b
XL
132 let const_kind =
133 const_kind.expect("`const_check_violated` may only be called inside a const context");
f9f354fc 134
60c5eb7d 135 let required_gates = required_gates.unwrap_or(&[]);
dfeec247
XL
136 let missing_gates: Vec<_> =
137 required_gates.iter().copied().filter(|&g| !features.enabled(g)).collect();
60c5eb7d
XL
138
139 match missing_gates.as_slice() {
5e7ed085 140 [] => {
2b03887a
FG
141 tcx.sess.emit_err(ExprNotAllowedInContext {
142 span,
143 expr: expr.name(),
144 context: const_kind.keyword_name(),
145 });
5e7ed085 146 }
60c5eb7d 147
3c0e092e 148 [missing_primary, ref missing_secondary @ ..] => {
2b03887a
FG
149 let msg =
150 format!("{} is not allowed in a `{}`", expr.name(), const_kind.keyword_name());
3c0e092e 151 let mut err = feature_err(&tcx.sess.parse_sess, *missing_primary, span, &msg);
60c5eb7d
XL
152
153 // If multiple feature gates would be required to enable this expression, include
154 // them as help messages. Don't emit a separate error for each missing feature gate.
155 //
156 // FIXME(ecstaticmorse): Maybe this could be incorporated into `feature_err`? This
157 // is a pretty narrow case, however.
fc512014 158 if tcx.sess.is_nightly_build() {
60c5eb7d
XL
159 for gate in missing_secondary {
160 let note = format!(
161 "add `#![feature({})]` to the crate attributes to enable",
162 gate,
163 );
164 err.help(&note);
165 }
166 }
167
168 err.emit();
169 }
170 }
171 }
172
173 /// Saves the parent `const_kind` before calling `f` and restores it afterwards.
f035d41b
XL
174 fn recurse_into(
175 &mut self,
176 kind: Option<hir::ConstContext>,
177 def_id: Option<LocalDefId>,
178 f: impl FnOnce(&mut Self),
179 ) {
180 let parent_def_id = self.def_id;
60c5eb7d 181 let parent_kind = self.const_kind;
f035d41b 182 self.def_id = def_id;
60c5eb7d
XL
183 self.const_kind = kind;
184 f(self);
f035d41b 185 self.def_id = parent_def_id;
60c5eb7d
XL
186 self.const_kind = parent_kind;
187 }
188}
189
190impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> {
5099ac24 191 type NestedFilter = nested_filter::OnlyBodies;
dfeec247 192
5099ac24
FG
193 fn nested_visit_map(&mut self) -> Self::Map {
194 self.tcx.hir()
60c5eb7d
XL
195 }
196
197 fn visit_anon_const(&mut self, anon: &'tcx hir::AnonConst) {
f9f354fc 198 let kind = Some(hir::ConstContext::Const);
f035d41b 199 self.recurse_into(kind, None, |this| intravisit::walk_anon_const(this, anon));
60c5eb7d
XL
200 }
201
dfeec247 202 fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
f9f354fc
XL
203 let owner = self.tcx.hir().body_owner_def_id(body.id());
204 let kind = self.tcx.hir().body_const_context(owner);
f035d41b 205 self.recurse_into(kind, Some(owner), |this| intravisit::walk_body(this, body));
60c5eb7d
XL
206 }
207
dfeec247 208 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
60c5eb7d
XL
209 match &e.kind {
210 // Skip the following checks if we are not currently in a const context.
211 _ if self.const_kind.is_none() => {}
212
5869c6ff 213 hir::ExprKind::Loop(_, _, source, _) => {
60c5eb7d
XL
214 self.const_check_violated(NonConstExpr::Loop(*source), e.span);
215 }
216
217 hir::ExprKind::Match(_, _, source) => {
218 let non_const_expr = match source {
219 // These are handled by `ExprKind::Loop` above.
94222f64 220 hir::MatchSource::ForLoopDesugar => None,
60c5eb7d
XL
221
222 _ => Some(NonConstExpr::Match(*source)),
223 };
224
225 if let Some(expr) = non_const_expr {
226 self.const_check_violated(expr, e.span);
227 }
228 }
229
dfeec247 230 _ => {}
60c5eb7d
XL
231 }
232
dfeec247 233 intravisit::walk_expr(self, e);
60c5eb7d
XL
234 }
235}