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