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