]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/meth.rs
auto merge of #15733 : sanxiyn/rust/use-from-type, r=alexcrichton
[rust.git] / src / librustc / middle / trans / meth.rs
1 // Copyright 2012 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
12 use back::abi;
13 use llvm;
14 use llvm::ValueRef;
15 use metadata::csearch;
16 use middle::subst;
17 use middle::trans::base::*;
18 use middle::trans::build::*;
19 use middle::trans::callee::*;
20 use middle::trans::callee;
21 use middle::trans::cleanup;
22 use middle::trans::common::*;
23 use middle::trans::datum::*;
24 use middle::trans::expr::{SaveIn, Ignore};
25 use middle::trans::expr;
26 use middle::trans::glue;
27 use middle::trans::monomorphize;
28 use middle::trans::type_::Type;
29 use middle::trans::type_of::*;
30 use middle::ty;
31 use middle::typeck;
32 use middle::typeck::MethodCall;
33 use util::common::indenter;
34 use util::ppaux::Repr;
35
36 use std::c_str::ToCStr;
37 use std::gc::Gc;
38 use syntax::abi::Rust;
39 use syntax::parse::token;
40 use syntax::{ast, ast_map, visit};
41 use syntax::ast_util::PostExpansionMethod;
42
43 /**
44 The main "translation" pass for methods.  Generates code
45 for non-monomorphized methods only.  Other methods will
46 be generated once they are invoked with specific type parameters,
47 see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
48 */
49 pub fn trans_impl(ccx: &CrateContext,
50                   name: ast::Ident,
51                   methods: &[Gc<ast::Method>],
52                   generics: &ast::Generics,
53                   id: ast::NodeId) {
54     let _icx = push_ctxt("meth::trans_impl");
55     let tcx = ccx.tcx();
56
57     debug!("trans_impl(name={}, id={:?})", name.repr(tcx), id);
58
59     // Both here and below with generic methods, be sure to recurse and look for
60     // items that we need to translate.
61     if !generics.ty_params.is_empty() {
62         let mut v = TransItemVisitor{ ccx: ccx };
63         for method in methods.iter() {
64             visit::walk_method_helper(&mut v, &**method, ());
65         }
66         return;
67     }
68     for method in methods.iter() {
69         if method.pe_generics().ty_params.len() == 0u {
70             let llfn = get_item_val(ccx, method.id);
71             trans_fn(ccx,
72                      &*method.pe_fn_decl(),
73                      &*method.pe_body(),
74                      llfn,
75                      &param_substs::empty(),
76                      method.id,
77                      []);
78         } else {
79             let mut v = TransItemVisitor{ ccx: ccx };
80             visit::walk_method_helper(&mut v, &**method, ());
81         }
82     }
83 }
84
85 pub fn trans_method_callee<'a>(
86                            bcx: &'a Block<'a>,
87                            method_call: MethodCall,
88                            self_expr: Option<&ast::Expr>,
89                            arg_cleanup_scope: cleanup::ScopeId)
90                            -> Callee<'a> {
91     let _icx = push_ctxt("meth::trans_method_callee");
92
93     let (origin, method_ty) = match bcx.tcx().method_map
94                                        .borrow().find(&method_call) {
95         Some(method) => {
96             debug!("trans_method_callee({:?}, method={})",
97                    method_call, method.repr(bcx.tcx()));
98             (method.origin, method.ty)
99         }
100         None => {
101             bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
102                                 "method call expr wasn't in method map")
103         }
104     };
105
106     match origin {
107         typeck::MethodStatic(did) => {
108             Callee {
109                 bcx: bcx,
110                 data: Fn(callee::trans_fn_ref(bcx, did, MethodCall(method_call)))
111             }
112         }
113         typeck::MethodParam(typeck::MethodParam {
114             trait_id: trait_id,
115             method_num: off,
116             param_num: p,
117             bound_num: b
118         }) => {
119             ty::populate_implementations_for_trait_if_necessary(
120                 bcx.tcx(),
121                 trait_id);
122
123             let vtbl = find_vtable(bcx.tcx(), bcx.fcx.param_substs, p, b);
124             trans_monomorphized_callee(bcx, method_call,
125                                        trait_id, off, vtbl)
126         }
127
128         typeck::MethodObject(ref mt) => {
129             let self_expr = match self_expr {
130                 Some(self_expr) => self_expr,
131                 None => {
132                     bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
133                                         "self expr wasn't provided for trait object \
134                                          callee (trying to call overloaded op?)")
135                 }
136             };
137             trans_trait_callee(bcx,
138                                monomorphize_type(bcx, method_ty),
139                                mt.real_index,
140                                self_expr,
141                                arg_cleanup_scope)
142         }
143     }
144 }
145
146 pub fn trans_static_method_callee(bcx: &Block,
147                                   method_id: ast::DefId,
148                                   trait_id: ast::DefId,
149                                   expr_id: ast::NodeId)
150                                   -> ValueRef {
151     let _icx = push_ctxt("meth::trans_static_method_callee");
152     let ccx = bcx.ccx();
153
154     debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \
155             expr_id={:?})",
156            method_id,
157            ty::item_path_str(bcx.tcx(), trait_id),
158            expr_id);
159     let _indenter = indenter();
160
161     ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trait_id);
162
163     let mname = if method_id.krate == ast::LOCAL_CRATE {
164         match bcx.tcx().map.get(method_id.node) {
165             ast_map::NodeTraitMethod(method) => {
166                 let ident = match *method {
167                     ast::Required(ref m) => m.ident,
168                     ast::Provided(ref m) => m.pe_ident()
169                 };
170                 ident.name
171             }
172             _ => fail!("callee is not a trait method")
173         }
174     } else {
175         csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name()
176     };
177     debug!("trans_static_method_callee: method_id={:?}, expr_id={:?}, \
178             name={}", method_id, expr_id, token::get_name(mname));
179
180     let vtable_key = MethodCall::expr(expr_id);
181     let vtbls = resolve_vtables_in_fn_ctxt(
182         bcx.fcx,
183         ccx.tcx.vtable_map.borrow().get(&vtable_key));
184
185     match *vtbls.get_self().unwrap().get(0) {
186         typeck::vtable_static(impl_did, ref rcvr_substs, ref rcvr_origins) => {
187             assert!(rcvr_substs.types.all(|t| !ty::type_needs_infer(*t)));
188
189             let mth_id = method_with_name(ccx, impl_did, mname);
190             let (callee_substs, callee_origins) =
191                 combine_impl_and_methods_tps(
192                     bcx, ExprId(expr_id),
193                     (*rcvr_substs).clone(), (*rcvr_origins).clone());
194
195             let llfn = trans_fn_ref_with_vtables(bcx, mth_id, ExprId(expr_id),
196                                                  callee_substs,
197                                                  callee_origins);
198
199             let callee_ty = node_id_type(bcx, expr_id);
200             let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
201             PointerCast(bcx, llfn, llty)
202         }
203         _ => {
204             fail!("vtable_param left in monomorphized \
205                    function's vtable substs");
206         }
207     }
208 }
209
210 fn method_with_name(ccx: &CrateContext,
211                     impl_id: ast::DefId,
212                     name: ast::Name) -> ast::DefId {
213     match ccx.impl_method_cache.borrow().find_copy(&(impl_id, name)) {
214         Some(m) => return m,
215         None => {}
216     }
217
218     let methods = ccx.tcx.impl_methods.borrow();
219     let methods = methods.find(&impl_id)
220                          .expect("could not find impl while translating");
221     let meth_did = methods.iter().find(|&did| ty::method(&ccx.tcx, *did).ident.name == name)
222                                  .expect("could not find method while translating");
223
224     ccx.impl_method_cache.borrow_mut().insert((impl_id, name), *meth_did);
225     *meth_did
226 }
227
228 fn trans_monomorphized_callee<'a>(bcx: &'a Block<'a>,
229                                   method_call: MethodCall,
230                                   trait_id: ast::DefId,
231                                   n_method: uint,
232                                   vtbl: typeck::vtable_origin)
233                                   -> Callee<'a> {
234     let _icx = push_ctxt("meth::trans_monomorphized_callee");
235     match vtbl {
236       typeck::vtable_static(impl_did, rcvr_substs, rcvr_origins) => {
237           let ccx = bcx.ccx();
238           let mname = ty::trait_method(ccx.tcx(), trait_id, n_method).ident;
239           let mth_id = method_with_name(bcx.ccx(), impl_did, mname.name);
240
241           // create a concatenated set of substitutions which includes
242           // those from the impl and those from the method:
243           let (callee_substs, callee_origins) =
244               combine_impl_and_methods_tps(
245                   bcx, MethodCall(method_call), rcvr_substs, rcvr_origins);
246
247           // translate the function
248           let llfn = trans_fn_ref_with_vtables(bcx,
249                                                mth_id,
250                                                MethodCall(method_call),
251                                                callee_substs,
252                                                callee_origins);
253
254           Callee { bcx: bcx, data: Fn(llfn) }
255       }
256       typeck::vtable_param(..) => {
257           bcx.tcx().sess.bug(
258               "vtable_param left in monomorphized function's vtable substs");
259       }
260       typeck::vtable_error => {
261           bcx.tcx().sess.bug(
262               "vtable_error left in monomorphized function's vtable substs");
263       }
264     }
265 }
266
267 fn combine_impl_and_methods_tps(bcx: &Block,
268                                 node: ExprOrMethodCall,
269                                 rcvr_substs: subst::Substs,
270                                 rcvr_origins: typeck::vtable_res)
271                                 -> (subst::Substs, typeck::vtable_res)
272 {
273     /*!
274      * Creates a concatenated set of substitutions which includes
275      * those from the impl and those from the method.  This are
276      * some subtle complications here.  Statically, we have a list
277      * of type parameters like `[T0, T1, T2, M1, M2, M3]` where
278      * `Tn` are type parameters that appear on the receiver.  For
279      * example, if the receiver is a method parameter `A` with a
280      * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
281      *
282      * The weird part is that the type `A` might now be bound to
283      * any other type, such as `foo<X>`.  In that case, the vector
284      * we want is: `[X, M1, M2, M3]`.  Therefore, what we do now is
285      * to slice off the method type parameters and append them to
286      * the type parameters from the type that the receiver is
287      * mapped to.
288      */
289
290     let ccx = bcx.ccx();
291
292     let vtable_key = match node {
293         ExprId(id) => MethodCall::expr(id),
294         MethodCall(method_call) => method_call
295     };
296     let node_substs = node_id_substs(bcx, node);
297     let node_vtables = node_vtables(bcx, vtable_key);
298
299     debug!("rcvr_substs={:?}", rcvr_substs.repr(ccx.tcx()));
300     debug!("node_substs={:?}", node_substs.repr(ccx.tcx()));
301
302     // Break apart the type parameters from the node and type
303     // parameters from the receiver.
304     let (_, _, node_method) = node_substs.types.split();
305     let (rcvr_type, rcvr_self, rcvr_method) = rcvr_substs.types.clone().split();
306     assert!(rcvr_method.is_empty());
307     let ty_substs = subst::Substs {
308         regions: subst::ErasedRegions,
309         types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
310     };
311
312     // Now do the same work for the vtables.
313     let (rcvr_type, rcvr_self, rcvr_method) = rcvr_origins.split();
314     let (_, _, node_method) = node_vtables.split();
315     assert!(rcvr_method.is_empty());
316     let vtables = subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method);
317
318     (ty_substs, vtables)
319 }
320
321 fn trans_trait_callee<'a>(bcx: &'a Block<'a>,
322                           method_ty: ty::t,
323                           n_method: uint,
324                           self_expr: &ast::Expr,
325                           arg_cleanup_scope: cleanup::ScopeId)
326                           -> Callee<'a> {
327     /*!
328      * Create a method callee where the method is coming from a trait
329      * object (e.g., Box<Trait> type).  In this case, we must pull the fn
330      * pointer out of the vtable that is packaged up with the object.
331      * Objects are represented as a pair, so we first evaluate the self
332      * expression and then extract the self data and vtable out of the
333      * pair.
334      */
335
336     let _icx = push_ctxt("meth::trans_trait_callee");
337     let mut bcx = bcx;
338
339     // Translate self_datum and take ownership of the value by
340     // converting to an rvalue.
341     let self_datum = unpack_datum!(
342         bcx, expr::trans(bcx, self_expr));
343
344     let llval = if ty::type_needs_drop(bcx.tcx(), self_datum.ty) {
345         let self_datum = unpack_datum!(
346             bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
347
348         // Convert to by-ref since `trans_trait_callee_from_llval` wants it
349         // that way.
350         let self_datum = unpack_datum!(
351             bcx, self_datum.to_ref_datum(bcx));
352
353         // Arrange cleanup in case something should go wrong before the
354         // actual call occurs.
355         self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
356     } else {
357         // We don't have to do anything about cleanups for &Trait and &mut Trait.
358         assert!(self_datum.kind.is_by_ref());
359         self_datum.val
360     };
361
362     trans_trait_callee_from_llval(bcx, method_ty, n_method, llval)
363 }
364
365 pub fn trans_trait_callee_from_llval<'a>(bcx: &'a Block<'a>,
366                                          callee_ty: ty::t,
367                                          n_method: uint,
368                                          llpair: ValueRef)
369                                          -> Callee<'a> {
370     /*!
371      * Same as `trans_trait_callee()` above, except that it is given
372      * a by-ref pointer to the object pair.
373      */
374
375     let _icx = push_ctxt("meth::trans_trait_callee");
376     let ccx = bcx.ccx();
377
378     // Load the data pointer from the object.
379     debug!("(translating trait callee) loading second index from pair");
380     let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]);
381     let llbox = Load(bcx, llboxptr);
382     let llself = PointerCast(bcx, llbox, Type::i8p(ccx));
383
384     // Load the function from the vtable and cast it to the expected type.
385     debug!("(translating trait callee) loading method");
386     // Replace the self type (&Self or Box<Self>) with an opaque pointer.
387     let llcallee_ty = match ty::get(callee_ty).sty {
388         ty::ty_bare_fn(ref f) if f.abi == Rust => {
389             type_of_rust_fn(ccx, true, f.sig.inputs.slice_from(1), f.sig.output)
390         }
391         _ => {
392             ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn");
393         }
394     };
395     let llvtable = Load(bcx,
396                         PointerCast(bcx,
397                                     GEPi(bcx, llpair,
398                                          [0u, abi::trt_field_vtable]),
399                                     Type::vtable(ccx).ptr_to().ptr_to()));
400     let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1]));
401     let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
402
403     return Callee {
404         bcx: bcx,
405         data: TraitMethod(MethodData {
406             llfn: mptr,
407             llself: llself,
408         })
409     };
410 }
411
412 /// Creates a returns a dynamic vtable for the given type and vtable origin.
413 /// This is used only for objects.
414 fn get_vtable(bcx: &Block,
415               self_ty: ty::t,
416               origins: typeck::vtable_param_res)
417               -> ValueRef
418 {
419     debug!("get_vtable(self_ty={}, origins={})",
420            self_ty.repr(bcx.tcx()),
421            origins.repr(bcx.tcx()));
422
423     let ccx = bcx.ccx();
424     let _icx = push_ctxt("meth::get_vtable");
425
426     // Check the cache.
427     let hash_id = (self_ty, monomorphize::make_vtable_id(ccx, origins.get(0)));
428     match ccx.vtables.borrow().find(&hash_id) {
429         Some(&val) => { return val }
430         None => { }
431     }
432
433     // Not in the cache. Actually build it.
434     let methods = origins.move_iter().flat_map(|origin| {
435         match origin {
436             typeck::vtable_static(id, substs, sub_vtables) => {
437                 emit_vtable_methods(bcx, id, substs, sub_vtables).move_iter()
438             }
439             _ => ccx.sess().bug("get_vtable: expected a static origin"),
440         }
441     });
442
443     // Generate a destructor for the vtable.
444     let drop_glue = glue::get_drop_glue(ccx, self_ty);
445     let vtable = make_vtable(ccx, drop_glue, methods);
446
447     ccx.vtables.borrow_mut().insert(hash_id, vtable);
448     vtable
449 }
450
451 /// Helper function to declare and initialize the vtable.
452 pub fn make_vtable<I: Iterator<ValueRef>>(ccx: &CrateContext,
453                                           drop_glue: ValueRef,
454                                           ptrs: I)
455                                           -> ValueRef {
456     let _icx = push_ctxt("meth::make_vtable");
457
458     let components: Vec<_> = Some(drop_glue).move_iter().chain(ptrs).collect();
459
460     unsafe {
461         let tbl = C_struct(ccx, components.as_slice(), false);
462         let sym = token::gensym("vtable");
463         let vt_gvar = format!("vtable{}", sym).with_c_str(|buf| {
464             llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl).to_ref(), buf)
465         });
466         llvm::LLVMSetInitializer(vt_gvar, tbl);
467         llvm::LLVMSetGlobalConstant(vt_gvar, llvm::True);
468         llvm::SetLinkage(vt_gvar, llvm::InternalLinkage);
469         vt_gvar
470     }
471 }
472
473 fn emit_vtable_methods(bcx: &Block,
474                        impl_id: ast::DefId,
475                        substs: subst::Substs,
476                        vtables: typeck::vtable_res)
477                        -> Vec<ValueRef> {
478     let ccx = bcx.ccx();
479     let tcx = ccx.tcx();
480
481     let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
482         Some(t_id) => t_id.def_id,
483         None       => ccx.sess().bug("make_impl_vtable: don't know how to \
484                                       make a vtable for a type impl!")
485     };
486
487     ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trt_id);
488
489     let trait_method_def_ids = ty::trait_method_def_ids(tcx, trt_id);
490     trait_method_def_ids.iter().map(|method_def_id| {
491         let ident = ty::method(tcx, *method_def_id).ident;
492         // The substitutions we have are on the impl, so we grab
493         // the method type from the impl to substitute into.
494         let m_id = method_with_name(ccx, impl_id, ident.name);
495         let m = ty::method(tcx, m_id);
496         debug!("(making impl vtable) emitting method {} at subst {}",
497                m.repr(tcx),
498                substs.repr(tcx));
499         if m.generics.has_type_params(subst::FnSpace) ||
500            ty::type_has_self(ty::mk_bare_fn(tcx, m.fty.clone())) {
501             debug!("(making impl vtable) method has self or type params: {}",
502                    token::get_ident(ident));
503             C_null(Type::nil(ccx).ptr_to())
504         } else {
505             let mut fn_ref = trans_fn_ref_with_vtables(bcx,
506                                                        m_id,
507                                                        ExprId(0),
508                                                        substs.clone(),
509                                                        vtables.clone());
510             if m.explicit_self == ty::ByValueExplicitSelfCategory {
511                 fn_ref = trans_unboxing_shim(bcx,
512                                              fn_ref,
513                                              &*m,
514                                              m_id,
515                                              substs.clone());
516             }
517             fn_ref
518         }
519     }).collect()
520 }
521
522 pub fn trans_trait_cast<'a>(bcx: &'a Block<'a>,
523                             datum: Datum<Expr>,
524                             id: ast::NodeId,
525                             dest: expr::Dest)
526                             -> &'a Block<'a> {
527     /*!
528      * Generates the code to convert from a pointer (`Box<T>`, `&T`, etc)
529      * into an object (`Box<Trait>`, `&Trait`, etc). This means creating a
530      * pair where the first word is the vtable and the second word is
531      * the pointer.
532      */
533
534     let mut bcx = bcx;
535     let _icx = push_ctxt("meth::trans_cast");
536
537     let lldest = match dest {
538         Ignore => {
539             return datum.clean(bcx, "trait_cast", id);
540         }
541         SaveIn(dest) => dest
542     };
543
544     let ccx = bcx.ccx();
545     let v_ty = datum.ty;
546     let llbox_ty = type_of(bcx.ccx(), datum.ty);
547
548     // Store the pointer into the first half of pair.
549     let mut llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]);
550     llboxdest = PointerCast(bcx, llboxdest, llbox_ty.ptr_to());
551     bcx = datum.store_to(bcx, llboxdest);
552
553     // Store the vtable into the second half of pair.
554     let origins = {
555         let vtable_map = ccx.tcx.vtable_map.borrow();
556         // This trait cast might be because of implicit coercion
557         let method_call = match ccx.tcx.adjustments.borrow().find(&id) {
558             Some(&ty::AutoObject(..)) => MethodCall::autoobject(id),
559             _ => MethodCall::expr(id)
560         };
561         let vres = vtable_map.get(&method_call).get_self().unwrap();
562         resolve_param_vtables_under_param_substs(ccx.tcx(), bcx.fcx.param_substs, vres)
563     };
564     let vtable = get_vtable(bcx, v_ty, origins);
565     let llvtabledest = GEPi(bcx, lldest, [0u, abi::trt_field_vtable]);
566     let llvtabledest = PointerCast(bcx, llvtabledest, val_ty(vtable).ptr_to());
567     Store(bcx, vtable, llvtabledest);
568
569     bcx
570 }