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.
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.
11 // Verifies that the types and values of const and static items
12 // are safe. The rules enforced by this module are:
14 // - For each *mutable* static item, it checks that its **type**:
15 // - doesn't have a destructor
16 // - doesn't own a box
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
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
27 use rustc::ty::cast::CastKind;
28 use rustc::hir::def::{Def, CtorKind};
29 use rustc::hir::def_id::DefId;
30 use rustc::hir::map::blocks::FnLikeNode;
31 use rustc::middle::expr_use_visitor as euv;
32 use rustc::middle::mem_categorization as mc;
33 use rustc::middle::mem_categorization::Categorization;
34 use rustc::ty::{self, Ty, TyCtxt};
35 use rustc::ty::query::Providers;
36 use rustc::ty::subst::Substs;
37 use rustc::util::nodemap::{ItemLocalSet, NodeSet};
39 use rustc_data_structures::sync::Lrc;
42 use syntax_pos::{Span, DUMMY_SP};
43 use self::Promotability::*;
44 use std::ops::{BitAnd, BitOr};
47 pub fn provide(providers: &mut Providers) {
48 *providers = Providers {
49 rvalue_promotable_map,
50 const_is_rvalue_promotable_to_static,
55 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
56 for &body_id in &tcx.hir.krate().body_ids {
57 let def_id = tcx.hir.body_owner_def_id(body_id);
58 tcx.const_is_rvalue_promotable_to_static(def_id);
60 tcx.sess.abort_if_errors();
63 fn const_is_rvalue_promotable_to_static<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
67 assert!(def_id.is_local());
69 let node_id = tcx.hir.as_local_node_id(def_id)
70 .expect("rvalue_promotable_map invoked with non-local def-id");
71 let body_id = tcx.hir.body_owned_by(node_id);
72 let body_hir_id = tcx.hir.node_to_hir_id(body_id.node_id);
73 tcx.rvalue_promotable_map(def_id).contains(&body_hir_id.local_id)
76 fn rvalue_promotable_map<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
80 let outer_def_id = tcx.closure_base_def_id(def_id);
81 if outer_def_id != def_id {
82 return tcx.rvalue_promotable_map(outer_def_id);
85 let mut visitor = CheckCrateVisitor {
87 tables: &ty::TypeckTables::empty(None),
90 mut_rvalue_borrows: NodeSet(),
91 param_env: ty::ParamEnv::empty(),
92 identity_substs: Substs::empty(),
93 result: ItemLocalSet(),
96 // `def_id` should be a `Body` owner
97 let node_id = tcx.hir.as_local_node_id(def_id)
98 .expect("rvalue_promotable_map invoked with non-local def-id");
99 let body_id = tcx.hir.body_owned_by(node_id);
100 let _ = visitor.check_nested_body(body_id);
102 Lrc::new(visitor.result)
105 struct CheckCrateVisitor<'a, 'tcx: 'a> {
106 tcx: TyCtxt<'a, 'tcx, 'tcx>,
109 mut_rvalue_borrows: NodeSet,
110 param_env: ty::ParamEnv<'tcx>,
111 identity_substs: &'tcx Substs<'tcx>,
112 tables: &'a ty::TypeckTables<'tcx>,
113 result: ItemLocalSet,
117 #[derive(Debug, PartialEq)]
123 impl BitAnd for Promotability {
126 fn bitand(self, rhs: Self) -> Self {
128 (Promotable, NotPromotable) => NotPromotable,
129 (NotPromotable, Promotable) => NotPromotable,
130 (NotPromotable, NotPromotable) => NotPromotable,
131 (Promotable, Promotable) => Promotable,
136 impl BitOr for Promotability {
139 fn bitor(self, rhs: Self) -> Self {
141 (Promotable, NotPromotable) => Promotable,
142 (NotPromotable, Promotable) => Promotable,
143 (NotPromotable, NotPromotable) => NotPromotable,
144 (Promotable, Promotable) => Promotable,
149 impl<'a, 'gcx> CheckCrateVisitor<'a, 'gcx> {
150 // Returns true iff all the values of the type are promotable.
151 fn type_promotability(&mut self, ty: Ty<'gcx>) -> Promotability {
152 debug!("type_promotability({})", ty);
154 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) &&
155 !ty.needs_drop(self.tcx, self.param_env) {
162 fn handle_const_fn_call(&mut self, def_id: DefId,
163 ret_ty: Ty<'gcx>, span: Span) -> Promotability {
164 if let NotPromotable = self.type_promotability(ret_ty) {
165 return NotPromotable;
168 let node_check = if let Some(fn_id) = self.tcx.hir.as_local_node_id(def_id) {
169 FnLikeNode::from_node(self.tcx.hir.get(fn_id)).map_or(false, |fn_like| {
170 fn_like.constness() == hir::Constness::Const
173 self.tcx.is_const_fn(def_id)
180 if let Some(&attr::Stability {
181 rustc_const_unstable: Some(attr::RustcConstUnstable {
182 feature: ref feature_name
184 .. }) = self.tcx.lookup_stability(def_id) {
186 // feature-gate is enabled,
188 .declared_lib_features
190 .any(|&(ref sym, _)| sym == feature_name) ||
192 // this comes from a crate with the feature-gate enabled,
193 !def_id.is_local() ||
195 // this comes from a macro that has #[allow_internal_unstable]
196 span.allows_unstable();
204 /// While the `ExprUseVisitor` walks, we will identify which
205 /// expressions are borrowed, and insert their ids into this
206 /// table. Actually, we insert the "borrow-id", which is normally
207 /// the id of the expession being borrowed: but in the case of
208 /// `ref mut` borrows, the `id` of the pattern is
209 /// inserted. Therefore later we remove that entry from the table
210 /// and transfer it over to the value being matched. This will
211 /// then prevent said value from being promoted.
212 fn remove_mut_rvalue_borrow(&mut self, pat: &hir::Pat) -> bool {
213 let mut any_removed = false;
215 any_removed |= self.mut_rvalue_borrows.remove(&p.id);
222 impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> {
223 fn check_nested_body(&mut self, body_id: hir::BodyId) -> Promotability {
224 let item_id = self.tcx.hir.body_owner(body_id);
225 let item_def_id = self.tcx.hir.local_def_id(item_id);
227 let outer_in_fn = self.in_fn;
228 let outer_tables = self.tables;
229 let outer_param_env = self.param_env;
230 let outer_identity_substs = self.identity_substs;
233 self.in_static = false;
235 match self.tcx.hir.body_owner_kind(item_id) {
236 hir::BodyOwnerKind::Fn => self.in_fn = true,
237 hir::BodyOwnerKind::Static(_) => self.in_static = true,
242 self.tables = self.tcx.typeck_tables_of(item_def_id);
243 self.param_env = self.tcx.param_env(item_def_id);
244 self.identity_substs = Substs::identity_for_item(self.tcx, item_def_id);
246 let body = self.tcx.hir.body(body_id);
249 let param_env = self.param_env;
250 let region_scope_tree = self.tcx.region_scope_tree(item_def_id);
251 euv::ExprUseVisitor::new(self, tcx, param_env, ®ion_scope_tree, self.tables, None)
254 let body_promotable = self.check_expr(&body.value);
255 self.in_fn = outer_in_fn;
256 self.tables = outer_tables;
257 self.param_env = outer_param_env;
258 self.identity_substs = outer_identity_substs;
262 fn check_stmt(&mut self, stmt: &'tcx hir::Stmt) -> Promotability {
264 hir::StmtDecl(ref decl, _node_id) => {
266 hir::DeclLocal(local) => {
267 if self.remove_mut_rvalue_borrow(&local.pat) {
268 if let Some(init) = &local.init {
269 self.mut_rvalue_borrows.insert(init.id);
274 Some(ref expr) => { let _ = self.check_expr(&expr); },
279 // Item statements are allowed
280 hir::DeclItem(_) => Promotable
283 hir::StmtExpr(ref box_expr, _node_id) |
284 hir::StmtSemi(ref box_expr, _node_id) => {
285 let _ = self.check_expr(box_expr);
291 fn check_expr(&mut self, ex: &'tcx hir::Expr) -> Promotability {
292 let node_ty = self.tables.node_id_to_type(ex.hir_id);
293 let mut outer = check_expr_kind(self, ex, node_ty);
294 outer = outer & check_adjustments(self, ex);
296 // Handle borrows on (or inside the autorefs of) this expression.
297 if self.mut_rvalue_borrows.remove(&ex.id) {
298 outer = NotPromotable
301 if outer == Promotable {
302 self.result.insert(ex.hir_id.local_id);
307 fn check_block(&mut self, block: &'tcx hir::Block) -> Promotability {
308 let mut iter_result = Promotable;
309 for index in block.stmts.iter() {
310 iter_result = iter_result & self.check_stmt(index);
313 Some(ref box_expr) => iter_result & self.check_expr(&*box_expr),
319 /// This function is used to enforce the constraints on
320 /// const/static items. It walks through the *value*
321 /// of the item walking down the expression and evaluating
322 /// every nested expression. If the expression is not part
323 /// of a const/static item, it is qualified for promotion
324 /// instead of producing errors.
325 fn check_expr_kind<'a, 'tcx>(
326 v: &mut CheckCrateVisitor<'a, 'tcx>,
327 e: &'tcx hir::Expr, node_ty: Ty<'tcx>) -> Promotability {
329 let ty_result = match node_ty.sty {
330 ty::TyAdt(def, _) if def.has_dtor(v.tcx) => {
336 let node_result = match e.node {
337 hir::ExprBox(ref expr) => {
338 let _ = v.check_expr(&expr);
341 hir::ExprUnary(op, ref expr) => {
342 let expr_promotability = v.check_expr(expr);
343 if v.tables.is_method_call(e) {
344 return NotPromotable;
346 if op == hir::UnDeref {
347 return NotPromotable;
351 hir::ExprBinary(op, ref lhs, ref rhs) => {
352 let lefty = v.check_expr(lhs);
353 let righty = v.check_expr(rhs);
354 if v.tables.is_method_call(e) {
355 return NotPromotable;
357 match v.tables.node_id_to_type(lhs.hir_id).sty {
359 assert!(op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne ||
360 op.node == hir::BinOpKind::Le || op.node == hir::BinOpKind::Lt ||
361 op.node == hir::BinOpKind::Ge || op.node == hir::BinOpKind::Gt);
368 hir::ExprCast(ref from, _) => {
369 let expr_promotability = v.check_expr(from);
370 debug!("Checking const cast(id={})", from.id);
371 match v.tables.cast_kinds().get(from.hir_id) {
373 v.tcx.sess.delay_span_bug(e.span, "no kind for cast");
376 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
379 _ => expr_promotability
382 hir::ExprPath(ref qpath) => {
383 let def = v.tables.qpath_def(qpath, e.hir_id);
385 Def::VariantCtor(..) | Def::StructCtor(..) |
386 Def::Fn(..) | Def::Method(..) => Promotable,
388 // References to a static that are themselves within a static
389 // are inherently promotable with the exception
390 // of "#[thread_local]" statics, which may not
391 // outlive the current function
392 Def::Static(did, _) => {
395 for attr in &v.tcx.get_attrs(did)[..] {
396 if attr.check_name("thread_local") {
397 debug!("Reference to Static(id={:?}) is unpromotable \
398 due to a #[thread_local] attribute", did);
399 return NotPromotable;
404 debug!("Reference to Static(id={:?}) is unpromotable as it is not \
405 referenced from a static", did);
412 Def::AssociatedConst(did) => {
413 let promotable = if v.tcx.trait_of_item(did).is_some() {
414 // Don't peek inside trait associated constants.
416 } else if v.tcx.at(e.span).const_is_rvalue_promotable_to_static(did) {
421 // Just in case the type is more specific than the definition,
422 // e.g. impl associated const with type parameters, check it.
423 // Also, trait associated consts are relaxed by this.
424 promotable | v.type_promotability(node_ty)
429 hir::ExprCall(ref callee, ref hirvec) => {
430 let mut call_result = v.check_expr(callee);
431 for index in hirvec.iter() {
432 call_result = call_result & v.check_expr(index);
434 let mut callee = &**callee;
436 callee = match callee.node {
437 hir::ExprBlock(ref block, _) => match block.expr {
438 Some(ref tail) => &tail,
444 // The callee is an arbitrary expression, it doesn't necessarily have a definition.
445 let def = if let hir::ExprPath(ref qpath) = callee.node {
446 v.tables.qpath_def(qpath, callee.hir_id)
450 let def_result = match def {
451 Def::StructCtor(_, CtorKind::Fn) |
452 Def::VariantCtor(_, CtorKind::Fn) => Promotable,
454 v.handle_const_fn_call(did, node_ty, e.span)
456 Def::Method(did) => {
457 match v.tcx.associated_item(did).container {
458 ty::ImplContainer(_) => {
459 v.handle_const_fn_call(did, node_ty, e.span)
461 ty::TraitContainer(_) => NotPromotable,
466 def_result & call_result
468 hir::ExprMethodCall(ref _pathsegment, ref _span, ref hirvec) => {
469 let mut method_call_result = Promotable;
470 for index in hirvec.iter() {
471 method_call_result = method_call_result & v.check_expr(index);
473 if let Some(def) = v.tables.type_dependent_defs().get(e.hir_id) {
474 let def_id = def.def_id();
475 match v.tcx.associated_item(def_id).container {
476 ty::ImplContainer(_) => {
477 method_call_result = method_call_result
478 & v.handle_const_fn_call(def_id, node_ty, e.span);
480 ty::TraitContainer(_) => return NotPromotable,
483 v.tcx.sess.delay_span_bug(e.span, "no type-dependent def for method call");
487 hir::ExprStruct(ref _qpath, ref hirvec, ref option_expr) => {
488 let mut struct_result = Promotable;
489 for index in hirvec.iter() {
490 struct_result = struct_result & v.check_expr(&index.expr);
493 Some(ref expr) => { struct_result = struct_result & v.check_expr(&expr); },
496 if let ty::TyAdt(adt, ..) = v.tables.expr_ty(e).sty {
497 // unsafe_cell_type doesn't necessarily exist with no_core
498 if Some(adt.did) == v.tcx.lang_items().unsafe_cell_type() {
499 return NotPromotable;
505 hir::ExprLit(_) => Promotable,
507 hir::ExprAddrOf(_, ref expr) |
508 hir::ExprRepeat(ref expr, _) => {
512 hir::ExprClosure(_capture_clause, ref _box_fn_decl,
513 body_id, _span, _option_generator_movability) => {
514 let nested_body_promotable = v.check_nested_body(body_id);
515 // Paths in constant contexts cannot refer to local variables,
516 // as there are none, and thus closures can't have upvars there.
517 if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
520 nested_body_promotable
524 hir::ExprField(ref expr, _ident) => {
525 let expr_promotability = v.check_expr(&expr);
526 if let Some(def) = v.tables.expr_ty(expr).ty_adt_def() {
528 return NotPromotable;
534 hir::ExprBlock(ref box_block, ref _option_label) => {
535 v.check_block(box_block)
538 hir::ExprIndex(ref lhs, ref rhs) => {
539 let lefty = v.check_expr(lhs);
540 let righty = v.check_expr(rhs);
541 if v.tables.is_method_call(e) {
542 return NotPromotable;
547 hir::ExprArray(ref hirvec) => {
548 let mut array_result = Promotable;
549 for index in hirvec.iter() {
550 array_result = array_result & v.check_expr(index);
555 hir::ExprType(ref expr, ref _ty) => {
559 hir::ExprTup(ref hirvec) => {
560 let mut tup_result = Promotable;
561 for index in hirvec.iter() {
562 tup_result = tup_result & v.check_expr(index);
568 // Conditional control flow (possible to implement).
569 hir::ExprMatch(ref expr, ref hirvec_arm, ref _match_source) => {
570 // Compute the most demanding borrow from all the arms'
571 // patterns and set that on the discriminator.
572 let mut mut_borrow = false;
573 for pat in hirvec_arm.iter().flat_map(|arm| &arm.pats) {
574 mut_borrow = v.remove_mut_rvalue_borrow(pat);
577 v.mut_rvalue_borrows.insert(expr.id);
580 let _ = v.check_expr(expr);
581 for index in hirvec_arm.iter() {
582 let _ = v.check_expr(&*index.body);
585 let _ = v.check_expr(&expr);
593 hir::ExprIf(ref lhs, ref rhs, ref option_expr) => {
594 let _ = v.check_expr(lhs);
595 let _ = v.check_expr(rhs);
597 Some(ref expr) => { let _ = v.check_expr(&expr); },
603 // Loops (not very meaningful in constants).
604 hir::ExprWhile(ref expr, ref box_block, ref _option_label) => {
605 let _ = v.check_expr(expr);
606 let _ = v.check_block(box_block);
610 hir::ExprLoop(ref box_block, ref _option_label, ref _loop_source) => {
611 let _ = v.check_block(box_block);
615 // More control flow (also not very meaningful).
616 hir::ExprBreak(_, ref option_expr) | hir::ExprRet(ref option_expr) => {
618 Some(ref expr) => { let _ = v.check_expr(&expr); },
624 hir::ExprContinue(_) => {
628 // Generator expressions
629 hir::ExprYield(ref expr) => {
630 let _ = v.check_expr(&expr);
634 // Expressions with side-effects.
635 hir::ExprAssignOp(_, ref lhs, ref rhs) | hir::ExprAssign(ref lhs, ref rhs) => {
636 let _ = v.check_expr(lhs);
637 let _ = v.check_expr(rhs);
641 hir::ExprInlineAsm(ref _inline_asm, ref hirvec_lhs, ref hirvec_rhs) => {
642 for index in hirvec_lhs.iter() {
643 let _ = v.check_expr(index);
645 for index in hirvec_rhs.iter() {
646 let _ = v.check_expr(index);
651 ty_result & node_result
654 /// Check the adjustments of an expression
655 fn check_adjustments<'a, 'tcx>(
656 v: &mut CheckCrateVisitor<'a, 'tcx>,
657 e: &hir::Expr) -> Promotability {
658 use rustc::ty::adjustment::*;
660 let mut adjustments = v.tables.expr_adjustments(e).iter().peekable();
661 while let Some(adjustment) = adjustments.next() {
662 match adjustment.kind {
664 Adjust::ReifyFnPointer |
665 Adjust::UnsafeFnPointer |
666 Adjust::ClosureFnPointer |
667 Adjust::MutToConstPointer |
671 Adjust::Deref(_) => {
672 if let Some(next_adjustment) = adjustments.peek() {
673 if let Adjust::Borrow(_) = next_adjustment.kind {
677 return NotPromotable;
684 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> {
685 fn consume(&mut self,
686 _consume_id: ast::NodeId,
689 _mode: euv::ConsumeMode) {}
692 borrow_id: ast::NodeId,
694 cmt: &mc::cmt_<'tcx>,
695 _loan_region: ty::Region<'tcx>,
697 loan_cause: euv::LoanCause) {
699 "borrow(borrow_id={:?}, cmt={:?}, bk={:?}, loan_cause={:?})",
706 // Kind of hacky, but we allow Unsafe coercions in constants.
707 // These occur when we convert a &T or *T to a *U, as well as
708 // when making a thin pointer (e.g., `*T`) into a fat pointer
711 euv::LoanCause::AutoUnsafe => {
720 Categorization::Rvalue(..) => {
721 if loan_cause == euv::MatchDiscriminant {
722 // Ignore the dummy immutable borrow created by EUV.
725 if bk.to_mutbl_lossy() == hir::MutMutable {
726 self.mut_rvalue_borrows.insert(borrow_id);
730 Categorization::StaticItem => {
733 Categorization::Deref(ref cmt, _) |
734 Categorization::Downcast(ref cmt, _) |
735 Categorization::Interior(ref cmt, _) => {
739 Categorization::Upvar(..) |
740 Categorization::Local(..) => break,
745 fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {}
747 _assignment_id: ast::NodeId,
748 _assignment_span: Span,
749 _assignee_cmt: &mc::cmt_,
750 _mode: euv::MutateMode) {
753 fn matched_pat(&mut self, _: &hir::Pat, _: &mc::cmt_, _: euv::MatchMode) {}
755 fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: &mc::cmt_, _mode: euv::ConsumeMode) {}