]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/consts.rs
intern CodeExtents
[rust.git] / src / librustc_passes / consts.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 rustc::ty::cast::CastKind;
28 use rustc_const_eval::ConstContext;
29 use rustc::middle::const_val::ConstEvalErr;
30 use rustc::middle::const_val::ErrKind::{IndexOpFeatureGated, UnimplementedConstVal, MiscCatchAll};
31 use rustc::middle::const_val::ErrKind::{ErroneousReferencedConstant, MiscBinaryOp, NonConstPath};
32 use rustc::middle::const_val::ErrKind::{TypeckError, Math};
33 use rustc_const_math::{ConstMathErr, Op};
34 use rustc::hir::def::{Def, CtorKind};
35 use rustc::hir::def_id::DefId;
36 use rustc::hir::map::blocks::FnLikeNode;
37 use rustc::middle::expr_use_visitor as euv;
38 use rustc::middle::mem_categorization as mc;
39 use rustc::middle::mem_categorization::Categorization;
40 use rustc::mir::transform::MirSource;
41 use rustc::ty::{self, Ty, TyCtxt};
42 use rustc::traits::Reveal;
43 use rustc::util::common::ErrorReported;
44 use rustc::util::nodemap::NodeSet;
45 use rustc::lint::builtin::CONST_ERR;
46
47 use rustc::hir::{self, PatKind, RangeEnd};
48 use syntax::ast;
49 use syntax_pos::{Span, DUMMY_SP};
50 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
51
52 use std::collections::hash_map::Entry;
53 use std::cmp::Ordering;
54 use std::mem;
55
56 struct CheckCrateVisitor<'a, 'tcx: 'a> {
57     tcx: TyCtxt<'a, 'tcx, 'tcx>,
58     in_fn: bool,
59     promotable: bool,
60     mut_rvalue_borrows: NodeSet,
61     param_env: ty::ParameterEnvironment<'tcx>,
62     tables: &'a ty::TypeckTables<'tcx>,
63 }
64
65 impl<'a, 'gcx> CheckCrateVisitor<'a, 'gcx> {
66     fn check_const_eval(&self, expr: &'gcx hir::Expr) {
67         let const_cx = ConstContext::with_tables(self.tcx, self.tables);
68         if let Err(err) = const_cx.eval(expr) {
69             match err.kind {
70                 UnimplementedConstVal(_) => {}
71                 IndexOpFeatureGated => {}
72                 ErroneousReferencedConstant(_) => {}
73                 TypeckError => {}
74                 _ => {
75                     self.tcx.sess.add_lint(CONST_ERR,
76                                            expr.id,
77                                            expr.span,
78                                            format!("constant evaluation error: {}. This will \
79                                                     become a HARD ERROR in the future",
80                                                    err.description().into_oneline()))
81                 }
82             }
83         }
84     }
85
86     // Adds the worst effect out of all the values of one type.
87     fn add_type(&mut self, ty: Ty<'gcx>) {
88         if !ty.is_freeze(self.tcx, &self.param_env, DUMMY_SP) {
89             self.promotable = false;
90         }
91
92         if ty.needs_drop(self.tcx, &self.param_env) {
93             self.promotable = false;
94         }
95     }
96
97     fn handle_const_fn_call(&mut self, def_id: DefId, ret_ty: Ty<'gcx>) {
98         self.add_type(ret_ty);
99
100         self.promotable &= if let Some(fn_id) = self.tcx.hir.as_local_node_id(def_id) {
101             FnLikeNode::from_node(self.tcx.hir.get(fn_id)).map_or(false, |fn_like| {
102                 fn_like.constness() == hir::Constness::Const
103             })
104         } else {
105             self.tcx.sess.cstore.is_const_fn(def_id)
106         };
107     }
108 }
109
110 impl<'a, 'tcx> Visitor<'tcx> for CheckCrateVisitor<'a, 'tcx> {
111     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
112         NestedVisitorMap::None
113     }
114
115     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
116         match self.tcx.rvalue_promotable_to_static.borrow_mut().entry(body_id.node_id) {
117             Entry::Occupied(_) => return,
118             Entry::Vacant(entry) => {
119                 // Prevent infinite recursion on re-entry.
120                 entry.insert(false);
121             }
122         }
123
124         let item_id = self.tcx.hir.body_owner(body_id);
125
126         let outer_in_fn = self.in_fn;
127         self.in_fn = match MirSource::from_node(self.tcx, item_id) {
128             MirSource::Fn(_) => true,
129             _ => false
130         };
131
132         let outer_tables = self.tables;
133         self.tables = self.tcx.typeck_tables_of(self.tcx.hir.local_def_id(item_id));
134
135         let body = self.tcx.hir.body(body_id);
136         if !self.in_fn {
137             self.check_const_eval(&body.value);
138         }
139
140         let outer_penv = self.tcx.infer_ctxt(body_id, Reveal::UserFacing).enter(|infcx| {
141             let param_env = infcx.parameter_environment.clone();
142             let outer_penv = mem::replace(&mut self.param_env, param_env);
143             euv::ExprUseVisitor::new(self, &infcx).consume_body(body);
144             outer_penv
145         });
146
147         self.visit_body(body);
148
149         self.param_env = outer_penv;
150         self.tables = outer_tables;
151         self.in_fn = outer_in_fn;
152     }
153
154     fn visit_pat(&mut self, p: &'tcx hir::Pat) {
155         match p.node {
156             PatKind::Lit(ref lit) => {
157                 self.check_const_eval(lit);
158             }
159             PatKind::Range(ref start, ref end, RangeEnd::Excluded) => {
160                 let const_cx = ConstContext::with_tables(self.tcx, self.tables);
161                 match const_cx.compare_lit_exprs(p.span, start, end) {
162                     Ok(Ordering::Less) => {}
163                     Ok(Ordering::Equal) |
164                     Ok(Ordering::Greater) => {
165                         span_err!(self.tcx.sess,
166                                   start.span,
167                                   E0579,
168                                   "lower range bound must be less than upper");
169                     }
170                     Err(ErrorReported) => {}
171                 }
172             }
173             PatKind::Range(ref start, ref end, RangeEnd::Included) => {
174                 let const_cx = ConstContext::with_tables(self.tcx, self.tables);
175                 match const_cx.compare_lit_exprs(p.span, start, end) {
176                     Ok(Ordering::Less) |
177                     Ok(Ordering::Equal) => {}
178                     Ok(Ordering::Greater) => {
179                         struct_span_err!(self.tcx.sess, start.span, E0030,
180                             "lower range bound must be less than or equal to upper")
181                             .span_label(start.span, &format!("lower bound larger than upper bound"))
182                             .emit();
183                     }
184                     Err(ErrorReported) => {}
185                 }
186             }
187             _ => {}
188         }
189         intravisit::walk_pat(self, p);
190     }
191
192     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
193         match stmt.node {
194             hir::StmtDecl(ref decl, _) => {
195                 match decl.node {
196                     hir::DeclLocal(_) => {
197                         self.promotable = false;
198                     }
199                     // Item statements are allowed
200                     hir::DeclItem(_) => {}
201                 }
202             }
203             hir::StmtExpr(..) |
204             hir::StmtSemi(..) => {
205                 self.promotable = false;
206             }
207         }
208         intravisit::walk_stmt(self, stmt);
209     }
210
211     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
212         let outer = self.promotable;
213         self.promotable = true;
214
215         let node_ty = self.tables.node_id_to_type(ex.id);
216         check_expr(self, ex, node_ty);
217         check_adjustments(self, ex);
218
219         if let hir::ExprMatch(ref discr, ref arms, _) = ex.node {
220             // Compute the most demanding borrow from all the arms'
221             // patterns and set that on the discriminator.
222             let mut mut_borrow = false;
223             for pat in arms.iter().flat_map(|arm| &arm.pats) {
224                 if self.mut_rvalue_borrows.remove(&pat.id) {
225                     mut_borrow = true;
226                 }
227             }
228             if mut_borrow {
229                 self.mut_rvalue_borrows.insert(discr.id);
230             }
231         }
232
233         intravisit::walk_expr(self, ex);
234
235         // Handle borrows on (or inside the autorefs of) this expression.
236         if self.mut_rvalue_borrows.remove(&ex.id) {
237             self.promotable = false;
238         }
239
240         if self.in_fn && self.promotable {
241             let const_cx = ConstContext::with_tables(self.tcx, self.tables);
242             match const_cx.eval(ex) {
243                 Ok(_) => {}
244                 Err(ConstEvalErr { kind: UnimplementedConstVal(_), .. }) |
245                 Err(ConstEvalErr { kind: MiscCatchAll, .. }) |
246                 Err(ConstEvalErr { kind: MiscBinaryOp, .. }) |
247                 Err(ConstEvalErr { kind: NonConstPath, .. }) |
248                 Err(ConstEvalErr { kind: ErroneousReferencedConstant(_), .. }) |
249                 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shr)), .. }) |
250                 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shl)), .. }) |
251                 Err(ConstEvalErr { kind: IndexOpFeatureGated, .. }) => {}
252                 Err(ConstEvalErr { kind: TypeckError, .. }) => {}
253                 Err(msg) => {
254                     self.tcx.sess.add_lint(CONST_ERR,
255                                            ex.id,
256                                            msg.span,
257                                            msg.description().into_oneline().into_owned())
258                 }
259             }
260         }
261
262         self.tcx.rvalue_promotable_to_static.borrow_mut().insert(ex.id, self.promotable);
263         self.promotable &= outer;
264     }
265 }
266
267 /// This function is used to enforce the constraints on
268 /// const/static items. It walks through the *value*
269 /// of the item walking down the expression and evaluating
270 /// every nested expression. If the expression is not part
271 /// of a const/static item, it is qualified for promotion
272 /// instead of producing errors.
273 fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr, node_ty: Ty<'tcx>) {
274     match node_ty.sty {
275         ty::TyAdt(def, _) if def.has_dtor(v.tcx) => {
276             v.promotable = false;
277         }
278         _ => {}
279     }
280
281     let method_call = ty::MethodCall::expr(e.id);
282     match e.node {
283         hir::ExprUnary(..) |
284         hir::ExprBinary(..) |
285         hir::ExprIndex(..) if v.tables.method_map.contains_key(&method_call) => {
286             v.promotable = false;
287         }
288         hir::ExprBox(_) => {
289             v.promotable = false;
290         }
291         hir::ExprUnary(op, ref inner) => {
292             match v.tables.node_id_to_type(inner.id).sty {
293                 ty::TyRawPtr(_) => {
294                     assert!(op == hir::UnDeref);
295
296                     v.promotable = false;
297                 }
298                 _ => {}
299             }
300         }
301         hir::ExprBinary(op, ref lhs, _) => {
302             match v.tables.node_id_to_type(lhs.id).sty {
303                 ty::TyRawPtr(_) => {
304                     assert!(op.node == hir::BiEq || op.node == hir::BiNe ||
305                             op.node == hir::BiLe || op.node == hir::BiLt ||
306                             op.node == hir::BiGe || op.node == hir::BiGt);
307
308                     v.promotable = false;
309                 }
310                 _ => {}
311             }
312         }
313         hir::ExprCast(ref from, _) => {
314             debug!("Checking const cast(id={})", from.id);
315             match v.tables.cast_kinds.get(&from.id) {
316                 None => span_bug!(e.span, "no kind for cast"),
317                 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
318                     v.promotable = false;
319                 }
320                 _ => {}
321             }
322         }
323         hir::ExprPath(ref qpath) => {
324             let def = v.tables.qpath_def(qpath, e.id);
325             match def {
326                 Def::VariantCtor(..) | Def::StructCtor(..) |
327                 Def::Fn(..) | Def::Method(..) => {}
328                 Def::AssociatedConst(_) => v.add_type(node_ty),
329                 Def::Const(did) => {
330                     v.promotable &= if let Some(node_id) = v.tcx.hir.as_local_node_id(did) {
331                         match v.tcx.hir.expect_item(node_id).node {
332                             hir::ItemConst(_, body) => {
333                                 v.visit_nested_body(body);
334                                 v.tcx.rvalue_promotable_to_static.borrow()[&body.node_id]
335                             }
336                             _ => false
337                         }
338                     } else {
339                         v.tcx.sess.cstore.const_is_rvalue_promotable_to_static(did)
340                     };
341                 }
342                 _ => {
343                     v.promotable = false;
344                 }
345             }
346         }
347         hir::ExprCall(ref callee, _) => {
348             let mut callee = &**callee;
349             loop {
350                 callee = match callee.node {
351                     hir::ExprBlock(ref block) => match block.expr {
352                         Some(ref tail) => &tail,
353                         None => break
354                     },
355                     _ => break
356                 };
357             }
358             // The callee is an arbitrary expression, it doesn't necessarily have a definition.
359             let def = if let hir::ExprPath(ref qpath) = callee.node {
360                 v.tables.qpath_def(qpath, callee.id)
361             } else {
362                 Def::Err
363             };
364             match def {
365                 Def::StructCtor(_, CtorKind::Fn) |
366                 Def::VariantCtor(_, CtorKind::Fn) => {}
367                 Def::Fn(did) => {
368                     v.handle_const_fn_call(did, node_ty)
369                 }
370                 Def::Method(did) => {
371                     match v.tcx.associated_item(did).container {
372                         ty::ImplContainer(_) => {
373                             v.handle_const_fn_call(did, node_ty)
374                         }
375                         ty::TraitContainer(_) => v.promotable = false
376                     }
377                 }
378                 _ => v.promotable = false
379             }
380         }
381         hir::ExprMethodCall(..) => {
382             let method = v.tables.method_map[&method_call];
383             match v.tcx.associated_item(method.def_id).container {
384                 ty::ImplContainer(_) => v.handle_const_fn_call(method.def_id, node_ty),
385                 ty::TraitContainer(_) => v.promotable = false
386             }
387         }
388         hir::ExprStruct(..) => {
389             if let ty::TyAdt(adt, ..) = v.tables.expr_ty(e).sty {
390                 // unsafe_cell_type doesn't necessarily exist with no_core
391                 if Some(adt.did) == v.tcx.lang_items.unsafe_cell_type() {
392                     v.promotable = false;
393                 }
394             }
395         }
396
397         hir::ExprLit(_) |
398         hir::ExprAddrOf(..) |
399         hir::ExprRepeat(..) => {}
400
401         hir::ExprClosure(..) => {
402             // Paths in constant contexts cannot refer to local variables,
403             // as there are none, and thus closures can't have upvars there.
404             if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
405                 v.promotable = false;
406             }
407         }
408
409         hir::ExprBlock(_) |
410         hir::ExprIndex(..) |
411         hir::ExprField(..) |
412         hir::ExprTupField(..) |
413         hir::ExprArray(_) |
414         hir::ExprType(..) |
415         hir::ExprTup(..) => {}
416
417         // Conditional control flow (possible to implement).
418         hir::ExprMatch(..) |
419         hir::ExprIf(..) |
420
421         // Loops (not very meaningful in constants).
422         hir::ExprWhile(..) |
423         hir::ExprLoop(..) |
424
425         // More control flow (also not very meaningful).
426         hir::ExprBreak(..) |
427         hir::ExprAgain(_) |
428         hir::ExprRet(_) |
429
430         // Expressions with side-effects.
431         hir::ExprAssign(..) |
432         hir::ExprAssignOp(..) |
433         hir::ExprInlineAsm(..) => {
434             v.promotable = false;
435         }
436     }
437 }
438
439 /// Check the adjustments of an expression
440 fn check_adjustments<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr) {
441     use rustc::ty::adjustment::*;
442
443     match v.tables.adjustments.get(&e.id).map(|adj| adj.kind) {
444         None |
445         Some(Adjust::NeverToAny) |
446         Some(Adjust::ReifyFnPointer) |
447         Some(Adjust::UnsafeFnPointer) |
448         Some(Adjust::ClosureFnPointer) |
449         Some(Adjust::MutToConstPointer) => {}
450
451         Some(Adjust::DerefRef { autoderefs, .. }) => {
452             if (0..autoderefs as u32)
453                 .any(|autoderef| v.tables.is_overloaded_autoderef(e.id, autoderef)) {
454                 v.promotable = false;
455             }
456         }
457     }
458 }
459
460 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
461     tcx.hir.krate().visit_all_item_likes(&mut CheckCrateVisitor {
462         tcx: tcx,
463         tables: &ty::TypeckTables::empty(),
464         in_fn: false,
465         promotable: false,
466         mut_rvalue_borrows: NodeSet(),
467         param_env: tcx.empty_parameter_environment(),
468     }.as_deep_visitor());
469     tcx.sess.abort_if_errors();
470 }
471
472 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> {
473     fn consume(&mut self,
474                _consume_id: ast::NodeId,
475                _consume_span: Span,
476                _cmt: mc::cmt,
477                _mode: euv::ConsumeMode) {}
478
479     fn borrow(&mut self,
480               borrow_id: ast::NodeId,
481               _borrow_span: Span,
482               cmt: mc::cmt<'tcx>,
483               _loan_region: ty::Region<'tcx>,
484               bk: ty::BorrowKind,
485               loan_cause: euv::LoanCause) {
486         // Kind of hacky, but we allow Unsafe coercions in constants.
487         // These occur when we convert a &T or *T to a *U, as well as
488         // when making a thin pointer (e.g., `*T`) into a fat pointer
489         // (e.g., `*Trait`).
490         match loan_cause {
491             euv::LoanCause::AutoUnsafe => {
492                 return;
493             }
494             _ => {}
495         }
496
497         let mut cur = &cmt;
498         loop {
499             match cur.cat {
500                 Categorization::Rvalue(..) => {
501                     if loan_cause == euv::MatchDiscriminant {
502                         // Ignore the dummy immutable borrow created by EUV.
503                         break;
504                     }
505                     if bk.to_mutbl_lossy() == hir::MutMutable {
506                         self.mut_rvalue_borrows.insert(borrow_id);
507                     }
508                     break;
509                 }
510                 Categorization::StaticItem => {
511                     break;
512                 }
513                 Categorization::Deref(ref cmt, ..) |
514                 Categorization::Downcast(ref cmt, _) |
515                 Categorization::Interior(ref cmt, _) => {
516                     cur = cmt;
517                 }
518
519                 Categorization::Upvar(..) |
520                 Categorization::Local(..) => break,
521             }
522         }
523     }
524
525     fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {}
526     fn mutate(&mut self,
527               _assignment_id: ast::NodeId,
528               _assignment_span: Span,
529               _assignee_cmt: mc::cmt,
530               _mode: euv::MutateMode) {
531     }
532
533     fn matched_pat(&mut self, _: &hir::Pat, _: mc::cmt, _: euv::MatchMode) {}
534
535     fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: mc::cmt, _mode: euv::ConsumeMode) {}
536 }