]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/check_const.rs
24bc088e24a705a47855ad0cbab420d0ff69b2b7
[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::hir::def_id::DefId;
11 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
12 use rustc::hir::map::Map;
13 use rustc::hir;
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};
18 use syntax::span_err;
19 use syntax_pos::{sym, Span};
20 use rustc_error_codes::*;
21
22 use std::fmt;
23
24 /// An expression that is not *always* legal in a const context.
25 #[derive(Clone, Copy)]
26 enum NonConstExpr {
27     Loop(hir::LoopSource),
28     Match(hir::MatchSource),
29 }
30
31 impl NonConstExpr {
32     fn name(self) -> &'static str {
33         match self {
34             Self::Loop(src) => src.name(),
35             Self::Match(src) => src.name(),
36         }
37     }
38
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::*;
43         match self {
44             | Self::Match(Normal)
45             | Self::Match(IfDesugar { .. })
46             | Self::Match(IfLetDesugar { .. })
47             => Some(features.const_if_match),
48
49             _ => None,
50         }
51     }
52 }
53
54 #[derive(Copy, Clone)]
55 enum ConstKind {
56     Static,
57     StaticMut,
58     ConstFn,
59     Const,
60     AnonConst,
61 }
62
63 impl ConstKind {
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();
66
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,
72
73             hir::BodyOwnerKind::Fn if is_const_fn(owner) => Self::ConstFn,
74             hir::BodyOwnerKind::Fn | hir::BodyOwnerKind::Closure => return None,
75         };
76
77         Some(const_kind)
78     }
79 }
80
81 impl fmt::Display for ConstKind {
82     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83         let s = match self {
84             Self::Static => "static",
85             Self::StaticMut => "static mut",
86             Self::Const | Self::AnonConst => "const",
87             Self::ConstFn => "const fn",
88         };
89
90         write!(f, "{}", s)
91     }
92 }
93
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());
97 }
98
99 pub(crate) fn provide(providers: &mut Providers<'_>) {
100     *providers = Providers {
101         check_mod_const_bodies,
102         ..*providers
103     };
104 }
105
106 #[derive(Copy, Clone)]
107 struct CheckConstVisitor<'tcx> {
108     tcx: TyCtxt<'tcx>,
109     const_kind: Option<ConstKind>,
110 }
111
112 impl<'tcx> CheckConstVisitor<'tcx> {
113     fn new(tcx: TyCtxt<'tcx>) -> Self {
114         CheckConstVisitor {
115             tcx,
116             const_kind: None,
117         }
118     }
119
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,
125
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");
129                 return;
130             }
131
132             _ => {}
133         }
134
135         let const_kind = self.const_kind
136             .expect("`const_check_violated` may only be called inside a const context");
137
138         let msg = format!("`{}` is not allowed in a `{}`", expr.name(), const_kind);
139         match expr {
140             | NonConstExpr::Match(hir::MatchSource::Normal)
141             | NonConstExpr::Match(hir::MatchSource::IfDesugar { .. })
142             | NonConstExpr::Match(hir::MatchSource::IfLetDesugar { .. })
143             => emit_feature_err(
144                 &self.tcx.sess.parse_sess,
145                 sym::const_if_match,
146                 span,
147                 GateIssue::Language,
148                 &msg
149             ),
150
151             _ => span_err!(self.tcx.sess, span, E0744, "{}", msg),
152         }
153     }
154
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;
159         f(self);
160         self.const_kind = parent_kind;
161     }
162 }
163
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())
167     }
168
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));
172     }
173
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));
177     }
178
179     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
180         match &e.kind {
181             // Skip the following checks if we are not currently in a const context.
182             _ if self.const_kind.is_none() => {}
183
184             hir::ExprKind::Loop(_, _, source) => {
185                 self.const_check_violated(NonConstExpr::Loop(*source), e.span);
186             }
187
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
194                     => None,
195
196                     _ => Some(NonConstExpr::Match(*source)),
197                 };
198
199                 if let Some(expr) = non_const_expr {
200                     self.const_check_violated(expr, e.span);
201                 }
202             }
203
204             _ => {},
205         }
206
207         hir::intravisit::walk_expr(self, e);
208     }
209 }