]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/consts.rs
eb955ccf6bf70d4b902ea5e65c9d533be19602fd
[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, LayoutError};
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::ty::subst::Substs;
43 use rustc::traits::Reveal;
44 use rustc::util::common::ErrorReported;
45 use rustc::util::nodemap::NodeSet;
46 use rustc::lint::builtin::CONST_ERR;
47
48 use rustc::hir::{self, PatKind, RangeEnd};
49 use syntax::ast;
50 use syntax_pos::{Span, DUMMY_SP};
51 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
52
53 use std::collections::hash_map::Entry;
54 use std::cmp::Ordering;
55
56 struct CheckCrateVisitor<'a, 'tcx: 'a> {
57     tcx: TyCtxt<'a, 'tcx, 'tcx>,
58     in_fn: bool,
59     in_static: bool,
60     promotable: bool,
61     mut_rvalue_borrows: NodeSet,
62     param_env: ty::ParamEnv<'tcx>,
63     identity_substs: &'tcx Substs<'tcx>,
64     tables: &'a ty::TypeckTables<'tcx>,
65 }
66
67 impl<'a, 'gcx> CheckCrateVisitor<'a, 'gcx> {
68     fn const_cx(&self) -> ConstContext<'a, 'gcx> {
69         ConstContext::new(self.tcx, self.param_env.and(self.identity_substs), self.tables)
70     }
71
72     fn check_const_eval(&self, expr: &'gcx hir::Expr) {
73         if let Err(err) = self.const_cx().eval(expr) {
74             match err.kind {
75                 UnimplementedConstVal(_) => {}
76                 IndexOpFeatureGated => {}
77                 ErroneousReferencedConstant(_) => {}
78                 TypeckError => {}
79                 _ => {
80                     self.tcx.lint_node(CONST_ERR,
81                                        expr.id,
82                                        expr.span,
83                                        &format!("constant evaluation error: {}. This will \
84                                                  become a HARD ERROR in the future",
85                                                 err.description().into_oneline()));
86                 }
87             }
88         }
89     }
90
91     // Returns true iff all the values of the type are promotable.
92     fn type_has_only_promotable_values(&mut self, ty: Ty<'gcx>) -> bool {
93         ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) &&
94         !ty.needs_drop(self.tcx, self.param_env)
95     }
96
97     fn handle_const_fn_call(&mut self, def_id: DefId, ret_ty: Ty<'gcx>) {
98         self.promotable &= self.type_has_only_promotable_values(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.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         let item_def_id = self.tcx.hir.local_def_id(item_id);
126
127         let outer_in_fn = self.in_fn;
128         let outer_tables = self.tables;
129         let outer_param_env = self.param_env;
130         let outer_identity_substs = self.identity_substs;
131
132         self.in_fn = false;
133         self.in_static = false;
134
135         match MirSource::from_node(self.tcx, item_id) {
136             MirSource::Fn(_) => self.in_fn = true,
137             MirSource::Static(_, _) => self.in_static = true,
138             _ => {}
139         };
140
141
142         self.tables = self.tcx.typeck_tables_of(item_def_id);
143         self.param_env = self.tcx.param_env(item_def_id);
144         self.identity_substs = Substs::identity_for_item(self.tcx, item_def_id);
145
146         let body = self.tcx.hir.body(body_id);
147         if !self.in_fn {
148             self.check_const_eval(&body.value);
149         }
150
151         let tcx = self.tcx;
152         let param_env = self.param_env;
153         let region_scope_tree = self.tcx.region_scope_tree(item_def_id);
154         euv::ExprUseVisitor::new(self, tcx, param_env, &region_scope_tree, self.tables)
155             .consume_body(body);
156
157         self.visit_body(body);
158
159         self.in_fn = outer_in_fn;
160         self.tables = outer_tables;
161         self.param_env = outer_param_env;
162         self.identity_substs = outer_identity_substs;
163     }
164
165     fn visit_pat(&mut self, p: &'tcx hir::Pat) {
166         match p.node {
167             PatKind::Lit(ref lit) => {
168                 self.check_const_eval(lit);
169             }
170             PatKind::Range(ref start, ref end, RangeEnd::Excluded) => {
171                 match self.const_cx().compare_lit_exprs(p.span, start, end) {
172                     Ok(Ordering::Less) => {}
173                     Ok(Ordering::Equal) |
174                     Ok(Ordering::Greater) => {
175                         span_err!(self.tcx.sess,
176                                   start.span,
177                                   E0579,
178                                   "lower range bound must be less than upper");
179                     }
180                     Err(ErrorReported) => {}
181                 }
182             }
183             PatKind::Range(ref start, ref end, RangeEnd::Included) => {
184                 match self.const_cx().compare_lit_exprs(p.span, start, end) {
185                     Ok(Ordering::Less) |
186                     Ok(Ordering::Equal) => {}
187                     Ok(Ordering::Greater) => {
188                         struct_span_err!(self.tcx.sess, start.span, E0030,
189                             "lower range bound must be less than or equal to upper")
190                             .span_label(start.span, "lower bound larger than upper bound")
191                             .emit();
192                     }
193                     Err(ErrorReported) => {}
194                 }
195             }
196             _ => {}
197         }
198         intravisit::walk_pat(self, p);
199     }
200
201     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
202         match stmt.node {
203             hir::StmtDecl(ref decl, _) => {
204                 match decl.node {
205                     hir::DeclLocal(_) => {
206                         self.promotable = false;
207                     }
208                     // Item statements are allowed
209                     hir::DeclItem(_) => {}
210                 }
211             }
212             hir::StmtExpr(..) |
213             hir::StmtSemi(..) => {
214                 self.promotable = false;
215             }
216         }
217         intravisit::walk_stmt(self, stmt);
218     }
219
220     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
221         let outer = self.promotable;
222         self.promotable = true;
223
224         let node_ty = self.tables.node_id_to_type(ex.hir_id);
225         check_expr(self, ex, node_ty);
226         check_adjustments(self, ex);
227
228         if let hir::ExprMatch(ref discr, ref arms, _) = ex.node {
229             // Compute the most demanding borrow from all the arms'
230             // patterns and set that on the discriminator.
231             let mut mut_borrow = false;
232             for pat in arms.iter().flat_map(|arm| &arm.pats) {
233                 if self.mut_rvalue_borrows.remove(&pat.id) {
234                     mut_borrow = true;
235                 }
236             }
237             if mut_borrow {
238                 self.mut_rvalue_borrows.insert(discr.id);
239             }
240         }
241
242         intravisit::walk_expr(self, ex);
243
244         // Handle borrows on (or inside the autorefs of) this expression.
245         if self.mut_rvalue_borrows.remove(&ex.id) {
246             self.promotable = false;
247         }
248
249         if self.in_fn && self.promotable {
250             match self.const_cx().eval(ex) {
251                 Ok(_) => {}
252                 Err(ConstEvalErr { kind: UnimplementedConstVal(_), .. }) |
253                 Err(ConstEvalErr { kind: MiscCatchAll, .. }) |
254                 Err(ConstEvalErr { kind: MiscBinaryOp, .. }) |
255                 Err(ConstEvalErr { kind: NonConstPath, .. }) |
256                 Err(ConstEvalErr { kind: ErroneousReferencedConstant(_), .. }) |
257                 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shr)), .. }) |
258                 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shl)), .. }) |
259                 Err(ConstEvalErr { kind: IndexOpFeatureGated, .. }) => {}
260                 Err(ConstEvalErr { kind: TypeckError, .. }) => {}
261                 Err(ConstEvalErr {
262                     kind: LayoutError(ty::layout::LayoutError::Unknown(_)), ..
263                 }) => {}
264                 Err(msg) => {
265                     self.tcx.lint_node(CONST_ERR,
266                                        ex.id,
267                                        msg.span,
268                                        &msg.description().into_oneline().into_owned());
269                 }
270             }
271         }
272
273         self.tcx.rvalue_promotable_to_static.borrow_mut().insert(ex.id, self.promotable);
274         self.promotable &= outer;
275     }
276 }
277
278 /// This function is used to enforce the constraints on
279 /// const/static items. It walks through the *value*
280 /// of the item walking down the expression and evaluating
281 /// every nested expression. If the expression is not part
282 /// of a const/static item, it is qualified for promotion
283 /// instead of producing errors.
284 fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr, node_ty: Ty<'tcx>) {
285     match node_ty.sty {
286         ty::TyAdt(def, _) if def.has_dtor(v.tcx) => {
287             v.promotable = false;
288         }
289         _ => {}
290     }
291
292     match e.node {
293         hir::ExprUnary(..) |
294         hir::ExprBinary(..) |
295         hir::ExprIndex(..) if v.tables.is_method_call(e) => {
296             v.promotable = false;
297         }
298         hir::ExprBox(_) => {
299             v.promotable = false;
300         }
301         hir::ExprUnary(op, ref inner) => {
302             match v.tables.node_id_to_type(inner.hir_id).sty {
303                 ty::TyRawPtr(_) => {
304                     assert!(op == hir::UnDeref);
305
306                     v.promotable = false;
307                 }
308                 _ => {}
309             }
310         }
311         hir::ExprBinary(op, ref lhs, _) => {
312             match v.tables.node_id_to_type(lhs.hir_id).sty {
313                 ty::TyRawPtr(_) => {
314                     assert!(op.node == hir::BiEq || op.node == hir::BiNe ||
315                             op.node == hir::BiLe || op.node == hir::BiLt ||
316                             op.node == hir::BiGe || op.node == hir::BiGt);
317
318                     v.promotable = false;
319                 }
320                 _ => {}
321             }
322         }
323         hir::ExprCast(ref from, _) => {
324             debug!("Checking const cast(id={})", from.id);
325             match v.tables.cast_kinds().get(from.hir_id) {
326                 None => span_bug!(e.span, "no kind for cast"),
327                 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
328                     v.promotable = false;
329                 }
330                 _ => {}
331             }
332         }
333         hir::ExprPath(ref qpath) => {
334             let def = v.tables.qpath_def(qpath, e.hir_id);
335             match def {
336                 Def::VariantCtor(..) | Def::StructCtor(..) |
337                 Def::Fn(..) | Def::Method(..) =>  {}
338
339                 // References to a static are inherently promotable,
340                 // with the exception of "#[thread_loca]" statics.
341                 // The latter may not outlive the current function
342                 Def::Static(did, _) => {
343
344                     if v.in_static {
345                         let mut thread_local = false;
346
347                         for attr in &v.tcx.get_attrs(did)[..] {
348                             if attr.check_name("thread_local") {
349                                 debug!("Reference to Static(id={:?}) is unpromotable \
350                                        due to a #[thread_local] attribute", did);
351                                 v.promotable = false;
352                                 thread_local = true;
353                                 break;
354                             }
355                         }
356
357                         if !thread_local {
358                             debug!("Allowing promotion of reference to Static(id={:?})", did);
359                         }
360                     } else {
361                         debug!("Reference to Static(id={:?}) is unpromotable as it is not \
362                                referenced from a static", did);
363                         v.promotable = false;
364
365                     }
366                 }
367
368                 Def::Const(did) |
369                 Def::AssociatedConst(did) => {
370                     let promotable = if v.tcx.trait_of_item(did).is_some() {
371                         // Don't peek inside trait associated constants.
372                         false
373                     } else if let Some(node_id) = v.tcx.hir.as_local_node_id(did) {
374                         match v.tcx.hir.maybe_body_owned_by(node_id) {
375                             Some(body) => {
376                                 v.visit_nested_body(body);
377                                 v.tcx.rvalue_promotable_to_static.borrow()[&body.node_id]
378                             }
379                             None => false
380                         }
381                     } else {
382                         v.tcx.const_is_rvalue_promotable_to_static(did)
383                     };
384
385                     // Just in case the type is more specific than the definition,
386                     // e.g. impl associated const with type parameters, check it.
387                     // Also, trait associated consts are relaxed by this.
388                     v.promotable &= promotable || v.type_has_only_promotable_values(node_ty);
389                 }
390
391                 _ => {
392                     v.promotable = false;
393                 }
394             }
395         }
396         hir::ExprCall(ref callee, _) => {
397             let mut callee = &**callee;
398             loop {
399                 callee = match callee.node {
400                     hir::ExprBlock(ref block) => match block.expr {
401                         Some(ref tail) => &tail,
402                         None => break
403                     },
404                     _ => break
405                 };
406             }
407             // The callee is an arbitrary expression, it doesn't necessarily have a definition.
408             let def = if let hir::ExprPath(ref qpath) = callee.node {
409                 v.tables.qpath_def(qpath, callee.hir_id)
410             } else {
411                 Def::Err
412             };
413             match def {
414                 Def::StructCtor(_, CtorKind::Fn) |
415                 Def::VariantCtor(_, CtorKind::Fn) => {}
416                 Def::Fn(did) => {
417                     v.handle_const_fn_call(did, node_ty)
418                 }
419                 Def::Method(did) => {
420                     match v.tcx.associated_item(did).container {
421                         ty::ImplContainer(_) => {
422                             v.handle_const_fn_call(did, node_ty)
423                         }
424                         ty::TraitContainer(_) => v.promotable = false
425                     }
426                 }
427                 _ => v.promotable = false
428             }
429         }
430         hir::ExprMethodCall(..) => {
431             let def_id = v.tables.type_dependent_defs()[e.hir_id].def_id();
432             match v.tcx.associated_item(def_id).container {
433                 ty::ImplContainer(_) => v.handle_const_fn_call(def_id, node_ty),
434                 ty::TraitContainer(_) => v.promotable = false
435             }
436         }
437         hir::ExprStruct(..) => {
438             if let ty::TyAdt(adt, ..) = v.tables.expr_ty(e).sty {
439                 // unsafe_cell_type doesn't necessarily exist with no_core
440                 if Some(adt.did) == v.tcx.lang_items().unsafe_cell_type() {
441                     v.promotable = false;
442                 }
443             }
444         }
445
446         hir::ExprLit(_) |
447         hir::ExprAddrOf(..) |
448         hir::ExprRepeat(..) => {}
449
450         hir::ExprClosure(..) => {
451             // Paths in constant contexts cannot refer to local variables,
452             // as there are none, and thus closures can't have upvars there.
453             if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
454                 v.promotable = false;
455             }
456         }
457
458         hir::ExprBlock(_) |
459         hir::ExprIndex(..) |
460         hir::ExprField(..) |
461         hir::ExprTupField(..) |
462         hir::ExprArray(_) |
463         hir::ExprType(..) |
464         hir::ExprTup(..) => {}
465
466         // Conditional control flow (possible to implement).
467         hir::ExprMatch(..) |
468         hir::ExprIf(..) |
469
470         // Loops (not very meaningful in constants).
471         hir::ExprWhile(..) |
472         hir::ExprLoop(..) |
473
474         // More control flow (also not very meaningful).
475         hir::ExprBreak(..) |
476         hir::ExprAgain(_) |
477         hir::ExprRet(_) |
478
479         // Generator expressions
480         hir::ExprYield(_) |
481
482         // Expressions with side-effects.
483         hir::ExprAssign(..) |
484         hir::ExprAssignOp(..) |
485         hir::ExprInlineAsm(..) => {
486             v.promotable = false;
487         }
488     }
489 }
490
491 /// Check the adjustments of an expression
492 fn check_adjustments<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr) {
493     use rustc::ty::adjustment::*;
494
495     for adjustment in v.tables.expr_adjustments(e) {
496         match adjustment.kind {
497             Adjust::NeverToAny |
498             Adjust::ReifyFnPointer |
499             Adjust::UnsafeFnPointer |
500             Adjust::ClosureFnPointer |
501             Adjust::MutToConstPointer |
502             Adjust::Borrow(_) |
503             Adjust::Unsize => {}
504
505             Adjust::Deref(ref overloaded) => {
506                 if overloaded.is_some() {
507                     v.promotable = false;
508                     break;
509                 }
510             }
511         }
512     }
513 }
514
515 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
516     tcx.hir.krate().visit_all_item_likes(&mut CheckCrateVisitor {
517         tcx,
518         tables: &ty::TypeckTables::empty(None),
519         in_fn: false,
520         in_static: false,
521         promotable: false,
522         mut_rvalue_borrows: NodeSet(),
523         param_env: ty::ParamEnv::empty(Reveal::UserFacing),
524         identity_substs: Substs::empty(),
525     }.as_deep_visitor());
526     tcx.sess.abort_if_errors();
527 }
528
529 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> {
530     fn consume(&mut self,
531                _consume_id: ast::NodeId,
532                _consume_span: Span,
533                _cmt: mc::cmt,
534                _mode: euv::ConsumeMode) {}
535
536     fn borrow(&mut self,
537               borrow_id: ast::NodeId,
538               _borrow_span: Span,
539               cmt: mc::cmt<'tcx>,
540               _loan_region: ty::Region<'tcx>,
541               bk: ty::BorrowKind,
542               loan_cause: euv::LoanCause) {
543         // Kind of hacky, but we allow Unsafe coercions in constants.
544         // These occur when we convert a &T or *T to a *U, as well as
545         // when making a thin pointer (e.g., `*T`) into a fat pointer
546         // (e.g., `*Trait`).
547         match loan_cause {
548             euv::LoanCause::AutoUnsafe => {
549                 return;
550             }
551             _ => {}
552         }
553
554         let mut cur = &cmt;
555         loop {
556             match cur.cat {
557                 Categorization::Rvalue(..) => {
558                     if loan_cause == euv::MatchDiscriminant {
559                         // Ignore the dummy immutable borrow created by EUV.
560                         break;
561                     }
562                     if bk.to_mutbl_lossy() == hir::MutMutable {
563                         self.mut_rvalue_borrows.insert(borrow_id);
564                     }
565                     break;
566                 }
567                 Categorization::StaticItem => {
568                     break;
569                 }
570                 Categorization::Deref(ref cmt, _) |
571                 Categorization::Downcast(ref cmt, _) |
572                 Categorization::Interior(ref cmt, _) => {
573                     cur = cmt;
574                 }
575
576                 Categorization::Upvar(..) |
577                 Categorization::Local(..) => break,
578             }
579         }
580     }
581
582     fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {}
583     fn mutate(&mut self,
584               _assignment_id: ast::NodeId,
585               _assignment_span: Span,
586               _assignee_cmt: mc::cmt,
587               _mode: euv::MutateMode) {
588     }
589
590     fn matched_pat(&mut self, _: &hir::Pat, _: mc::cmt, _: euv::MatchMode) {}
591
592     fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: mc::cmt, _mode: euv::ConsumeMode) {}
593 }