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