]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/meth.rs
f5b2ff755966e6cf3f29ff2f7b2cb2fe26202d19
[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::trans::base::*;
18 use middle::trans::build::*;
19 use middle::trans::callee::*;
20 use middle::trans::callee;
21 use middle::trans::common::*;
22 use middle::trans::datum::*;
23 use middle::trans::expr::{SaveIn, Ignore};
24 use middle::trans::expr;
25 use middle::trans::glue;
26 use middle::trans::monomorphize;
27 use middle::trans::type_of::*;
28 use middle::ty;
29 use middle::typeck;
30 use util::common::indenter;
31 use util::ppaux::Repr;
32
33 use middle::trans::type_::Type;
34
35 use std::c_str::ToCStr;
36 use std::vec;
37 use syntax::ast_map::{path, path_mod, path_name};
38 use syntax::ast_util;
39 use syntax::{ast, ast_map};
40
41 /**
42 The main "translation" pass for methods.  Generates code
43 for non-monomorphized methods only.  Other methods will
44 be generated once they are invoked with specific type parameters,
45 see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
46 */
47 pub fn trans_impl(ccx: @mut CrateContext,
48                   path: path,
49                   name: ast::ident,
50                   methods: &[@ast::method],
51                   generics: &ast::Generics,
52                   id: ast::NodeId) {
53     let _icx = push_ctxt("impl::trans_impl");
54     let tcx = ccx.tcx;
55
56     debug!("trans_impl(path=%s, name=%s, id=%?)",
57            path.repr(tcx), name.repr(tcx), id);
58
59     if !generics.ty_params.is_empty() { return; }
60     let sub_path = vec::append_one(path, path_name(name));
61     for method in methods.iter() {
62         if method.generics.ty_params.len() == 0u {
63             let llfn = get_item_val(ccx, method.id);
64             let path = vec::append_one(sub_path.clone(),
65                                        path_name(method.ident));
66
67             trans_method(ccx,
68                          path,
69                          *method,
70                          None,
71                          llfn);
72         }
73     }
74 }
75
76 /// Translates a (possibly monomorphized) method body.
77 ///
78 /// Parameters:
79 /// * `path`: the path to the method
80 /// * `method`: the AST node for the method
81 /// * `param_substs`: if this is a generic method, the current values for
82 ///   type parameters and so forth, else none
83 /// * `llfn`: the LLVM ValueRef for the method
84 /// * `impl_id`: the node ID of the impl this method is inside
85 ///
86 /// XXX(pcwalton) Can we take `path` by reference?
87 pub fn trans_method(ccx: @mut CrateContext,
88                     path: path,
89                     method: &ast::method,
90                     param_substs: Option<@param_substs>,
91                     llfn: ValueRef) {
92     // figure out how self is being passed
93     let self_arg = match method.explicit_self.node {
94       ast::sty_static => {
95         no_self
96       }
97       _ => {
98         // determine the (monomorphized) type that `self` maps to for
99         // this method
100         let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id);
101         let self_ty = match param_substs {
102             None => self_ty,
103             Some(@param_substs {tys: ref tys, self_ty: ref self_sub, _}) => {
104                 ty::subst_tps(ccx.tcx, *tys, *self_sub, self_ty)
105             }
106         };
107         debug!("calling trans_fn with self_ty %s",
108                self_ty.repr(ccx.tcx));
109         match method.explicit_self.node {
110           ast::sty_value => impl_self(self_ty, ty::ByRef),
111           _ => impl_self(self_ty, ty::ByCopy),
112         }
113       }
114     };
115
116     // generate the actual code
117     trans_fn(ccx,
118              path,
119              &method.decl,
120              &method.body,
121              llfn,
122              self_arg,
123              param_substs,
124              method.id,
125              []);
126 }
127
128 pub fn trans_self_arg(bcx: @mut Block,
129                       base: @ast::expr,
130                       temp_cleanups: &mut ~[ValueRef],
131                       mentry: typeck::method_map_entry) -> Result {
132     let _icx = push_ctxt("impl::trans_self_arg");
133
134     // self is passed as an opaque box in the environment slot
135     let self_ty = ty::mk_opaque_box(bcx.tcx());
136     trans_arg_expr(bcx,
137                    self_ty,
138                    mentry.self_mode,
139                    base,
140                    temp_cleanups,
141                    DontAutorefArg)
142 }
143
144 pub fn trans_method_callee(bcx: @mut Block,
145                            callee_id: ast::NodeId,
146                            this: @ast::expr,
147                            mentry: typeck::method_map_entry)
148                            -> Callee {
149     let _icx = push_ctxt("impl::trans_method_callee");
150
151     debug!("trans_method_callee(callee_id=%?, this=%s, mentry=%s)",
152            callee_id,
153            bcx.expr_to_str(this),
154            mentry.repr(bcx.tcx()));
155
156     match mentry.origin {
157         typeck::method_static(did) => {
158             let callee_fn = callee::trans_fn_ref(bcx, did, callee_id);
159             let mut temp_cleanups = ~[];
160             let Result {bcx, val} = trans_self_arg(bcx, this, &mut temp_cleanups, mentry);
161             Callee {
162                 bcx: bcx,
163                 data: Method(MethodData {
164                     llfn: callee_fn.llfn,
165                     llself: val,
166                     temp_cleanup: temp_cleanups.head_opt().map_move(|v| *v),
167                     self_mode: mentry.self_mode,
168                 })
169             }
170         }
171         typeck::method_param(typeck::method_param {
172             trait_id: trait_id,
173             method_num: off,
174             param_num: p,
175             bound_num: b
176         }) => {
177             match bcx.fcx.param_substs {
178                 Some(substs) => {
179                     let vtbl = find_vtable(bcx.tcx(), substs,
180                                            p, b);
181                     trans_monomorphized_callee(bcx, callee_id, this, mentry,
182                                                trait_id, off, vtbl)
183                 }
184                 // how to get rid of this?
185                 None => fail!("trans_method_callee: missing param_substs")
186             }
187         }
188
189         typeck::method_trait(_, off) => {
190             trans_trait_callee(bcx,
191                                callee_id,
192                                off,
193                                this)
194         }
195     }
196 }
197
198 pub fn trans_static_method_callee(bcx: @mut Block,
199                                   method_id: ast::def_id,
200                                   trait_id: ast::def_id,
201                                   callee_id: ast::NodeId)
202                                -> FnData {
203     let _icx = push_ctxt("impl::trans_static_method_callee");
204     let ccx = bcx.ccx();
205
206     debug!("trans_static_method_callee(method_id=%?, trait_id=%s, \
207             callee_id=%?)",
208            method_id,
209            ty::item_path_str(bcx.tcx(), trait_id),
210            callee_id);
211     let _indenter = indenter();
212
213     // When we translate a static fn defined in a trait like:
214     //
215     //   trait<T1...Tn> Trait {
216     //       fn foo<M1...Mn>(...) {...}
217     //   }
218     //
219     // this winds up being translated as something like:
220     //
221     //   fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...}
222     //
223     // So when we see a call to this function foo, we have to figure
224     // out which impl the `Trait<T1...Tn>` bound on the type `self` was
225     // bound to.
226     let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id).
227         generics.type_param_defs.len();
228
229     let mname = if method_id.crate == ast::LOCAL_CRATE {
230         match bcx.tcx().items.get_copy(&method_id.node) {
231             ast_map::node_trait_method(trait_method, _, _) => {
232                 ast_util::trait_method_to_ty_method(trait_method).ident
233             }
234             _ => fail!("callee is not a trait method")
235         }
236     } else {
237         let path = csearch::get_item_path(bcx.tcx(), method_id);
238         match path[path.len()-1] {
239             path_name(s) => { s }
240             path_mod(_) => { fail!("path doesn't have a name?") }
241         }
242     };
243     debug!("trans_static_method_callee: method_id=%?, callee_id=%?, \
244             name=%s", method_id, callee_id, ccx.sess.str_of(mname));
245
246     let vtbls = resolve_vtables_in_fn_ctxt(
247         bcx.fcx, ccx.maps.vtable_map.get_copy(&callee_id));
248
249     match vtbls[bound_index][0] {
250         typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
251             assert!(rcvr_substs.iter().all(|t| !ty::type_needs_infer(*t)));
252
253             let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
254             let (callee_substs, callee_origins) =
255                 combine_impl_and_methods_tps(
256                     bcx, mth_id, callee_id,
257                     *rcvr_substs, rcvr_origins);
258
259             let FnData {llfn: lval} =
260                 trans_fn_ref_with_vtables(bcx,
261                                           mth_id,
262                                           callee_id,
263                                           callee_substs,
264                                           Some(callee_origins));
265
266             let callee_ty = node_id_type(bcx, callee_id);
267             let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
268             FnData {llfn: PointerCast(bcx, lval, llty)}
269         }
270         _ => {
271             fail!("vtable_param left in monomorphized \
272                    function's vtable substs");
273         }
274     }
275 }
276
277 pub fn method_with_name(ccx: &mut CrateContext,
278                         impl_id: ast::def_id,
279                         name: ast::ident) -> ast::def_id {
280     let meth_id_opt = ccx.impl_method_cache.find_copy(&(impl_id, name));
281     match meth_id_opt {
282         Some(m) => return m,
283         None => {}
284     }
285
286     let imp = ccx.tcx.impls.find(&impl_id)
287         .expect("could not find impl while translating");
288     let meth = imp.methods.iter().find(|m| m.ident == name)
289         .expect("could not find method while translating");
290
291     ccx.impl_method_cache.insert((impl_id, name), meth.def_id);
292     meth.def_id
293 }
294
295 pub fn trans_monomorphized_callee(bcx: @mut Block,
296                                   callee_id: ast::NodeId,
297                                   base: @ast::expr,
298                                   mentry: typeck::method_map_entry,
299                                   trait_id: ast::def_id,
300                                   n_method: uint,
301                                   vtbl: typeck::vtable_origin)
302                                   -> Callee {
303     let _icx = push_ctxt("impl::trans_monomorphized_callee");
304     return match vtbl {
305       typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
306           let ccx = bcx.ccx();
307           let mname = ty::trait_method(ccx.tcx, trait_id, n_method).ident;
308           let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
309
310           // obtain the `self` value:
311           let mut temp_cleanups = ~[];
312           let Result {bcx, val: llself_val} =
313               trans_self_arg(bcx, base, &mut temp_cleanups, mentry);
314
315           // create a concatenated set of substitutions which includes
316           // those from the impl and those from the method:
317           let (callee_substs, callee_origins) =
318               combine_impl_and_methods_tps(
319                   bcx, mth_id, callee_id,
320                   *rcvr_substs, rcvr_origins);
321
322           // translate the function
323           let callee = trans_fn_ref_with_vtables(bcx,
324                                                  mth_id,
325                                                  callee_id,
326                                                  callee_substs,
327                                                  Some(callee_origins));
328
329           // create a llvalue that represents the fn ptr
330           let fn_ty = node_id_type(bcx, callee_id);
331           let llfn_ty = type_of_fn_from_ty(ccx, fn_ty).ptr_to();
332           let llfn_val = PointerCast(bcx, callee.llfn, llfn_ty);
333
334           // combine the self environment with the rest
335           Callee {
336               bcx: bcx,
337               data: Method(MethodData {
338                   llfn: llfn_val,
339                   llself: llself_val,
340                   temp_cleanup: temp_cleanups.head_opt().map_move(|v| *v),
341                   self_mode: mentry.self_mode,
342               })
343           }
344       }
345       typeck::vtable_param(*) => {
346           fail!("vtable_param left in monomorphized function's vtable substs");
347       }
348     };
349
350 }
351
352 pub fn combine_impl_and_methods_tps(bcx: @mut Block,
353                                     mth_did: ast::def_id,
354                                     callee_id: ast::NodeId,
355                                     rcvr_substs: &[ty::t],
356                                     rcvr_origins: typeck::vtable_res)
357                                     -> (~[ty::t], typeck::vtable_res) {
358     /*!
359     *
360     * Creates a concatenated set of substitutions which includes
361     * those from the impl and those from the method.  This are
362     * some subtle complications here.  Statically, we have a list
363     * of type parameters like `[T0, T1, T2, M1, M2, M3]` where
364     * `Tn` are type parameters that appear on the receiver.  For
365     * example, if the receiver is a method parameter `A` with a
366     * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
367     *
368     * The weird part is that the type `A` might now be bound to
369     * any other type, such as `foo<X>`.  In that case, the vector
370     * we want is: `[X, M1, M2, M3]`.  Therefore, what we do now is
371     * to slice off the method type parameters and append them to
372     * the type parameters from the type that the receiver is
373     * mapped to. */
374
375     let ccx = bcx.ccx();
376     let method = ty::method(ccx.tcx, mth_did);
377     let n_m_tps = method.generics.type_param_defs.len();
378     let node_substs = node_id_type_params(bcx, callee_id);
379     debug!("rcvr_substs=%?", rcvr_substs.repr(ccx.tcx));
380     let ty_substs
381         = vec::append(rcvr_substs.to_owned(),
382                       node_substs.tailn(node_substs.len() - n_m_tps));
383     debug!("n_m_tps=%?", n_m_tps);
384     debug!("node_substs=%?", node_substs.repr(ccx.tcx));
385     debug!("ty_substs=%?", ty_substs.repr(ccx.tcx));
386
387
388     // Now, do the same work for the vtables.  The vtables might not
389     // exist, in which case we need to make them.
390     let r_m_origins = match node_vtables(bcx, callee_id) {
391         Some(vt) => vt,
392         None => @vec::from_elem(node_substs.len(), @~[])
393     };
394     let vtables
395         = @vec::append(rcvr_origins.to_owned(),
396                        r_m_origins.tailn(r_m_origins.len() - n_m_tps));
397
398     return (ty_substs, vtables);
399 }
400
401
402 pub fn trans_trait_callee(bcx: @mut Block,
403                           callee_id: ast::NodeId,
404                           n_method: uint,
405                           self_expr: @ast::expr)
406                           -> Callee {
407     /*!
408      * Create a method callee where the method is coming from a trait
409      * object (e.g., @Trait type).  In this case, we must pull the fn
410      * pointer out of the vtable that is packaged up with the object.
411      * Objects are represented as a pair, so we first evaluate the self
412      * expression and then extract the self data and vtable out of the
413      * pair.
414      */
415
416     let _icx = push_ctxt("impl::trans_trait_callee");
417     let mut bcx = bcx;
418
419     let self_ty = expr_ty_adjusted(bcx, self_expr);
420     let self_scratch = scratch_datum(bcx, self_ty, "__trait_callee", false);
421     bcx = expr::trans_into(bcx, self_expr, expr::SaveIn(self_scratch.val));
422
423     // Arrange a temporary cleanup for the object in case something
424     // should go wrong before the method is actually *invoked*.
425     self_scratch.add_clean(bcx);
426
427     let callee_ty = node_id_type(bcx, callee_id);
428     trans_trait_callee_from_llval(bcx,
429                                   callee_ty,
430                                   n_method,
431                                   self_scratch.val,
432                                   Some(self_scratch.val))
433 }
434
435 pub fn trans_trait_callee_from_llval(bcx: @mut Block,
436                                      callee_ty: ty::t,
437                                      n_method: uint,
438                                      llpair: ValueRef,
439                                      temp_cleanup: Option<ValueRef>)
440                                   -> Callee {
441     /*!
442      * Same as `trans_trait_callee()` above, except that it is given
443      * a by-ref pointer to the object pair.
444      */
445
446     let _icx = push_ctxt("impl::trans_trait_callee");
447     let ccx = bcx.ccx();
448
449     // Load the data pointer from the object.
450     debug!("(translating trait callee) loading second index from pair");
451     let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]);
452     let llbox = Load(bcx, llboxptr);
453     let llself = PointerCast(bcx, llbox, Type::opaque_box(ccx).ptr_to());
454
455     // Load the function from the vtable and cast it to the expected type.
456     debug!("(translating trait callee) loading method");
457     let llcallee_ty = type_of_fn_from_ty(ccx, callee_ty);
458     let llvtable = Load(bcx,
459                         PointerCast(bcx,
460                                     GEPi(bcx, llpair,
461                                          [0u, abi::trt_field_vtable]),
462                                     Type::vtable().ptr_to().ptr_to()));
463     let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1]));
464     let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
465
466     return Callee {
467         bcx: bcx,
468         data: Method(MethodData {
469             llfn: mptr,
470             llself: llself,
471             temp_cleanup: temp_cleanup,
472
473                 // We know that the func declaration is &self, ~self,
474                 // or @self, and such functions are always by-copy
475                 // (right now, at least).
476             self_mode: ty::ByCopy,
477         })
478     };
479 }
480
481 pub fn vtable_id(ccx: @mut CrateContext,
482                  origin: &typeck::vtable_origin)
483               -> mono_id {
484     match origin {
485         &typeck::vtable_static(impl_id, ref substs, sub_vtables) => {
486             let psubsts = param_substs {
487                 tys: (*substs).clone(),
488                 vtables: Some(sub_vtables),
489                 self_ty: None,
490                 self_vtables: None
491             };
492
493             monomorphize::make_mono_id(
494                 ccx,
495                 impl_id,
496                 &psubsts,
497                 None)
498         }
499
500         // can't this be checked at the callee?
501         _ => fail!("vtable_id")
502     }
503 }
504
505 /// Creates a returns a dynamic vtable for the given type and vtable origin.
506 /// This is used only for objects.
507 pub fn get_vtable(bcx: @mut Block,
508                   self_ty: ty::t,
509                   origin: typeck::vtable_origin)
510                   -> ValueRef {
511     let hash_id = vtable_id(bcx.ccx(), &origin);
512     match bcx.ccx().vtables.find(&hash_id) {
513         Some(&val) => val,
514         None => {
515             match origin {
516                 typeck::vtable_static(id, substs, sub_vtables) => {
517                     make_impl_vtable(bcx, id, self_ty, substs, sub_vtables)
518                 }
519                 _ => fail!("get_vtable: expected a static origin"),
520             }
521         }
522     }
523 }
524
525 /// Helper function to declare and initialize the vtable.
526 pub fn make_vtable(ccx: &mut CrateContext,
527                    tydesc: &tydesc_info,
528                    ptrs: &[ValueRef])
529                    -> ValueRef {
530     unsafe {
531         let _icx = push_ctxt("impl::make_vtable");
532
533         let mut components = ~[ tydesc.tydesc ];
534         for &ptr in ptrs.iter() {
535             components.push(ptr)
536         }
537
538         let tbl = C_struct(components);
539         let vtable = ccx.sess.str_of(gensym_name("vtable"));
540         let vt_gvar = do vtable.to_c_str().with_ref |buf| {
541             llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl).to_ref(), buf)
542         };
543         llvm::LLVMSetInitializer(vt_gvar, tbl);
544         llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True);
545         lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage);
546         vt_gvar
547     }
548 }
549
550 /// Generates a dynamic vtable for objects.
551 pub fn make_impl_vtable(bcx: @mut Block,
552                         impl_id: ast::def_id,
553                         self_ty: ty::t,
554                         substs: &[ty::t],
555                         vtables: typeck::vtable_res)
556                         -> ValueRef {
557     let ccx = bcx.ccx();
558     let _icx = push_ctxt("impl::make_impl_vtable");
559     let tcx = ccx.tcx;
560
561     let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
562         Some(t_id) => t_id.def_id,
563         None       => ccx.sess.bug("make_impl_vtable: don't know how to \
564                                     make a vtable for a type impl!")
565     };
566
567     let trait_method_def_ids = ty::trait_method_def_ids(tcx, trt_id);
568     let methods = do trait_method_def_ids.map |method_def_id| {
569         let im = ty::method(tcx, *method_def_id);
570         let fty = ty::subst_tps(tcx,
571                                 substs,
572                                 None,
573                                 ty::mk_bare_fn(tcx, im.fty.clone()));
574         if im.generics.has_type_params() || ty::type_has_self(fty) {
575             debug!("(making impl vtable) method has self or type params: %s",
576                    tcx.sess.str_of(im.ident));
577             C_null(Type::nil().ptr_to())
578         } else {
579             debug!("(making impl vtable) adding method to vtable: %s",
580                    tcx.sess.str_of(im.ident));
581             let m_id = method_with_name(ccx, impl_id, im.ident);
582
583             trans_fn_ref_with_vtables(bcx, m_id, 0,
584                                       substs, Some(vtables)).llfn
585         }
586     };
587
588     // Generate a type descriptor for the vtable.
589     let tydesc = get_tydesc(ccx, self_ty);
590     glue::lazily_emit_all_tydesc_glue(ccx, tydesc);
591
592     make_vtable(ccx, tydesc, methods)
593 }
594
595 pub fn trans_trait_cast(bcx: @mut Block,
596                         val: @ast::expr,
597                         id: ast::NodeId,
598                         dest: expr::Dest,
599                         _store: ty::TraitStore)
600                      -> @mut Block {
601     let mut bcx = bcx;
602     let _icx = push_ctxt("impl::trans_cast");
603
604     let lldest = match dest {
605         Ignore => {
606             return expr::trans_into(bcx, val, Ignore);
607         }
608         SaveIn(dest) => dest
609     };
610
611     let ccx = bcx.ccx();
612     let v_ty = expr_ty(bcx, val);
613
614     let mut llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]);
615     // Just store the pointer into the pair. (Region/borrowed
616     // and boxed trait objects are represented as pairs, and
617     // have no type descriptor field.)
618     llboxdest = PointerCast(bcx,
619                             llboxdest,
620                             type_of(bcx.ccx(), v_ty).ptr_to());
621     bcx = expr::trans_into(bcx, val, SaveIn(llboxdest));
622
623     // Store the vtable into the pair or triple.
624     let orig = ccx.maps.vtable_map.get(&id)[0][0].clone();
625     let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, &orig);
626     let vtable = get_vtable(bcx, v_ty, orig);
627     Store(bcx, vtable, PointerCast(bcx,
628                                    GEPi(bcx, lldest, [0u, abi::trt_field_vtable]),
629                                    val_ty(vtable).ptr_to()));
630
631     bcx
632 }