]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/intrinsicck.rs
libsyntax/parse: improve associated item error reporting
[rust.git] / src / librustc / middle / intrinsicck.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 use dep_graph::DepNode;
12 use hir::def::Def;
13 use hir::def_id::DefId;
14 use infer::InferCtxt;
15 use traits::Reveal;
16 use ty::{self, Ty, TyCtxt};
17 use ty::layout::{LayoutError, Pointer, SizeSkeleton};
18
19 use syntax::abi::Abi::RustIntrinsic;
20 use syntax_pos::Span;
21 use hir::intravisit::{self, Visitor, NestedVisitorMap};
22 use hir;
23
24 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
25     let mut visitor = ItemVisitor {
26         tcx: tcx
27     };
28     tcx.visit_all_item_likes_in_krate(DepNode::IntrinsicCheck, &mut visitor.as_deep_visitor());
29 }
30
31 struct ItemVisitor<'a, 'tcx: 'a> {
32     tcx: TyCtxt<'a, 'tcx, 'tcx>
33 }
34
35 struct ExprVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
36     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>
37 }
38
39 /// If the type is `Option<T>`, it will return `T`, otherwise
40 /// the type itself. Works on most `Option`-like types.
41 fn unpack_option_like<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
42                                 ty: Ty<'tcx>)
43                                 -> Ty<'tcx> {
44     let (def, substs) = match ty.sty {
45         ty::TyAdt(def, substs) => (def, substs),
46         _ => return ty
47     };
48
49     if def.variants.len() == 2 && !def.repr.c && def.repr.int.is_none() {
50         let data_idx;
51
52         if def.variants[0].fields.is_empty() {
53             data_idx = 1;
54         } else if def.variants[1].fields.is_empty() {
55             data_idx = 0;
56         } else {
57             return ty;
58         }
59
60         if def.variants[data_idx].fields.len() == 1 {
61             return def.variants[data_idx].fields[0].ty(tcx, substs);
62         }
63     }
64
65     ty
66 }
67
68 impl<'a, 'gcx, 'tcx> ExprVisitor<'a, 'gcx, 'tcx> {
69     fn def_id_is_transmute(&self, def_id: DefId) -> bool {
70         let intrinsic = match self.infcx.tcx.item_type(def_id).sty {
71             ty::TyFnDef(.., bfty) => bfty.abi() == RustIntrinsic,
72             _ => return false
73         };
74         intrinsic && self.infcx.tcx.item_name(def_id) == "transmute"
75     }
76
77     fn check_transmute(&self, span: Span, from: Ty<'gcx>, to: Ty<'gcx>) {
78         let sk_from = SizeSkeleton::compute(from, self.infcx);
79         let sk_to = SizeSkeleton::compute(to, self.infcx);
80
81         // Check for same size using the skeletons.
82         if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
83             if sk_from.same_size(sk_to) {
84                 return;
85             }
86
87             // Special-case transmutting from `typeof(function)` and
88             // `Option<typeof(function)>` to present a clearer error.
89             let from = unpack_option_like(self.infcx.tcx.global_tcx(), from);
90             match (&from.sty, sk_to) {
91                 (&ty::TyFnDef(..), SizeSkeleton::Known(size_to))
92                         if size_to == Pointer.size(self.infcx) => {
93                     struct_span_err!(self.infcx.tcx.sess, span, E0591,
94                                      "`{}` is zero-sized and can't be transmuted to `{}`",
95                                      from, to)
96                         .span_note(span, &format!("cast with `as` to a pointer instead"))
97                         .emit();
98                     return;
99                 }
100                 _ => {}
101             }
102         }
103
104         // Try to display a sensible error with as much information as possible.
105         let skeleton_string = |ty: Ty<'gcx>, sk| {
106             match sk {
107                 Ok(SizeSkeleton::Known(size)) => {
108                     format!("{} bits", size.bits())
109                 }
110                 Ok(SizeSkeleton::Pointer { tail, .. }) => {
111                     format!("pointer to {}", tail)
112                 }
113                 Err(LayoutError::Unknown(bad)) => {
114                     if bad == ty {
115                         format!("size can vary")
116                     } else {
117                         format!("size can vary because of {}", bad)
118                     }
119                 }
120                 Err(err) => err.to_string()
121             }
122         };
123
124         struct_span_err!(self.infcx.tcx.sess, span, E0512,
125                   "transmute called with differently sized types: \
126                    {} ({}) to {} ({})",
127                   from, skeleton_string(from, sk_from),
128                   to, skeleton_string(to, sk_to))
129             .span_label(span,
130                 &format!("transmuting between {} and {}",
131                     skeleton_string(from, sk_from),
132                     skeleton_string(to, sk_to)))
133             .emit();
134     }
135 }
136
137 impl<'a, 'tcx> Visitor<'tcx> for ItemVisitor<'a, 'tcx> {
138     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
139         NestedVisitorMap::None
140     }
141
142     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
143         let body = self.tcx.hir.body(body_id);
144         self.tcx.infer_ctxt(body_id, Reveal::All).enter(|infcx| {
145             let mut visitor = ExprVisitor {
146                 infcx: &infcx
147             };
148             visitor.visit_body(body);
149         });
150         self.visit_body(body);
151     }
152 }
153
154 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for ExprVisitor<'a, 'gcx, 'tcx> {
155     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
156         NestedVisitorMap::None
157     }
158
159     fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
160         let def = if let hir::ExprPath(ref qpath) = expr.node {
161             self.infcx.tables.borrow().qpath_def(qpath, expr.id)
162         } else {
163             Def::Err
164         };
165         match def {
166             Def::Fn(did) if self.def_id_is_transmute(did) => {
167                 let typ = self.infcx.tables.borrow().node_id_to_type(expr.id);
168                 let typ = self.infcx.tcx.lift_to_global(&typ).unwrap();
169                 match typ.sty {
170                     ty::TyFnDef(.., sig) if sig.abi() == RustIntrinsic => {
171                         let from = sig.inputs().skip_binder()[0];
172                         let to = *sig.output().skip_binder();
173                         self.check_transmute(expr.span, from, to);
174                     }
175                     _ => {
176                         span_bug!(expr.span, "transmute wasn't a bare fn?!");
177                     }
178                 }
179             }
180             _ => {}
181         }
182
183         intravisit::walk_expr(self, expr);
184     }
185 }