]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/consts.rs
Add an unstable FileTypeExt extension trait for Windows
[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, LayoutError};
33 use rustc_const_math::{ConstMathErr, Op};
34 use rustc::hir::def::{Def, CtorKind};
35 use rustc::hir::def_id::DefId;
36 use rustc::hir::map::blocks::FnLikeNode;
37 use rustc::middle::expr_use_visitor as euv;
38 use rustc::middle::mem_categorization as mc;
39 use rustc::middle::mem_categorization::Categorization;
40 use rustc::ty::{self, Ty, TyCtxt};
41 use rustc::ty::maps::{queries, Providers};
42 use rustc::ty::subst::Substs;
43 use rustc::traits::Reveal;
44 use rustc::util::common::ErrorReported;
45 use rustc::util::nodemap::{ItemLocalSet, NodeSet};
46 use rustc::lint::builtin::CONST_ERR;
47 use rustc::hir::{self, PatKind, RangeEnd};
48 use std::rc::Rc;
49 use syntax::ast;
50 use syntax_pos::{Span, DUMMY_SP};
51 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
52
53 use std::cmp::Ordering;
54
55 pub fn provide(providers: &mut Providers) {
56     *providers = Providers {
57         rvalue_promotable_map,
58         const_is_rvalue_promotable_to_static,
59         ..*providers
60     };
61 }
62
63 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
64     for &body_id in &tcx.hir.krate().body_ids {
65         let def_id = tcx.hir.body_owner_def_id(body_id);
66         tcx.const_is_rvalue_promotable_to_static(def_id);
67     }
68     tcx.sess.abort_if_errors();
69 }
70
71 fn const_is_rvalue_promotable_to_static<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
72                                                   def_id: DefId)
73                                                   -> bool
74 {
75     assert!(def_id.is_local());
76
77     let node_id = tcx.hir.as_local_node_id(def_id)
78                      .expect("rvalue_promotable_map invoked with non-local def-id");
79     let body_id = tcx.hir.body_owned_by(node_id);
80     let body_hir_id = tcx.hir.node_to_hir_id(body_id.node_id);
81     tcx.rvalue_promotable_map(def_id).contains(&body_hir_id.local_id)
82 }
83
84 fn rvalue_promotable_map<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
85                                    def_id: DefId)
86                                    -> Rc<ItemLocalSet>
87 {
88     let outer_def_id = tcx.closure_base_def_id(def_id);
89     if outer_def_id != def_id {
90         return tcx.rvalue_promotable_map(outer_def_id);
91     }
92
93     let mut visitor = CheckCrateVisitor {
94         tcx,
95         tables: &ty::TypeckTables::empty(None),
96         in_fn: false,
97         in_static: false,
98         promotable: false,
99         mut_rvalue_borrows: NodeSet(),
100         param_env: ty::ParamEnv::empty(Reveal::UserFacing),
101         identity_substs: Substs::empty(),
102         result: ItemLocalSet(),
103     };
104
105     // `def_id` should be a `Body` owner
106     let node_id = tcx.hir.as_local_node_id(def_id)
107                      .expect("rvalue_promotable_map invoked with non-local def-id");
108     let body_id = tcx.hir.body_owned_by(node_id);
109     visitor.visit_nested_body(body_id);
110
111     Rc::new(visitor.result)
112 }
113
114 struct CheckCrateVisitor<'a, 'tcx: 'a> {
115     tcx: TyCtxt<'a, 'tcx, 'tcx>,
116     in_fn: bool,
117     in_static: bool,
118     promotable: bool,
119     mut_rvalue_borrows: NodeSet,
120     param_env: ty::ParamEnv<'tcx>,
121     identity_substs: &'tcx Substs<'tcx>,
122     tables: &'a ty::TypeckTables<'tcx>,
123     result: ItemLocalSet,
124 }
125
126 impl<'a, 'gcx> CheckCrateVisitor<'a, 'gcx> {
127     fn const_cx(&self) -> ConstContext<'a, 'gcx> {
128         ConstContext::new(self.tcx, self.param_env.and(self.identity_substs), self.tables)
129     }
130
131     fn check_const_eval(&self, expr: &'gcx hir::Expr) {
132         if let Err(err) = self.const_cx().eval(expr) {
133             match err.kind {
134                 UnimplementedConstVal(_) => {}
135                 IndexOpFeatureGated => {}
136                 ErroneousReferencedConstant(_) => {}
137                 TypeckError => {}
138                 MiscCatchAll => {}
139                 _ => {
140                     self.tcx.lint_node(CONST_ERR,
141                                        expr.id,
142                                        expr.span,
143                                        &format!("constant evaluation error: {}",
144                                                 err.description().into_oneline()));
145                 }
146             }
147         }
148     }
149
150     // Returns true iff all the values of the type are promotable.
151     fn type_has_only_promotable_values(&mut self, ty: Ty<'gcx>) -> bool {
152         ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) &&
153         !ty.needs_drop(self.tcx, self.param_env)
154     }
155
156     fn handle_const_fn_call(&mut self, def_id: DefId, ret_ty: Ty<'gcx>) {
157         self.promotable &= self.type_has_only_promotable_values(ret_ty);
158
159         self.promotable &= if let Some(fn_id) = self.tcx.hir.as_local_node_id(def_id) {
160             FnLikeNode::from_node(self.tcx.hir.get(fn_id)).map_or(false, |fn_like| {
161                 fn_like.constness() == hir::Constness::Const
162             })
163         } else {
164             self.tcx.is_const_fn(def_id)
165         };
166     }
167 }
168
169 impl<'a, 'tcx> Visitor<'tcx> for CheckCrateVisitor<'a, 'tcx> {
170     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
171         // note that we *do* visit nested bodies, because we override `visit_nested_body` below
172         NestedVisitorMap::None
173     }
174
175     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
176         let item_id = self.tcx.hir.body_owner(body_id);
177         let item_def_id = self.tcx.hir.local_def_id(item_id);
178
179         let outer_in_fn = self.in_fn;
180         let outer_tables = self.tables;
181         let outer_param_env = self.param_env;
182         let outer_identity_substs = self.identity_substs;
183
184         self.in_fn = false;
185         self.in_static = false;
186
187         match self.tcx.hir.body_owner_kind(item_id) {
188             hir::BodyOwnerKind::Fn => self.in_fn = true,
189             hir::BodyOwnerKind::Static(_) => self.in_static = true,
190             _ => {}
191         };
192
193
194         self.tables = self.tcx.typeck_tables_of(item_def_id);
195         self.param_env = self.tcx.param_env(item_def_id);
196         self.identity_substs = Substs::identity_for_item(self.tcx, item_def_id);
197
198         let body = self.tcx.hir.body(body_id);
199         if !self.in_fn {
200             self.check_const_eval(&body.value);
201         }
202
203         let tcx = self.tcx;
204         let param_env = self.param_env;
205         let region_scope_tree = self.tcx.region_scope_tree(item_def_id);
206         euv::ExprUseVisitor::new(self, tcx, param_env, &region_scope_tree, self.tables, None)
207             .consume_body(body);
208
209         self.visit_body(body);
210
211         self.in_fn = outer_in_fn;
212         self.tables = outer_tables;
213         self.param_env = outer_param_env;
214         self.identity_substs = outer_identity_substs;
215     }
216
217     fn visit_pat(&mut self, p: &'tcx hir::Pat) {
218         match p.node {
219             PatKind::Lit(ref lit) => {
220                 self.check_const_eval(lit);
221             }
222             PatKind::Range(ref start, ref end, RangeEnd::Excluded) => {
223                 match self.const_cx().compare_lit_exprs(p.span, start, end) {
224                     Ok(Ordering::Less) => {}
225                     Ok(Ordering::Equal) |
226                     Ok(Ordering::Greater) => {
227                         span_err!(self.tcx.sess,
228                                   start.span,
229                                   E0579,
230                                   "lower range bound must be less than upper");
231                     }
232                     Err(ErrorReported) => {}
233                 }
234             }
235             PatKind::Range(ref start, ref end, RangeEnd::Included) => {
236                 match self.const_cx().compare_lit_exprs(p.span, start, end) {
237                     Ok(Ordering::Less) |
238                     Ok(Ordering::Equal) => {}
239                     Ok(Ordering::Greater) => {
240                         struct_span_err!(self.tcx.sess, start.span, E0030,
241                             "lower range bound must be less than or equal to upper")
242                             .span_label(start.span, "lower bound larger than upper bound")
243                             .emit();
244                     }
245                     Err(ErrorReported) => {}
246                 }
247             }
248             _ => {}
249         }
250         intravisit::walk_pat(self, p);
251     }
252
253     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
254         match stmt.node {
255             hir::StmtDecl(ref decl, _) => {
256                 match decl.node {
257                     hir::DeclLocal(_) => {
258                         self.promotable = false;
259                     }
260                     // Item statements are allowed
261                     hir::DeclItem(_) => {}
262                 }
263             }
264             hir::StmtExpr(..) |
265             hir::StmtSemi(..) => {
266                 self.promotable = false;
267             }
268         }
269         intravisit::walk_stmt(self, stmt);
270     }
271
272     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
273         let outer = self.promotable;
274         self.promotable = true;
275
276         let node_ty = self.tables.node_id_to_type(ex.hir_id);
277         check_expr(self, ex, node_ty);
278         check_adjustments(self, ex);
279
280         if let hir::ExprMatch(ref discr, ref arms, _) = ex.node {
281             // Compute the most demanding borrow from all the arms'
282             // patterns and set that on the discriminator.
283             let mut mut_borrow = false;
284             for pat in arms.iter().flat_map(|arm| &arm.pats) {
285                 if self.mut_rvalue_borrows.remove(&pat.id) {
286                     mut_borrow = true;
287                 }
288             }
289             if mut_borrow {
290                 self.mut_rvalue_borrows.insert(discr.id);
291             }
292         }
293
294         intravisit::walk_expr(self, ex);
295
296         // Handle borrows on (or inside the autorefs of) this expression.
297         if self.mut_rvalue_borrows.remove(&ex.id) {
298             self.promotable = false;
299         }
300
301         if self.in_fn && self.promotable {
302             match self.const_cx().eval(ex) {
303                 Ok(_) => {}
304                 Err(ConstEvalErr { kind: UnimplementedConstVal(_), .. }) |
305                 Err(ConstEvalErr { kind: MiscCatchAll, .. }) |
306                 Err(ConstEvalErr { kind: MiscBinaryOp, .. }) |
307                 Err(ConstEvalErr { kind: NonConstPath, .. }) |
308                 Err(ConstEvalErr { kind: ErroneousReferencedConstant(_), .. }) |
309                 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shr)), .. }) |
310                 Err(ConstEvalErr { kind: Math(ConstMathErr::Overflow(Op::Shl)), .. }) |
311                 Err(ConstEvalErr { kind: IndexOpFeatureGated, .. }) => {}
312                 Err(ConstEvalErr { kind: TypeckError, .. }) => {}
313                 Err(ConstEvalErr {
314                     kind: LayoutError(ty::layout::LayoutError::Unknown(_)), ..
315                 }) => {}
316                 Err(msg) => {
317                     self.tcx.lint_node(CONST_ERR,
318                                        ex.id,
319                                        msg.span,
320                                        &msg.description().into_oneline().into_owned());
321                 }
322             }
323         }
324
325         if self.promotable {
326             self.result.insert(ex.hir_id.local_id);
327         }
328         self.promotable &= outer;
329     }
330 }
331
332 /// This function is used to enforce the constraints on
333 /// const/static items. It walks through the *value*
334 /// of the item walking down the expression and evaluating
335 /// every nested expression. If the expression is not part
336 /// of a const/static item, it is qualified for promotion
337 /// instead of producing errors.
338 fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr, node_ty: Ty<'tcx>) {
339     match node_ty.sty {
340         ty::TyAdt(def, _) if def.has_dtor(v.tcx) => {
341             v.promotable = false;
342         }
343         _ => {}
344     }
345
346     match e.node {
347         hir::ExprUnary(..) |
348         hir::ExprBinary(..) |
349         hir::ExprIndex(..) if v.tables.is_method_call(e) => {
350             v.promotable = false;
351         }
352         hir::ExprBox(_) => {
353             v.promotable = false;
354         }
355         hir::ExprUnary(op, ref inner) => {
356             match v.tables.node_id_to_type(inner.hir_id).sty {
357                 ty::TyRawPtr(_) => {
358                     assert!(op == hir::UnDeref);
359
360                     v.promotable = false;
361                 }
362                 _ => {}
363             }
364         }
365         hir::ExprBinary(op, ref lhs, _) => {
366             match v.tables.node_id_to_type(lhs.hir_id).sty {
367                 ty::TyRawPtr(_) => {
368                     assert!(op.node == hir::BiEq || op.node == hir::BiNe ||
369                             op.node == hir::BiLe || op.node == hir::BiLt ||
370                             op.node == hir::BiGe || op.node == hir::BiGt);
371
372                     v.promotable = false;
373                 }
374                 _ => {}
375             }
376         }
377         hir::ExprCast(ref from, _) => {
378             debug!("Checking const cast(id={})", from.id);
379             match v.tables.cast_kinds().get(from.hir_id) {
380                 None => span_bug!(e.span, "no kind for cast"),
381                 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
382                     v.promotable = false;
383                 }
384                 _ => {}
385             }
386         }
387         hir::ExprPath(ref qpath) => {
388             let def = v.tables.qpath_def(qpath, e.hir_id);
389             match def {
390                 Def::VariantCtor(..) | Def::StructCtor(..) |
391                 Def::Fn(..) | Def::Method(..) =>  {}
392
393                 // References to a static that are themselves within a static
394                 // are inherently promotable with the exception
395                 //  of "#[thread_loca]" statics, which may not
396                 // outlive the current function
397                 Def::Static(did, _) => {
398
399                     if v.in_static {
400                         let mut thread_local = false;
401
402                         for attr in &v.tcx.get_attrs(did)[..] {
403                             if attr.check_name("thread_local") {
404                                 debug!("Reference to Static(id={:?}) is unpromotable \
405                                        due to a #[thread_local] attribute", did);
406                                 v.promotable = false;
407                                 thread_local = true;
408                                 break;
409                             }
410                         }
411
412                         if !thread_local {
413                             debug!("Allowing promotion of reference to Static(id={:?})", did);
414                         }
415                     } else {
416                         debug!("Reference to Static(id={:?}) is unpromotable as it is not \
417                                referenced from a static", did);
418                         v.promotable = false;
419
420                     }
421                 }
422
423                 Def::Const(did) |
424                 Def::AssociatedConst(did) => {
425                     let promotable = if v.tcx.trait_of_item(did).is_some() {
426                         // Don't peek inside trait associated constants.
427                         false
428                     } else {
429                         queries::const_is_rvalue_promotable_to_static::try_get(v.tcx, e.span, did)
430                             .unwrap_or_else(|mut err| {
431                                 // A cycle between constants ought to be reported elsewhere.
432                                 err.cancel();
433                                 v.tcx.sess.delay_span_bug(
434                                     e.span,
435                                     &format!("cycle encountered during const qualification: {:?}",
436                                              did));
437                                 false
438                             })
439                     };
440
441                     // Just in case the type is more specific than the definition,
442                     // e.g. impl associated const with type parameters, check it.
443                     // Also, trait associated consts are relaxed by this.
444                     v.promotable &= promotable || v.type_has_only_promotable_values(node_ty);
445                 }
446
447                 _ => {
448                     v.promotable = false;
449                 }
450             }
451         }
452         hir::ExprCall(ref callee, _) => {
453             let mut callee = &**callee;
454             loop {
455                 callee = match callee.node {
456                     hir::ExprBlock(ref block) => match block.expr {
457                         Some(ref tail) => &tail,
458                         None => break
459                     },
460                     _ => break
461                 };
462             }
463             // The callee is an arbitrary expression, it doesn't necessarily have a definition.
464             let def = if let hir::ExprPath(ref qpath) = callee.node {
465                 v.tables.qpath_def(qpath, callee.hir_id)
466             } else {
467                 Def::Err
468             };
469             match def {
470                 Def::StructCtor(_, CtorKind::Fn) |
471                 Def::VariantCtor(_, CtorKind::Fn) => {}
472                 Def::Fn(did) => {
473                     v.handle_const_fn_call(did, node_ty)
474                 }
475                 Def::Method(did) => {
476                     match v.tcx.associated_item(did).container {
477                         ty::ImplContainer(_) => {
478                             v.handle_const_fn_call(did, node_ty)
479                         }
480                         ty::TraitContainer(_) => v.promotable = false
481                     }
482                 }
483                 _ => v.promotable = false
484             }
485         }
486         hir::ExprMethodCall(..) => {
487             let def_id = v.tables.type_dependent_defs()[e.hir_id].def_id();
488             match v.tcx.associated_item(def_id).container {
489                 ty::ImplContainer(_) => v.handle_const_fn_call(def_id, node_ty),
490                 ty::TraitContainer(_) => v.promotable = false
491             }
492         }
493         hir::ExprStruct(..) => {
494             if let ty::TyAdt(adt, ..) = v.tables.expr_ty(e).sty {
495                 // unsafe_cell_type doesn't necessarily exist with no_core
496                 if Some(adt.did) == v.tcx.lang_items().unsafe_cell_type() {
497                     v.promotable = false;
498                 }
499             }
500         }
501
502         hir::ExprLit(_) |
503         hir::ExprAddrOf(..) |
504         hir::ExprRepeat(..) => {}
505
506         hir::ExprClosure(..) => {
507             // Paths in constant contexts cannot refer to local variables,
508             // as there are none, and thus closures can't have upvars there.
509             if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
510                 v.promotable = false;
511             }
512         }
513
514         hir::ExprBlock(_) |
515         hir::ExprIndex(..) |
516         hir::ExprField(..) |
517         hir::ExprTupField(..) |
518         hir::ExprArray(_) |
519         hir::ExprType(..) |
520         hir::ExprTup(..) => {}
521
522         // Conditional control flow (possible to implement).
523         hir::ExprMatch(..) |
524         hir::ExprIf(..) |
525
526         // Loops (not very meaningful in constants).
527         hir::ExprWhile(..) |
528         hir::ExprLoop(..) |
529
530         // More control flow (also not very meaningful).
531         hir::ExprBreak(..) |
532         hir::ExprAgain(_) |
533         hir::ExprRet(_) |
534
535         // Generator expressions
536         hir::ExprYield(_) |
537
538         // Expressions with side-effects.
539         hir::ExprAssign(..) |
540         hir::ExprAssignOp(..) |
541         hir::ExprInlineAsm(..) => {
542             v.promotable = false;
543         }
544     }
545 }
546
547 /// Check the adjustments of an expression
548 fn check_adjustments<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr) {
549     use rustc::ty::adjustment::*;
550
551     for adjustment in v.tables.expr_adjustments(e) {
552         match adjustment.kind {
553             Adjust::NeverToAny |
554             Adjust::ReifyFnPointer |
555             Adjust::UnsafeFnPointer |
556             Adjust::ClosureFnPointer |
557             Adjust::MutToConstPointer |
558             Adjust::Borrow(_) |
559             Adjust::Unsize => {}
560
561             Adjust::Deref(ref overloaded) => {
562                 if overloaded.is_some() {
563                     v.promotable = false;
564                     break;
565                 }
566             }
567         }
568     }
569 }
570
571 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> {
572     fn consume(&mut self,
573                _consume_id: ast::NodeId,
574                _consume_span: Span,
575                _cmt: mc::cmt,
576                _mode: euv::ConsumeMode) {}
577
578     fn borrow(&mut self,
579               borrow_id: ast::NodeId,
580               _borrow_span: Span,
581               cmt: mc::cmt<'tcx>,
582               _loan_region: ty::Region<'tcx>,
583               bk: ty::BorrowKind,
584               loan_cause: euv::LoanCause) {
585         // Kind of hacky, but we allow Unsafe coercions in constants.
586         // These occur when we convert a &T or *T to a *U, as well as
587         // when making a thin pointer (e.g., `*T`) into a fat pointer
588         // (e.g., `*Trait`).
589         match loan_cause {
590             euv::LoanCause::AutoUnsafe => {
591                 return;
592             }
593             _ => {}
594         }
595
596         let mut cur = &cmt;
597         loop {
598             match cur.cat {
599                 Categorization::Rvalue(..) => {
600                     if loan_cause == euv::MatchDiscriminant {
601                         // Ignore the dummy immutable borrow created by EUV.
602                         break;
603                     }
604                     if bk.to_mutbl_lossy() == hir::MutMutable {
605                         self.mut_rvalue_borrows.insert(borrow_id);
606                     }
607                     break;
608                 }
609                 Categorization::StaticItem => {
610                     break;
611                 }
612                 Categorization::Deref(ref cmt, _) |
613                 Categorization::Downcast(ref cmt, _) |
614                 Categorization::Interior(ref cmt, _) => {
615                     cur = cmt;
616                 }
617
618                 Categorization::Upvar(..) |
619                 Categorization::Local(..) => break,
620             }
621         }
622     }
623
624     fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {}
625     fn mutate(&mut self,
626               _assignment_id: ast::NodeId,
627               _assignment_span: Span,
628               _assignee_cmt: mc::cmt,
629               _mode: euv::MutateMode) {
630     }
631
632     fn matched_pat(&mut self, _: &hir::Pat, _: mc::cmt, _: euv::MatchMode) {}
633
634     fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: mc::cmt, _mode: euv::ConsumeMode) {}
635 }