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_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::ty::{self, Ty, TyCtxt};
41 use rustc::ty::maps::{queries, Providers};
42 use rustc::ty::subst::Substs;
43 use rustc::traits::Reveal;
44 use rustc::util::common::ErrorReported;
45 use rustc::util::nodemap::{ItemLocalSet, NodeSet};
46 use rustc::lint::builtin::CONST_ERR;
47 use rustc::hir::{self, PatKind, RangeEnd};
50 use syntax_pos::{Span, DUMMY_SP};
51 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
53 use std::cmp::Ordering;
55 pub fn provide(providers: &mut Providers) {
56 *providers = Providers {
57 rvalue_promotable_map,
58 const_is_rvalue_promotable_to_static,
63 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
64 for &body_id in &tcx.hir.krate().body_ids {
65 let def_id = tcx.hir.body_owner_def_id(body_id);
66 tcx.const_is_rvalue_promotable_to_static(def_id);
68 tcx.sess.abort_if_errors();
71 fn const_is_rvalue_promotable_to_static<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
75 assert!(def_id.is_local());
77 let node_id = tcx.hir.as_local_node_id(def_id)
78 .expect("rvalue_promotable_map invoked with non-local def-id");
79 let body_id = tcx.hir.body_owned_by(node_id);
80 let body_hir_id = tcx.hir.node_to_hir_id(body_id.node_id);
81 tcx.rvalue_promotable_map(def_id).contains(&body_hir_id.local_id)
84 fn rvalue_promotable_map<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
88 let outer_def_id = tcx.closure_base_def_id(def_id);
89 if outer_def_id != def_id {
90 return tcx.rvalue_promotable_map(outer_def_id);
93 let mut visitor = CheckCrateVisitor {
95 tables: &ty::TypeckTables::empty(None),
99 mut_rvalue_borrows: NodeSet(),
100 param_env: ty::ParamEnv::empty(Reveal::UserFacing),
101 identity_substs: Substs::empty(),
102 result: ItemLocalSet(),
105 // `def_id` should be a `Body` owner
106 let node_id = tcx.hir.as_local_node_id(def_id)
107 .expect("rvalue_promotable_map invoked with non-local def-id");
108 let body_id = tcx.hir.body_owned_by(node_id);
109 visitor.visit_nested_body(body_id);
111 Rc::new(visitor.result)
114 struct CheckCrateVisitor<'a, 'tcx: 'a> {
115 tcx: TyCtxt<'a, 'tcx, 'tcx>,
119 mut_rvalue_borrows: NodeSet,
120 param_env: ty::ParamEnv<'tcx>,
121 identity_substs: &'tcx Substs<'tcx>,
122 tables: &'a ty::TypeckTables<'tcx>,
123 result: ItemLocalSet,
126 impl<'a, 'gcx> CheckCrateVisitor<'a, 'gcx> {
127 fn const_cx(&self) -> ConstContext<'a, 'gcx> {
128 ConstContext::new(self.tcx, self.param_env.and(self.identity_substs), self.tables)
131 fn check_const_eval(&self, expr: &'gcx hir::Expr) {
132 if let Err(err) = self.const_cx().eval(expr) {
134 UnimplementedConstVal(_) => {}
135 IndexOpFeatureGated => {}
136 ErroneousReferencedConstant(_) => {}
140 self.tcx.lint_node(CONST_ERR,
143 &format!("constant evaluation error: {}",
144 err.description().into_oneline()));
150 // Returns true iff all the values of the type are promotable.
151 fn type_has_only_promotable_values(&mut self, ty: Ty<'gcx>) -> bool {
152 ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) &&
153 !ty.needs_drop(self.tcx, self.param_env)
156 fn handle_const_fn_call(&mut self, def_id: DefId, ret_ty: Ty<'gcx>) {
157 self.promotable &= self.type_has_only_promotable_values(ret_ty);
159 self.promotable &= if let Some(fn_id) = self.tcx.hir.as_local_node_id(def_id) {
160 FnLikeNode::from_node(self.tcx.hir.get(fn_id)).map_or(false, |fn_like| {
161 fn_like.constness() == hir::Constness::Const
164 self.tcx.is_const_fn(def_id)
169 impl<'a, 'tcx> Visitor<'tcx> for CheckCrateVisitor<'a, 'tcx> {
170 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
171 // note that we *do* visit nested bodies, because we override `visit_nested_body` below
172 NestedVisitorMap::None
175 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
176 let item_id = self.tcx.hir.body_owner(body_id);
177 let item_def_id = self.tcx.hir.local_def_id(item_id);
179 let outer_in_fn = self.in_fn;
180 let outer_tables = self.tables;
181 let outer_param_env = self.param_env;
182 let outer_identity_substs = self.identity_substs;
185 self.in_static = false;
187 match self.tcx.hir.body_owner_kind(item_id) {
188 hir::BodyOwnerKind::Fn => self.in_fn = true,
189 hir::BodyOwnerKind::Static(_) => self.in_static = true,
194 self.tables = self.tcx.typeck_tables_of(item_def_id);
195 self.param_env = self.tcx.param_env(item_def_id);
196 self.identity_substs = Substs::identity_for_item(self.tcx, item_def_id);
198 let body = self.tcx.hir.body(body_id);
200 self.check_const_eval(&body.value);
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_pat(&mut self, p: &'tcx hir::Pat) {
219 PatKind::Lit(ref lit) => {
220 self.check_const_eval(lit);
222 PatKind::Range(ref start, ref end, RangeEnd::Excluded) => {
223 match self.const_cx().compare_lit_exprs(p.span, start, end) {
224 Ok(Ordering::Less) => {}
225 Ok(Ordering::Equal) |
226 Ok(Ordering::Greater) => {
227 span_err!(self.tcx.sess,
230 "lower range bound must be less than upper");
232 Err(ErrorReported) => {}
235 PatKind::Range(ref start, ref end, RangeEnd::Included) => {
236 match self.const_cx().compare_lit_exprs(p.span, start, end) {
238 Ok(Ordering::Equal) => {}
239 Ok(Ordering::Greater) => {
240 struct_span_err!(self.tcx.sess, start.span, E0030,
241 "lower range bound must be less than or equal to upper")
242 .span_label(start.span, "lower bound larger than upper bound")
245 Err(ErrorReported) => {}
250 intravisit::walk_pat(self, p);
253 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
255 hir::StmtDecl(ref decl, _) => {
257 hir::DeclLocal(_) => {
258 self.promotable = false;
260 // Item statements are allowed
261 hir::DeclItem(_) => {}
265 hir::StmtSemi(..) => {
266 self.promotable = false;
269 intravisit::walk_stmt(self, stmt);
272 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
273 let outer = self.promotable;
274 self.promotable = true;
276 let node_ty = self.tables.node_id_to_type(ex.hir_id);
277 check_expr(self, ex, node_ty);
278 check_adjustments(self, ex);
280 if let hir::ExprMatch(ref discr, ref arms, _) = ex.node {
281 // Compute the most demanding borrow from all the arms'
282 // patterns and set that on the discriminator.
283 let mut mut_borrow = false;
284 for pat in arms.iter().flat_map(|arm| &arm.pats) {
285 if self.mut_rvalue_borrows.remove(&pat.id) {
290 self.mut_rvalue_borrows.insert(discr.id);
294 intravisit::walk_expr(self, ex);
296 // Handle borrows on (or inside the autorefs of) this expression.
297 if self.mut_rvalue_borrows.remove(&ex.id) {
298 self.promotable = false;
301 if self.in_fn && self.promotable {
302 match self.const_cx().eval(ex) {
304 Err(ConstEvalErr { kind: UnimplementedConstVal(_), .. }) |
305 Err(ConstEvalErr { kind: MiscCatchAll, .. }) |
306 Err(ConstEvalErr { kind: MiscBinaryOp, .. }) |
307 Err(ConstEvalErr { kind: NonConstPath, .. }) |
308 Err(ConstEvalErr { kind: ErroneousReferencedConstant(_), .. }) |
309 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shr)), .. }) |
310 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shl)), .. }) |
311 Err(ConstEvalErr { kind: IndexOpFeatureGated, .. }) => {}
312 Err(ConstEvalErr { kind: TypeckError, .. }) => {}
314 kind: LayoutError(ty::layout::LayoutError::Unknown(_)), ..
317 self.tcx.lint_node(CONST_ERR,
320 &msg.description().into_oneline().into_owned());
326 self.result.insert(ex.hir_id.local_id);
328 self.promotable &= outer;
332 /// This function is used to enforce the constraints on
333 /// const/static items. It walks through the *value*
334 /// of the item walking down the expression and evaluating
335 /// every nested expression. If the expression is not part
336 /// of a const/static item, it is qualified for promotion
337 /// instead of producing errors.
338 fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr, node_ty: Ty<'tcx>) {
340 ty::TyAdt(def, _) if def.has_dtor(v.tcx) => {
341 v.promotable = false;
348 hir::ExprBinary(..) |
349 hir::ExprIndex(..) if v.tables.is_method_call(e) => {
350 v.promotable = false;
353 v.promotable = false;
355 hir::ExprUnary(op, ref inner) => {
356 match v.tables.node_id_to_type(inner.hir_id).sty {
358 assert!(op == hir::UnDeref);
360 v.promotable = false;
365 hir::ExprBinary(op, ref lhs, _) => {
366 match v.tables.node_id_to_type(lhs.hir_id).sty {
368 assert!(op.node == hir::BiEq || op.node == hir::BiNe ||
369 op.node == hir::BiLe || op.node == hir::BiLt ||
370 op.node == hir::BiGe || op.node == hir::BiGt);
372 v.promotable = false;
377 hir::ExprCast(ref from, _) => {
378 debug!("Checking const cast(id={})", from.id);
379 match v.tables.cast_kinds().get(from.hir_id) {
380 None => span_bug!(e.span, "no kind for cast"),
381 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
382 v.promotable = false;
387 hir::ExprPath(ref qpath) => {
388 let def = v.tables.qpath_def(qpath, e.hir_id);
390 Def::VariantCtor(..) | Def::StructCtor(..) |
391 Def::Fn(..) | Def::Method(..) => {}
393 // References to a static that are themselves within a static
394 // are inherently promotable with the exception
395 // of "#[thread_loca]" statics, which may not
396 // outlive the current function
397 Def::Static(did, _) => {
400 let mut thread_local = false;
402 for attr in &v.tcx.get_attrs(did)[..] {
403 if attr.check_name("thread_local") {
404 debug!("Reference to Static(id={:?}) is unpromotable \
405 due to a #[thread_local] attribute", did);
406 v.promotable = false;
413 debug!("Allowing promotion of reference to Static(id={:?})", did);
416 debug!("Reference to Static(id={:?}) is unpromotable as it is not \
417 referenced from a static", did);
418 v.promotable = false;
424 Def::AssociatedConst(did) => {
425 let promotable = if v.tcx.trait_of_item(did).is_some() {
426 // Don't peek inside trait associated constants.
429 queries::const_is_rvalue_promotable_to_static::try_get(v.tcx, e.span, did)
430 .unwrap_or_else(|mut err| {
431 // A cycle between constants ought to be reported elsewhere.
433 v.tcx.sess.delay_span_bug(
435 &format!("cycle encountered during const qualification: {:?}",
441 // Just in case the type is more specific than the definition,
442 // e.g. impl associated const with type parameters, check it.
443 // Also, trait associated consts are relaxed by this.
444 v.promotable &= promotable || v.type_has_only_promotable_values(node_ty);
448 v.promotable = false;
452 hir::ExprCall(ref callee, _) => {
453 let mut callee = &**callee;
455 callee = match callee.node {
456 hir::ExprBlock(ref block) => match block.expr {
457 Some(ref tail) => &tail,
463 // The callee is an arbitrary expression, it doesn't necessarily have a definition.
464 let def = if let hir::ExprPath(ref qpath) = callee.node {
465 v.tables.qpath_def(qpath, callee.hir_id)
470 Def::StructCtor(_, CtorKind::Fn) |
471 Def::VariantCtor(_, CtorKind::Fn) => {}
473 v.handle_const_fn_call(did, node_ty)
475 Def::Method(did) => {
476 match v.tcx.associated_item(did).container {
477 ty::ImplContainer(_) => {
478 v.handle_const_fn_call(did, node_ty)
480 ty::TraitContainer(_) => v.promotable = false
483 _ => v.promotable = false
486 hir::ExprMethodCall(..) => {
487 let def_id = v.tables.type_dependent_defs()[e.hir_id].def_id();
488 match v.tcx.associated_item(def_id).container {
489 ty::ImplContainer(_) => v.handle_const_fn_call(def_id, node_ty),
490 ty::TraitContainer(_) => v.promotable = false
493 hir::ExprStruct(..) => {
494 if let ty::TyAdt(adt, ..) = v.tables.expr_ty(e).sty {
495 // unsafe_cell_type doesn't necessarily exist with no_core
496 if Some(adt.did) == v.tcx.lang_items().unsafe_cell_type() {
497 v.promotable = false;
503 hir::ExprAddrOf(..) |
504 hir::ExprRepeat(..) => {}
506 hir::ExprClosure(..) => {
507 // Paths in constant contexts cannot refer to local variables,
508 // as there are none, and thus closures can't have upvars there.
509 if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
510 v.promotable = false;
517 hir::ExprTupField(..) |
520 hir::ExprTup(..) => {}
522 // Conditional control flow (possible to implement).
526 // Loops (not very meaningful in constants).
530 // More control flow (also not very meaningful).
535 // Generator expressions
538 // Expressions with side-effects.
539 hir::ExprAssign(..) |
540 hir::ExprAssignOp(..) |
541 hir::ExprInlineAsm(..) => {
542 v.promotable = false;
547 /// Check the adjustments of an expression
548 fn check_adjustments<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr) {
549 use rustc::ty::adjustment::*;
551 for adjustment in v.tables.expr_adjustments(e) {
552 match adjustment.kind {
554 Adjust::ReifyFnPointer |
555 Adjust::UnsafeFnPointer |
556 Adjust::ClosureFnPointer |
557 Adjust::MutToConstPointer |
561 Adjust::Deref(ref overloaded) => {
562 if overloaded.is_some() {
563 v.promotable = false;
571 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> {
572 fn consume(&mut self,
573 _consume_id: ast::NodeId,
576 _mode: euv::ConsumeMode) {}
579 borrow_id: ast::NodeId,
582 _loan_region: ty::Region<'tcx>,
584 loan_cause: euv::LoanCause) {
585 // Kind of hacky, but we allow Unsafe coercions in constants.
586 // These occur when we convert a &T or *T to a *U, as well as
587 // when making a thin pointer (e.g., `*T`) into a fat pointer
590 euv::LoanCause::AutoUnsafe => {
599 Categorization::Rvalue(..) => {
600 if loan_cause == euv::MatchDiscriminant {
601 // Ignore the dummy immutable borrow created by EUV.
604 if bk.to_mutbl_lossy() == hir::MutMutable {
605 self.mut_rvalue_borrows.insert(borrow_id);
609 Categorization::StaticItem => {
612 Categorization::Deref(ref cmt, _) |
613 Categorization::Downcast(ref cmt, _) |
614 Categorization::Interior(ref cmt, _) => {
618 Categorization::Upvar(..) |
619 Categorization::Local(..) => break,
624 fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {}
626 _assignment_id: ast::NodeId,
627 _assignment_span: Span,
628 _assignee_cmt: mc::cmt,
629 _mode: euv::MutateMode) {
632 fn matched_pat(&mut self, _: &hir::Pat, _: mc::cmt, _: euv::MatchMode) {}
634 fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: mc::cmt, _mode: euv::ConsumeMode) {}