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::mir::transform::MirSource;
41 use rustc::ty::{self, Ty, TyCtxt};
42 use rustc::ty::subst::Substs;
43 use rustc::traits::Reveal;
44 use rustc::util::common::ErrorReported;
45 use rustc::util::nodemap::NodeSet;
46 use rustc::lint::builtin::CONST_ERR;
48 use rustc::hir::{self, PatKind, RangeEnd};
50 use syntax_pos::{Span, DUMMY_SP};
51 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
53 use std::collections::hash_map::Entry;
54 use std::cmp::Ordering;
56 struct CheckCrateVisitor<'a, 'tcx: 'a> {
57 tcx: TyCtxt<'a, 'tcx, 'tcx>,
61 mut_rvalue_borrows: NodeSet,
62 param_env: ty::ParamEnv<'tcx>,
63 identity_substs: &'tcx Substs<'tcx>,
64 tables: &'a ty::TypeckTables<'tcx>,
67 impl<'a, 'gcx> CheckCrateVisitor<'a, 'gcx> {
68 fn const_cx(&self) -> ConstContext<'a, 'gcx> {
69 ConstContext::new(self.tcx, self.param_env.and(self.identity_substs), self.tables)
72 fn check_const_eval(&self, expr: &'gcx hir::Expr) {
73 if let Err(err) = self.const_cx().eval(expr) {
75 UnimplementedConstVal(_) => {}
76 IndexOpFeatureGated => {}
77 ErroneousReferencedConstant(_) => {}
80 self.tcx.lint_node(CONST_ERR,
83 &format!("constant evaluation error: {}. This will \
84 become a HARD ERROR in the future",
85 err.description().into_oneline()));
91 // Returns true iff all the values of the type are promotable.
92 fn type_has_only_promotable_values(&mut self, ty: Ty<'gcx>) -> bool {
93 ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) &&
94 !ty.needs_drop(self.tcx, self.param_env)
97 fn handle_const_fn_call(&mut self, def_id: DefId, ret_ty: Ty<'gcx>) {
98 self.promotable &= self.type_has_only_promotable_values(ret_ty);
100 self.promotable &= if let Some(fn_id) = self.tcx.hir.as_local_node_id(def_id) {
101 FnLikeNode::from_node(self.tcx.hir.get(fn_id)).map_or(false, |fn_like| {
102 fn_like.constness() == hir::Constness::Const
105 self.tcx.is_const_fn(def_id)
110 impl<'a, 'tcx> Visitor<'tcx> for CheckCrateVisitor<'a, 'tcx> {
111 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
112 NestedVisitorMap::None
115 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
116 match self.tcx.rvalue_promotable_to_static.borrow_mut().entry(body_id.node_id) {
117 Entry::Occupied(_) => return,
118 Entry::Vacant(entry) => {
119 // Prevent infinite recursion on re-entry.
124 let item_id = self.tcx.hir.body_owner(body_id);
125 let item_def_id = self.tcx.hir.local_def_id(item_id);
127 let outer_in_fn = self.in_fn;
128 let outer_tables = self.tables;
129 let outer_param_env = self.param_env;
130 let outer_identity_substs = self.identity_substs;
133 self.in_static = false;
135 match MirSource::from_node(self.tcx, item_id) {
136 MirSource::Fn(_) => self.in_fn = true,
137 MirSource::Static(_, _) => self.in_static = true,
142 self.tables = self.tcx.typeck_tables_of(item_def_id);
143 self.param_env = self.tcx.param_env(item_def_id);
144 self.identity_substs = Substs::identity_for_item(self.tcx, item_def_id);
146 let body = self.tcx.hir.body(body_id);
148 self.check_const_eval(&body.value);
152 let param_env = self.param_env;
153 let region_scope_tree = self.tcx.region_scope_tree(item_def_id);
154 euv::ExprUseVisitor::new(self, tcx, param_env, ®ion_scope_tree, self.tables)
157 self.visit_body(body);
159 self.in_fn = outer_in_fn;
160 self.tables = outer_tables;
161 self.param_env = outer_param_env;
162 self.identity_substs = outer_identity_substs;
165 fn visit_pat(&mut self, p: &'tcx hir::Pat) {
167 PatKind::Lit(ref lit) => {
168 self.check_const_eval(lit);
170 PatKind::Range(ref start, ref end, RangeEnd::Excluded) => {
171 match self.const_cx().compare_lit_exprs(p.span, start, end) {
172 Ok(Ordering::Less) => {}
173 Ok(Ordering::Equal) |
174 Ok(Ordering::Greater) => {
175 span_err!(self.tcx.sess,
178 "lower range bound must be less than upper");
180 Err(ErrorReported) => {}
183 PatKind::Range(ref start, ref end, RangeEnd::Included) => {
184 match self.const_cx().compare_lit_exprs(p.span, start, end) {
186 Ok(Ordering::Equal) => {}
187 Ok(Ordering::Greater) => {
188 struct_span_err!(self.tcx.sess, start.span, E0030,
189 "lower range bound must be less than or equal to upper")
190 .span_label(start.span, "lower bound larger than upper bound")
193 Err(ErrorReported) => {}
198 intravisit::walk_pat(self, p);
201 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
203 hir::StmtDecl(ref decl, _) => {
205 hir::DeclLocal(_) => {
206 self.promotable = false;
208 // Item statements are allowed
209 hir::DeclItem(_) => {}
213 hir::StmtSemi(..) => {
214 self.promotable = false;
217 intravisit::walk_stmt(self, stmt);
220 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
221 let outer = self.promotable;
222 self.promotable = true;
224 let node_ty = self.tables.node_id_to_type(ex.hir_id);
225 check_expr(self, ex, node_ty);
226 check_adjustments(self, ex);
228 if let hir::ExprMatch(ref discr, ref arms, _) = ex.node {
229 // Compute the most demanding borrow from all the arms'
230 // patterns and set that on the discriminator.
231 let mut mut_borrow = false;
232 for pat in arms.iter().flat_map(|arm| &arm.pats) {
233 if self.mut_rvalue_borrows.remove(&pat.id) {
238 self.mut_rvalue_borrows.insert(discr.id);
242 intravisit::walk_expr(self, ex);
244 // Handle borrows on (or inside the autorefs of) this expression.
245 if self.mut_rvalue_borrows.remove(&ex.id) {
246 self.promotable = false;
249 if self.in_fn && self.promotable {
250 match self.const_cx().eval(ex) {
252 Err(ConstEvalErr { kind: UnimplementedConstVal(_), .. }) |
253 Err(ConstEvalErr { kind: MiscCatchAll, .. }) |
254 Err(ConstEvalErr { kind: MiscBinaryOp, .. }) |
255 Err(ConstEvalErr { kind: NonConstPath, .. }) |
256 Err(ConstEvalErr { kind: ErroneousReferencedConstant(_), .. }) |
257 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shr)), .. }) |
258 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shl)), .. }) |
259 Err(ConstEvalErr { kind: IndexOpFeatureGated, .. }) => {}
260 Err(ConstEvalErr { kind: TypeckError, .. }) => {}
262 kind: LayoutError(ty::layout::LayoutError::Unknown(_)), ..
265 self.tcx.lint_node(CONST_ERR,
268 &msg.description().into_oneline().into_owned());
273 self.tcx.rvalue_promotable_to_static.borrow_mut().insert(ex.id, self.promotable);
274 self.promotable &= outer;
278 /// This function is used to enforce the constraints on
279 /// const/static items. It walks through the *value*
280 /// of the item walking down the expression and evaluating
281 /// every nested expression. If the expression is not part
282 /// of a const/static item, it is qualified for promotion
283 /// instead of producing errors.
284 fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr, node_ty: Ty<'tcx>) {
286 ty::TyAdt(def, _) if def.has_dtor(v.tcx) => {
287 v.promotable = false;
294 hir::ExprBinary(..) |
295 hir::ExprIndex(..) if v.tables.is_method_call(e) => {
296 v.promotable = false;
299 v.promotable = false;
301 hir::ExprUnary(op, ref inner) => {
302 match v.tables.node_id_to_type(inner.hir_id).sty {
304 assert!(op == hir::UnDeref);
306 v.promotable = false;
311 hir::ExprBinary(op, ref lhs, _) => {
312 match v.tables.node_id_to_type(lhs.hir_id).sty {
314 assert!(op.node == hir::BiEq || op.node == hir::BiNe ||
315 op.node == hir::BiLe || op.node == hir::BiLt ||
316 op.node == hir::BiGe || op.node == hir::BiGt);
318 v.promotable = false;
323 hir::ExprCast(ref from, _) => {
324 debug!("Checking const cast(id={})", from.id);
325 match v.tables.cast_kinds().get(from.hir_id) {
326 None => span_bug!(e.span, "no kind for cast"),
327 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
328 v.promotable = false;
333 hir::ExprPath(ref qpath) => {
334 let def = v.tables.qpath_def(qpath, e.hir_id);
336 Def::VariantCtor(..) | Def::StructCtor(..) |
337 Def::Fn(..) | Def::Method(..) => {}
339 // References to a static that are themselves within a static
340 // are inherently promotable with the exception
341 // of "#[thread_loca]" statics, which may not
342 // outlive the current function
343 Def::Static(did, _) => {
346 let mut thread_local = false;
348 for attr in &v.tcx.get_attrs(did)[..] {
349 if attr.check_name("thread_local") {
350 debug!("Reference to Static(id={:?}) is unpromotable \
351 due to a #[thread_local] attribute", did);
352 v.promotable = false;
359 debug!("Allowing promotion of reference to Static(id={:?})", did);
362 debug!("Reference to Static(id={:?}) is unpromotable as it is not \
363 referenced from a static", did);
364 v.promotable = false;
370 Def::AssociatedConst(did) => {
371 let promotable = if v.tcx.trait_of_item(did).is_some() {
372 // Don't peek inside trait associated constants.
374 } else if let Some(node_id) = v.tcx.hir.as_local_node_id(did) {
375 match v.tcx.hir.maybe_body_owned_by(node_id) {
377 v.visit_nested_body(body);
378 v.tcx.rvalue_promotable_to_static.borrow()[&body.node_id]
383 v.tcx.const_is_rvalue_promotable_to_static(did)
386 // Just in case the type is more specific than the definition,
387 // e.g. impl associated const with type parameters, check it.
388 // Also, trait associated consts are relaxed by this.
389 v.promotable &= promotable || v.type_has_only_promotable_values(node_ty);
393 v.promotable = false;
397 hir::ExprCall(ref callee, _) => {
398 let mut callee = &**callee;
400 callee = match callee.node {
401 hir::ExprBlock(ref block) => match block.expr {
402 Some(ref tail) => &tail,
408 // The callee is an arbitrary expression, it doesn't necessarily have a definition.
409 let def = if let hir::ExprPath(ref qpath) = callee.node {
410 v.tables.qpath_def(qpath, callee.hir_id)
415 Def::StructCtor(_, CtorKind::Fn) |
416 Def::VariantCtor(_, CtorKind::Fn) => {}
418 v.handle_const_fn_call(did, node_ty)
420 Def::Method(did) => {
421 match v.tcx.associated_item(did).container {
422 ty::ImplContainer(_) => {
423 v.handle_const_fn_call(did, node_ty)
425 ty::TraitContainer(_) => v.promotable = false
428 _ => v.promotable = false
431 hir::ExprMethodCall(..) => {
432 let def_id = v.tables.type_dependent_defs()[e.hir_id].def_id();
433 match v.tcx.associated_item(def_id).container {
434 ty::ImplContainer(_) => v.handle_const_fn_call(def_id, node_ty),
435 ty::TraitContainer(_) => v.promotable = false
438 hir::ExprStruct(..) => {
439 if let ty::TyAdt(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 v.promotable = false;
448 hir::ExprAddrOf(..) |
449 hir::ExprRepeat(..) => {}
451 hir::ExprClosure(..) => {
452 // Paths in constant contexts cannot refer to local variables,
453 // as there are none, and thus closures can't have upvars there.
454 if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
455 v.promotable = false;
462 hir::ExprTupField(..) |
465 hir::ExprTup(..) => {}
467 // Conditional control flow (possible to implement).
471 // Loops (not very meaningful in constants).
475 // More control flow (also not very meaningful).
480 // Generator expressions
483 // Expressions with side-effects.
484 hir::ExprAssign(..) |
485 hir::ExprAssignOp(..) |
486 hir::ExprInlineAsm(..) => {
487 v.promotable = false;
492 /// Check the adjustments of an expression
493 fn check_adjustments<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr) {
494 use rustc::ty::adjustment::*;
496 for adjustment in v.tables.expr_adjustments(e) {
497 match adjustment.kind {
499 Adjust::ReifyFnPointer |
500 Adjust::UnsafeFnPointer |
501 Adjust::ClosureFnPointer |
502 Adjust::MutToConstPointer |
506 Adjust::Deref(ref overloaded) => {
507 if overloaded.is_some() {
508 v.promotable = false;
516 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
517 tcx.hir.krate().visit_all_item_likes(&mut CheckCrateVisitor {
519 tables: &ty::TypeckTables::empty(None),
523 mut_rvalue_borrows: NodeSet(),
524 param_env: ty::ParamEnv::empty(Reveal::UserFacing),
525 identity_substs: Substs::empty(),
526 }.as_deep_visitor());
527 tcx.sess.abort_if_errors();
530 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> {
531 fn consume(&mut self,
532 _consume_id: ast::NodeId,
535 _mode: euv::ConsumeMode) {}
538 borrow_id: ast::NodeId,
541 _loan_region: ty::Region<'tcx>,
543 loan_cause: euv::LoanCause) {
544 // Kind of hacky, but we allow Unsafe coercions in constants.
545 // These occur when we convert a &T or *T to a *U, as well as
546 // when making a thin pointer (e.g., `*T`) into a fat pointer
549 euv::LoanCause::AutoUnsafe => {
558 Categorization::Rvalue(..) => {
559 if loan_cause == euv::MatchDiscriminant {
560 // Ignore the dummy immutable borrow created by EUV.
563 if bk.to_mutbl_lossy() == hir::MutMutable {
564 self.mut_rvalue_borrows.insert(borrow_id);
568 Categorization::StaticItem => {
571 Categorization::Deref(ref cmt, _) |
572 Categorization::Downcast(ref cmt, _) |
573 Categorization::Interior(ref cmt, _) => {
577 Categorization::Upvar(..) |
578 Categorization::Local(..) => break,
583 fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {}
585 _assignment_id: ast::NodeId,
586 _assignment_span: Span,
587 _assignee_cmt: mc::cmt,
588 _mode: euv::MutateMode) {
591 fn matched_pat(&mut self, _: &hir::Pat, _: mc::cmt, _: euv::MatchMode) {}
593 fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: mc::cmt, _mode: euv::ConsumeMode) {}