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