]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/consts.rs
608238dfe3735d6f46ea5b71648f0a1d7424e308
[rust.git] / src / librustc_passes / consts.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Verifies that the types and values of const and static items
12 // are safe. The rules enforced by this module are:
13 //
14 // - For each *mutable* static item, it checks that its **type**:
15 //     - doesn't have a destructor
16 //     - doesn't own a box
17 //
18 // - For each *immutable* static item, it checks that its **value**:
19 //       - doesn't own a box
20 //       - doesn't contain a struct literal or a call to an enum variant / struct constructor where
21 //           - the type of the struct/enum has a dtor
22 //
23 // Rules Enforced Elsewhere:
24 // - It's not possible to take the address of a static item with unsafe interior. This is enforced
25 // by borrowck::gather_loans
26
27 use rustc::ty::cast::CastKind;
28 use rustc_const_eval::ConstContext;
29 use rustc::middle::const_val::ConstEvalErr;
30 use rustc::middle::const_val::ErrKind::{IndexOpFeatureGated, UnimplementedConstVal, MiscCatchAll};
31 use rustc::middle::const_val::ErrKind::{ErroneousReferencedConstant, MiscBinaryOp, NonConstPath};
32 use rustc::middle::const_val::ErrKind::{TypeckError, Math};
33 use rustc_const_math::{ConstMathErr, Op};
34 use rustc::hir::def::{Def, CtorKind};
35 use rustc::hir::def_id::DefId;
36 use rustc::hir::map::blocks::FnLikeNode;
37 use rustc::middle::expr_use_visitor as euv;
38 use rustc::middle::mem_categorization as mc;
39 use rustc::middle::mem_categorization::Categorization;
40 use rustc::mir::transform::MirSource;
41 use rustc::ty::{self, Ty, TyCtxt};
42 use rustc::traits::Reveal;
43 use rustc::util::common::ErrorReported;
44 use rustc::util::nodemap::NodeSet;
45 use rustc::lint::builtin::CONST_ERR;
46
47 use rustc::hir::{self, PatKind, RangeEnd};
48 use syntax::ast;
49 use syntax_pos::{Span, DUMMY_SP};
50 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
51
52 use std::collections::hash_map::Entry;
53 use std::cmp::Ordering;
54 use std::mem;
55
56 struct CheckCrateVisitor<'a, 'tcx: 'a> {
57     tcx: TyCtxt<'a, 'tcx, 'tcx>,
58     in_fn: bool,
59     promotable: bool,
60     mut_rvalue_borrows: NodeSet,
61     param_env: ty::ParameterEnvironment<'tcx>,
62     tables: &'a ty::TypeckTables<'tcx>,
63 }
64
65 impl<'a, 'gcx> CheckCrateVisitor<'a, 'gcx> {
66     fn check_const_eval(&self, expr: &'gcx hir::Expr) {
67         let const_cx = ConstContext::with_tables(self.tcx, self.tables);
68         if let Err(err) = const_cx.eval(expr) {
69             match err.kind {
70                 UnimplementedConstVal(_) => {}
71                 IndexOpFeatureGated => {}
72                 ErroneousReferencedConstant(_) => {}
73                 TypeckError => {}
74                 _ => {
75                     self.tcx.sess.add_lint(CONST_ERR,
76                                            expr.id,
77                                            expr.span,
78                                            format!("constant evaluation error: {}. This will \
79                                                     become a HARD ERROR in the future",
80                                                    err.description().into_oneline()))
81                 }
82             }
83         }
84     }
85
86     // Adds the worst effect out of all the values of one type.
87     fn add_type(&mut self, ty: Ty<'gcx>) {
88         if !ty.is_freeze(self.tcx, &self.param_env, DUMMY_SP) {
89             self.promotable = false;
90         }
91
92         if ty.needs_drop(self.tcx, &self.param_env) {
93             self.promotable = false;
94         }
95     }
96
97     fn handle_const_fn_call(&mut self, def_id: DefId, ret_ty: Ty<'gcx>) {
98         self.add_type(ret_ty);
99
100         self.promotable &= if let Some(fn_id) = self.tcx.hir.as_local_node_id(def_id) {
101             FnLikeNode::from_node(self.tcx.hir.get(fn_id)).map_or(false, |fn_like| {
102                 fn_like.constness() == hir::Constness::Const
103             })
104         } else {
105             self.tcx.sess.cstore.is_const_fn(def_id)
106         };
107     }
108 }
109
110 impl<'a, 'tcx> Visitor<'tcx> for CheckCrateVisitor<'a, 'tcx> {
111     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
112         NestedVisitorMap::None
113     }
114
115     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
116         match self.tcx.rvalue_promotable_to_static.borrow_mut().entry(body_id.node_id) {
117             Entry::Occupied(_) => return,
118             Entry::Vacant(entry) => {
119                 // Prevent infinite recursion on re-entry.
120                 entry.insert(false);
121             }
122         }
123
124         let item_id = self.tcx.hir.body_owner(body_id);
125
126         let outer_in_fn = self.in_fn;
127         self.in_fn = match MirSource::from_node(self.tcx, item_id) {
128             MirSource::Fn(_) => true,
129             _ => false
130         };
131
132         let outer_tables = self.tables;
133         let item_def_id = self.tcx.hir.local_def_id(item_id);
134         self.tables = self.tcx.typeck_tables_of(item_def_id);
135
136         let body = self.tcx.hir.body(body_id);
137         if !self.in_fn {
138             self.check_const_eval(&body.value);
139         }
140
141         let outer_penv = self.tcx.infer_ctxt(body_id, Reveal::UserFacing).enter(|infcx| {
142             let param_env = infcx.parameter_environment.clone();
143             let outer_penv = mem::replace(&mut self.param_env, param_env);
144             let region_maps = &self.tcx.region_maps(item_def_id);;
145             euv::ExprUseVisitor::new(self, region_maps, &infcx).consume_body(body);
146             outer_penv
147         });
148
149         self.visit_body(body);
150
151         self.param_env = outer_penv;
152         self.tables = outer_tables;
153         self.in_fn = outer_in_fn;
154     }
155
156     fn visit_pat(&mut self, p: &'tcx hir::Pat) {
157         match p.node {
158             PatKind::Lit(ref lit) => {
159                 self.check_const_eval(lit);
160             }
161             PatKind::Range(ref start, ref end, RangeEnd::Excluded) => {
162                 let const_cx = ConstContext::with_tables(self.tcx, self.tables);
163                 match const_cx.compare_lit_exprs(p.span, start, end) {
164                     Ok(Ordering::Less) => {}
165                     Ok(Ordering::Equal) |
166                     Ok(Ordering::Greater) => {
167                         span_err!(self.tcx.sess,
168                                   start.span,
169                                   E0579,
170                                   "lower range bound must be less than upper");
171                     }
172                     Err(ErrorReported) => {}
173                 }
174             }
175             PatKind::Range(ref start, ref end, RangeEnd::Included) => {
176                 let const_cx = ConstContext::with_tables(self.tcx, self.tables);
177                 match const_cx.compare_lit_exprs(p.span, start, end) {
178                     Ok(Ordering::Less) |
179                     Ok(Ordering::Equal) => {}
180                     Ok(Ordering::Greater) => {
181                         struct_span_err!(self.tcx.sess, start.span, E0030,
182                             "lower range bound must be less than or equal to upper")
183                             .span_label(start.span, &format!("lower bound larger than upper bound"))
184                             .emit();
185                     }
186                     Err(ErrorReported) => {}
187                 }
188             }
189             _ => {}
190         }
191         intravisit::walk_pat(self, p);
192     }
193
194     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
195         match stmt.node {
196             hir::StmtDecl(ref decl, _) => {
197                 match decl.node {
198                     hir::DeclLocal(_) => {
199                         self.promotable = false;
200                     }
201                     // Item statements are allowed
202                     hir::DeclItem(_) => {}
203                 }
204             }
205             hir::StmtExpr(..) |
206             hir::StmtSemi(..) => {
207                 self.promotable = false;
208             }
209         }
210         intravisit::walk_stmt(self, stmt);
211     }
212
213     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
214         let outer = self.promotable;
215         self.promotable = true;
216
217         let node_ty = self.tables.node_id_to_type(ex.id);
218         check_expr(self, ex, node_ty);
219         check_adjustments(self, ex);
220
221         if let hir::ExprMatch(ref discr, ref arms, _) = ex.node {
222             // Compute the most demanding borrow from all the arms'
223             // patterns and set that on the discriminator.
224             let mut mut_borrow = false;
225             for pat in arms.iter().flat_map(|arm| &arm.pats) {
226                 if self.mut_rvalue_borrows.remove(&pat.id) {
227                     mut_borrow = true;
228                 }
229             }
230             if mut_borrow {
231                 self.mut_rvalue_borrows.insert(discr.id);
232             }
233         }
234
235         intravisit::walk_expr(self, ex);
236
237         // Handle borrows on (or inside the autorefs of) this expression.
238         if self.mut_rvalue_borrows.remove(&ex.id) {
239             self.promotable = false;
240         }
241
242         if self.in_fn && self.promotable {
243             let const_cx = ConstContext::with_tables(self.tcx, self.tables);
244             match const_cx.eval(ex) {
245                 Ok(_) => {}
246                 Err(ConstEvalErr { kind: UnimplementedConstVal(_), .. }) |
247                 Err(ConstEvalErr { kind: MiscCatchAll, .. }) |
248                 Err(ConstEvalErr { kind: MiscBinaryOp, .. }) |
249                 Err(ConstEvalErr { kind: NonConstPath, .. }) |
250                 Err(ConstEvalErr { kind: ErroneousReferencedConstant(_), .. }) |
251                 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shr)), .. }) |
252                 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shl)), .. }) |
253                 Err(ConstEvalErr { kind: IndexOpFeatureGated, .. }) => {}
254                 Err(ConstEvalErr { kind: TypeckError, .. }) => {}
255                 Err(msg) => {
256                     self.tcx.sess.add_lint(CONST_ERR,
257                                            ex.id,
258                                            msg.span,
259                                            msg.description().into_oneline().into_owned())
260                 }
261             }
262         }
263
264         self.tcx.rvalue_promotable_to_static.borrow_mut().insert(ex.id, self.promotable);
265         self.promotable &= outer;
266     }
267 }
268
269 /// This function is used to enforce the constraints on
270 /// const/static items. It walks through the *value*
271 /// of the item walking down the expression and evaluating
272 /// every nested expression. If the expression is not part
273 /// of a const/static item, it is qualified for promotion
274 /// instead of producing errors.
275 fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr, node_ty: Ty<'tcx>) {
276     match node_ty.sty {
277         ty::TyAdt(def, _) if def.has_dtor(v.tcx) => {
278             v.promotable = false;
279         }
280         _ => {}
281     }
282
283     let method_call = ty::MethodCall::expr(e.id);
284     match e.node {
285         hir::ExprUnary(..) |
286         hir::ExprBinary(..) |
287         hir::ExprIndex(..) if v.tables.method_map.contains_key(&method_call) => {
288             v.promotable = false;
289         }
290         hir::ExprBox(_) => {
291             v.promotable = false;
292         }
293         hir::ExprUnary(op, ref inner) => {
294             match v.tables.node_id_to_type(inner.id).sty {
295                 ty::TyRawPtr(_) => {
296                     assert!(op == hir::UnDeref);
297
298                     v.promotable = false;
299                 }
300                 _ => {}
301             }
302         }
303         hir::ExprBinary(op, ref lhs, _) => {
304             match v.tables.node_id_to_type(lhs.id).sty {
305                 ty::TyRawPtr(_) => {
306                     assert!(op.node == hir::BiEq || op.node == hir::BiNe ||
307                             op.node == hir::BiLe || op.node == hir::BiLt ||
308                             op.node == hir::BiGe || op.node == hir::BiGt);
309
310                     v.promotable = false;
311                 }
312                 _ => {}
313             }
314         }
315         hir::ExprCast(ref from, _) => {
316             debug!("Checking const cast(id={})", from.id);
317             match v.tables.cast_kinds.get(&from.id) {
318                 None => span_bug!(e.span, "no kind for cast"),
319                 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
320                     v.promotable = false;
321                 }
322                 _ => {}
323             }
324         }
325         hir::ExprPath(ref qpath) => {
326             let def = v.tables.qpath_def(qpath, e.id);
327             match def {
328                 Def::VariantCtor(..) | Def::StructCtor(..) |
329                 Def::Fn(..) | Def::Method(..) => {}
330                 Def::AssociatedConst(_) => v.add_type(node_ty),
331                 Def::Const(did) => {
332                     v.promotable &= if let Some(node_id) = v.tcx.hir.as_local_node_id(did) {
333                         match v.tcx.hir.expect_item(node_id).node {
334                             hir::ItemConst(_, body) => {
335                                 v.visit_nested_body(body);
336                                 v.tcx.rvalue_promotable_to_static.borrow()[&body.node_id]
337                             }
338                             _ => false
339                         }
340                     } else {
341                         v.tcx.const_is_rvalue_promotable_to_static(did)
342                     };
343                 }
344                 _ => {
345                     v.promotable = false;
346                 }
347             }
348         }
349         hir::ExprCall(ref callee, _) => {
350             let mut callee = &**callee;
351             loop {
352                 callee = match callee.node {
353                     hir::ExprBlock(ref block) => match block.expr {
354                         Some(ref tail) => &tail,
355                         None => break
356                     },
357                     _ => break
358                 };
359             }
360             // The callee is an arbitrary expression, it doesn't necessarily have a definition.
361             let def = if let hir::ExprPath(ref qpath) = callee.node {
362                 v.tables.qpath_def(qpath, callee.id)
363             } else {
364                 Def::Err
365             };
366             match def {
367                 Def::StructCtor(_, CtorKind::Fn) |
368                 Def::VariantCtor(_, CtorKind::Fn) => {}
369                 Def::Fn(did) => {
370                     v.handle_const_fn_call(did, node_ty)
371                 }
372                 Def::Method(did) => {
373                     match v.tcx.associated_item(did).container {
374                         ty::ImplContainer(_) => {
375                             v.handle_const_fn_call(did, node_ty)
376                         }
377                         ty::TraitContainer(_) => v.promotable = false
378                     }
379                 }
380                 _ => v.promotable = false
381             }
382         }
383         hir::ExprMethodCall(..) => {
384             let method = v.tables.method_map[&method_call];
385             match v.tcx.associated_item(method.def_id).container {
386                 ty::ImplContainer(_) => v.handle_const_fn_call(method.def_id, node_ty),
387                 ty::TraitContainer(_) => v.promotable = false
388             }
389         }
390         hir::ExprStruct(..) => {
391             if let ty::TyAdt(adt, ..) = v.tables.expr_ty(e).sty {
392                 // unsafe_cell_type doesn't necessarily exist with no_core
393                 if Some(adt.did) == v.tcx.lang_items.unsafe_cell_type() {
394                     v.promotable = false;
395                 }
396             }
397         }
398
399         hir::ExprLit(_) |
400         hir::ExprAddrOf(..) |
401         hir::ExprRepeat(..) => {}
402
403         hir::ExprClosure(..) => {
404             // Paths in constant contexts cannot refer to local variables,
405             // as there are none, and thus closures can't have upvars there.
406             if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
407                 v.promotable = false;
408             }
409         }
410
411         hir::ExprBlock(_) |
412         hir::ExprIndex(..) |
413         hir::ExprField(..) |
414         hir::ExprTupField(..) |
415         hir::ExprArray(_) |
416         hir::ExprType(..) |
417         hir::ExprTup(..) => {}
418
419         // Conditional control flow (possible to implement).
420         hir::ExprMatch(..) |
421         hir::ExprIf(..) |
422
423         // Loops (not very meaningful in constants).
424         hir::ExprWhile(..) |
425         hir::ExprLoop(..) |
426
427         // More control flow (also not very meaningful).
428         hir::ExprBreak(..) |
429         hir::ExprAgain(_) |
430         hir::ExprRet(_) |
431
432         // Expressions with side-effects.
433         hir::ExprAssign(..) |
434         hir::ExprAssignOp(..) |
435         hir::ExprInlineAsm(..) => {
436             v.promotable = false;
437         }
438     }
439 }
440
441 /// Check the adjustments of an expression
442 fn check_adjustments<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr) {
443     use rustc::ty::adjustment::*;
444
445     match v.tables.adjustments.get(&e.id).map(|adj| adj.kind) {
446         None |
447         Some(Adjust::NeverToAny) |
448         Some(Adjust::ReifyFnPointer) |
449         Some(Adjust::UnsafeFnPointer) |
450         Some(Adjust::ClosureFnPointer) |
451         Some(Adjust::MutToConstPointer) => {}
452
453         Some(Adjust::DerefRef { autoderefs, .. }) => {
454             if (0..autoderefs as u32)
455                 .any(|autoderef| v.tables.is_overloaded_autoderef(e.id, autoderef)) {
456                 v.promotable = false;
457             }
458         }
459     }
460 }
461
462 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
463     tcx.hir.krate().visit_all_item_likes(&mut CheckCrateVisitor {
464         tcx: tcx,
465         tables: &ty::TypeckTables::empty(),
466         in_fn: false,
467         promotable: false,
468         mut_rvalue_borrows: NodeSet(),
469         param_env: tcx.empty_parameter_environment(),
470     }.as_deep_visitor());
471     tcx.sess.abort_if_errors();
472 }
473
474 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> {
475     fn consume(&mut self,
476                _consume_id: ast::NodeId,
477                _consume_span: Span,
478                _cmt: mc::cmt,
479                _mode: euv::ConsumeMode) {}
480
481     fn borrow(&mut self,
482               borrow_id: ast::NodeId,
483               _borrow_span: Span,
484               cmt: mc::cmt<'tcx>,
485               _loan_region: ty::Region<'tcx>,
486               bk: ty::BorrowKind,
487               loan_cause: euv::LoanCause) {
488         // Kind of hacky, but we allow Unsafe coercions in constants.
489         // These occur when we convert a &T or *T to a *U, as well as
490         // when making a thin pointer (e.g., `*T`) into a fat pointer
491         // (e.g., `*Trait`).
492         match loan_cause {
493             euv::LoanCause::AutoUnsafe => {
494                 return;
495             }
496             _ => {}
497         }
498
499         let mut cur = &cmt;
500         loop {
501             match cur.cat {
502                 Categorization::Rvalue(..) => {
503                     if loan_cause == euv::MatchDiscriminant {
504                         // Ignore the dummy immutable borrow created by EUV.
505                         break;
506                     }
507                     if bk.to_mutbl_lossy() == hir::MutMutable {
508                         self.mut_rvalue_borrows.insert(borrow_id);
509                     }
510                     break;
511                 }
512                 Categorization::StaticItem => {
513                     break;
514                 }
515                 Categorization::Deref(ref cmt, ..) |
516                 Categorization::Downcast(ref cmt, _) |
517                 Categorization::Interior(ref cmt, _) => {
518                     cur = cmt;
519                 }
520
521                 Categorization::Upvar(..) |
522                 Categorization::Local(..) => break,
523             }
524         }
525     }
526
527     fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {}
528     fn mutate(&mut self,
529               _assignment_id: ast::NodeId,
530               _assignment_span: Span,
531               _assignee_cmt: mc::cmt,
532               _mode: euv::MutateMode) {
533     }
534
535     fn matched_pat(&mut self, _: &hir::Pat, _: mc::cmt, _: euv::MatchMode) {}
536
537     fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: mc::cmt, _mode: euv::ConsumeMode) {}
538 }