1 // Copyright 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.
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.
13 use middle::subst::{mod, Subst};
15 use middle::ty::{mod, Ty};
16 use middle::typeck::check::{mod, FnCtxt, NoPreference, PreferMutLvalue};
17 use middle::typeck::{MethodCall, MethodCallee, MethodObject, MethodOrigin,
18 MethodParam, MethodStatic, MethodTraitObject, MethodTypeParam};
19 use middle::typeck::infer::{mod, InferCtxt};
20 use middle::ty_fold::HigherRankedFoldable;
22 use syntax::codemap::Span;
25 use util::ppaux::Repr;
27 struct ConfirmContext<'a, 'tcx:'a> {
28 fcx: &'a FnCtxt<'a, 'tcx>,
30 self_expr: &'a ast::Expr,
31 call_expr: &'a ast::Expr,
34 struct InstantiatedMethodSig<'tcx> {
35 /// Function signature of the method being invoked. The 0th
36 /// argument is the receiver.
37 method_sig: ty::FnSig<'tcx>,
39 /// Substitutions for all types/early-bound-regions declared on
41 all_substs: subst::Substs<'tcx>,
43 /// Substitution to use when adding obligations from the method
44 /// bounds. Normally equal to `all_substs` except for object
45 /// receivers. See FIXME in instantiate_method_sig() for
47 method_bounds_substs: subst::Substs<'tcx>,
49 /// Generic bounds on the method's parameters which must be added
50 /// as pending obligations.
51 method_bounds: ty::GenericBounds<'tcx>,
54 pub fn confirm<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
56 self_expr: &ast::Expr,
57 call_expr: &ast::Expr,
58 unadjusted_self_ty: Ty<'tcx>,
59 pick: probe::Pick<'tcx>,
60 supplied_method_types: Vec<Ty<'tcx>>)
63 debug!("confirm(unadjusted_self_ty={}, pick={}, supplied_method_types={})",
64 unadjusted_self_ty.repr(fcx.tcx()),
66 supplied_method_types.repr(fcx.tcx()));
68 let mut confirm_cx = ConfirmContext::new(fcx, span, self_expr, call_expr);
69 confirm_cx.confirm(unadjusted_self_ty, pick, supplied_method_types)
72 impl<'a,'tcx> ConfirmContext<'a,'tcx> {
73 fn new(fcx: &'a FnCtxt<'a, 'tcx>,
75 self_expr: &'a ast::Expr,
76 call_expr: &'a ast::Expr)
77 -> ConfirmContext<'a, 'tcx>
79 ConfirmContext { fcx: fcx, span: span, self_expr: self_expr, call_expr: call_expr }
83 unadjusted_self_ty: Ty<'tcx>,
84 pick: probe::Pick<'tcx>,
85 supplied_method_types: Vec<Ty<'tcx>>)
88 // Adjust the self expression the user provided and obtain the adjusted type.
89 let self_ty = self.adjust_self_ty(unadjusted_self_ty, &pick.adjustment);
91 // Make sure nobody calls `drop()` explicitly.
92 self.enforce_drop_trait_limitations(&pick);
94 // Create substitutions for the method's type parameters.
95 let (rcvr_substs, method_origin) =
96 self.fresh_receiver_substs(self_ty, &pick);
97 let (method_types, method_regions) =
98 self.instantiate_method_substs(&pick, supplied_method_types);
99 let all_substs = rcvr_substs.with_method(method_types, method_regions);
100 debug!("all_substs={}", all_substs.repr(self.tcx()));
102 // Create the final signature for the method, replacing late-bound regions.
103 let InstantiatedMethodSig {
104 method_sig, all_substs, method_bounds_substs, method_bounds
105 } = self.instantiate_method_sig(&pick, all_substs);
106 let method_self_ty = method_sig.inputs[0];
108 // Unify the (adjusted) self type with what the method expects.
109 self.unify_receivers(self_ty, method_self_ty);
111 // Add any trait/regions obligations specified on the method's type parameters.
112 self.add_obligations(&pick, &method_bounds_substs, &method_bounds);
114 // Create the final `MethodCallee`.
115 let fty = ty::mk_bare_fn(self.tcx(), ty::BareFnTy {
117 fn_style: pick.method_ty.fty.fn_style,
118 abi: pick.method_ty.fty.abi.clone(),
120 let callee = MethodCallee {
121 origin: method_origin,
126 // If this is an `&mut self` method, bias the receiver
127 // expression towards mutability (this will switch
128 // e.g. `Deref` to `DerefMut` in oveloaded derefs and so on).
129 self.fixup_derefs_on_method_receiver_if_necessary(&callee);
134 ///////////////////////////////////////////////////////////////////////////
137 fn adjust_self_ty(&mut self,
138 unadjusted_self_ty: Ty<'tcx>,
139 adjustment: &probe::PickAdjustment)
142 // Construct the actual adjustment and write it into the table
143 let auto_deref_ref = self.create_ty_adjustment(adjustment);
145 // Commit the autoderefs by calling `autoderef again, but this
146 // time writing the results into the various tables.
147 let (autoderefd_ty, n, result) =
149 self.fcx, self.span, unadjusted_self_ty, Some(self.self_expr.id), NoPreference,
150 |_, n| if n == auto_deref_ref.autoderefs { Some(()) } else { None });
151 assert_eq!(n, auto_deref_ref.autoderefs);
152 assert_eq!(result, Some(()));
155 ty::adjust_ty_for_autoref(self.tcx(), self.span, autoderefd_ty,
156 auto_deref_ref.autoref.as_ref());
158 // Write out the final adjustment.
159 self.fcx.write_adjustment(self.self_expr.id, self.span, ty::AdjustDerefRef(auto_deref_ref));
164 fn create_ty_adjustment(&mut self,
165 adjustment: &probe::PickAdjustment)
166 -> ty::AutoDerefRef<'tcx>
169 probe::AutoDeref(num) => {
175 probe::AutoUnsizeLength(autoderefs, len) => {
177 autoderefs: autoderefs,
178 autoref: Some(ty::AutoUnsize(ty::UnsizeLength(len)))
181 probe::AutoRef(mutability, ref sub_adjustment) => {
182 let deref = self.create_ty_adjustment(&**sub_adjustment);
183 let region = self.infcx().next_region_var(infer::Autoref(self.span));
184 wrap_autoref(deref, |base| ty::AutoPtr(region, mutability, base))
189 ///////////////////////////////////////////////////////////////////////////
192 /// Returns a set of substitutions for the method *receiver* where all type and region
193 /// parameters are instantiated with fresh variables. This substitution does not include any
194 /// parameters declared on the method itself.
196 /// Note that this substitution may include late-bound regions from the impl level. If so,
197 /// these are instantiated later in the `instantiate_method_sig` routine.
198 fn fresh_receiver_substs(&mut self,
200 pick: &probe::Pick<'tcx>)
201 -> (subst::Substs<'tcx>, MethodOrigin<'tcx>)
204 probe::InherentImplPick(impl_def_id) => {
205 assert!(ty::impl_trait_ref(self.tcx(), impl_def_id).is_none(),
206 "impl {} is not an inherent impl", impl_def_id);
207 let impl_polytype = check::impl_self_ty(self.fcx, self.span, impl_def_id);
209 (impl_polytype.substs, MethodStatic(pick.method_ty.def_id))
212 probe::ObjectPick(trait_def_id, method_num, real_index) => {
213 self.extract_trait_ref(self_ty, |this, object_ty, data| {
214 // The object data has no entry for the Self
215 // Type. For the purposes of this method call, we
216 // substitute the object type itself. This
217 // wouldn't be a sound substitution in all cases,
218 // since each instance of the object type is a
219 // different existential and hence could match
220 // distinct types (e.g., if `Self` appeared as an
221 // argument type), but those cases have already
222 // been ruled out when we deemed the trait to be
224 let substs = data.principal.substs.clone().with_self_ty(object_ty);
225 let original_trait_ref =
226 Rc::new(ty::TraitRef::new(data.principal.def_id, substs));
227 let upcast_trait_ref = this.upcast(original_trait_ref.clone(), trait_def_id);
228 debug!("original_trait_ref={} upcast_trait_ref={} target_trait={}",
229 original_trait_ref.repr(this.tcx()),
230 upcast_trait_ref.repr(this.tcx()),
231 trait_def_id.repr(this.tcx()));
232 let substs = upcast_trait_ref.substs.clone();
233 let origin = MethodTraitObject(MethodObject {
234 trait_ref: upcast_trait_ref,
235 object_trait_id: trait_def_id,
236 method_num: method_num,
237 real_index: real_index,
243 probe::ExtensionImplPick(impl_def_id, method_num) => {
244 // The method being invoked is the method as defined on the trait,
245 // so return the substitutions from the trait. Consider:
247 // impl<A,B,C> Trait<A,B> for Foo<C> { ... }
249 // If we instantiate A, B, and C with $A, $B, and $C
250 // respectively, then we want to return the type
251 // parameters from the trait ([$A,$B]), not those from
252 // the impl ([$A,$B,$C]) not the receiver type ([$C]).
253 let impl_polytype = check::impl_self_ty(self.fcx, self.span, impl_def_id);
254 let impl_trait_ref = ty::impl_trait_ref(self.tcx(), impl_def_id)
256 .subst(self.tcx(), &impl_polytype.substs);
257 let origin = MethodTypeParam(MethodParam { trait_ref: impl_trait_ref.clone(),
258 method_num: method_num });
259 (impl_trait_ref.substs.clone(), origin)
262 probe::TraitPick(trait_def_id, method_num) => {
263 let trait_def = ty::lookup_trait_def(self.tcx(), trait_def_id);
265 // Make a trait reference `$0 : Trait<$1...$n>`
266 // consisting entirely of type variables. Later on in
267 // the process we will unify the transformed-self-type
268 // of the method with the actual type in order to
269 // unify some of these variables.
270 let substs = self.infcx().fresh_substs_for_trait(self.span,
272 self.infcx().next_ty_var());
274 let trait_ref = Rc::new(ty::TraitRef::new(trait_def_id, substs.clone()));
275 let origin = MethodTypeParam(MethodParam { trait_ref: trait_ref,
276 method_num: method_num });
280 probe::WhereClausePick(ref trait_ref, method_num) => {
281 let origin = MethodTypeParam(MethodParam { trait_ref: (*trait_ref).clone(),
282 method_num: method_num });
283 (trait_ref.substs.clone(), origin)
288 fn extract_trait_ref<R>(&mut self,
290 closure: |&mut ConfirmContext<'a,'tcx>,
291 Ty<'tcx>, &ty::TyTrait<'tcx>| -> R)
294 // If we specified that this is an object method, then the
295 // self-type ought to be something that can be dereferenced to
296 // yield an object-type (e.g., `&Object` or `Box<Object>`
301 self.fcx, self.span, self_ty, None, NoPreference,
304 ty::ty_trait(ref data) => Some(closure(self, ty, &**data)),
312 self.tcx().sess.span_bug(
314 format!("self-type `{}` for ObjectPick never dereferenced to an object",
315 self_ty.repr(self.tcx()))[])
320 fn instantiate_method_substs(&mut self,
321 pick: &probe::Pick<'tcx>,
322 supplied_method_types: Vec<Ty<'tcx>>)
323 -> (Vec<Ty<'tcx>>, Vec<ty::Region>)
325 // Determine the values for the generic parameters of the method.
326 // If they were not explicitly supplied, just construct fresh
328 let num_supplied_types = supplied_method_types.len();
329 let num_method_types = pick.method_ty.generics.types.len(subst::FnSpace);
331 if num_supplied_types == 0u {
332 self.fcx.infcx().next_ty_vars(num_method_types)
333 } else if num_method_types == 0u {
334 span_err!(self.tcx().sess, self.span, E0035,
335 "does not take type parameters");
336 self.fcx.infcx().next_ty_vars(num_method_types)
337 } else if num_supplied_types != num_method_types {
338 span_err!(self.tcx().sess, self.span, E0036,
339 "incorrect number of type parameters given for this method");
340 Vec::from_elem(num_method_types, ty::mk_err())
342 supplied_method_types
346 // Create subst for early-bound lifetime parameters, combining
347 // parameters from the type and those from the method.
349 // FIXME -- permit users to manually specify lifetimes
351 self.fcx.infcx().region_vars_for_defs(
353 pick.method_ty.generics.regions.get_slice(subst::FnSpace));
355 (method_types, method_regions)
358 fn unify_receivers(&mut self,
360 method_self_ty: Ty<'tcx>)
362 match self.fcx.mk_subty(false, infer::Misc(self.span), self_ty, method_self_ty) {
365 self.tcx().sess.span_bug(
368 "{} was a subtype of {} but now is not?",
369 self_ty.repr(self.tcx()),
370 method_self_ty.repr(self.tcx()))[]);
375 ///////////////////////////////////////////////////////////////////////////
378 fn instantiate_method_sig(&mut self,
379 pick: &probe::Pick<'tcx>,
380 all_substs: subst::Substs<'tcx>)
381 -> InstantiatedMethodSig<'tcx>
383 // If this method comes from an impl (as opposed to a trait),
384 // it may have late-bound regions from the impl that appear in
385 // the substitutions, method signature, and
386 // bounds. Instantiate those at this point. (If it comes from
387 // a trait, this step has no effect, as there are no
388 // late-bound regions to instantiate.)
390 // The binder level here corresponds to the impl.
391 let (all_substs, (method_sig, method_generics)) =
392 self.replace_late_bound_regions_with_fresh_var(
393 &ty::bind((all_substs,
394 (pick.method_ty.fty.sig.clone(),
395 pick.method_ty.generics.clone())))).value;
397 debug!("late-bound lifetimes from impl instantiated, \
398 all_substs={} method_sig={} method_generics={}",
399 all_substs.repr(self.tcx()),
400 method_sig.repr(self.tcx()),
401 method_generics.repr(self.tcx()));
403 // Instantiate the bounds on the method with the
404 // type/early-bound-regions substitutions performed. The only
405 // late-bound-regions that can appear in bounds are from the
406 // impl, and those were already instantiated above.
408 // FIXME(DST). Super hack. For a method on a trait object
409 // `Trait`, the generic signature requires that
410 // `Self:Trait`. Since, for an object, we bind `Self` to the
411 // type `Trait`, this leads to an obligation
412 // `Trait:Trait`. Until such time we DST is fully implemented,
413 // that obligation is not necessarily satisfied. (In the
414 // future, it would be.)
416 // To sidestep this, we overwrite the binding for `Self` with
417 // `err` (just for trait objects) when we generate the
418 // obligations. This causes us to generate the obligation
419 // `err:Trait`, and the error type is considered to implement
420 // all traits, so we're all good. Hack hack hack.
421 let method_bounds_substs = match pick.kind {
422 probe::ObjectPick(..) => {
423 let mut temp_substs = all_substs.clone();
424 temp_substs.types.get_mut_slice(subst::SelfSpace)[0] = ty::mk_err();
432 method_generics.to_bounds(self.tcx(), &method_bounds_substs);
434 debug!("method_bounds after subst = {}",
435 method_bounds.repr(self.tcx()));
437 // Substitute the type/early-bound-regions into the method
438 // signature. In addition, the method signature may bind
439 // late-bound regions, so instantiate those.
440 let method_sig = method_sig.subst(self.tcx(), &all_substs);
441 let method_sig = self.replace_late_bound_regions_with_fresh_var(&method_sig);
443 debug!("late-bound lifetimes from method instantiated, method_sig={}",
444 method_sig.repr(self.tcx()));
446 InstantiatedMethodSig {
447 method_sig: method_sig,
448 all_substs: all_substs,
449 method_bounds_substs: method_bounds_substs,
450 method_bounds: method_bounds,
454 fn add_obligations(&mut self,
455 pick: &probe::Pick<'tcx>,
456 method_bounds_substs: &subst::Substs<'tcx>,
457 method_bounds: &ty::GenericBounds<'tcx>) {
458 debug!("add_obligations: pick={} method_bounds_substs={} method_bounds={}",
459 pick.repr(self.tcx()),
460 method_bounds_substs.repr(self.tcx()),
461 method_bounds.repr(self.tcx()));
463 self.fcx.add_obligations_for_parameters(
464 traits::ObligationCause::misc(self.span),
465 method_bounds_substs,
468 self.fcx.add_default_region_param_bounds(
469 method_bounds_substs,
473 ///////////////////////////////////////////////////////////////////////////
476 /// When we select a method with an `&mut self` receiver, we have to go convert any
477 /// auto-derefs, indices, etc from `Deref` and `Index` into `DerefMut` and `IndexMut`
479 fn fixup_derefs_on_method_receiver_if_necessary(&self,
480 method_callee: &MethodCallee) {
481 let sig = match method_callee.ty.sty {
482 ty::ty_bare_fn(ref f) => f.sig.clone(),
483 ty::ty_closure(ref f) => f.sig.clone(),
487 match sig.inputs[0].sty {
488 ty::ty_rptr(_, ty::mt {
490 mutbl: ast::MutMutable,
495 // Gather up expressions we want to munge.
496 let mut exprs = Vec::new();
497 exprs.push(self.self_expr);
499 let last = exprs[exprs.len() - 1];
501 ast::ExprParen(ref expr) |
502 ast::ExprField(ref expr, _) |
503 ast::ExprTupField(ref expr, _) |
504 ast::ExprSlice(ref expr, _, _, _) |
505 ast::ExprIndex(ref expr, _) |
506 ast::ExprUnary(ast::UnDeref, ref expr) => exprs.push(&**expr),
511 debug!("fixup_derefs_on_method_receiver_if_necessary: exprs={}",
512 exprs.repr(self.tcx()));
514 // Fix up autoderefs and derefs.
515 for (i, expr) in exprs.iter().rev().enumerate() {
517 let autoderef_count = match self.fcx
522 Some(&ty::AdjustDerefRef(ty::AutoDerefRef {
523 autoderefs: autoderef_count,
525 })) => autoderef_count,
529 debug!("fixup_derefs_on_method_receiver_if_necessary: i={} expr={} autoderef_count={}",
530 i, expr.repr(self.tcx()), autoderef_count);
532 if autoderef_count > 0 {
533 check::autoderef(self.fcx,
535 self.fcx.expr_ty(*expr),
539 if autoderefs == autoderef_count + 1 {
547 // Don't retry the first one or we might infinite loop!
550 ast::ExprIndex(ref base_expr, _) => {
551 let mut base_adjustment =
552 match self.fcx.inh.adjustments.borrow().get(&base_expr.id) {
553 Some(&ty::AdjustDerefRef(ref adr)) => (*adr).clone(),
554 None => ty::AutoDerefRef { autoderefs: 0, autoref: None },
556 self.tcx().sess.span_bug(
558 "unexpected adjustment type");
562 // If this is an overloaded index, the
563 // adjustment will include an extra layer of
564 // autoref because the method is an &self/&mut
565 // self method. We have to peel it off to get
566 // the raw adjustment that `try_index_step`
567 // expects. This is annoying and horrible. We
568 // ought to recode this routine so it doesn't
569 // (ab)use the normal type checking paths.
570 base_adjustment.autoref = match base_adjustment.autoref {
572 Some(ty::AutoPtr(_, _, None)) => { None }
573 Some(ty::AutoPtr(_, _, Some(box r))) => { Some(r) }
575 self.tcx().sess.span_bug(
577 "unexpected adjustment autoref");
581 let adjusted_base_ty =
582 self.fcx.adjust_expr_ty(
584 Some(&ty::AdjustDerefRef(base_adjustment.clone())));
586 check::try_index_step(
588 MethodCall::expr(expr.id),
595 ast::ExprUnary(ast::UnDeref, ref base_expr) => {
596 // if this is an overloaded deref, then re-evaluate with
597 // a preference for mut
598 let method_call = MethodCall::expr(expr.id);
599 if self.fcx.inh.method_map.borrow().contains_key(&method_call) {
600 check::try_overloaded_deref(
605 self.fcx.expr_ty(&**base_expr),
615 ///////////////////////////////////////////////////////////////////////////
618 fn tcx(&self) -> &'a ty::ctxt<'tcx> {
622 fn infcx(&self) -> &'a InferCtxt<'a, 'tcx> {
626 fn enforce_drop_trait_limitations(&self, pick: &probe::Pick) {
627 // Disallow calls to the method `drop` defined in the `Drop` trait.
628 match pick.method_ty.container {
629 ty::TraitContainer(trait_def_id) => {
630 if Some(trait_def_id) == self.tcx().lang_items.drop_trait() {
631 span_err!(self.tcx().sess, self.span, E0040,
632 "explicit call to destructor");
635 ty::ImplContainer(..) => {
636 // Since `drop` is a trait method, we expect that any
637 // potential calls to it will wind up in the other
638 // arm. But just to be sure, check that the method id
639 // does not appear in the list of destructors.
640 assert!(!self.tcx().destructors.borrow().contains(&pick.method_ty.def_id));
646 source_trait_ref: Rc<ty::TraitRef<'tcx>>,
647 target_trait_def_id: ast::DefId)
648 -> Rc<ty::TraitRef<'tcx>>
650 for super_trait_ref in traits::supertraits(self.tcx(), source_trait_ref.clone()) {
651 if super_trait_ref.def_id == target_trait_def_id {
652 return super_trait_ref;
656 self.tcx().sess.span_bug(
658 format!("cannot upcast `{}` to `{}`",
659 source_trait_ref.repr(self.tcx()),
660 target_trait_def_id.repr(self.tcx()))[]);
663 fn replace_late_bound_regions_with_fresh_var<T>(&self, value: &T) -> T
664 where T : HigherRankedFoldable<'tcx>
666 self.infcx().replace_late_bound_regions_with_fresh_var(
667 self.span, infer::FnCall, value).0
671 fn wrap_autoref<'tcx>(mut deref: ty::AutoDerefRef<'tcx>,
672 base_fn: |Option<Box<ty::AutoRef<'tcx>>>| -> ty::AutoRef<'tcx>)
673 -> ty::AutoDerefRef<'tcx> {
674 let autoref = mem::replace(&mut deref.autoref, None);
675 let autoref = autoref.map(|r| box r);
676 deref.autoref = Some(base_fn(autoref));