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