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
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.
10 use rustc::hir::def_id::DefId;
11 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
12 use rustc::hir::map::Map;
14 use rustc::ty::TyCtxt;
15 use rustc::ty::query::Providers;
16 use syntax::ast::Mutability;
17 use syntax::feature_gate::{emit_feature_err, Features, GateIssue};
19 use syntax_pos::{sym, Span};
20 use rustc_error_codes::*;
24 /// An expression that is not *always* legal in a const context.
25 #[derive(Clone, Copy)]
27 Loop(hir::LoopSource),
28 Match(hir::MatchSource),
32 fn name(self) -> &'static str {
34 Self::Loop(src) => src.name(),
35 Self::Match(src) => src.name(),
39 /// Returns `true` if all feature gates required to enable this expression are turned on, or
40 /// `None` if there is no feature gate corresponding to this expression.
41 fn is_feature_gate_enabled(self, features: &Features) -> Option<bool> {
42 use hir::MatchSource::*;
45 | Self::Match(IfDesugar { .. })
46 | Self::Match(IfLetDesugar { .. })
47 => Some(features.const_if_match),
54 #[derive(Copy, Clone)]
64 fn for_body(body: &hir::Body, hir_map: &Map<'_>) -> Option<Self> {
65 let is_const_fn = |id| hir_map.fn_sig_by_hir_id(id).unwrap().header.is_const();
67 let owner = hir_map.body_owner(body.id());
68 let const_kind = match hir_map.body_owner_kind(owner) {
69 hir::BodyOwnerKind::Const => Self::Const,
70 hir::BodyOwnerKind::Static(Mutability::Mutable) => Self::StaticMut,
71 hir::BodyOwnerKind::Static(Mutability::Immutable) => Self::Static,
73 hir::BodyOwnerKind::Fn if is_const_fn(owner) => Self::ConstFn,
74 hir::BodyOwnerKind::Fn | hir::BodyOwnerKind::Closure => return None,
81 impl fmt::Display for ConstKind {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 Self::Static => "static",
85 Self::StaticMut => "static mut",
86 Self::Const | Self::AnonConst => "const",
87 Self::ConstFn => "const fn",
94 fn check_mod_const_bodies(tcx: TyCtxt<'_>, module_def_id: DefId) {
95 let mut vis = CheckConstVisitor::new(tcx);
96 tcx.hir().visit_item_likes_in_module(module_def_id, &mut vis.as_deep_visitor());
99 pub(crate) fn provide(providers: &mut Providers<'_>) {
100 *providers = Providers {
101 check_mod_const_bodies,
106 #[derive(Copy, Clone)]
107 struct CheckConstVisitor<'tcx> {
109 const_kind: Option<ConstKind>,
112 impl<'tcx> CheckConstVisitor<'tcx> {
113 fn new(tcx: TyCtxt<'tcx>) -> Self {
120 /// Emits an error when an unsupported expression is found in a const context.
121 fn const_check_violated(&self, expr: NonConstExpr, span: Span) {
122 match expr.is_feature_gate_enabled(self.tcx.features()) {
123 // Don't emit an error if the user has enabled the requisite feature gates.
124 Some(true) => return,
126 // Users of `-Zunleash-the-miri-inside-of-you` must use feature gates when possible.
127 None if self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you => {
128 self.tcx.sess.span_warn(span, "skipping const checks");
135 let const_kind = self.const_kind
136 .expect("`const_check_violated` may only be called inside a const context");
138 let msg = format!("`{}` is not allowed in a `{}`", expr.name(), const_kind);
140 | NonConstExpr::Match(hir::MatchSource::Normal)
141 | NonConstExpr::Match(hir::MatchSource::IfDesugar { .. })
142 | NonConstExpr::Match(hir::MatchSource::IfLetDesugar { .. })
144 &self.tcx.sess.parse_sess,
151 _ => span_err!(self.tcx.sess, span, E0744, "{}", msg),
155 /// Saves the parent `const_kind` before calling `f` and restores it afterwards.
156 fn recurse_into(&mut self, kind: Option<ConstKind>, f: impl FnOnce(&mut Self)) {
157 let parent_kind = self.const_kind;
158 self.const_kind = kind;
160 self.const_kind = parent_kind;
164 impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> {
165 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
166 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
169 fn visit_anon_const(&mut self, anon: &'tcx hir::AnonConst) {
170 let kind = Some(ConstKind::AnonConst);
171 self.recurse_into(kind, |this| hir::intravisit::walk_anon_const(this, anon));
174 fn visit_body(&mut self, body: &'tcx hir::Body) {
175 let kind = ConstKind::for_body(body, self.tcx.hir());
176 self.recurse_into(kind, |this| hir::intravisit::walk_body(this, body));
179 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
181 // Skip the following checks if we are not currently in a const context.
182 _ if self.const_kind.is_none() => {}
184 hir::ExprKind::Loop(_, _, source) => {
185 self.const_check_violated(NonConstExpr::Loop(*source), e.span);
188 hir::ExprKind::Match(_, _, source) => {
189 let non_const_expr = match source {
190 // These are handled by `ExprKind::Loop` above.
191 | hir::MatchSource::WhileDesugar
192 | hir::MatchSource::WhileLetDesugar
193 | hir::MatchSource::ForLoopDesugar
196 _ => Some(NonConstExpr::Match(*source)),
199 if let Some(expr) = non_const_expr {
200 self.const_check_violated(expr, e.span);
207 hir::intravisit::walk_expr(self, e);