]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/check_const.rs
Auto merge of #96348 - overdrivenpotato:inline-location, r=the8472
[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;
17 use rustc_middle::ty::query::Providers;
18 use rustc_middle::ty::TyCtxt;
19 use rustc_session::parse::feature_err;
20 use rustc_span::{sym, Span, Symbol};
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) => &[],
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.as_deep_visitor());
61     tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckConstTraitVisitor::new(tcx));
62 }
63
64 pub(crate) fn provide(providers: &mut Providers) {
65     *providers = Providers { check_mod_const_bodies, ..*providers };
66 }
67
68 struct CheckConstTraitVisitor<'tcx> {
69     tcx: TyCtxt<'tcx>,
70 }
71
72 impl<'tcx> CheckConstTraitVisitor<'tcx> {
73     fn new(tcx: TyCtxt<'tcx>) -> Self {
74         CheckConstTraitVisitor { tcx }
75     }
76 }
77
78 impl<'tcx> hir::itemlikevisit::ItemLikeVisitor<'tcx> for CheckConstTraitVisitor<'tcx> {
79     /// check for const trait impls, and errors if the impl uses provided/default functions
80     /// of the trait being implemented; as those provided functions can be non-const.
81     fn visit_item<'hir>(&mut self, item: &'hir hir::Item<'hir>) {
82         let _: Option<_> = try {
83             if let hir::ItemKind::Impl(ref imp) = item.kind && let hir::Constness::Const = imp.constness {
84                     let trait_def_id = imp.of_trait.as_ref()?.trait_def_id()?;
85                     let ancestors = self
86                         .tcx
87                         .trait_def(trait_def_id)
88                         .ancestors(self.tcx, item.def_id.to_def_id())
89                         .ok()?;
90                     let mut to_implement = Vec::new();
91
92                     for trait_item in self.tcx.associated_items(trait_def_id).in_definition_order()
93                     {
94                         if let ty::AssocItem {
95                             kind: ty::AssocKind::Fn,
96                             defaultness,
97                             def_id: trait_item_id,
98                             ..
99                         } = *trait_item
100                         {
101                             // we can ignore functions that do not have default bodies:
102                             // if those are unimplemented it will be caught by typeck.
103                             if !defaultness.has_value()
104                                 || self
105                                     .tcx
106                                     .has_attr(trait_item_id, sym::default_method_body_is_const)
107                             {
108                                 continue;
109                             }
110
111                             let is_implemented = ancestors
112                                 .leaf_def(self.tcx, trait_item_id)
113                                 .map(|node_item| !node_item.defining_node.is_from_trait())
114                                 .unwrap_or(false);
115
116                             if !is_implemented {
117                                 to_implement.push(self.tcx.item_name(trait_item_id).to_string());
118                             }
119                         }
120                     }
121
122                     // all nonconst trait functions (not marked with #[default_method_body_is_const])
123                     // must be implemented
124                     if !to_implement.is_empty() {
125                         self.tcx
126                             .sess
127                             .struct_span_err(
128                                 item.span,
129                                 "const trait implementations may not use non-const default functions",
130                             )
131                             .note(&format!("`{}` not implemented", to_implement.join("`, `")))
132                             .emit();
133                     }
134             }
135         };
136     }
137
138     fn visit_trait_item<'hir>(&mut self, _: &'hir hir::TraitItem<'hir>) {}
139
140     fn visit_impl_item<'hir>(&mut self, _: &'hir hir::ImplItem<'hir>) {}
141
142     fn visit_foreign_item<'hir>(&mut self, _: &'hir hir::ForeignItem<'hir>) {}
143 }
144
145 #[derive(Copy, Clone)]
146 struct CheckConstVisitor<'tcx> {
147     tcx: TyCtxt<'tcx>,
148     const_kind: Option<hir::ConstContext>,
149     def_id: Option<LocalDefId>,
150 }
151
152 impl<'tcx> CheckConstVisitor<'tcx> {
153     fn new(tcx: TyCtxt<'tcx>) -> Self {
154         CheckConstVisitor { tcx, const_kind: None, def_id: None }
155     }
156
157     /// Emits an error when an unsupported expression is found in a const context.
158     fn const_check_violated(&self, expr: NonConstExpr, span: Span) {
159         let Self { tcx, def_id, const_kind } = *self;
160
161         let features = tcx.features();
162         let required_gates = expr.required_feature_gates();
163
164         let is_feature_allowed = |feature_gate| {
165             // All features require that the corresponding gate be enabled,
166             // even if the function has `#[rustc_allow_const_fn_unstable(the_gate)]`.
167             if !tcx.features().enabled(feature_gate) {
168                 return false;
169             }
170
171             // If `def_id` is `None`, we don't need to consider stability attributes.
172             let def_id = match def_id {
173                 Some(x) => x.to_def_id(),
174                 None => return true,
175             };
176
177             // If the function belongs to a trait, then it must enable the const_trait_impl
178             // feature to use that trait function (with a const default body).
179             if tcx.trait_of_item(def_id).is_some() {
180                 return true;
181             }
182
183             // If this crate is not using stability attributes, or this function is not claiming to be a
184             // stable `const fn`, that is all that is required.
185             if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
186                 return true;
187             }
188
189             // However, we cannot allow stable `const fn`s to use unstable features without an explicit
190             // opt-in via `rustc_allow_const_fn_unstable`.
191             attr::rustc_allow_const_fn_unstable(&tcx.sess, &tcx.get_attrs(def_id))
192                 .any(|name| name == feature_gate)
193         };
194
195         match required_gates {
196             // Don't emit an error if the user has enabled the requisite feature gates.
197             Some(gates) if gates.iter().copied().all(is_feature_allowed) => return,
198
199             // `-Zunleash-the-miri-inside-of-you` only works for expressions that don't have a
200             // corresponding feature gate. This encourages nightly users to use feature gates when
201             // possible.
202             None if tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you => {
203                 tcx.sess.span_warn(span, "skipping const checks");
204                 return;
205             }
206
207             _ => {}
208         }
209
210         let const_kind =
211             const_kind.expect("`const_check_violated` may only be called inside a const context");
212
213         let msg = format!("{} is not allowed in a `{}`", expr.name(), const_kind.keyword_name());
214
215         let required_gates = required_gates.unwrap_or(&[]);
216         let missing_gates: Vec<_> =
217             required_gates.iter().copied().filter(|&g| !features.enabled(g)).collect();
218
219         match missing_gates.as_slice() {
220             [] => {
221                 struct_span_err!(tcx.sess, span, E0744, "{}", msg).emit();
222             }
223
224             [missing_primary, ref missing_secondary @ ..] => {
225                 let mut err = feature_err(&tcx.sess.parse_sess, *missing_primary, span, &msg);
226
227                 // If multiple feature gates would be required to enable this expression, include
228                 // them as help messages. Don't emit a separate error for each missing feature gate.
229                 //
230                 // FIXME(ecstaticmorse): Maybe this could be incorporated into `feature_err`? This
231                 // is a pretty narrow case, however.
232                 if tcx.sess.is_nightly_build() {
233                     for gate in missing_secondary {
234                         let note = format!(
235                             "add `#![feature({})]` to the crate attributes to enable",
236                             gate,
237                         );
238                         err.help(&note);
239                     }
240                 }
241
242                 err.emit();
243             }
244         }
245     }
246
247     /// Saves the parent `const_kind` before calling `f` and restores it afterwards.
248     fn recurse_into(
249         &mut self,
250         kind: Option<hir::ConstContext>,
251         def_id: Option<LocalDefId>,
252         f: impl FnOnce(&mut Self),
253     ) {
254         let parent_def_id = self.def_id;
255         let parent_kind = self.const_kind;
256         self.def_id = def_id;
257         self.const_kind = kind;
258         f(self);
259         self.def_id = parent_def_id;
260         self.const_kind = parent_kind;
261     }
262 }
263
264 impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> {
265     type NestedFilter = nested_filter::OnlyBodies;
266
267     fn nested_visit_map(&mut self) -> Self::Map {
268         self.tcx.hir()
269     }
270
271     fn visit_anon_const(&mut self, anon: &'tcx hir::AnonConst) {
272         let kind = Some(hir::ConstContext::Const);
273         self.recurse_into(kind, None, |this| intravisit::walk_anon_const(this, anon));
274     }
275
276     fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
277         let owner = self.tcx.hir().body_owner_def_id(body.id());
278         let kind = self.tcx.hir().body_const_context(owner);
279         self.recurse_into(kind, Some(owner), |this| intravisit::walk_body(this, body));
280     }
281
282     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
283         match &e.kind {
284             // Skip the following checks if we are not currently in a const context.
285             _ if self.const_kind.is_none() => {}
286
287             hir::ExprKind::Loop(_, _, source, _) => {
288                 self.const_check_violated(NonConstExpr::Loop(*source), e.span);
289             }
290
291             hir::ExprKind::Match(_, _, source) => {
292                 let non_const_expr = match source {
293                     // These are handled by `ExprKind::Loop` above.
294                     hir::MatchSource::ForLoopDesugar => None,
295
296                     _ => Some(NonConstExpr::Match(*source)),
297                 };
298
299                 if let Some(expr) = non_const_expr {
300                     self.const_check_violated(expr, e.span);
301                 }
302             }
303
304             _ => {}
305         }
306
307         intravisit::walk_expr(self, e);
308     }
309 }