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 middle::ty::cast::{CastKind};
28 use middle::const_eval;
29 use middle::const_eval::EvalHint::ExprTypeChecked;
31 use middle::def_id::DefId;
32 use middle::expr_use_visitor as euv;
34 use middle::mem_categorization as mc;
36 use middle::ty::{self, Ty};
37 use util::nodemap::NodeMap;
41 use syntax::codemap::Span;
42 use syntax::feature_gate::UnstableFeatures;
43 use rustc_front::visit::{self, FnKind, Visitor};
45 use std::collections::hash_map::Entry;
46 use std::cmp::Ordering;
48 // Const qualification, from partial to completely promotable.
50 #[derive(RustcEncodable, RustcDecodable)]
51 flags ConstQualif: u8 {
52 // Inner mutability (can not be placed behind a reference) or behind
53 // &mut in a non-global expression. Can be copied from static memory.
54 const MUTABLE_MEM = 1 << 0,
55 // Constant value with a type that implements Drop. Can be copied
56 // from static memory, similar to MUTABLE_MEM.
57 const NEEDS_DROP = 1 << 1,
58 // Even if the value can be placed in static memory, copying it from
59 // there is more expensive than in-place instantiation, and/or it may
60 // be too large. This applies to [T; N] and everything containing it.
61 // N.B.: references need to clear this flag to not end up on the stack.
62 const PREFER_IN_PLACE = 1 << 2,
63 // May use more than 0 bytes of memory, doesn't impact the constness
64 // directly, but is not allowed to be borrowed mutably in a constant.
65 const NON_ZERO_SIZED = 1 << 3,
66 // Actually borrowed, has to always be in static memory. Does not
67 // propagate, and requires the expression to behave like a 'static
68 // lvalue. The set of expressions with this flag is the minimum
69 // that have to be promoted.
70 const HAS_STATIC_BORROWS = 1 << 4,
71 // Invalid const for miscellaneous reasons (e.g. not implemented).
72 const NOT_CONST = 1 << 5,
74 // Borrowing the expression won't produce &'static T if any of these
75 // bits are set, though the value could be copied from static memory
76 // if `NOT_CONST` isn't set.
77 const NON_STATIC_BORROWS = ConstQualif::MUTABLE_MEM.bits |
78 ConstQualif::NEEDS_DROP.bits |
79 ConstQualif::NOT_CONST.bits
83 #[derive(Copy, Clone, Eq, PartialEq)]
90 // An expression that occurs outside of any constant context
91 // (i.e. `const`, `static`, array lengths, etc.). The value
92 // can be variable at runtime, but will be promotable to
93 // static memory if we can prove it is actually constant.
97 struct CheckCrateVisitor<'a, 'tcx: 'a> {
98 tcx: &'a ty::ctxt<'tcx>,
101 rvalue_borrows: NodeMap<hir::Mutability>
104 impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> {
105 fn with_mode<F, R>(&mut self, mode: Mode, f: F) -> R where
106 F: FnOnce(&mut CheckCrateVisitor<'a, 'tcx>) -> R,
108 let (old_mode, old_qualif) = (self.mode, self.qualif);
110 self.qualif = ConstQualif::empty();
112 self.mode = old_mode;
113 self.qualif = old_qualif;
117 fn with_euv<'b, F, R>(&'b mut self, item_id: Option<ast::NodeId>, f: F) -> R where
118 F: for<'t> FnOnce(&mut euv::ExprUseVisitor<'b, 't, 'b, 'tcx>) -> R,
120 let param_env = match item_id {
121 Some(item_id) => ty::ParameterEnvironment::for_item(self.tcx, item_id),
122 None => self.tcx.empty_parameter_environment()
125 let infcx = infer::new_infer_ctxt(self.tcx, &self.tcx.tables, Some(param_env), false);
127 f(&mut euv::ExprUseVisitor::new(self, &infcx))
130 fn global_expr(&mut self, mode: Mode, expr: &hir::Expr) -> ConstQualif {
131 assert!(mode != Mode::Var);
132 match self.tcx.const_qualif_map.borrow_mut().entry(expr.id) {
133 Entry::Occupied(entry) => return *entry.get(),
134 Entry::Vacant(entry) => {
135 // Prevent infinite recursion on re-entry.
136 entry.insert(ConstQualif::empty());
139 self.with_mode(mode, |this| {
140 this.with_euv(None, |euv| euv.consume_expr(expr));
141 this.visit_expr(expr);
146 fn fn_like(&mut self,
153 match self.tcx.const_qualif_map.borrow_mut().entry(fn_id) {
154 Entry::Occupied(entry) => return *entry.get(),
155 Entry::Vacant(entry) => {
156 // Prevent infinite recursion on re-entry.
157 entry.insert(ConstQualif::empty());
161 let mode = match fk {
162 FnKind::ItemFn(_, _, _, hir::Constness::Const, _, _) => {
165 FnKind::Method(_, m, _) => {
166 if m.constness == hir::Constness::Const {
175 // Ensure the arguments are simple, not mutable/by-ref or patterns.
176 if mode == Mode::ConstFn {
177 for arg in &fd.inputs {
179 hir::PatWild(_) => {}
180 hir::PatIdent(hir::BindByValue(hir::MutImmutable), _, None) => {}
182 span_err!(self.tcx.sess, arg.pat.span, E0022,
183 "arguments of constant functions can only \
184 be immutable by-value bindings");
190 let qualif = self.with_mode(mode, |this| {
191 this.with_euv(Some(fn_id), |euv| euv.walk_fn(fd, b));
192 visit::walk_fn(this, fk, fd, b, s);
196 // Keep only bits that aren't affected by function body (NON_ZERO_SIZED),
197 // and bits that don't change semantics, just optimizations (PREFER_IN_PLACE).
198 let qualif = qualif & (ConstQualif::NON_ZERO_SIZED | ConstQualif::PREFER_IN_PLACE);
200 self.tcx.const_qualif_map.borrow_mut().insert(fn_id, qualif);
204 fn add_qualif(&mut self, qualif: ConstQualif) {
205 self.qualif = self.qualif | qualif;
208 /// Returns true if the call is to a const fn or method.
209 fn handle_const_fn_call(&mut self,
214 if let Some(fn_like) = const_eval::lookup_const_fn_by_id(self.tcx, def_id) {
216 // we are in a static/const initializer
217 self.mode != Mode::Var &&
219 // feature-gate is not enabled
220 !self.tcx.sess.features.borrow().const_fn &&
222 // this doesn't come from a macro that has #[allow_internal_unstable]
223 !self.tcx.sess.codemap().span_allows_unstable(expr.span)
225 self.tcx.sess.span_err(
227 &format!("const fns are an unstable feature"));
231 "in Nightly builds, add `#![feature(const_fn)]` to the crate \
232 attributes to enable");
235 let qualif = self.fn_like(fn_like.kind(),
240 self.add_qualif(qualif);
242 if ret_ty.type_contents(self.tcx).interior_unsafe() {
243 self.add_qualif(ConstQualif::MUTABLE_MEM);
252 fn record_borrow(&mut self, id: ast::NodeId, mutbl: hir::Mutability) {
253 match self.rvalue_borrows.entry(id) {
254 Entry::Occupied(mut entry) => {
255 // Merge the two borrows, taking the most demanding
256 // one, mutability-wise.
257 if mutbl == hir::MutMutable {
261 Entry::Vacant(entry) => {
267 fn msg(&self) -> &'static str {
269 Mode::Const => "constant",
270 Mode::ConstFn => "constant function",
271 Mode::StaticMut | Mode::Static => "static",
272 Mode::Var => unreachable!(),
276 fn check_static_mut_type(&self, e: &hir::Expr) {
277 let node_ty = self.tcx.node_id_to_type(e.id);
278 let tcontents = node_ty.type_contents(self.tcx);
280 let suffix = if tcontents.has_dtor() {
282 } else if tcontents.owns_owned() {
288 span_err!(self.tcx.sess, e.span, E0397,
289 "mutable statics are not allowed to have {}", suffix);
292 fn check_static_type(&self, e: &hir::Expr) {
293 let ty = self.tcx.node_id_to_type(e.id);
294 let infcx = infer::new_infer_ctxt(self.tcx, &self.tcx.tables, None, false);
295 let cause = traits::ObligationCause::new(e.span, e.id, traits::SharedStatic);
296 let mut fulfill_cx = infcx.fulfillment_cx.borrow_mut();
297 fulfill_cx.register_builtin_bound(&infcx, ty, ty::BoundSync, cause);
298 match fulfill_cx.select_all_or_error(&infcx) {
301 traits::report_fulfillment_errors(&infcx, errors);
307 impl<'a, 'tcx, 'v> Visitor<'v> for CheckCrateVisitor<'a, 'tcx> {
308 fn visit_item(&mut self, i: &hir::Item) {
309 debug!("visit_item(item={})", self.tcx.map.node_to_string(i.id));
311 hir::ItemStatic(_, hir::MutImmutable, ref expr) => {
312 self.check_static_type(&**expr);
313 self.global_expr(Mode::Static, &**expr);
315 hir::ItemStatic(_, hir::MutMutable, ref expr) => {
316 self.check_static_mut_type(&**expr);
317 self.global_expr(Mode::StaticMut, &**expr);
319 hir::ItemConst(_, ref expr) => {
320 self.global_expr(Mode::Const, &**expr);
322 hir::ItemEnum(ref enum_definition, _) => {
323 for var in &enum_definition.variants {
324 if let Some(ref ex) = var.node.disr_expr {
325 self.global_expr(Mode::Const, &**ex);
330 self.with_mode(Mode::Var, |v| visit::walk_item(v, i));
335 fn visit_trait_item(&mut self, t: &'v hir::TraitItem) {
337 hir::ConstTraitItem(_, ref default) => {
338 if let Some(ref expr) = *default {
339 self.global_expr(Mode::Const, &*expr);
341 visit::walk_trait_item(self, t);
344 _ => self.with_mode(Mode::Var, |v| visit::walk_trait_item(v, t)),
348 fn visit_impl_item(&mut self, i: &'v hir::ImplItem) {
350 hir::ConstImplItem(_, ref expr) => {
351 self.global_expr(Mode::Const, &*expr);
353 _ => self.with_mode(Mode::Var, |v| visit::walk_impl_item(v, i)),
357 fn visit_fn(&mut self,
362 fn_id: ast::NodeId) {
363 self.fn_like(fk, fd, b, s, fn_id);
366 fn visit_pat(&mut self, p: &hir::Pat) {
368 hir::PatLit(ref lit) => {
369 self.global_expr(Mode::Const, &**lit);
371 hir::PatRange(ref start, ref end) => {
372 self.global_expr(Mode::Const, &**start);
373 self.global_expr(Mode::Const, &**end);
375 match const_eval::compare_lit_exprs(self.tcx, start, end) {
376 Some(Ordering::Less) |
377 Some(Ordering::Equal) => {}
378 Some(Ordering::Greater) => {
379 span_err!(self.tcx.sess, start.span, E0030,
380 "lower range bound must be less than or equal to upper");
383 self.tcx.sess.delay_span_bug(start.span,
384 "non-constant path in constant expr");
388 _ => visit::walk_pat(self, p)
392 fn visit_block(&mut self, block: &hir::Block) {
393 // Check all statements in the block
394 for stmt in &block.stmts {
395 let span = match stmt.node {
396 hir::StmtDecl(ref decl, _) => {
398 hir::DeclLocal(_) => decl.span,
400 // Item statements are allowed
401 hir::DeclItem(_) => continue
404 hir::StmtExpr(ref expr, _) => expr.span,
405 hir::StmtSemi(ref semi, _) => semi.span,
407 self.add_qualif(ConstQualif::NOT_CONST);
408 if self.mode != Mode::Var {
409 span_err!(self.tcx.sess, span, E0016,
410 "blocks in {}s are limited to items and \
411 tail expressions", self.msg());
414 visit::walk_block(self, block);
417 fn visit_expr(&mut self, ex: &hir::Expr) {
418 let mut outer = self.qualif;
419 self.qualif = ConstQualif::empty();
421 let node_ty = self.tcx.node_id_to_type(ex.id);
422 check_expr(self, ex, node_ty);
423 check_adjustments(self, ex);
425 // Special-case some expressions to avoid certain flags bubbling up.
427 hir::ExprCall(ref callee, ref args) => {
429 self.visit_expr(&**arg)
432 let inner = self.qualif;
433 self.visit_expr(&**callee);
434 // The callee's size doesn't count in the call.
435 let added = self.qualif - inner;
436 self.qualif = inner | (added - ConstQualif::NON_ZERO_SIZED);
438 hir::ExprRepeat(ref element, _) => {
439 self.visit_expr(&**element);
440 // The count is checked elsewhere (typeck).
441 let count = match node_ty.sty {
442 ty::TyArray(_, n) => n,
445 // [element; 0] is always zero-sized.
447 self.qualif.remove(ConstQualif::NON_ZERO_SIZED | ConstQualif::PREFER_IN_PLACE);
450 hir::ExprMatch(ref discr, ref arms, _) => {
451 // Compute the most demanding borrow from all the arms'
452 // patterns and set that on the discriminator.
453 let mut borrow = None;
454 for pat in arms.iter().flat_map(|arm| &arm.pats) {
455 let pat_borrow = self.rvalue_borrows.remove(&pat.id);
456 match (borrow, pat_borrow) {
457 (None, _) | (_, Some(hir::MutMutable)) => {
463 if let Some(mutbl) = borrow {
464 self.record_borrow(discr.id, mutbl);
466 visit::walk_expr(self, ex);
468 // Division by zero and overflow checking.
469 hir::ExprBinary(op, _, _) => {
470 visit::walk_expr(self, ex);
471 let div_or_rem = op.node == hir::BiDiv || op.node == hir::BiRem;
473 ty::TyUint(_) | ty::TyInt(_) if div_or_rem => {
474 if !self.qualif.intersects(ConstQualif::NOT_CONST) {
475 match const_eval::eval_const_expr_partial(
476 self.tcx, ex, ExprTypeChecked, None) {
479 self.tcx.sess.add_lint(::lint::builtin::CONST_ERR, ex.id,
481 msg.description().into_owned())
489 _ => visit::walk_expr(self, ex)
492 // Handle borrows on (or inside the autorefs of) this expression.
493 match self.rvalue_borrows.remove(&ex.id) {
494 Some(hir::MutImmutable) => {
495 // Constants cannot be borrowed if they contain interior mutability as
496 // it means that our "silent insertion of statics" could change
497 // initializer values (very bad).
498 // If the type doesn't have interior mutability, then `ConstQualif::MUTABLE_MEM` has
499 // propagated from another error, so erroring again would be just noise.
500 let tc = node_ty.type_contents(self.tcx);
501 if self.qualif.intersects(ConstQualif::MUTABLE_MEM) && tc.interior_unsafe() {
502 outer = outer | ConstQualif::NOT_CONST;
503 if self.mode != Mode::Var {
504 span_err!(self.tcx.sess, ex.span, E0492,
505 "cannot borrow a constant which contains \
506 interior mutability, create a static instead");
509 // If the reference has to be 'static, avoid in-place initialization
510 // as that will end up pointing to the stack instead.
511 if !self.qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
512 self.qualif = self.qualif - ConstQualif::PREFER_IN_PLACE;
513 self.add_qualif(ConstQualif::HAS_STATIC_BORROWS);
516 Some(hir::MutMutable) => {
517 // `&mut expr` means expr could be mutated, unless it's zero-sized.
518 if self.qualif.intersects(ConstQualif::NON_ZERO_SIZED) {
519 if self.mode == Mode::Var {
520 outer = outer | ConstQualif::NOT_CONST;
521 self.add_qualif(ConstQualif::MUTABLE_MEM);
523 span_err!(self.tcx.sess, ex.span, E0017,
524 "references in {}s may only refer \
525 to immutable values", self.msg())
528 if !self.qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
529 self.add_qualif(ConstQualif::HAS_STATIC_BORROWS);
534 self.tcx.const_qualif_map.borrow_mut().insert(ex.id, self.qualif);
535 // Don't propagate certain flags.
536 self.qualif = outer | (self.qualif - ConstQualif::HAS_STATIC_BORROWS);
540 /// This function is used to enforce the constraints on
541 /// const/static items. It walks through the *value*
542 /// of the item walking down the expression and evaluating
543 /// every nested expression. If the expression is not part
544 /// of a const/static item, it is qualified for promotion
545 /// instead of producing errors.
546 fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>,
547 e: &hir::Expr, node_ty: Ty<'tcx>) {
549 ty::TyStruct(def, _) |
550 ty::TyEnum(def, _) if def.has_dtor() => {
551 v.add_qualif(ConstQualif::NEEDS_DROP);
552 if v.mode != Mode::Var {
553 span_err!(v.tcx.sess, e.span, E0493,
554 "{}s are not allowed to have destructors",
561 let method_call = ty::MethodCall::expr(e.id);
564 hir::ExprBinary(..) |
565 hir::ExprIndex(..) if v.tcx.tables.borrow().method_map.contains_key(&method_call) => {
566 v.add_qualif(ConstQualif::NOT_CONST);
567 if v.mode != Mode::Var {
568 span_err!(v.tcx.sess, e.span, E0011,
569 "user-defined operators are not allowed in {}s", v.msg());
573 v.add_qualif(ConstQualif::NOT_CONST);
574 if v.mode != Mode::Var {
575 span_err!(v.tcx.sess, e.span, E0010,
576 "allocations are not allowed in {}s", v.msg());
579 hir::ExprUnary(op, ref inner) => {
580 match v.tcx.node_id_to_type(inner.id).sty {
582 assert!(op == hir::UnDeref);
584 v.add_qualif(ConstQualif::NOT_CONST);
585 if v.mode != Mode::Var {
586 span_err!(v.tcx.sess, e.span, E0396,
587 "raw pointers cannot be dereferenced in {}s", v.msg());
593 hir::ExprBinary(op, ref lhs, _) => {
594 match v.tcx.node_id_to_type(lhs.id).sty {
596 assert!(op.node == hir::BiEq || op.node == hir::BiNe ||
597 op.node == hir::BiLe || op.node == hir::BiLt ||
598 op.node == hir::BiGe || op.node == hir::BiGt);
600 v.add_qualif(ConstQualif::NOT_CONST);
601 if v.mode != Mode::Var {
602 span_err!(v.tcx.sess, e.span, E0395,
603 "raw pointers cannot be compared in {}s", v.msg());
609 hir::ExprCast(ref from, _) => {
610 debug!("Checking const cast(id={})", from.id);
611 match v.tcx.cast_kinds.borrow().get(&from.id) {
612 None => v.tcx.sess.span_bug(e.span, "no kind for cast"),
613 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
614 v.add_qualif(ConstQualif::NOT_CONST);
615 if v.mode != Mode::Var {
616 span_err!(v.tcx.sess, e.span, E0018,
617 "raw pointers cannot be cast to integers in {}s", v.msg());
623 hir::ExprPath(..) => {
624 let def = v.tcx.def_map.borrow().get(&e.id).map(|d| d.full_def());
626 Some(def::DefVariant(_, _, _)) => {
627 // Count the discriminator or function pointer.
628 v.add_qualif(ConstQualif::NON_ZERO_SIZED);
630 Some(def::DefStruct(_)) => {
631 if let ty::TyBareFn(..) = node_ty.sty {
632 // Count the function pointer.
633 v.add_qualif(ConstQualif::NON_ZERO_SIZED);
636 Some(def::DefFn(..)) | Some(def::DefMethod(..)) => {
637 // Count the function pointer.
638 v.add_qualif(ConstQualif::NON_ZERO_SIZED);
640 Some(def::DefStatic(..)) => {
642 Mode::Static | Mode::StaticMut => {}
643 Mode::Const | Mode::ConstFn => {
644 span_err!(v.tcx.sess, e.span, E0013,
645 "{}s cannot refer to other statics, insert \
646 an intermediate constant instead", v.msg());
648 Mode::Var => v.add_qualif(ConstQualif::NOT_CONST)
651 Some(def::DefConst(did)) |
652 Some(def::DefAssociatedConst(did)) => {
653 if let Some(expr) = const_eval::lookup_const_by_id(v.tcx, did,
655 let inner = v.global_expr(Mode::Const, expr);
658 v.tcx.sess.span_bug(e.span,
659 "DefConst or DefAssociatedConst \
660 doesn't point to a constant");
663 Some(def::DefLocal(..)) if v.mode == Mode::ConstFn => {
664 // Sadly, we can't determine whether the types are zero-sized.
665 v.add_qualif(ConstQualif::NOT_CONST | ConstQualif::NON_ZERO_SIZED);
668 v.add_qualif(ConstQualif::NOT_CONST);
669 if v.mode != Mode::Var {
670 debug!("(checking const) found bad def: {:?}", def);
671 span_err!(v.tcx.sess, e.span, E0014,
672 "paths in {}s may only refer to constants \
673 or functions", v.msg());
678 hir::ExprCall(ref callee, _) => {
679 let mut callee = &**callee;
681 callee = match callee.node {
682 hir::ExprBlock(ref block) => match block.expr {
683 Some(ref tail) => &**tail,
689 let def = v.tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def());
690 let is_const = match def {
691 Some(def::DefStruct(..)) => true,
692 Some(def::DefVariant(..)) => {
693 // Count the discriminator.
694 v.add_qualif(ConstQualif::NON_ZERO_SIZED);
697 Some(def::DefFn(did, _)) => {
698 v.handle_const_fn_call(e, did, node_ty)
700 Some(def::DefMethod(did)) => {
701 match v.tcx.impl_or_trait_item(did).container() {
702 ty::ImplContainer(_) => {
703 v.handle_const_fn_call(e, did, node_ty)
705 ty::TraitContainer(_) => false
711 v.add_qualif(ConstQualif::NOT_CONST);
712 if v.mode != Mode::Var {
713 fn span_limited_call_error(tcx: &ty::ctxt, span: Span, s: &str) {
714 span_err!(tcx.sess, span, E0015, "{}", s);
717 // FIXME(#24111) Remove this check when const fn stabilizes
718 if let UnstableFeatures::Disallow = v.tcx.sess.opts.unstable_features {
719 span_limited_call_error(&v.tcx, e.span,
720 &format!("function calls in {}s are limited to \
721 struct and enum constructors",
723 v.tcx.sess.span_note(e.span,
724 "a limited form of compile-time function \
725 evaluation is available on a nightly \
726 compiler via `const fn`");
728 span_limited_call_error(&v.tcx, e.span,
729 &format!("function calls in {}s are limited \
730 to constant functions, \
731 struct and enum constructors",
737 hir::ExprMethodCall(..) => {
738 let method = v.tcx.tables.borrow().method_map[&method_call];
739 let is_const = match v.tcx.impl_or_trait_item(method.def_id).container() {
740 ty::ImplContainer(_) => v.handle_const_fn_call(e, method.def_id, node_ty),
741 ty::TraitContainer(_) => false
744 v.add_qualif(ConstQualif::NOT_CONST);
745 if v.mode != Mode::Var {
746 span_err!(v.tcx.sess, e.span, E0378,
747 "method calls in {}s are limited to \
748 constant inherent methods", v.msg());
752 hir::ExprStruct(..) => {
753 let did = v.tcx.def_map.borrow().get(&e.id).map(|def| def.def_id());
754 if did == v.tcx.lang_items.unsafe_cell_type() {
755 v.add_qualif(ConstQualif::MUTABLE_MEM);
760 hir::ExprAddrOf(..) => {
761 v.add_qualif(ConstQualif::NON_ZERO_SIZED);
764 hir::ExprRepeat(..) => {
765 v.add_qualif(ConstQualif::PREFER_IN_PLACE);
768 hir::ExprClosure(..) => {
769 // Paths in constant contexts cannot refer to local variables,
770 // as there are none, and thus closures can't have upvars there.
771 if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
772 assert!(v.mode == Mode::Var,
773 "global closures can't capture anything");
774 v.add_qualif(ConstQualif::NOT_CONST);
781 hir::ExprTupField(..) |
783 hir::ExprTup(..) => {}
785 // Conditional control flow (possible to implement).
789 // Loops (not very meaningful in constants).
793 // More control flow (also not very meaningful).
798 // Miscellaneous expressions that could be implemented.
801 // Expressions with side-effects.
802 hir::ExprAssign(..) |
803 hir::ExprAssignOp(..) |
804 hir::ExprInlineAsm(_) => {
805 v.add_qualif(ConstQualif::NOT_CONST);
806 if v.mode != Mode::Var {
807 span_err!(v.tcx.sess, e.span, E0019,
808 "{} contains unimplemented expression type", v.msg());
814 /// Check the adjustments of an expression
815 fn check_adjustments<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr) {
816 match v.tcx.tables.borrow().adjustments.get(&e.id) {
818 Some(&ty::adjustment::AdjustReifyFnPointer) |
819 Some(&ty::adjustment::AdjustUnsafeFnPointer) => {}
821 Some(&ty::adjustment::AdjustDerefRef(
822 ty::adjustment::AutoDerefRef { autoderefs, .. }
824 if (0..autoderefs as u32).any(|autoderef| {
825 v.tcx.is_overloaded_autoderef(e.id, autoderef)
827 v.add_qualif(ConstQualif::NOT_CONST);
828 if v.mode != Mode::Var {
829 span_err!(v.tcx.sess, e.span, E0400,
830 "user-defined dereference operators are not allowed in {}s",
838 pub fn check_crate(tcx: &ty::ctxt) {
839 visit::walk_crate(&mut CheckCrateVisitor {
842 qualif: ConstQualif::NOT_CONST,
843 rvalue_borrows: NodeMap()
846 tcx.sess.abort_if_errors();
849 impl<'a, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'tcx> {
850 fn consume(&mut self,
851 _consume_id: ast::NodeId,
854 _mode: euv::ConsumeMode) {
858 mc::cat_static_item => {
859 if self.mode != Mode::Var {
860 // statics cannot be consumed by value at any time, that would imply
861 // that they're an initializer (what a const is for) or kept in sync
862 // over time (not feasible), so deny it outright.
863 span_err!(self.tcx.sess, consume_span, E0394,
864 "cannot refer to other statics by value, use the \
865 address-of operator or a constant instead");
869 mc::cat_deref(ref cmt, _, _) |
870 mc::cat_downcast(ref cmt, _) |
871 mc::cat_interior(ref cmt, _) => cur = cmt,
875 mc::cat_local(..) => break
880 borrow_id: ast::NodeId,
883 _loan_region: ty::Region,
885 loan_cause: euv::LoanCause)
887 // Kind of hacky, but we allow Unsafe coercions in constants.
888 // These occur when we convert a &T or *T to a *U, as well as
889 // when making a thin pointer (e.g., `*T`) into a fat pointer
892 euv::LoanCause::AutoUnsafe => {
899 let mut is_interior = false;
902 mc::cat_rvalue(..) => {
903 if loan_cause == euv::MatchDiscriminant {
904 // Ignore the dummy immutable borrow created by EUV.
907 let mutbl = bk.to_mutbl_lossy();
908 if mutbl == hir::MutMutable && self.mode == Mode::StaticMut {
909 // Mutable slices are the only `&mut` allowed in
910 // globals, but only in `static mut`, nowhere else.
911 // FIXME: This exception is really weird... there isn't
912 // any fundamental reason to restrict this based on
913 // type of the expression. `&mut [1]` has exactly the
914 // same representation as &mut 1.
916 ty::TyArray(_, _) | ty::TySlice(_) => break,
920 self.record_borrow(borrow_id, mutbl);
923 mc::cat_static_item => {
924 if is_interior && self.mode != Mode::Var {
925 // Borrowed statics can specifically *only* have their address taken,
926 // not any number of other borrows such as borrowing fields, reading
927 // elements of an array, etc.
928 span_err!(self.tcx.sess, borrow_span, E0494,
929 "cannot refer to the interior of another \
930 static, use a constant instead");
934 mc::cat_deref(ref cmt, _, _) |
935 mc::cat_downcast(ref cmt, _) |
936 mc::cat_interior(ref cmt, _) => {
942 mc::cat_local(..) => break
947 fn decl_without_init(&mut self,
951 _assignment_id: ast::NodeId,
952 _assignment_span: Span,
953 _assignee_cmt: mc::cmt,
954 _mode: euv::MutateMode) {}
956 fn matched_pat(&mut self,
959 _: euv::MatchMode) {}
961 fn consume_pat(&mut self,
962 _consume_pat: &hir::Pat,
964 _mode: euv::ConsumeMode) {}