]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/check_const.rs
Rollup merge of #107532 - compiler-errors:erase-regions-in-uninhabited, r=jackh726
[rust.git] / compiler / rustc_passes / src / check_const.rs
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
10 use rustc_attr as attr;
11 use rustc_hir as hir;
12 use rustc_hir::def_id::LocalDefId;
13 use rustc_hir::intravisit::{self, Visitor};
14 use rustc_middle::hir::nested_filter;
15 use rustc_middle::ty::query::Providers;
16 use rustc_middle::ty::TyCtxt;
17 use rustc_session::parse::feature_err;
18 use rustc_span::{sym, Span, Symbol};
19
20 use crate::errors::{ExprNotAllowedInContext, SkippingConstChecks};
21
22 /// An expression that is not *always* legal in a const context.
23 #[derive(Clone, Copy)]
24 enum NonConstExpr {
25     Loop(hir::LoopSource),
26     Match(hir::MatchSource),
27 }
28
29 impl NonConstExpr {
30     fn name(self) -> String {
31         match self {
32             Self::Loop(src) => format!("`{}`", src.name()),
33             Self::Match(src) => format!("`{}`", src.name()),
34         }
35     }
36
37     fn required_feature_gates(self) -> Option<&'static [Symbol]> {
38         use hir::LoopSource::*;
39         use hir::MatchSource::*;
40
41         let gates: &[_] = match self {
42             Self::Match(AwaitDesugar) => {
43                 return None;
44             }
45
46             Self::Loop(ForLoop) | Self::Match(ForLoopDesugar) => &[sym::const_for],
47
48             Self::Match(TryDesugar) => &[sym::const_try],
49
50             // All other expressions are allowed.
51             Self::Loop(Loop | While) | Self::Match(Normal | FormatArgs) => &[],
52         };
53
54         Some(gates)
55     }
56 }
57
58 fn check_mod_const_bodies(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
59     let mut vis = CheckConstVisitor::new(tcx);
60     tcx.hir().visit_item_likes_in_module(module_def_id, &mut vis);
61 }
62
63 pub(crate) fn provide(providers: &mut Providers) {
64     *providers = Providers { check_mod_const_bodies, ..*providers };
65 }
66
67 #[derive(Copy, Clone)]
68 struct CheckConstVisitor<'tcx> {
69     tcx: TyCtxt<'tcx>,
70     const_kind: Option<hir::ConstContext>,
71     def_id: Option<LocalDefId>,
72 }
73
74 impl<'tcx> CheckConstVisitor<'tcx> {
75     fn new(tcx: TyCtxt<'tcx>) -> Self {
76         CheckConstVisitor { tcx, const_kind: None, def_id: None }
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) {
81         let Self { tcx, def_id, const_kind } = *self;
82
83         let features = tcx.features();
84         let required_gates = expr.required_feature_gates();
85
86         let is_feature_allowed = |feature_gate| {
87             // All features require that the corresponding gate be enabled,
88             // even if the function has `#[rustc_allow_const_fn_unstable(the_gate)]`.
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 {
95                 Some(x) => x,
96                 None => return true,
97             };
98
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).
101             if tcx.trait_of_item(def_id.to_def_id()).is_some() {
102                 return true;
103             }
104
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.
107             if !tcx.features().staged_api
108                 || tcx.has_attr(def_id.to_def_id(), sym::rustc_const_unstable)
109             {
110                 return true;
111             }
112
113             // However, we cannot allow stable `const fn`s to use unstable features without an explicit
114             // opt-in via `rustc_allow_const_fn_unstable`.
115             let attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(def_id));
116             attr::rustc_allow_const_fn_unstable(&tcx.sess, attrs).any(|name| name == feature_gate)
117         };
118
119         match required_gates {
120             // Don't emit an error if the user has enabled the requisite feature gates.
121             Some(gates) if gates.iter().copied().all(is_feature_allowed) => return,
122
123             // `-Zunleash-the-miri-inside-of-you` only works for expressions that don't have a
124             // corresponding feature gate. This encourages nightly users to use feature gates when
125             // possible.
126             None if tcx.sess.opts.unstable_opts.unleash_the_miri_inside_of_you => {
127                 tcx.sess.emit_warning(SkippingConstChecks { span });
128                 return;
129             }
130
131             _ => {}
132         }
133
134         let const_kind =
135             const_kind.expect("`const_check_violated` may only be called inside a const context");
136
137         let required_gates = required_gates.unwrap_or(&[]);
138         let missing_gates: Vec<_> =
139             required_gates.iter().copied().filter(|&g| !features.enabled(g)).collect();
140
141         match missing_gates.as_slice() {
142             [] => {
143                 tcx.sess.emit_err(ExprNotAllowedInContext {
144                     span,
145                     expr: expr.name(),
146                     context: const_kind.keyword_name(),
147                 });
148             }
149
150             [missing_primary, ref missing_secondary @ ..] => {
151                 let msg =
152                     format!("{} is not allowed in a `{}`", expr.name(), const_kind.keyword_name());
153                 let mut err = feature_err(&tcx.sess.parse_sess, *missing_primary, span, &msg);
154
155                 // If multiple feature gates would be required to enable this expression, include
156                 // them as help messages. Don't emit a separate error for each missing feature gate.
157                 //
158                 // FIXME(ecstaticmorse): Maybe this could be incorporated into `feature_err`? This
159                 // is a pretty narrow case, however.
160                 if tcx.sess.is_nightly_build() {
161                     for gate in missing_secondary {
162                         let note = format!(
163                             "add `#![feature({})]` to the crate attributes to enable",
164                             gate,
165                         );
166                         err.help(&note);
167                     }
168                 }
169
170                 err.emit();
171             }
172         }
173     }
174
175     /// Saves the parent `const_kind` before calling `f` and restores it afterwards.
176     fn recurse_into(
177         &mut self,
178         kind: Option<hir::ConstContext>,
179         def_id: Option<LocalDefId>,
180         f: impl FnOnce(&mut Self),
181     ) {
182         let parent_def_id = self.def_id;
183         let parent_kind = self.const_kind;
184         self.def_id = def_id;
185         self.const_kind = kind;
186         f(self);
187         self.def_id = parent_def_id;
188         self.const_kind = parent_kind;
189     }
190 }
191
192 impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> {
193     type NestedFilter = nested_filter::OnlyBodies;
194
195     fn nested_visit_map(&mut self) -> Self::Map {
196         self.tcx.hir()
197     }
198
199     fn visit_anon_const(&mut self, anon: &'tcx hir::AnonConst) {
200         let kind = Some(hir::ConstContext::Const);
201         self.recurse_into(kind, None, |this| intravisit::walk_anon_const(this, anon));
202     }
203
204     fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
205         let owner = self.tcx.hir().body_owner_def_id(body.id());
206         let kind = self.tcx.hir().body_const_context(owner);
207         self.recurse_into(kind, Some(owner), |this| intravisit::walk_body(this, body));
208     }
209
210     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
211         match &e.kind {
212             // Skip the following checks if we are not currently in a const context.
213             _ if self.const_kind.is_none() => {}
214
215             hir::ExprKind::Loop(_, _, source, _) => {
216                 self.const_check_violated(NonConstExpr::Loop(*source), e.span);
217             }
218
219             hir::ExprKind::Match(_, _, source) => {
220                 let non_const_expr = match source {
221                     // These are handled by `ExprKind::Loop` above.
222                     hir::MatchSource::ForLoopDesugar => None,
223
224                     _ => Some(NonConstExpr::Match(*source)),
225                 };
226
227                 if let Some(expr) = non_const_expr {
228                     self.const_check_violated(expr, e.span);
229                 }
230             }
231
232             _ => {}
233         }
234
235         intravisit::walk_expr(self, e);
236     }
237 }