]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/check_const.rs
Rollup merge of #28772 - tshepang:improve-paragraph, r=steveklabnik
[rust.git] / src / librustc / middle / check_const.rs
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.
4 //
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.
10
11 // Verifies that the types and values of const and static items
12 // are safe. The rules enforced by this module are:
13 //
14 // - For each *mutable* static item, it checks that its **type**:
15 //     - doesn't have a destructor
16 //     - doesn't own a box
17 //
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
22 //
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
26
27 use middle::ty::cast::{CastKind};
28 use middle::const_eval;
29 use middle::const_eval::EvalHint::ExprTypeChecked;
30 use middle::def;
31 use middle::def_id::DefId;
32 use middle::expr_use_visitor as euv;
33 use middle::infer;
34 use middle::mem_categorization as mc;
35 use middle::traits;
36 use middle::ty::{self, Ty};
37 use util::nodemap::NodeMap;
38
39 use rustc_front::hir;
40 use syntax::ast;
41 use syntax::codemap::Span;
42 use syntax::feature_gate::UnstableFeatures;
43 use rustc_front::visit::{self, FnKind, Visitor};
44
45 use std::collections::hash_map::Entry;
46 use std::cmp::Ordering;
47
48 // Const qualification, from partial to completely promotable.
49 bitflags! {
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,
73
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
80     }
81 }
82
83 #[derive(Copy, Clone, Eq, PartialEq)]
84 enum Mode {
85     Const,
86     ConstFn,
87     Static,
88     StaticMut,
89
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.
94     Var,
95 }
96
97 struct CheckCrateVisitor<'a, 'tcx: 'a> {
98     tcx: &'a ty::ctxt<'tcx>,
99     mode: Mode,
100     qualif: ConstQualif,
101     rvalue_borrows: NodeMap<hir::Mutability>
102 }
103
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,
107     {
108         let (old_mode, old_qualif) = (self.mode, self.qualif);
109         self.mode = mode;
110         self.qualif = ConstQualif::empty();
111         let r = f(self);
112         self.mode = old_mode;
113         self.qualif = old_qualif;
114         r
115     }
116
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,
119     {
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()
123         };
124
125         let infcx = infer::new_infer_ctxt(self.tcx, &self.tcx.tables, Some(param_env), false);
126
127         f(&mut euv::ExprUseVisitor::new(self, &infcx))
128     }
129
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());
137             }
138         }
139         self.with_mode(mode, |this| {
140             this.with_euv(None, |euv| euv.consume_expr(expr));
141             this.visit_expr(expr);
142             this.qualif
143         })
144     }
145
146     fn fn_like(&mut self,
147                fk: FnKind,
148                fd: &hir::FnDecl,
149                b: &hir::Block,
150                s: Span,
151                fn_id: ast::NodeId)
152                -> ConstQualif {
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());
158             }
159         }
160
161         let mode = match fk {
162             FnKind::ItemFn(_, _, _, hir::Constness::Const, _, _) => {
163                 Mode::ConstFn
164             }
165             FnKind::Method(_, m, _) => {
166                 if m.constness == hir::Constness::Const {
167                     Mode::ConstFn
168                 } else {
169                     Mode::Var
170                 }
171             }
172             _ => Mode::Var
173         };
174
175         // Ensure the arguments are simple, not mutable/by-ref or patterns.
176         if mode == Mode::ConstFn {
177             for arg in &fd.inputs {
178                 match arg.pat.node {
179                     hir::PatIdent(hir::BindByValue(hir::MutImmutable), _, None) => {}
180                     _ => {
181                         span_err!(self.tcx.sess, arg.pat.span, E0022,
182                                   "arguments of constant functions can only \
183                                    be immutable by-value bindings");
184                     }
185                 }
186             }
187         }
188
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);
192             this.qualif
193         });
194
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);
198
199         self.tcx.const_qualif_map.borrow_mut().insert(fn_id, qualif);
200         qualif
201     }
202
203     fn add_qualif(&mut self, qualif: ConstQualif) {
204         self.qualif = self.qualif | qualif;
205     }
206
207     /// Returns true if the call is to a const fn or method.
208     fn handle_const_fn_call(&mut self,
209                             expr: &hir::Expr,
210                             def_id: DefId,
211                             ret_ty: Ty<'tcx>)
212                             -> bool {
213         if let Some(fn_like) = const_eval::lookup_const_fn_by_id(self.tcx, def_id) {
214             if
215                 // we are in a static/const initializer
216                 self.mode != Mode::Var &&
217
218                 // feature-gate is not enabled
219                 !self.tcx.sess.features.borrow().const_fn &&
220
221                 // this doesn't come from a macro that has #[allow_internal_unstable]
222                 !self.tcx.sess.codemap().span_allows_unstable(expr.span)
223             {
224                 self.tcx.sess.span_err(
225                     expr.span,
226                     &format!("const fns are an unstable feature"));
227                 fileline_help!(
228                     self.tcx.sess,
229                     expr.span,
230                     "in Nightly builds, add `#![feature(const_fn)]` to the crate \
231                      attributes to enable");
232             }
233
234             let qualif = self.fn_like(fn_like.kind(),
235                                       fn_like.decl(),
236                                       fn_like.body(),
237                                       fn_like.span(),
238                                       fn_like.id());
239             self.add_qualif(qualif);
240
241             if ret_ty.type_contents(self.tcx).interior_unsafe() {
242                 self.add_qualif(ConstQualif::MUTABLE_MEM);
243             }
244
245             true
246         } else {
247             false
248         }
249     }
250
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 {
257                     entry.insert(mutbl);
258                 }
259             }
260             Entry::Vacant(entry) => {
261                 entry.insert(mutbl);
262             }
263         }
264     }
265
266     fn msg(&self) -> &'static str {
267         match self.mode {
268             Mode::Const => "constant",
269             Mode::ConstFn => "constant function",
270             Mode::StaticMut | Mode::Static => "static",
271             Mode::Var => unreachable!(),
272         }
273     }
274
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);
278
279         let suffix = if tcontents.has_dtor() {
280             "destructors"
281         } else if tcontents.owns_owned() {
282             "boxes"
283         } else {
284             return
285         };
286
287         span_err!(self.tcx.sess, e.span, E0397,
288                  "mutable statics are not allowed to have {}", suffix);
289     }
290
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) {
298             Ok(()) => { },
299             Err(ref errors) => {
300                 traits::report_fulfillment_errors(&infcx, errors);
301             }
302         }
303     }
304 }
305
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));
309         match i.node {
310             hir::ItemStatic(_, hir::MutImmutable, ref expr) => {
311                 self.check_static_type(&**expr);
312                 self.global_expr(Mode::Static, &**expr);
313             }
314             hir::ItemStatic(_, hir::MutMutable, ref expr) => {
315                 self.check_static_mut_type(&**expr);
316                 self.global_expr(Mode::StaticMut, &**expr);
317             }
318             hir::ItemConst(_, ref expr) => {
319                 self.global_expr(Mode::Const, &**expr);
320             }
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);
325                     }
326                 }
327             }
328             _ => {
329                 self.with_mode(Mode::Var, |v| visit::walk_item(v, i));
330             }
331         }
332     }
333
334     fn visit_trait_item(&mut self, t: &'v hir::TraitItem) {
335         match t.node {
336             hir::ConstTraitItem(_, ref default) => {
337                 if let Some(ref expr) = *default {
338                     self.global_expr(Mode::Const, &*expr);
339                 } else {
340                     visit::walk_trait_item(self, t);
341                 }
342             }
343             _ => self.with_mode(Mode::Var, |v| visit::walk_trait_item(v, t)),
344         }
345     }
346
347     fn visit_impl_item(&mut self, i: &'v hir::ImplItem) {
348         match i.node {
349             hir::ConstImplItem(_, ref expr) => {
350                 self.global_expr(Mode::Const, &*expr);
351             }
352             _ => self.with_mode(Mode::Var, |v| visit::walk_impl_item(v, i)),
353         }
354     }
355
356     fn visit_fn(&mut self,
357                 fk: FnKind<'v>,
358                 fd: &'v hir::FnDecl,
359                 b: &'v hir::Block,
360                 s: Span,
361                 fn_id: ast::NodeId) {
362         self.fn_like(fk, fd, b, s, fn_id);
363     }
364
365     fn visit_pat(&mut self, p: &hir::Pat) {
366         match p.node {
367             hir::PatLit(ref lit) => {
368                 self.global_expr(Mode::Const, &**lit);
369             }
370             hir::PatRange(ref start, ref end) => {
371                 self.global_expr(Mode::Const, &**start);
372                 self.global_expr(Mode::Const, &**end);
373
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");
380                     }
381                     None => {
382                         self.tcx.sess.delay_span_bug(start.span,
383                                                      "non-constant path in constant expr");
384                     }
385                 }
386             }
387             _ => visit::walk_pat(self, p)
388         }
389     }
390
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, _) => {
396                     match decl.node {
397                         hir::DeclLocal(_) => decl.span,
398
399                         // Item statements are allowed
400                         hir::DeclItem(_) => continue
401                     }
402                 }
403                 hir::StmtExpr(ref expr, _) => expr.span,
404                 hir::StmtSemi(ref semi, _) => semi.span,
405             };
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());
411             }
412         }
413         visit::walk_block(self, block);
414     }
415
416     fn visit_expr(&mut self, ex: &hir::Expr) {
417         let mut outer = self.qualif;
418         self.qualif = ConstQualif::empty();
419
420         let node_ty = self.tcx.node_id_to_type(ex.id);
421         check_expr(self, ex, node_ty);
422         check_adjustments(self, ex);
423
424         // Special-case some expressions to avoid certain flags bubbling up.
425         match ex.node {
426             hir::ExprCall(ref callee, ref args) => {
427                 for arg in args {
428                     self.visit_expr(&**arg)
429                 }
430
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);
436             }
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,
442                     _ => unreachable!()
443                 };
444                 // [element; 0] is always zero-sized.
445                 if count == 0 {
446                     self.qualif.remove(ConstQualif::NON_ZERO_SIZED | ConstQualif::PREFER_IN_PLACE);
447                 }
448             }
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)) => {
457                             borrow = pat_borrow;
458                         }
459                         _ => {}
460                     }
461                 }
462                 if let Some(mutbl) = borrow {
463                     self.record_borrow(discr.id, mutbl);
464                 }
465                 visit::walk_expr(self, ex);
466             }
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;
471                 match node_ty.sty {
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) {
476                                 Ok(_) => {}
477                                 Err(msg) => {
478                                     span_err!(self.tcx.sess, msg.span, E0020,
479                                               "{} in a constant expression",
480                                               msg.description())
481                                 }
482                             }
483                         }
484                     }
485                     _ => {}
486                 }
487             }
488             _ => visit::walk_expr(self, ex)
489         }
490
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");
506                     }
507                 }
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);
513                 }
514             }
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);
521                     } else {
522                         span_err!(self.tcx.sess, ex.span, E0017,
523                             "references in {}s may only refer \
524                              to immutable values", self.msg())
525                     }
526                 }
527                 if !self.qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
528                     self.add_qualif(ConstQualif::HAS_STATIC_BORROWS);
529                 }
530             }
531             None => {}
532         }
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);
536     }
537 }
538
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>) {
547     match node_ty.sty {
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",
554                           v.msg());
555             }
556         }
557         _ => {}
558     }
559
560     let method_call = ty::MethodCall::expr(e.id);
561     match e.node {
562         hir::ExprUnary(..) |
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());
569             }
570         }
571         hir::ExprBox(_) => {
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());
576             }
577         }
578         hir::ExprUnary(op, ref inner) => {
579             match v.tcx.node_id_to_type(inner.id).sty {
580                 ty::TyRawPtr(_) => {
581                     assert!(op == hir::UnDeref);
582
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());
587                     }
588                 }
589                 _ => {}
590             }
591         }
592         hir::ExprBinary(op, ref lhs, _) => {
593             match v.tcx.node_id_to_type(lhs.id).sty {
594                 ty::TyRawPtr(_) => {
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);
598
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());
603                     }
604                 }
605                 _ => {}
606             }
607         }
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());
617                     }
618                 }
619                 _ => {}
620             }
621         }
622         hir::ExprPath(..) => {
623             let def = v.tcx.def_map.borrow().get(&e.id).map(|d| d.full_def());
624             match def {
625                 Some(def::DefVariant(_, _, _)) => {
626                     // Count the discriminator or function pointer.
627                     v.add_qualif(ConstQualif::NON_ZERO_SIZED);
628                 }
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);
633                     }
634                 }
635                 Some(def::DefFn(..)) | Some(def::DefMethod(..)) => {
636                     // Count the function pointer.
637                     v.add_qualif(ConstQualif::NON_ZERO_SIZED);
638                 }
639                 Some(def::DefStatic(..)) => {
640                     match v.mode {
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());
646                         }
647                         Mode::Var => v.add_qualif(ConstQualif::NOT_CONST)
648                     }
649                 }
650                 Some(def::DefConst(did)) |
651                 Some(def::DefAssociatedConst(did)) => {
652                     if let Some(expr) = const_eval::lookup_const_by_id(v.tcx, did,
653                                                                        Some(e.id)) {
654                         let inner = v.global_expr(Mode::Const, expr);
655                         v.add_qualif(inner);
656                     } else {
657                         v.tcx.sess.span_bug(e.span,
658                                             "DefConst or DefAssociatedConst \
659                                              doesn't point to a constant");
660                     }
661                 }
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);
665                 }
666                 def => {
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());
673                     }
674                 }
675             }
676         }
677         hir::ExprCall(ref callee, _) => {
678             let mut callee = &**callee;
679             loop {
680                 callee = match callee.node {
681                     hir::ExprBlock(ref block) => match block.expr {
682                         Some(ref tail) => &**tail,
683                         None => break
684                     },
685                     _ => break
686                 };
687             }
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);
694                     true
695                 }
696                 Some(def::DefFn(did, _)) => {
697                     v.handle_const_fn_call(e, did, node_ty)
698                 }
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)
703                         }
704                         ty::TraitContainer(_) => false
705                     }
706                 }
707                 _ => false
708             };
709             if !is_const {
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);
714                     }
715
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",
721                                                          v.msg()));
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`");
726                     } else {
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",
731                                                          v.msg()));
732                     }
733                 }
734             }
735         }
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
741             };
742             if !is_const {
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());
748                 }
749             }
750         }
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);
755             }
756         }
757
758         hir::ExprLit(_) |
759         hir::ExprAddrOf(..) => {
760             v.add_qualif(ConstQualif::NON_ZERO_SIZED);
761         }
762
763         hir::ExprRepeat(..) => {
764             v.add_qualif(ConstQualif::PREFER_IN_PLACE);
765         }
766
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);
774             }
775         }
776
777         hir::ExprBlock(_) |
778         hir::ExprIndex(..) |
779         hir::ExprField(..) |
780         hir::ExprTupField(..) |
781         hir::ExprVec(_) |
782         hir::ExprTup(..) => {}
783
784         // Conditional control flow (possible to implement).
785         hir::ExprMatch(..) |
786         hir::ExprIf(..) |
787
788         // Loops (not very meaningful in constants).
789         hir::ExprWhile(..) |
790         hir::ExprLoop(..) |
791
792         // More control flow (also not very meaningful).
793         hir::ExprBreak(_) |
794         hir::ExprAgain(_) |
795         hir::ExprRet(_) |
796
797         // Miscellaneous expressions that could be implemented.
798         hir::ExprRange(..) |
799
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());
808             }
809         }
810     }
811 }
812
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) {
816         None |
817         Some(&ty::adjustment::AdjustReifyFnPointer) |
818         Some(&ty::adjustment::AdjustUnsafeFnPointer) => {}
819
820         Some(&ty::adjustment::AdjustDerefRef(
821             ty::adjustment::AutoDerefRef { autoderefs, .. }
822         )) => {
823             if (0..autoderefs as u32).any(|autoderef| {
824                     v.tcx.is_overloaded_autoderef(e.id, autoderef)
825             }) {
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",
830                               v.msg());
831                 }
832             }
833         }
834     }
835 }
836
837 pub fn check_crate(tcx: &ty::ctxt) {
838     visit::walk_crate(&mut CheckCrateVisitor {
839         tcx: tcx,
840         mode: Mode::Var,
841         qualif: ConstQualif::NOT_CONST,
842         rvalue_borrows: NodeMap()
843     }, tcx.map.krate());
844
845     tcx.sess.abort_if_errors();
846 }
847
848 impl<'a, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'tcx> {
849     fn consume(&mut self,
850                _consume_id: ast::NodeId,
851                consume_span: Span,
852                cmt: mc::cmt,
853                _mode: euv::ConsumeMode) {
854         let mut cur = &cmt;
855         loop {
856             match cur.cat {
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");
865                     }
866                     break;
867                 }
868                 mc::cat_deref(ref cmt, _, _) |
869                 mc::cat_downcast(ref cmt, _) |
870                 mc::cat_interior(ref cmt, _) => cur = cmt,
871
872                 mc::cat_rvalue(..) |
873                 mc::cat_upvar(..) |
874                 mc::cat_local(..) => break
875             }
876         }
877     }
878     fn borrow(&mut self,
879               borrow_id: ast::NodeId,
880               borrow_span: Span,
881               cmt: mc::cmt<'tcx>,
882               _loan_region: ty::Region,
883               bk: ty::BorrowKind,
884               loan_cause: euv::LoanCause)
885     {
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
889         // (e.g., `*Trait`).
890         match loan_cause {
891             euv::LoanCause::AutoUnsafe => {
892                 return;
893             }
894             _ => { }
895         }
896
897         let mut cur = &cmt;
898         let mut is_interior = false;
899         loop {
900             match cur.cat {
901                 mc::cat_rvalue(..) => {
902                     if loan_cause == euv::MatchDiscriminant {
903                         // Ignore the dummy immutable borrow created by EUV.
904                         break;
905                     }
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.
914                         match cmt.ty.sty {
915                             ty::TyArray(_, _) | ty::TySlice(_) => break,
916                             _ => {}
917                         }
918                     }
919                     self.record_borrow(borrow_id, mutbl);
920                     break;
921                 }
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");
930                     }
931                     break;
932                 }
933                 mc::cat_deref(ref cmt, _, _) |
934                 mc::cat_downcast(ref cmt, _) |
935                 mc::cat_interior(ref cmt, _) => {
936                     is_interior = true;
937                     cur = cmt;
938                 }
939
940                 mc::cat_upvar(..) |
941                 mc::cat_local(..) => break
942             }
943         }
944     }
945
946     fn decl_without_init(&mut self,
947                          _id: ast::NodeId,
948                          _span: Span) {}
949     fn mutate(&mut self,
950               _assignment_id: ast::NodeId,
951               _assignment_span: Span,
952               _assignee_cmt: mc::cmt,
953               _mode: euv::MutateMode) {}
954
955     fn matched_pat(&mut self,
956                    _: &hir::Pat,
957                    _: mc::cmt,
958                    _: euv::MatchMode) {}
959
960     fn consume_pat(&mut self,
961                    _consume_pat: &hir::Pat,
962                    _cmt: mc::cmt,
963                    _mode: euv::ConsumeMode) {}
964 }