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 rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
45 pub fn provide(providers: &mut Providers) {
46 *providers = Providers {
47 rvalue_promotable_map,
48 const_is_rvalue_promotable_to_static,
53 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
54 for &body_id in &tcx.hir.krate().body_ids {
55 let def_id = tcx.hir.body_owner_def_id(body_id);
56 tcx.const_is_rvalue_promotable_to_static(def_id);
58 tcx.sess.abort_if_errors();
61 fn const_is_rvalue_promotable_to_static<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
65 assert!(def_id.is_local());
67 let node_id = tcx.hir.as_local_node_id(def_id)
68 .expect("rvalue_promotable_map invoked with non-local def-id");
69 let body_id = tcx.hir.body_owned_by(node_id);
70 let body_hir_id = tcx.hir.node_to_hir_id(body_id.node_id);
71 tcx.rvalue_promotable_map(def_id).contains(&body_hir_id.local_id)
74 fn rvalue_promotable_map<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
78 let outer_def_id = tcx.closure_base_def_id(def_id);
79 if outer_def_id != def_id {
80 return tcx.rvalue_promotable_map(outer_def_id);
83 let mut visitor = CheckCrateVisitor {
85 tables: &ty::TypeckTables::empty(None),
89 mut_rvalue_borrows: NodeSet(),
90 param_env: ty::ParamEnv::empty(),
91 identity_substs: Substs::empty(),
92 result: ItemLocalSet(),
95 // `def_id` should be a `Body` owner
96 let node_id = tcx.hir.as_local_node_id(def_id)
97 .expect("rvalue_promotable_map invoked with non-local def-id");
98 let body_id = tcx.hir.body_owned_by(node_id);
99 visitor.visit_nested_body(body_id);
101 Lrc::new(visitor.result)
104 struct CheckCrateVisitor<'a, 'tcx: 'a> {
105 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,
116 impl<'a, 'gcx> CheckCrateVisitor<'a, 'gcx> {
117 // Returns true iff all the values of the type are promotable.
118 fn type_has_only_promotable_values(&mut self, ty: Ty<'gcx>) -> bool {
119 ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) &&
120 !ty.needs_drop(self.tcx, self.param_env)
123 fn handle_const_fn_call(&mut self, def_id: DefId, ret_ty: Ty<'gcx>, span: Span) {
124 self.promotable &= self.type_has_only_promotable_values(ret_ty);
126 self.promotable &= if let Some(fn_id) = self.tcx.hir.as_local_node_id(def_id) {
127 FnLikeNode::from_node(self.tcx.hir.get(fn_id)).map_or(false, |fn_like| {
128 fn_like.constness() == hir::Constness::Const
131 self.tcx.is_const_fn(def_id)
134 if let Some(&attr::Stability {
135 rustc_const_unstable: Some(attr::RustcConstUnstable {
136 feature: ref feature_name
138 .. }) = self.tcx.lookup_stability(def_id) {
140 // feature-gate is enabled,
142 .declared_lib_features
144 .any(|&(ref sym, _)| sym == feature_name) ||
146 // this comes from a crate with the feature-gate enabled,
147 !def_id.is_local() ||
149 // this comes from a macro that has #[allow_internal_unstable]
150 span.allows_unstable();
154 /// While the `ExprUseVisitor` walks, we will identify which
155 /// expressions are borrowed, and insert their ids into this
156 /// table. Actually, we insert the "borrow-id", which is normally
157 /// the id of the expession being borrowed: but in the case of
158 /// `ref mut` borrows, the `id` of the pattern is
159 /// inserted. Therefore later we remove that entry from the table
160 /// and transfer it over to the value being matched. This will
161 /// then prevent said value from being promoted.
162 fn remove_mut_rvalue_borrow(&mut self, pat: &hir::Pat) -> bool {
163 let mut any_removed = false;
165 any_removed |= self.mut_rvalue_borrows.remove(&p.id);
172 impl<'a, 'tcx> Visitor<'tcx> for CheckCrateVisitor<'a, 'tcx> {
173 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
174 // note that we *do* visit nested bodies, because we override `visit_nested_body` below
175 NestedVisitorMap::None
178 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
179 let item_id = self.tcx.hir.body_owner(body_id);
180 let item_def_id = self.tcx.hir.local_def_id(item_id);
182 let outer_in_fn = self.in_fn;
183 let outer_tables = self.tables;
184 let outer_param_env = self.param_env;
185 let outer_identity_substs = self.identity_substs;
188 self.in_static = false;
190 match self.tcx.hir.body_owner_kind(item_id) {
191 hir::BodyOwnerKind::Fn => self.in_fn = true,
192 hir::BodyOwnerKind::Static(_) => self.in_static = true,
197 self.tables = self.tcx.typeck_tables_of(item_def_id);
198 self.param_env = self.tcx.param_env(item_def_id);
199 self.identity_substs = Substs::identity_for_item(self.tcx, item_def_id);
201 let body = self.tcx.hir.body(body_id);
204 let param_env = self.param_env;
205 let region_scope_tree = self.tcx.region_scope_tree(item_def_id);
206 euv::ExprUseVisitor::new(self, tcx, param_env, ®ion_scope_tree, self.tables, None)
209 self.visit_body(body);
211 self.in_fn = outer_in_fn;
212 self.tables = outer_tables;
213 self.param_env = outer_param_env;
214 self.identity_substs = outer_identity_substs;
217 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
219 hir::StmtDecl(ref decl, _) => {
221 hir::DeclLocal(local) => {
222 self.promotable = false;
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 // Item statements are allowed
231 hir::DeclItem(_) => {}
235 hir::StmtSemi(..) => {
236 self.promotable = false;
239 intravisit::walk_stmt(self, stmt);
242 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
243 let outer = self.promotable;
244 self.promotable = true;
246 let node_ty = self.tables.node_id_to_type(ex.hir_id);
247 check_expr(self, ex, node_ty);
248 check_adjustments(self, ex);
250 if let hir::ExprMatch(ref discr, ref arms, _) = ex.node {
251 // Compute the most demanding borrow from all the arms'
252 // patterns and set that on the discriminator.
253 let mut mut_borrow = false;
254 for pat in arms.iter().flat_map(|arm| &arm.pats) {
255 mut_borrow = self.remove_mut_rvalue_borrow(pat);
258 self.mut_rvalue_borrows.insert(discr.id);
262 intravisit::walk_expr(self, ex);
264 // Handle borrows on (or inside the autorefs of) this expression.
265 if self.mut_rvalue_borrows.remove(&ex.id) {
266 self.promotable = false;
270 self.result.insert(ex.hir_id.local_id);
272 self.promotable &= outer;
276 /// This function is used to enforce the constraints on
277 /// const/static items. It walks through the *value*
278 /// of the item walking down the expression and evaluating
279 /// every nested expression. If the expression is not part
280 /// of a const/static item, it is qualified for promotion
281 /// instead of producing errors.
282 fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr, node_ty: Ty<'tcx>) {
284 ty::TyAdt(def, _) if def.has_dtor(v.tcx) => {
285 v.promotable = false;
292 hir::ExprBinary(..) |
293 hir::ExprIndex(..) if v.tables.is_method_call(e) => {
294 v.promotable = false;
297 v.promotable = false;
299 hir::ExprUnary(op, _) => {
300 if op == hir::UnDeref {
301 v.promotable = false;
304 hir::ExprBinary(op, ref lhs, _) => {
305 match v.tables.node_id_to_type(lhs.hir_id).sty {
307 assert!(op.node == hir::BiEq || op.node == hir::BiNe ||
308 op.node == hir::BiLe || op.node == hir::BiLt ||
309 op.node == hir::BiGe || op.node == hir::BiGt);
311 v.promotable = false;
316 hir::ExprCast(ref from, _) => {
317 debug!("Checking const cast(id={})", from.id);
318 match v.tables.cast_kinds().get(from.hir_id) {
319 None => v.tcx.sess.delay_span_bug(e.span, "no kind for cast"),
320 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
321 v.promotable = false;
326 hir::ExprPath(ref qpath) => {
327 let def = v.tables.qpath_def(qpath, e.hir_id);
329 Def::VariantCtor(..) | Def::StructCtor(..) |
330 Def::Fn(..) | Def::Method(..) => {}
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 Def::Static(did, _) => {
339 let mut thread_local = false;
341 for attr in &v.tcx.get_attrs(did)[..] {
342 if attr.check_name("thread_local") {
343 debug!("Reference to Static(id={:?}) is unpromotable \
344 due to a #[thread_local] attribute", did);
345 v.promotable = false;
352 debug!("Allowing promotion of reference to Static(id={:?})", did);
355 debug!("Reference to Static(id={:?}) is unpromotable as it is not \
356 referenced from a static", did);
357 v.promotable = false;
363 Def::AssociatedConst(did) => {
364 let promotable = if v.tcx.trait_of_item(did).is_some() {
365 // Don't peek inside trait associated constants.
368 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 v.promotable &= promotable || v.type_has_only_promotable_values(node_ty);
378 v.promotable = false;
382 hir::ExprCall(ref callee, _) => {
383 let mut callee = &**callee;
385 callee = match callee.node {
386 hir::ExprBlock(ref block, _) => match block.expr {
387 Some(ref tail) => &tail,
393 // The callee is an arbitrary expression, it doesn't necessarily have a definition.
394 let def = if let hir::ExprPath(ref qpath) = callee.node {
395 v.tables.qpath_def(qpath, callee.hir_id)
400 Def::StructCtor(_, CtorKind::Fn) |
401 Def::VariantCtor(_, CtorKind::Fn) => {}
403 v.handle_const_fn_call(did, node_ty, e.span)
405 Def::Method(did) => {
406 match v.tcx.associated_item(did).container {
407 ty::ImplContainer(_) => {
408 v.handle_const_fn_call(did, node_ty, e.span)
410 ty::TraitContainer(_) => v.promotable = false
413 _ => v.promotable = false
416 hir::ExprMethodCall(..) => {
417 if let Some(def) = v.tables.type_dependent_defs().get(e.hir_id) {
418 let def_id = def.def_id();
419 match v.tcx.associated_item(def_id).container {
420 ty::ImplContainer(_) => v.handle_const_fn_call(def_id, node_ty, e.span),
421 ty::TraitContainer(_) => v.promotable = false
424 v.tcx.sess.delay_span_bug(e.span, "no type-dependent def for method call");
427 hir::ExprStruct(..) => {
428 if let ty::TyAdt(adt, ..) = v.tables.expr_ty(e).sty {
429 // unsafe_cell_type doesn't necessarily exist with no_core
430 if Some(adt.did) == v.tcx.lang_items().unsafe_cell_type() {
431 v.promotable = false;
437 hir::ExprAddrOf(..) |
438 hir::ExprRepeat(..) => {}
440 hir::ExprClosure(..) => {
441 // Paths in constant contexts cannot refer to local variables,
442 // as there are none, and thus closures can't have upvars there.
443 if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
444 v.promotable = false;
448 hir::ExprField(ref expr, _) => {
449 if let Some(def) = v.tables.expr_ty(expr).ty_adt_def() {
460 hir::ExprTup(..) => {}
462 // Conditional control flow (possible to implement).
466 // Loops (not very meaningful in constants).
470 // More control flow (also not very meaningful).
475 // Generator expressions
478 // Expressions with side-effects.
479 hir::ExprAssign(..) |
480 hir::ExprAssignOp(..) |
481 hir::ExprInlineAsm(..) => {
482 v.promotable = false;
487 /// Check the adjustments of an expression
488 fn check_adjustments<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr) {
489 use rustc::ty::adjustment::*;
491 let mut adjustments = v.tables.expr_adjustments(e).iter().peekable();
492 while let Some(adjustment) = adjustments.next() {
493 match adjustment.kind {
495 Adjust::ReifyFnPointer |
496 Adjust::UnsafeFnPointer |
497 Adjust::ClosureFnPointer |
498 Adjust::MutToConstPointer |
502 Adjust::Deref(_) => {
503 if let Some(next_adjustment) = adjustments.peek() {
504 if let Adjust::Borrow(_) = next_adjustment.kind {
508 v.promotable = false;
515 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> {
516 fn consume(&mut self,
517 _consume_id: ast::NodeId,
520 _mode: euv::ConsumeMode) {}
523 borrow_id: ast::NodeId,
525 cmt: &mc::cmt_<'tcx>,
526 _loan_region: ty::Region<'tcx>,
528 loan_cause: euv::LoanCause) {
530 "borrow(borrow_id={:?}, cmt={:?}, bk={:?}, loan_cause={:?})",
537 // Kind of hacky, but we allow Unsafe coercions in constants.
538 // These occur when we convert a &T or *T to a *U, as well as
539 // when making a thin pointer (e.g., `*T`) into a fat pointer
542 euv::LoanCause::AutoUnsafe => {
551 Categorization::Rvalue(..) => {
552 if loan_cause == euv::MatchDiscriminant {
553 // Ignore the dummy immutable borrow created by EUV.
556 if bk.to_mutbl_lossy() == hir::MutMutable {
557 self.mut_rvalue_borrows.insert(borrow_id);
561 Categorization::StaticItem => {
564 Categorization::Deref(ref cmt, _) |
565 Categorization::Downcast(ref cmt, _) |
566 Categorization::Interior(ref cmt, _) => {
570 Categorization::Upvar(..) |
571 Categorization::Local(..) => break,
576 fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {}
578 _assignment_id: ast::NodeId,
579 _assignment_span: Span,
580 _assignee_cmt: &mc::cmt_,
581 _mode: euv::MutateMode) {
584 fn matched_pat(&mut self, _: &hir::Pat, _: &mc::cmt_, _: euv::MatchMode) {}
586 fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: &mc::cmt_, _mode: euv::ConsumeMode) {}