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::PatIdent(hir::BindByValue(hir::MutImmutable), _, None) => {}
181 span_err!(self.tcx.sess, arg.pat.span, E0022,
182 "arguments of constant functions can only \
183 be immutable by-value bindings");
189 let qualif = self.with_mode(mode, |this| {
190 this.with_euv(Some(fn_id), |euv| euv.walk_fn(fd, b));
191 visit::walk_fn(this, fk, fd, b, s);
195 // Keep only bits that aren't affected by function body (NON_ZERO_SIZED),
196 // and bits that don't change semantics, just optimizations (PREFER_IN_PLACE).
197 let qualif = qualif & (ConstQualif::NON_ZERO_SIZED | ConstQualif::PREFER_IN_PLACE);
199 self.tcx.const_qualif_map.borrow_mut().insert(fn_id, qualif);
203 fn add_qualif(&mut self, qualif: ConstQualif) {
204 self.qualif = self.qualif | qualif;
207 /// Returns true if the call is to a const fn or method.
208 fn handle_const_fn_call(&mut self,
213 if let Some(fn_like) = const_eval::lookup_const_fn_by_id(self.tcx, def_id) {
215 // we are in a static/const initializer
216 self.mode != Mode::Var &&
218 // feature-gate is not enabled
219 !self.tcx.sess.features.borrow().const_fn &&
221 // this doesn't come from a macro that has #[allow_internal_unstable]
222 !self.tcx.sess.codemap().span_allows_unstable(expr.span)
224 self.tcx.sess.span_err(
226 &format!("const fns are an unstable feature"));
230 "in Nightly builds, add `#![feature(const_fn)]` to the crate \
231 attributes to enable");
234 let qualif = self.fn_like(fn_like.kind(),
239 self.add_qualif(qualif);
241 if ret_ty.type_contents(self.tcx).interior_unsafe() {
242 self.add_qualif(ConstQualif::MUTABLE_MEM);
251 fn record_borrow(&mut self, id: ast::NodeId, mutbl: hir::Mutability) {
252 match self.rvalue_borrows.entry(id) {
253 Entry::Occupied(mut entry) => {
254 // Merge the two borrows, taking the most demanding
255 // one, mutability-wise.
256 if mutbl == hir::MutMutable {
260 Entry::Vacant(entry) => {
266 fn msg(&self) -> &'static str {
268 Mode::Const => "constant",
269 Mode::ConstFn => "constant function",
270 Mode::StaticMut | Mode::Static => "static",
271 Mode::Var => unreachable!(),
275 fn check_static_mut_type(&self, e: &hir::Expr) {
276 let node_ty = self.tcx.node_id_to_type(e.id);
277 let tcontents = node_ty.type_contents(self.tcx);
279 let suffix = if tcontents.has_dtor() {
281 } else if tcontents.owns_owned() {
287 span_err!(self.tcx.sess, e.span, E0397,
288 "mutable statics are not allowed to have {}", suffix);
291 fn check_static_type(&self, e: &hir::Expr) {
292 let ty = self.tcx.node_id_to_type(e.id);
293 let infcx = infer::new_infer_ctxt(self.tcx, &self.tcx.tables, None, false);
294 let cause = traits::ObligationCause::new(e.span, e.id, traits::SharedStatic);
295 let mut fulfill_cx = infcx.fulfillment_cx.borrow_mut();
296 fulfill_cx.register_builtin_bound(&infcx, ty, ty::BoundSync, cause);
297 match fulfill_cx.select_all_or_error(&infcx) {
300 traits::report_fulfillment_errors(&infcx, errors);
306 impl<'a, 'tcx, 'v> Visitor<'v> for CheckCrateVisitor<'a, 'tcx> {
307 fn visit_item(&mut self, i: &hir::Item) {
308 debug!("visit_item(item={})", self.tcx.map.node_to_string(i.id));
310 hir::ItemStatic(_, hir::MutImmutable, ref expr) => {
311 self.check_static_type(&**expr);
312 self.global_expr(Mode::Static, &**expr);
314 hir::ItemStatic(_, hir::MutMutable, ref expr) => {
315 self.check_static_mut_type(&**expr);
316 self.global_expr(Mode::StaticMut, &**expr);
318 hir::ItemConst(_, ref expr) => {
319 self.global_expr(Mode::Const, &**expr);
321 hir::ItemEnum(ref enum_definition, _) => {
322 for var in &enum_definition.variants {
323 if let Some(ref ex) = var.node.disr_expr {
324 self.global_expr(Mode::Const, &**ex);
329 self.with_mode(Mode::Var, |v| visit::walk_item(v, i));
334 fn visit_trait_item(&mut self, t: &'v hir::TraitItem) {
336 hir::ConstTraitItem(_, ref default) => {
337 if let Some(ref expr) = *default {
338 self.global_expr(Mode::Const, &*expr);
340 visit::walk_trait_item(self, t);
343 _ => self.with_mode(Mode::Var, |v| visit::walk_trait_item(v, t)),
347 fn visit_impl_item(&mut self, i: &'v hir::ImplItem) {
349 hir::ConstImplItem(_, ref expr) => {
350 self.global_expr(Mode::Const, &*expr);
352 _ => self.with_mode(Mode::Var, |v| visit::walk_impl_item(v, i)),
356 fn visit_fn(&mut self,
361 fn_id: ast::NodeId) {
362 self.fn_like(fk, fd, b, s, fn_id);
365 fn visit_pat(&mut self, p: &hir::Pat) {
367 hir::PatLit(ref lit) => {
368 self.global_expr(Mode::Const, &**lit);
370 hir::PatRange(ref start, ref end) => {
371 self.global_expr(Mode::Const, &**start);
372 self.global_expr(Mode::Const, &**end);
374 match const_eval::compare_lit_exprs(self.tcx, start, end) {
375 Some(Ordering::Less) |
376 Some(Ordering::Equal) => {}
377 Some(Ordering::Greater) => {
378 span_err!(self.tcx.sess, start.span, E0030,
379 "lower range bound must be less than or equal to upper");
382 self.tcx.sess.delay_span_bug(start.span,
383 "non-constant path in constant expr");
387 _ => visit::walk_pat(self, p)
391 fn visit_block(&mut self, block: &hir::Block) {
392 // Check all statements in the block
393 for stmt in &block.stmts {
394 let span = match stmt.node {
395 hir::StmtDecl(ref decl, _) => {
397 hir::DeclLocal(_) => decl.span,
399 // Item statements are allowed
400 hir::DeclItem(_) => continue
403 hir::StmtExpr(ref expr, _) => expr.span,
404 hir::StmtSemi(ref semi, _) => semi.span,
406 self.add_qualif(ConstQualif::NOT_CONST);
407 if self.mode != Mode::Var {
408 span_err!(self.tcx.sess, span, E0016,
409 "blocks in {}s are limited to items and \
410 tail expressions", self.msg());
413 visit::walk_block(self, block);
416 fn visit_expr(&mut self, ex: &hir::Expr) {
417 let mut outer = self.qualif;
418 self.qualif = ConstQualif::empty();
420 let node_ty = self.tcx.node_id_to_type(ex.id);
421 check_expr(self, ex, node_ty);
422 check_adjustments(self, ex);
424 // Special-case some expressions to avoid certain flags bubbling up.
426 hir::ExprCall(ref callee, ref args) => {
428 self.visit_expr(&**arg)
431 let inner = self.qualif;
432 self.visit_expr(&**callee);
433 // The callee's size doesn't count in the call.
434 let added = self.qualif - inner;
435 self.qualif = inner | (added - ConstQualif::NON_ZERO_SIZED);
437 hir::ExprRepeat(ref element, _) => {
438 self.visit_expr(&**element);
439 // The count is checked elsewhere (typeck).
440 let count = match node_ty.sty {
441 ty::TyArray(_, n) => n,
444 // [element; 0] is always zero-sized.
446 self.qualif.remove(ConstQualif::NON_ZERO_SIZED | ConstQualif::PREFER_IN_PLACE);
449 hir::ExprMatch(ref discr, ref arms, _) => {
450 // Compute the most demanding borrow from all the arms'
451 // patterns and set that on the discriminator.
452 let mut borrow = None;
453 for pat in arms.iter().flat_map(|arm| &arm.pats) {
454 let pat_borrow = self.rvalue_borrows.remove(&pat.id);
455 match (borrow, pat_borrow) {
456 (None, _) | (_, Some(hir::MutMutable)) => {
462 if let Some(mutbl) = borrow {
463 self.record_borrow(discr.id, mutbl);
465 visit::walk_expr(self, ex);
467 // Division by zero and overflow checking.
468 hir::ExprBinary(op, _, _) => {
469 visit::walk_expr(self, ex);
470 let div_or_rem = op.node == hir::BiDiv || op.node == hir::BiRem;
472 ty::TyUint(_) | ty::TyInt(_) if div_or_rem => {
473 if !self.qualif.intersects(ConstQualif::NOT_CONST) {
474 match const_eval::eval_const_expr_partial(
475 self.tcx, ex, ExprTypeChecked) {
478 span_err!(self.tcx.sess, msg.span, E0020,
479 "{} in a constant expression",
488 _ => visit::walk_expr(self, ex)
491 // Handle borrows on (or inside the autorefs of) this expression.
492 match self.rvalue_borrows.remove(&ex.id) {
493 Some(hir::MutImmutable) => {
494 // Constants cannot be borrowed if they contain interior mutability as
495 // it means that our "silent insertion of statics" could change
496 // initializer values (very bad).
497 // If the type doesn't have interior mutability, then `ConstQualif::MUTABLE_MEM` has
498 // propagated from another error, so erroring again would be just noise.
499 let tc = node_ty.type_contents(self.tcx);
500 if self.qualif.intersects(ConstQualif::MUTABLE_MEM) && tc.interior_unsafe() {
501 outer = outer | ConstQualif::NOT_CONST;
502 if self.mode != Mode::Var {
503 span_err!(self.tcx.sess, ex.span, E0492,
504 "cannot borrow a constant which contains \
505 interior mutability, create a static instead");
508 // If the reference has to be 'static, avoid in-place initialization
509 // as that will end up pointing to the stack instead.
510 if !self.qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
511 self.qualif = self.qualif - ConstQualif::PREFER_IN_PLACE;
512 self.add_qualif(ConstQualif::HAS_STATIC_BORROWS);
515 Some(hir::MutMutable) => {
516 // `&mut expr` means expr could be mutated, unless it's zero-sized.
517 if self.qualif.intersects(ConstQualif::NON_ZERO_SIZED) {
518 if self.mode == Mode::Var {
519 outer = outer | ConstQualif::NOT_CONST;
520 self.add_qualif(ConstQualif::MUTABLE_MEM);
522 span_err!(self.tcx.sess, ex.span, E0017,
523 "references in {}s may only refer \
524 to immutable values", self.msg())
527 if !self.qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
528 self.add_qualif(ConstQualif::HAS_STATIC_BORROWS);
533 self.tcx.const_qualif_map.borrow_mut().insert(ex.id, self.qualif);
534 // Don't propagate certain flags.
535 self.qualif = outer | (self.qualif - ConstQualif::HAS_STATIC_BORROWS);
539 /// This function is used to enforce the constraints on
540 /// const/static items. It walks through the *value*
541 /// of the item walking down the expression and evaluating
542 /// every nested expression. If the expression is not part
543 /// of a const/static item, it is qualified for promotion
544 /// instead of producing errors.
545 fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>,
546 e: &hir::Expr, node_ty: Ty<'tcx>) {
548 ty::TyStruct(def, _) |
549 ty::TyEnum(def, _) if def.has_dtor() => {
550 v.add_qualif(ConstQualif::NEEDS_DROP);
551 if v.mode != Mode::Var {
552 span_err!(v.tcx.sess, e.span, E0493,
553 "{}s are not allowed to have destructors",
560 let method_call = ty::MethodCall::expr(e.id);
563 hir::ExprBinary(..) |
564 hir::ExprIndex(..) if v.tcx.tables.borrow().method_map.contains_key(&method_call) => {
565 v.add_qualif(ConstQualif::NOT_CONST);
566 if v.mode != Mode::Var {
567 span_err!(v.tcx.sess, e.span, E0011,
568 "user-defined operators are not allowed in {}s", v.msg());
572 v.add_qualif(ConstQualif::NOT_CONST);
573 if v.mode != Mode::Var {
574 span_err!(v.tcx.sess, e.span, E0010,
575 "allocations are not allowed in {}s", v.msg());
578 hir::ExprUnary(op, ref inner) => {
579 match v.tcx.node_id_to_type(inner.id).sty {
581 assert!(op == hir::UnDeref);
583 v.add_qualif(ConstQualif::NOT_CONST);
584 if v.mode != Mode::Var {
585 span_err!(v.tcx.sess, e.span, E0396,
586 "raw pointers cannot be dereferenced in {}s", v.msg());
592 hir::ExprBinary(op, ref lhs, _) => {
593 match v.tcx.node_id_to_type(lhs.id).sty {
595 assert!(op.node == hir::BiEq || op.node == hir::BiNe ||
596 op.node == hir::BiLe || op.node == hir::BiLt ||
597 op.node == hir::BiGe || op.node == hir::BiGt);
599 v.add_qualif(ConstQualif::NOT_CONST);
600 if v.mode != Mode::Var {
601 span_err!(v.tcx.sess, e.span, E0395,
602 "raw pointers cannot be compared in {}s", v.msg());
608 hir::ExprCast(ref from, _) => {
609 debug!("Checking const cast(id={})", from.id);
610 match v.tcx.cast_kinds.borrow().get(&from.id) {
611 None => v.tcx.sess.span_bug(e.span, "no kind for cast"),
612 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
613 v.add_qualif(ConstQualif::NOT_CONST);
614 if v.mode != Mode::Var {
615 span_err!(v.tcx.sess, e.span, E0018,
616 "raw pointers cannot be cast to integers in {}s", v.msg());
622 hir::ExprPath(..) => {
623 let def = v.tcx.def_map.borrow().get(&e.id).map(|d| d.full_def());
625 Some(def::DefVariant(_, _, _)) => {
626 // Count the discriminator or function pointer.
627 v.add_qualif(ConstQualif::NON_ZERO_SIZED);
629 Some(def::DefStruct(_)) => {
630 if let ty::TyBareFn(..) = node_ty.sty {
631 // Count the function pointer.
632 v.add_qualif(ConstQualif::NON_ZERO_SIZED);
635 Some(def::DefFn(..)) | Some(def::DefMethod(..)) => {
636 // Count the function pointer.
637 v.add_qualif(ConstQualif::NON_ZERO_SIZED);
639 Some(def::DefStatic(..)) => {
641 Mode::Static | Mode::StaticMut => {}
642 Mode::Const | Mode::ConstFn => {
643 span_err!(v.tcx.sess, e.span, E0013,
644 "{}s cannot refer to other statics, insert \
645 an intermediate constant instead", v.msg());
647 Mode::Var => v.add_qualif(ConstQualif::NOT_CONST)
650 Some(def::DefConst(did)) |
651 Some(def::DefAssociatedConst(did)) => {
652 if let Some(expr) = const_eval::lookup_const_by_id(v.tcx, did,
654 let inner = v.global_expr(Mode::Const, expr);
657 v.tcx.sess.span_bug(e.span,
658 "DefConst or DefAssociatedConst \
659 doesn't point to a constant");
662 Some(def::DefLocal(_)) if v.mode == Mode::ConstFn => {
663 // Sadly, we can't determine whether the types are zero-sized.
664 v.add_qualif(ConstQualif::NOT_CONST | ConstQualif::NON_ZERO_SIZED);
667 v.add_qualif(ConstQualif::NOT_CONST);
668 if v.mode != Mode::Var {
669 debug!("(checking const) found bad def: {:?}", def);
670 span_err!(v.tcx.sess, e.span, E0014,
671 "paths in {}s may only refer to constants \
672 or functions", v.msg());
677 hir::ExprCall(ref callee, _) => {
678 let mut callee = &**callee;
680 callee = match callee.node {
681 hir::ExprBlock(ref block) => match block.expr {
682 Some(ref tail) => &**tail,
688 let def = v.tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def());
689 let is_const = match def {
690 Some(def::DefStruct(..)) => true,
691 Some(def::DefVariant(..)) => {
692 // Count the discriminator.
693 v.add_qualif(ConstQualif::NON_ZERO_SIZED);
696 Some(def::DefFn(did, _)) => {
697 v.handle_const_fn_call(e, did, node_ty)
699 Some(def::DefMethod(did)) => {
700 match v.tcx.impl_or_trait_item(did).container() {
701 ty::ImplContainer(_) => {
702 v.handle_const_fn_call(e, did, node_ty)
704 ty::TraitContainer(_) => false
710 v.add_qualif(ConstQualif::NOT_CONST);
711 if v.mode != Mode::Var {
712 fn span_limited_call_error(tcx: &ty::ctxt, span: Span, s: &str) {
713 span_err!(tcx.sess, span, E0015, "{}", s);
716 // FIXME(#24111) Remove this check when const fn stabilizes
717 if let UnstableFeatures::Disallow = v.tcx.sess.opts.unstable_features {
718 span_limited_call_error(&v.tcx, e.span,
719 &format!("function calls in {}s are limited to \
720 struct and enum constructors",
722 v.tcx.sess.span_note(e.span,
723 "a limited form of compile-time function \
724 evaluation is available on a nightly \
725 compiler via `const fn`");
727 span_limited_call_error(&v.tcx, e.span,
728 &format!("function calls in {}s are limited \
729 to constant functions, \
730 struct and enum constructors",
736 hir::ExprMethodCall(..) => {
737 let method = v.tcx.tables.borrow().method_map[&method_call];
738 let is_const = match v.tcx.impl_or_trait_item(method.def_id).container() {
739 ty::ImplContainer(_) => v.handle_const_fn_call(e, method.def_id, node_ty),
740 ty::TraitContainer(_) => false
743 v.add_qualif(ConstQualif::NOT_CONST);
744 if v.mode != Mode::Var {
745 span_err!(v.tcx.sess, e.span, E0378,
746 "method calls in {}s are limited to \
747 constant inherent methods", v.msg());
751 hir::ExprStruct(..) => {
752 let did = v.tcx.def_map.borrow().get(&e.id).map(|def| def.def_id());
753 if did == v.tcx.lang_items.unsafe_cell_type() {
754 v.add_qualif(ConstQualif::MUTABLE_MEM);
759 hir::ExprAddrOf(..) => {
760 v.add_qualif(ConstQualif::NON_ZERO_SIZED);
763 hir::ExprRepeat(..) => {
764 v.add_qualif(ConstQualif::PREFER_IN_PLACE);
767 hir::ExprClosure(..) => {
768 // Paths in constant contexts cannot refer to local variables,
769 // as there are none, and thus closures can't have upvars there.
770 if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
771 assert!(v.mode == Mode::Var,
772 "global closures can't capture anything");
773 v.add_qualif(ConstQualif::NOT_CONST);
780 hir::ExprTupField(..) |
782 hir::ExprTup(..) => {}
784 // Conditional control flow (possible to implement).
788 // Loops (not very meaningful in constants).
792 // More control flow (also not very meaningful).
797 // Miscellaneous expressions that could be implemented.
800 // Expressions with side-effects.
801 hir::ExprAssign(..) |
802 hir::ExprAssignOp(..) |
803 hir::ExprInlineAsm(_) => {
804 v.add_qualif(ConstQualif::NOT_CONST);
805 if v.mode != Mode::Var {
806 span_err!(v.tcx.sess, e.span, E0019,
807 "{} contains unimplemented expression type", v.msg());
813 /// Check the adjustments of an expression
814 fn check_adjustments<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr) {
815 match v.tcx.tables.borrow().adjustments.get(&e.id) {
817 Some(&ty::adjustment::AdjustReifyFnPointer) |
818 Some(&ty::adjustment::AdjustUnsafeFnPointer) => {}
820 Some(&ty::adjustment::AdjustDerefRef(
821 ty::adjustment::AutoDerefRef { autoderefs, .. }
823 if (0..autoderefs as u32).any(|autoderef| {
824 v.tcx.is_overloaded_autoderef(e.id, autoderef)
826 v.add_qualif(ConstQualif::NOT_CONST);
827 if v.mode != Mode::Var {
828 span_err!(v.tcx.sess, e.span, E0400,
829 "user-defined dereference operators are not allowed in {}s",
837 pub fn check_crate(tcx: &ty::ctxt) {
838 visit::walk_crate(&mut CheckCrateVisitor {
841 qualif: ConstQualif::NOT_CONST,
842 rvalue_borrows: NodeMap()
845 tcx.sess.abort_if_errors();
848 impl<'a, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'tcx> {
849 fn consume(&mut self,
850 _consume_id: ast::NodeId,
853 _mode: euv::ConsumeMode) {
857 mc::cat_static_item => {
858 if self.mode != Mode::Var {
859 // statics cannot be consumed by value at any time, that would imply
860 // that they're an initializer (what a const is for) or kept in sync
861 // over time (not feasible), so deny it outright.
862 span_err!(self.tcx.sess, consume_span, E0394,
863 "cannot refer to other statics by value, use the \
864 address-of operator or a constant instead");
868 mc::cat_deref(ref cmt, _, _) |
869 mc::cat_downcast(ref cmt, _) |
870 mc::cat_interior(ref cmt, _) => cur = cmt,
874 mc::cat_local(..) => break
879 borrow_id: ast::NodeId,
882 _loan_region: ty::Region,
884 loan_cause: euv::LoanCause)
886 // Kind of hacky, but we allow Unsafe coercions in constants.
887 // These occur when we convert a &T or *T to a *U, as well as
888 // when making a thin pointer (e.g., `*T`) into a fat pointer
891 euv::LoanCause::AutoUnsafe => {
898 let mut is_interior = false;
901 mc::cat_rvalue(..) => {
902 if loan_cause == euv::MatchDiscriminant {
903 // Ignore the dummy immutable borrow created by EUV.
906 let mutbl = bk.to_mutbl_lossy();
907 if mutbl == hir::MutMutable && self.mode == Mode::StaticMut {
908 // Mutable slices are the only `&mut` allowed in
909 // globals, but only in `static mut`, nowhere else.
910 // FIXME: This exception is really weird... there isn't
911 // any fundamental reason to restrict this based on
912 // type of the expression. `&mut [1]` has exactly the
913 // same representation as &mut 1.
915 ty::TyArray(_, _) | ty::TySlice(_) => break,
919 self.record_borrow(borrow_id, mutbl);
922 mc::cat_static_item => {
923 if is_interior && self.mode != Mode::Var {
924 // Borrowed statics can specifically *only* have their address taken,
925 // not any number of other borrows such as borrowing fields, reading
926 // elements of an array, etc.
927 span_err!(self.tcx.sess, borrow_span, E0494,
928 "cannot refer to the interior of another \
929 static, use a constant instead");
933 mc::cat_deref(ref cmt, _, _) |
934 mc::cat_downcast(ref cmt, _) |
935 mc::cat_interior(ref cmt, _) => {
941 mc::cat_local(..) => break
946 fn decl_without_init(&mut self,
950 _assignment_id: ast::NodeId,
951 _assignment_span: Span,
952 _assignee_cmt: mc::cmt,
953 _mode: euv::MutateMode) {}
955 fn matched_pat(&mut self,
958 _: euv::MatchMode) {}
960 fn consume_pat(&mut self,
961 _consume_pat: &hir::Pat,
963 _mode: euv::ConsumeMode) {}