1 // Verifies that the types and values of const and static items
2 // are safe. The rules enforced by this module are:
4 // - For each *mutable* static item, it checks that its **type**:
5 // - doesn't have a destructor
8 // - For each *immutable* static item, it checks that its **value**:
10 // - doesn't contain a struct literal or a call to an enum variant / struct constructor where
11 // - the type of the struct/enum has a dtor
13 // Rules Enforced Elsewhere:
14 // - It's not possible to take the address of a static item with unsafe interior. This is enforced
15 // by borrowck::gather_loans
17 use rustc::ty::cast::CastKind;
18 use rustc::hir::def::{Def, CtorKind};
19 use rustc::hir::def_id::DefId;
20 use rustc::middle::expr_use_visitor as euv;
21 use rustc::middle::mem_categorization as mc;
22 use rustc::middle::mem_categorization::Categorization;
23 use rustc::ty::{self, Ty, TyCtxt};
24 use rustc::ty::query::Providers;
25 use rustc::ty::subst::Substs;
26 use rustc::util::nodemap::{ItemLocalSet, NodeSet};
28 use rustc_data_structures::sync::Lrc;
30 use syntax_pos::{Span, DUMMY_SP};
31 use self::Promotability::*;
32 use std::ops::{BitAnd, BitAndAssign, BitOr};
34 pub fn provide(providers: &mut Providers) {
35 *providers = Providers {
36 rvalue_promotable_map,
37 const_is_rvalue_promotable_to_static,
42 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
43 for &body_id in &tcx.hir().krate().body_ids {
44 let def_id = tcx.hir().body_owner_def_id(body_id);
45 tcx.const_is_rvalue_promotable_to_static(def_id);
49 fn const_is_rvalue_promotable_to_static<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
53 assert!(def_id.is_local());
55 let node_id = tcx.hir().as_local_node_id(def_id)
56 .expect("rvalue_promotable_map invoked with non-local def-id");
57 let body_id = tcx.hir().body_owned_by(node_id);
58 let body_hir_id = tcx.hir().node_to_hir_id(body_id.node_id);
59 tcx.rvalue_promotable_map(def_id).contains(&body_hir_id.local_id)
62 fn rvalue_promotable_map<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
66 let outer_def_id = tcx.closure_base_def_id(def_id);
67 if outer_def_id != def_id {
68 return tcx.rvalue_promotable_map(outer_def_id);
71 let mut visitor = CheckCrateVisitor {
73 tables: &ty::TypeckTables::empty(None),
76 mut_rvalue_borrows: Default::default(),
77 param_env: ty::ParamEnv::empty(),
78 identity_substs: Substs::empty(),
79 result: ItemLocalSet::default(),
82 // `def_id` should be a `Body` owner
83 let node_id = tcx.hir().as_local_node_id(def_id)
84 .expect("rvalue_promotable_map invoked with non-local def-id");
85 let body_id = tcx.hir().body_owned_by(node_id);
86 let _ = visitor.check_nested_body(body_id);
88 Lrc::new(visitor.result)
91 struct CheckCrateVisitor<'a, 'tcx: 'a> {
92 tcx: TyCtxt<'a, 'tcx, 'tcx>,
95 mut_rvalue_borrows: NodeSet,
96 param_env: ty::ParamEnv<'tcx>,
97 identity_substs: &'tcx Substs<'tcx>,
98 tables: &'a ty::TypeckTables<'tcx>,
103 #[derive(Debug, Clone, Copy, PartialEq)]
109 impl BitAnd for Promotability {
112 fn bitand(self, rhs: Self) -> Self {
114 (Promotable, Promotable) => Promotable,
120 impl BitAndAssign for Promotability {
121 fn bitand_assign(&mut self, rhs: Self) {
126 impl BitOr for Promotability {
129 fn bitor(self, rhs: Self) -> Self {
131 (NotPromotable, NotPromotable) => NotPromotable,
137 impl<'a, 'gcx> CheckCrateVisitor<'a, 'gcx> {
138 // Returns true iff all the values of the type are promotable.
139 fn type_promotability(&mut self, ty: Ty<'gcx>) -> Promotability {
140 debug!("type_promotability({})", ty);
142 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) &&
143 !ty.needs_drop(self.tcx, self.param_env) {
150 fn handle_const_fn_call(
154 if self.tcx.is_promotable_const_fn(def_id) {
161 /// While the `ExprUseVisitor` walks, we will identify which
162 /// expressions are borrowed, and insert their ids into this
163 /// table. Actually, we insert the "borrow-id", which is normally
164 /// the id of the expression being borrowed: but in the case of
165 /// `ref mut` borrows, the `id` of the pattern is
166 /// inserted. Therefore later we remove that entry from the table
167 /// and transfer it over to the value being matched. This will
168 /// then prevent said value from being promoted.
169 fn remove_mut_rvalue_borrow(&mut self, pat: &hir::Pat) -> bool {
170 let mut any_removed = false;
172 any_removed |= self.mut_rvalue_borrows.remove(&p.id);
179 impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> {
180 fn check_nested_body(&mut self, body_id: hir::BodyId) -> Promotability {
181 let item_id = self.tcx.hir().body_owner(body_id);
182 let item_def_id = self.tcx.hir().local_def_id(item_id);
184 let outer_in_fn = self.in_fn;
185 let outer_tables = self.tables;
186 let outer_param_env = self.param_env;
187 let outer_identity_substs = self.identity_substs;
190 self.in_static = false;
192 match self.tcx.hir().body_owner_kind(item_id) {
193 hir::BodyOwnerKind::Closure |
194 hir::BodyOwnerKind::Fn => self.in_fn = true,
195 hir::BodyOwnerKind::Static(_) => self.in_static = true,
200 self.tables = self.tcx.typeck_tables_of(item_def_id);
201 self.param_env = self.tcx.param_env(item_def_id);
202 self.identity_substs = Substs::identity_for_item(self.tcx, item_def_id);
204 let body = self.tcx.hir().body(body_id);
207 let param_env = self.param_env;
208 let region_scope_tree = self.tcx.region_scope_tree(item_def_id);
209 let tables = self.tables;
210 euv::ExprUseVisitor::new(self, tcx, param_env, ®ion_scope_tree, tables, None)
213 let body_promotable = self.check_expr(&body.value);
214 self.in_fn = outer_in_fn;
215 self.tables = outer_tables;
216 self.param_env = outer_param_env;
217 self.identity_substs = outer_identity_substs;
221 fn check_stmt(&mut self, stmt: &'tcx hir::Stmt) -> Promotability {
223 hir::StmtKind::Local(ref local) => {
224 if self.remove_mut_rvalue_borrow(&local.pat) {
225 if let Some(init) = &local.init {
226 self.mut_rvalue_borrows.insert(init.id);
230 if let Some(ref expr) = local.init {
231 let _ = self.check_expr(&expr);
235 // Item statements are allowed
236 hir::StmtKind::Item(..) => Promotable,
237 hir::StmtKind::Expr(ref box_expr) |
238 hir::StmtKind::Semi(ref box_expr) => {
239 let _ = self.check_expr(box_expr);
245 fn check_expr(&mut self, ex: &'tcx hir::Expr) -> Promotability {
246 let node_ty = self.tables.node_id_to_type(ex.hir_id);
247 let mut outer = check_expr_kind(self, ex, node_ty);
248 outer &= check_adjustments(self, ex);
250 // Handle borrows on (or inside the autorefs of) this expression.
251 if self.mut_rvalue_borrows.remove(&ex.id) {
252 outer = NotPromotable
255 if outer == Promotable {
256 self.result.insert(ex.hir_id.local_id);
261 fn check_block(&mut self, block: &'tcx hir::Block) -> Promotability {
262 let mut iter_result = Promotable;
263 for index in block.stmts.iter() {
264 iter_result &= self.check_stmt(index);
267 Some(ref box_expr) => iter_result & self.check_expr(&*box_expr),
273 /// This function is used to enforce the constraints on
274 /// const/static items. It walks through the *value*
275 /// of the item walking down the expression and evaluating
276 /// every nested expression. If the expression is not part
277 /// of a const/static item, it is qualified for promotion
278 /// instead of producing errors.
279 fn check_expr_kind<'a, 'tcx>(
280 v: &mut CheckCrateVisitor<'a, 'tcx>,
281 e: &'tcx hir::Expr, node_ty: Ty<'tcx>) -> Promotability {
283 let ty_result = match node_ty.sty {
284 ty::Adt(def, _) if def.has_dtor(v.tcx) => {
290 let node_result = match e.node {
291 hir::ExprKind::Box(ref expr) => {
292 let _ = v.check_expr(&expr);
295 hir::ExprKind::Unary(op, ref expr) => {
296 let expr_promotability = v.check_expr(expr);
297 if v.tables.is_method_call(e) || op == hir::UnDeref {
298 return NotPromotable;
302 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
303 let lefty = v.check_expr(lhs);
304 let righty = v.check_expr(rhs);
305 if v.tables.is_method_call(e) {
306 return NotPromotable;
308 match v.tables.node_id_to_type(lhs.hir_id).sty {
309 ty::RawPtr(_) | ty::FnPtr(..) => {
310 assert!(op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne ||
311 op.node == hir::BinOpKind::Le || op.node == hir::BinOpKind::Lt ||
312 op.node == hir::BinOpKind::Ge || op.node == hir::BinOpKind::Gt);
319 hir::ExprKind::Cast(ref from, _) => {
320 let expr_promotability = v.check_expr(from);
321 debug!("Checking const cast(id={})", from.id);
322 match v.tables.cast_kinds().get(from.hir_id) {
324 v.tcx.sess.delay_span_bug(e.span, "no kind for cast");
327 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
330 _ => expr_promotability
333 hir::ExprKind::Path(ref qpath) => {
334 let def = v.tables.qpath_def(qpath, e.hir_id);
336 Def::VariantCtor(..) | Def::StructCtor(..) |
337 Def::Fn(..) | Def::Method(..) | Def::SelfCtor(..) => Promotable,
339 // References to a static that are themselves within a static
340 // are inherently promotable with the exception
341 // of "#[thread_local]" statics, which may not
342 // outlive the current function
343 Def::Static(did, _) => {
346 for attr in &v.tcx.get_attrs(did)[..] {
347 if attr.check_name("thread_local") {
348 debug!("Reference to Static(id={:?}) is unpromotable \
349 due to a #[thread_local] attribute", did);
350 return NotPromotable;
355 debug!("Reference to Static(id={:?}) is unpromotable as it is not \
356 referenced from a static", did);
362 Def::AssociatedConst(did) => {
363 let promotable = if v.tcx.trait_of_item(did).is_some() {
364 // Don't peek inside trait associated constants.
366 } else if v.tcx.at(e.span).const_is_rvalue_promotable_to_static(did) {
371 // Just in case the type is more specific than the definition,
372 // e.g., impl associated const with type parameters, check it.
373 // Also, trait associated consts are relaxed by this.
374 promotable | v.type_promotability(node_ty)
379 hir::ExprKind::Call(ref callee, ref hirvec) => {
380 let mut call_result = v.check_expr(callee);
381 for index in hirvec.iter() {
382 call_result &= v.check_expr(index);
384 let mut callee = &**callee;
386 callee = match callee.node {
387 hir::ExprKind::Block(ref block, _) => match block.expr {
388 Some(ref tail) => &tail,
394 // The callee is an arbitrary expression, it doesn't necessarily have a definition.
395 let def = if let hir::ExprKind::Path(ref qpath) = callee.node {
396 v.tables.qpath_def(qpath, callee.hir_id)
400 let def_result = match def {
401 Def::StructCtor(_, CtorKind::Fn) |
402 Def::VariantCtor(_, CtorKind::Fn) |
403 Def::SelfCtor(..) => Promotable,
404 Def::Fn(did) => v.handle_const_fn_call(did),
405 Def::Method(did) => {
406 match v.tcx.associated_item(did).container {
407 ty::ImplContainer(_) => v.handle_const_fn_call(did),
408 ty::TraitContainer(_) => NotPromotable,
413 def_result & call_result
415 hir::ExprKind::MethodCall(ref _pathsegment, ref _span, ref hirvec) => {
416 let mut method_call_result = Promotable;
417 for index in hirvec.iter() {
418 method_call_result &= v.check_expr(index);
420 if let Some(def) = v.tables.type_dependent_defs().get(e.hir_id) {
421 let def_id = def.def_id();
422 match v.tcx.associated_item(def_id).container {
423 ty::ImplContainer(_) => method_call_result & v.handle_const_fn_call(def_id),
424 ty::TraitContainer(_) => NotPromotable,
427 v.tcx.sess.delay_span_bug(e.span, "no type-dependent def for method call");
431 hir::ExprKind::Struct(ref _qpath, ref hirvec, ref option_expr) => {
432 let mut struct_result = Promotable;
433 for index in hirvec.iter() {
434 struct_result &= v.check_expr(&index.expr);
436 if let Some(ref expr) = *option_expr {
437 struct_result &= v.check_expr(&expr);
439 if let ty::Adt(adt, ..) = v.tables.expr_ty(e).sty {
440 // unsafe_cell_type doesn't necessarily exist with no_core
441 if Some(adt.did) == v.tcx.lang_items().unsafe_cell_type() {
442 return NotPromotable;
448 hir::ExprKind::Lit(_) |
449 hir::ExprKind::Err => Promotable,
451 hir::ExprKind::AddrOf(_, ref expr) |
452 hir::ExprKind::Repeat(ref expr, _) => {
456 hir::ExprKind::Closure(_capture_clause, ref _box_fn_decl,
457 body_id, _span, _option_generator_movability) => {
458 let nested_body_promotable = v.check_nested_body(body_id);
459 // Paths in constant contexts cannot refer to local variables,
460 // as there are none, and thus closures can't have upvars there.
461 if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
464 nested_body_promotable
468 hir::ExprKind::Field(ref expr, _ident) => {
469 let expr_promotability = v.check_expr(&expr);
470 if let Some(def) = v.tables.expr_ty(expr).ty_adt_def() {
472 return NotPromotable;
478 hir::ExprKind::Block(ref box_block, ref _option_label) => {
479 v.check_block(box_block)
482 hir::ExprKind::Index(ref lhs, ref rhs) => {
483 let lefty = v.check_expr(lhs);
484 let righty = v.check_expr(rhs);
485 if v.tables.is_method_call(e) {
486 return NotPromotable;
491 hir::ExprKind::Array(ref hirvec) => {
492 let mut array_result = Promotable;
493 for index in hirvec.iter() {
494 array_result &= v.check_expr(index);
499 hir::ExprKind::Type(ref expr, ref _ty) => {
503 hir::ExprKind::Tup(ref hirvec) => {
504 let mut tup_result = Promotable;
505 for index in hirvec.iter() {
506 tup_result &= v.check_expr(index);
512 // Conditional control flow (possible to implement).
513 hir::ExprKind::Match(ref expr, ref hirvec_arm, ref _match_source) => {
514 // Compute the most demanding borrow from all the arms'
515 // patterns and set that on the discriminator.
516 let mut mut_borrow = false;
517 for pat in hirvec_arm.iter().flat_map(|arm| &arm.pats) {
518 mut_borrow = v.remove_mut_rvalue_borrow(pat);
521 v.mut_rvalue_borrows.insert(expr.id);
524 let _ = v.check_expr(expr);
525 for index in hirvec_arm.iter() {
526 let _ = v.check_expr(&*index.body);
527 if let Some(hir::Guard::If(ref expr)) = index.guard {
528 let _ = v.check_expr(&expr);
534 hir::ExprKind::If(ref lhs, ref rhs, ref option_expr) => {
535 let _ = v.check_expr(lhs);
536 let _ = v.check_expr(rhs);
537 if let Some(ref expr) = option_expr {
538 let _ = v.check_expr(&expr);
543 // Loops (not very meaningful in constants).
544 hir::ExprKind::While(ref expr, ref box_block, ref _option_label) => {
545 let _ = v.check_expr(expr);
546 let _ = v.check_block(box_block);
550 hir::ExprKind::Loop(ref box_block, ref _option_label, ref _loop_source) => {
551 let _ = v.check_block(box_block);
555 // More control flow (also not very meaningful).
556 hir::ExprKind::Break(_, ref option_expr) | hir::ExprKind::Ret(ref option_expr) => {
557 if let Some(ref expr) = *option_expr {
558 let _ = v.check_expr(&expr);
563 hir::ExprKind::Continue(_) => {
567 // Generator expressions
568 hir::ExprKind::Yield(ref expr) => {
569 let _ = v.check_expr(&expr);
573 // Expressions with side-effects.
574 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) | hir::ExprKind::Assign(ref lhs, ref rhs) => {
575 let _ = v.check_expr(lhs);
576 let _ = v.check_expr(rhs);
580 hir::ExprKind::InlineAsm(ref _inline_asm, ref hirvec_lhs, ref hirvec_rhs) => {
581 for index in hirvec_lhs.iter().chain(hirvec_rhs.iter()) {
582 let _ = v.check_expr(index);
587 ty_result & node_result
590 /// Check the adjustments of an expression
591 fn check_adjustments<'a, 'tcx>(
592 v: &mut CheckCrateVisitor<'a, 'tcx>,
593 e: &hir::Expr) -> Promotability {
594 use rustc::ty::adjustment::*;
596 let mut adjustments = v.tables.expr_adjustments(e).iter().peekable();
597 while let Some(adjustment) = adjustments.next() {
598 match adjustment.kind {
600 Adjust::ReifyFnPointer |
601 Adjust::UnsafeFnPointer |
602 Adjust::ClosureFnPointer |
603 Adjust::MutToConstPointer |
607 Adjust::Deref(_) => {
608 if let Some(next_adjustment) = adjustments.peek() {
609 if let Adjust::Borrow(_) = next_adjustment.kind {
613 return NotPromotable;
620 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> {
621 fn consume(&mut self,
622 _consume_id: ast::NodeId,
625 _mode: euv::ConsumeMode) {}
628 borrow_id: ast::NodeId,
630 cmt: &mc::cmt_<'tcx>,
631 _loan_region: ty::Region<'tcx>,
633 loan_cause: euv::LoanCause) {
635 "borrow(borrow_id={:?}, cmt={:?}, bk={:?}, loan_cause={:?})",
642 // Kind of hacky, but we allow Unsafe coercions in constants.
643 // These occur when we convert a &T or *T to a *U, as well as
644 // when making a thin pointer (e.g., `*T`) into a fat pointer
646 if let euv::LoanCause::AutoUnsafe = loan_cause {
653 Categorization::ThreadLocal(..) |
654 Categorization::Rvalue(..) => {
655 if loan_cause == euv::MatchDiscriminant {
656 // Ignore the dummy immutable borrow created by EUV.
659 if bk.to_mutbl_lossy() == hir::MutMutable {
660 self.mut_rvalue_borrows.insert(borrow_id);
664 Categorization::StaticItem => {
667 Categorization::Deref(ref cmt, _) |
668 Categorization::Downcast(ref cmt, _) |
669 Categorization::Interior(ref cmt, _) => {
673 Categorization::Upvar(..) |
674 Categorization::Local(..) => break,
679 fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {}
681 _assignment_id: ast::NodeId,
682 _assignment_span: Span,
683 _assignee_cmt: &mc::cmt_,
684 _mode: euv::MutateMode) {
687 fn matched_pat(&mut self, _: &hir::Pat, _: &mc::cmt_, _: euv::MatchMode) {}
689 fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: &mc::cmt_, _mode: euv::ConsumeMode) {}