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::CastTy;
18 use rustc::hir::def::{Res, DefKind, 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::{InternalSubsts, SubstsRef};
26 use rustc::util::nodemap::{ItemLocalSet, HirIdSet};
28 use syntax::symbol::sym;
29 use syntax_pos::{Span, DUMMY_SP};
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 fn const_is_rvalue_promotable_to_static(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
43 assert!(def_id.is_local());
45 let hir_id = tcx.hir().as_local_hir_id(def_id)
46 .expect("rvalue_promotable_map invoked with non-local def-id");
47 let body_id = tcx.hir().body_owned_by(hir_id);
48 tcx.rvalue_promotable_map(def_id).contains(&body_id.hir_id.local_id)
51 fn rvalue_promotable_map(tcx: TyCtxt<'_>, def_id: DefId) -> &ItemLocalSet {
52 let outer_def_id = tcx.closure_base_def_id(def_id);
53 if outer_def_id != def_id {
54 return tcx.rvalue_promotable_map(outer_def_id);
57 let mut visitor = CheckCrateVisitor {
59 tables: &ty::TypeckTables::empty(None),
62 mut_rvalue_borrows: Default::default(),
63 param_env: ty::ParamEnv::empty(),
64 identity_substs: InternalSubsts::empty(),
65 result: ItemLocalSet::default(),
68 // `def_id` should be a `Body` owner
69 let hir_id = tcx.hir().as_local_hir_id(def_id)
70 .expect("rvalue_promotable_map invoked with non-local def-id");
71 let body_id = tcx.hir().body_owned_by(hir_id);
72 let _ = visitor.check_nested_body(body_id);
74 tcx.arena.alloc(visitor.result)
77 struct CheckCrateVisitor<'a, 'tcx> {
81 mut_rvalue_borrows: HirIdSet,
82 param_env: ty::ParamEnv<'tcx>,
83 identity_substs: SubstsRef<'tcx>,
84 tables: &'a ty::TypeckTables<'tcx>,
89 #[derive(Debug, Clone, Copy, PartialEq)]
95 impl BitAnd for Promotability {
98 fn bitand(self, rhs: Self) -> Self {
100 (Promotable, Promotable) => Promotable,
106 impl BitAndAssign for Promotability {
107 fn bitand_assign(&mut self, rhs: Self) {
112 impl BitOr for Promotability {
115 fn bitor(self, rhs: Self) -> Self {
117 (NotPromotable, NotPromotable) => NotPromotable,
123 impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> {
124 // Returns true iff all the values of the type are promotable.
125 fn type_promotability(&mut self, ty: Ty<'tcx>) -> Promotability {
126 debug!("type_promotability({})", ty);
128 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) &&
129 !ty.needs_drop(self.tcx, self.param_env) {
136 fn handle_const_fn_call(
140 if self.tcx.is_promotable_const_fn(def_id) {
147 /// While the `ExprUseVisitor` walks, we will identify which
148 /// expressions are borrowed, and insert their IDs into this
149 /// table. Actually, we insert the "borrow-id", which is normally
150 /// the ID of the expression being borrowed: but in the case of
151 /// `ref mut` borrows, the `id` of the pattern is
152 /// inserted. Therefore, later we remove that entry from the table
153 /// and transfer it over to the value being matched. This will
154 /// then prevent said value from being promoted.
155 fn remove_mut_rvalue_borrow(&mut self, pat: &hir::Pat) -> bool {
156 let mut any_removed = false;
158 any_removed |= self.mut_rvalue_borrows.remove(&p.hir_id);
165 impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> {
166 fn check_nested_body(&mut self, body_id: hir::BodyId) -> Promotability {
167 let item_id = self.tcx.hir().body_owner(body_id);
168 let item_def_id = self.tcx.hir().local_def_id(item_id);
170 let outer_in_fn = self.in_fn;
171 let outer_tables = self.tables;
172 let outer_param_env = self.param_env;
173 let outer_identity_substs = self.identity_substs;
176 self.in_static = false;
178 match self.tcx.hir().body_owner_kind(item_id) {
179 hir::BodyOwnerKind::Closure |
180 hir::BodyOwnerKind::Fn => self.in_fn = true,
181 hir::BodyOwnerKind::Static(_) => self.in_static = true,
186 self.tables = self.tcx.typeck_tables_of(item_def_id);
187 self.param_env = self.tcx.param_env(item_def_id);
188 self.identity_substs = InternalSubsts::identity_for_item(self.tcx, item_def_id);
190 let body = self.tcx.hir().body(body_id);
193 let param_env = self.param_env;
194 let region_scope_tree = self.tcx.region_scope_tree(item_def_id);
195 let tables = self.tables;
196 euv::ExprUseVisitor::new(
204 ).consume_body(body);
206 let body_promotable = self.check_expr(&body.value);
207 self.in_fn = outer_in_fn;
208 self.tables = outer_tables;
209 self.param_env = outer_param_env;
210 self.identity_substs = outer_identity_substs;
214 fn check_stmt(&mut self, stmt: &'tcx hir::Stmt) -> Promotability {
216 hir::StmtKind::Local(ref local) => {
217 if self.remove_mut_rvalue_borrow(&local.pat) {
218 if let Some(init) = &local.init {
219 self.mut_rvalue_borrows.insert(init.hir_id);
223 if let Some(ref expr) = local.init {
224 let _ = self.check_expr(&expr);
228 // Item statements are allowed
229 hir::StmtKind::Item(..) => Promotable,
230 hir::StmtKind::Expr(ref box_expr) |
231 hir::StmtKind::Semi(ref box_expr) => {
232 let _ = self.check_expr(box_expr);
238 fn check_expr(&mut self, ex: &'tcx hir::Expr) -> Promotability {
239 let node_ty = self.tables.node_type(ex.hir_id);
240 let mut outer = check_expr_kind(self, ex, node_ty);
241 outer &= check_adjustments(self, ex);
243 // Handle borrows on (or inside the autorefs of) this expression.
244 if self.mut_rvalue_borrows.remove(&ex.hir_id) {
245 outer = NotPromotable
248 if outer == Promotable {
249 self.result.insert(ex.hir_id.local_id);
254 fn check_block(&mut self, block: &'tcx hir::Block) -> Promotability {
255 let mut iter_result = Promotable;
256 for index in block.stmts.iter() {
257 iter_result &= self.check_stmt(index);
260 Some(ref box_expr) => iter_result & self.check_expr(&*box_expr),
266 /// This function is used to enforce the constraints on
267 /// const/static items. It walks through the *value*
268 /// of the item walking down the expression and evaluating
269 /// every nested expression. If the expression is not part
270 /// of a const/static item, it is qualified for promotion
271 /// instead of producing errors.
272 fn check_expr_kind<'a, 'tcx>(
273 v: &mut CheckCrateVisitor<'a, 'tcx>,
274 e: &'tcx hir::Expr, node_ty: Ty<'tcx>) -> Promotability {
276 let ty_result = match node_ty.sty {
277 ty::Adt(def, _) if def.has_dtor(v.tcx) => {
283 let node_result = match e.node {
284 hir::ExprKind::Box(ref expr) => {
285 let _ = v.check_expr(&expr);
288 hir::ExprKind::Unary(op, ref expr) => {
289 let expr_promotability = v.check_expr(expr);
290 if v.tables.is_method_call(e) || op == hir::UnDeref {
291 return NotPromotable;
295 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
296 let lefty = v.check_expr(lhs);
297 let righty = v.check_expr(rhs);
298 if v.tables.is_method_call(e) {
299 return NotPromotable;
301 match v.tables.node_type(lhs.hir_id).sty {
302 ty::RawPtr(_) | ty::FnPtr(..) => {
303 assert!(op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne ||
304 op.node == hir::BinOpKind::Le || op.node == hir::BinOpKind::Lt ||
305 op.node == hir::BinOpKind::Ge || op.node == hir::BinOpKind::Gt);
312 hir::ExprKind::Cast(ref from, _) => {
313 let expr_promotability = v.check_expr(from);
314 debug!("checking const cast(id={})", from.hir_id);
315 let cast_in = CastTy::from_ty(v.tables.expr_ty(from));
316 let cast_out = CastTy::from_ty(v.tables.expr_ty(e));
317 match (cast_in, cast_out) {
318 (Some(CastTy::FnPtr), Some(CastTy::Int(_))) |
319 (Some(CastTy::Ptr(_)), Some(CastTy::Int(_))) => NotPromotable,
320 (_, _) => expr_promotability
323 hir::ExprKind::Path(ref qpath) => {
324 let res = v.tables.qpath_res(qpath, e.hir_id);
326 Res::Def(DefKind::Ctor(..), _)
327 | Res::Def(DefKind::Fn, _)
328 | Res::Def(DefKind::Method, _)
329 | Res::SelfCtor(..) =>
332 // References to a static that are themselves within a static
333 // are inherently promotable with the exception
334 // of "#[thread_local]" statics, which may not
335 // outlive the current function
336 Res::Def(DefKind::Static, did) => {
339 for attr in &v.tcx.get_attrs(did)[..] {
340 if attr.check_name(sym::thread_local) {
341 debug!("reference to `Static(id={:?})` is unpromotable \
342 due to a `#[thread_local]` attribute", did);
343 return NotPromotable;
348 debug!("reference to `Static(id={:?})` is unpromotable as it is not \
349 referenced from a static", did);
354 Res::Def(DefKind::Const, did) |
355 Res::Def(DefKind::AssocConst, did) => {
356 let promotable = if v.tcx.trait_of_item(did).is_some() {
357 // Don't peek inside trait associated constants.
359 } else if v.tcx.at(e.span).const_is_rvalue_promotable_to_static(did) {
364 // Just in case the type is more specific than the definition,
365 // e.g., impl associated const with type parameters, check it.
366 // Also, trait associated consts are relaxed by this.
367 promotable | v.type_promotability(node_ty)
372 hir::ExprKind::Call(ref callee, ref hirvec) => {
373 let mut call_result = v.check_expr(callee);
374 for index in hirvec.iter() {
375 call_result &= v.check_expr(index);
377 let mut callee = &**callee;
379 callee = match callee.node {
380 hir::ExprKind::Block(ref block, _) => match block.expr {
381 Some(ref tail) => &tail,
387 // The callee is an arbitrary expression, it doesn't necessarily have a definition.
388 let def = if let hir::ExprKind::Path(ref qpath) = callee.node {
389 v.tables.qpath_res(qpath, callee.hir_id)
393 let def_result = match def {
394 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) |
395 Res::SelfCtor(..) => Promotable,
396 Res::Def(DefKind::Fn, did) => v.handle_const_fn_call(did),
397 Res::Def(DefKind::Method, did) => {
398 match v.tcx.associated_item(did).container {
399 ty::ImplContainer(_) => v.handle_const_fn_call(did),
400 ty::TraitContainer(_) => NotPromotable,
405 def_result & call_result
407 hir::ExprKind::MethodCall(ref _pathsegment, ref _span, ref hirvec) => {
408 let mut method_call_result = Promotable;
409 for index in hirvec.iter() {
410 method_call_result &= v.check_expr(index);
412 if let Some(def_id) = v.tables.type_dependent_def_id(e.hir_id) {
413 match v.tcx.associated_item(def_id).container {
414 ty::ImplContainer(_) => method_call_result & v.handle_const_fn_call(def_id),
415 ty::TraitContainer(_) => NotPromotable,
418 v.tcx.sess.delay_span_bug(e.span, "no type-dependent def for method call");
422 hir::ExprKind::Struct(ref _qpath, ref hirvec, ref option_expr) => {
423 let mut struct_result = Promotable;
424 for index in hirvec.iter() {
425 struct_result &= v.check_expr(&index.expr);
427 if let Some(ref expr) = *option_expr {
428 struct_result &= v.check_expr(&expr);
430 if let ty::Adt(adt, ..) = v.tables.expr_ty(e).sty {
431 // unsafe_cell_type doesn't necessarily exist with no_core
432 if Some(adt.did) == v.tcx.lang_items().unsafe_cell_type() {
433 return NotPromotable;
439 hir::ExprKind::Lit(_) |
440 hir::ExprKind::Err => Promotable,
442 hir::ExprKind::AddrOf(_, ref expr) |
443 hir::ExprKind::Repeat(ref expr, _) |
444 hir::ExprKind::Type(ref expr, _) |
445 hir::ExprKind::DropTemps(ref expr) => {
449 hir::ExprKind::Closure(_capture_clause, ref _box_fn_decl,
450 body_id, _span, _option_generator_movability) => {
451 let nested_body_promotable = v.check_nested_body(body_id);
452 // Paths in constant contexts cannot refer to local variables,
453 // as there are none, and thus closures can't have upvars there.
454 let closure_def_id = v.tcx.hir().local_def_id(e.hir_id);
455 if !v.tcx.upvars(closure_def_id).map_or(true, |v| v.is_empty()) {
458 nested_body_promotable
462 hir::ExprKind::Field(ref expr, _ident) => {
463 let expr_promotability = v.check_expr(&expr);
464 if let Some(def) = v.tables.expr_ty(expr).ty_adt_def() {
466 return NotPromotable;
472 hir::ExprKind::Block(ref box_block, ref _option_label) => {
473 v.check_block(box_block)
476 hir::ExprKind::Index(ref lhs, ref rhs) => {
477 let lefty = v.check_expr(lhs);
478 let righty = v.check_expr(rhs);
479 if v.tables.is_method_call(e) {
480 return NotPromotable;
485 hir::ExprKind::Array(ref hirvec) => {
486 let mut array_result = Promotable;
487 for index in hirvec.iter() {
488 array_result &= v.check_expr(index);
493 hir::ExprKind::Tup(ref hirvec) => {
494 let mut tup_result = Promotable;
495 for index in hirvec.iter() {
496 tup_result &= v.check_expr(index);
501 // Conditional control flow (possible to implement).
502 hir::ExprKind::Match(ref expr, ref hirvec_arm, ref _match_source) => {
503 // Compute the most demanding borrow from all the arms'
504 // patterns and set that on the discriminator.
505 let mut mut_borrow = false;
506 for pat in hirvec_arm.iter().flat_map(|arm| &arm.pats) {
507 mut_borrow = v.remove_mut_rvalue_borrow(pat);
510 v.mut_rvalue_borrows.insert(expr.hir_id);
513 let _ = v.check_expr(expr);
514 for index in hirvec_arm.iter() {
515 let _ = v.check_expr(&*index.body);
516 if let Some(hir::Guard::If(ref expr)) = index.guard {
517 let _ = v.check_expr(&expr);
523 hir::ExprKind::Loop(ref box_block, ref _option_label, ref _loop_source) => {
524 let _ = v.check_block(box_block);
528 // More control flow (also not very meaningful).
529 hir::ExprKind::Break(_, ref option_expr) | hir::ExprKind::Ret(ref option_expr) => {
530 if let Some(ref expr) = *option_expr {
531 let _ = v.check_expr(&expr);
536 hir::ExprKind::Continue(_) => {
540 // Generator expressions
541 hir::ExprKind::Yield(ref expr, _) => {
542 let _ = v.check_expr(&expr);
546 // Expressions with side-effects.
547 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) | hir::ExprKind::Assign(ref lhs, ref rhs) => {
548 let _ = v.check_expr(lhs);
549 let _ = v.check_expr(rhs);
553 hir::ExprKind::InlineAsm(ref _inline_asm, ref hirvec_lhs, ref hirvec_rhs) => {
554 for index in hirvec_lhs.iter().chain(hirvec_rhs.iter()) {
555 let _ = v.check_expr(index);
560 ty_result & node_result
563 /// Checks the adjustments of an expression.
564 fn check_adjustments<'a, 'tcx>(
565 v: &mut CheckCrateVisitor<'a, 'tcx>,
566 e: &hir::Expr) -> Promotability {
567 use rustc::ty::adjustment::*;
569 let mut adjustments = v.tables.expr_adjustments(e).iter().peekable();
570 while let Some(adjustment) = adjustments.next() {
571 match adjustment.kind {
574 Adjust::Borrow(_) => {}
576 Adjust::Deref(_) => {
577 if let Some(next_adjustment) = adjustments.peek() {
578 if let Adjust::Borrow(_) = next_adjustment.kind {
582 return NotPromotable;
589 impl<'a, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'tcx> {
590 fn consume(&mut self,
591 _consume_id: hir::HirId,
594 _mode: euv::ConsumeMode) {}
597 borrow_id: hir::HirId,
599 cmt: &mc::cmt_<'tcx>,
600 _loan_region: ty::Region<'tcx>,
602 loan_cause: euv::LoanCause) {
604 "borrow(borrow_id={:?}, cmt={:?}, bk={:?}, loan_cause={:?})",
611 // Kind of hacky, but we allow Unsafe coercions in constants.
612 // These occur when we convert a &T or *T to a *U, as well as
613 // when making a thin pointer (e.g., `*T`) into a fat pointer
615 if let euv::LoanCause::AutoUnsafe = loan_cause {
622 Categorization::ThreadLocal(..) |
623 Categorization::Rvalue(..) => {
624 if loan_cause == euv::MatchDiscriminant {
625 // Ignore the dummy immutable borrow created by EUV.
628 if bk.to_mutbl_lossy() == hir::MutMutable {
629 self.mut_rvalue_borrows.insert(borrow_id);
633 Categorization::StaticItem => {
636 Categorization::Deref(ref cmt, _) |
637 Categorization::Downcast(ref cmt, _) |
638 Categorization::Interior(ref cmt, _) => {
642 Categorization::Upvar(..) |
643 Categorization::Local(..) => break,
648 fn decl_without_init(&mut self, _id: hir::HirId, _span: Span) {}
650 _assignment_id: hir::HirId,
651 _assignment_span: Span,
652 _assignee_cmt: &mc::cmt_<'_>,
653 _mode: euv::MutateMode) {
656 fn matched_pat(&mut self, _: &hir::Pat, _: &mc::cmt_<'_>, _: euv::MatchMode) {}
658 fn consume_pat(&mut self,
659 _consume_pat: &hir::Pat,
661 _mode: euv::ConsumeMode) {}