]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/check_const.rs
Fix caching issue when building tools.
[rust.git] / src / librustc_passes / 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, NestedVisitorMap, Visitor};
15 use rustc_middle::hir::map::Map;
16 use rustc_middle::ty::query::Providers;
17 use rustc_middle::ty::TyCtxt;
18 use rustc_session::config::nightly_options;
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             // A `for` loop's desugaring contains a call to `IntoIterator::into_iter`,
43             // so they are not yet allowed.
44             // Likewise, `?` desugars to a call to `Try::into_result`.
45             Self::Loop(ForLoop) | Self::Match(ForLoopDesugar | TryDesugar | AwaitDesugar) => {
46                 return None;
47             }
48
49             // All other expressions are allowed.
50             Self::Loop(Loop | While | WhileLet)
51             | Self::Match(
52                 WhileDesugar | WhileLetDesugar | Normal | IfDesugar { .. } | IfLetDesugar { .. },
53             ) => &[],
54         };
55
56         Some(gates)
57     }
58 }
59
60 fn check_mod_const_bodies(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
61     let mut vis = CheckConstVisitor::new(tcx);
62     tcx.hir().visit_item_likes_in_module(module_def_id, &mut vis.as_deep_visitor());
63 }
64
65 pub(crate) fn provide(providers: &mut Providers<'_>) {
66     *providers = Providers { check_mod_const_bodies, ..*providers };
67 }
68
69 #[derive(Copy, Clone)]
70 struct CheckConstVisitor<'tcx> {
71     tcx: TyCtxt<'tcx>,
72     const_kind: Option<hir::ConstContext>,
73     def_id: Option<LocalDefId>,
74 }
75
76 impl<'tcx> CheckConstVisitor<'tcx> {
77     fn new(tcx: TyCtxt<'tcx>) -> Self {
78         CheckConstVisitor { tcx, const_kind: None, def_id: None }
79     }
80
81     /// Emits an error when an unsupported expression is found in a const context.
82     fn const_check_violated(&self, expr: NonConstExpr, span: Span) {
83         let Self { tcx, def_id, const_kind } = *self;
84
85         let features = tcx.features();
86         let required_gates = expr.required_feature_gates();
87
88         let is_feature_allowed = |feature_gate| {
89             // All features require that the corresponding gate be enabled,
90             // even if the function has `#[allow_internal_unstable(the_gate)]`.
91             if !tcx.features().enabled(feature_gate) {
92                 return false;
93             }
94
95             // If `def_id` is `None`, we don't need to consider stability attributes.
96             let def_id = match def_id {
97                 Some(x) => x.to_def_id(),
98                 None => return true,
99             };
100
101             // If this crate is not using stability attributes, or this function is not claiming to be a
102             // stable `const fn`, that is all that is required.
103             if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
104                 return true;
105             }
106
107             // However, we cannot allow stable `const fn`s to use unstable features without an explicit
108             // opt-in via `allow_internal_unstable`.
109             attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
110                 .map_or(false, |mut features| features.any(|name| name == feature_gate))
111         };
112
113         match required_gates {
114             // Don't emit an error if the user has enabled the requisite feature gates.
115             Some(gates) if gates.iter().copied().all(is_feature_allowed) => return,
116
117             // `-Zunleash-the-miri-inside-of-you` only works for expressions that don't have a
118             // corresponding feature gate. This encourages nightly users to use feature gates when
119             // possible.
120             None if tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you => {
121                 tcx.sess.span_warn(span, "skipping const checks");
122                 return;
123             }
124
125             _ => {}
126         }
127
128         let const_kind =
129             const_kind.expect("`const_check_violated` may only be called inside a const context");
130
131         let msg = format!("{} is not allowed in a `{}`", expr.name(), const_kind.keyword_name());
132
133         let required_gates = required_gates.unwrap_or(&[]);
134         let missing_gates: Vec<_> =
135             required_gates.iter().copied().filter(|&g| !features.enabled(g)).collect();
136
137         match missing_gates.as_slice() {
138             &[] => struct_span_err!(tcx.sess, span, E0744, "{}", msg).emit(),
139
140             &[missing_primary, ref missing_secondary @ ..] => {
141                 let mut err = feature_err(&tcx.sess.parse_sess, missing_primary, span, &msg);
142
143                 // If multiple feature gates would be required to enable this expression, include
144                 // them as help messages. Don't emit a separate error for each missing feature gate.
145                 //
146                 // FIXME(ecstaticmorse): Maybe this could be incorporated into `feature_err`? This
147                 // is a pretty narrow case, however.
148                 if nightly_options::is_nightly_build() {
149                     for gate in missing_secondary {
150                         let note = format!(
151                             "add `#![feature({})]` to the crate attributes to enable",
152                             gate,
153                         );
154                         err.help(&note);
155                     }
156                 }
157
158                 err.emit();
159             }
160         }
161     }
162
163     /// Saves the parent `const_kind` before calling `f` and restores it afterwards.
164     fn recurse_into(
165         &mut self,
166         kind: Option<hir::ConstContext>,
167         def_id: Option<LocalDefId>,
168         f: impl FnOnce(&mut Self),
169     ) {
170         let parent_def_id = self.def_id;
171         let parent_kind = self.const_kind;
172         self.def_id = def_id;
173         self.const_kind = kind;
174         f(self);
175         self.def_id = parent_def_id;
176         self.const_kind = parent_kind;
177     }
178 }
179
180 impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> {
181     type Map = Map<'tcx>;
182
183     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
184         NestedVisitorMap::OnlyBodies(self.tcx.hir())
185     }
186
187     fn visit_anon_const(&mut self, anon: &'tcx hir::AnonConst) {
188         let kind = Some(hir::ConstContext::Const);
189         self.recurse_into(kind, None, |this| intravisit::walk_anon_const(this, anon));
190     }
191
192     fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
193         let owner = self.tcx.hir().body_owner_def_id(body.id());
194         let kind = self.tcx.hir().body_const_context(owner);
195         self.recurse_into(kind, Some(owner), |this| intravisit::walk_body(this, body));
196     }
197
198     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
199         match &e.kind {
200             // Skip the following checks if we are not currently in a const context.
201             _ if self.const_kind.is_none() => {}
202
203             hir::ExprKind::Loop(_, _, source) => {
204                 self.const_check_violated(NonConstExpr::Loop(*source), e.span);
205             }
206
207             hir::ExprKind::Match(_, _, source) => {
208                 let non_const_expr = match source {
209                     // These are handled by `ExprKind::Loop` above.
210                     hir::MatchSource::WhileDesugar
211                     | hir::MatchSource::WhileLetDesugar
212                     | hir::MatchSource::ForLoopDesugar => None,
213
214                     _ => Some(NonConstExpr::Match(*source)),
215                 };
216
217                 if let Some(expr) = non_const_expr {
218                     self.const_check_violated(expr, e.span);
219                 }
220             }
221
222             _ => {}
223         }
224
225         intravisit::walk_expr(self, e);
226     }
227 }