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.
11 use super::{probe, MethodCallee};
14 use check::{FnCtxt, PlaceOp, callee, Needs};
15 use hir::def_id::DefId;
16 use rustc::ty::subst::Substs;
18 use rustc::ty::{self, Ty};
19 use rustc::ty::subst::Subst;
20 use rustc::ty::adjustment::{Adjustment, Adjust, OverloadedDeref};
21 use rustc::ty::adjustment::{AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
22 use rustc::ty::fold::TypeFoldable;
23 use rustc::infer::{self, InferOk};
29 struct ConfirmContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
30 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
32 self_expr: &'gcx hir::Expr,
33 call_expr: &'gcx hir::Expr,
36 impl<'a, 'gcx, 'tcx> Deref for ConfirmContext<'a, 'gcx, 'tcx> {
37 type Target = FnCtxt<'a, 'gcx, 'tcx>;
38 fn deref(&self) -> &Self::Target {
43 pub struct ConfirmResult<'tcx> {
44 pub callee: MethodCallee<'tcx>,
45 pub illegal_sized_bound: bool,
48 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
49 pub fn confirm_method(&self,
51 self_expr: &'gcx hir::Expr,
52 call_expr: &'gcx hir::Expr,
53 unadjusted_self_ty: Ty<'tcx>,
54 pick: probe::Pick<'tcx>,
55 segment: &hir::PathSegment)
56 -> ConfirmResult<'tcx> {
57 debug!("confirm(unadjusted_self_ty={:?}, pick={:?}, generic_args={:?})",
62 let mut confirm_cx = ConfirmContext::new(self, span, self_expr, call_expr);
63 confirm_cx.confirm(unadjusted_self_ty, pick, segment)
67 impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> {
68 fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
70 self_expr: &'gcx hir::Expr,
71 call_expr: &'gcx hir::Expr)
72 -> ConfirmContext<'a, 'gcx, 'tcx> {
82 unadjusted_self_ty: Ty<'tcx>,
83 pick: probe::Pick<'tcx>,
84 segment: &hir::PathSegment)
85 -> ConfirmResult<'tcx> {
86 // Adjust the self expression the user provided and obtain the adjusted type.
87 let self_ty = self.adjust_self_ty(unadjusted_self_ty, &pick);
89 // Create substitutions for the method's type parameters.
90 let rcvr_substs = self.fresh_receiver_substs(self_ty, &pick);
91 let all_substs = self.instantiate_method_substs(&pick, segment, rcvr_substs);
93 debug!("all_substs={:?}", all_substs);
95 // Create the final signature for the method, replacing late-bound regions.
96 let (method_sig, method_predicates) = self.instantiate_method_sig(&pick, all_substs);
98 // Unify the (adjusted) self type with what the method expects.
100 // SUBTLE: if we want good error messages, because of "guessing" while matching
101 // traits, no trait system method can be called before this point because they
102 // could alter our Self-type, except for normalizing the receiver from the
103 // signature (which is also done during probing).
104 let method_sig_rcvr =
105 self.normalize_associated_types_in(self.span, &method_sig.inputs()[0]);
106 self.unify_receivers(self_ty, method_sig_rcvr);
108 let (method_sig, method_predicates) =
109 self.normalize_associated_types_in(self.span, &(method_sig, method_predicates));
111 // Make sure nobody calls `drop()` explicitly.
112 self.enforce_illegal_method_limitations(&pick);
114 // If there is a `Self: Sized` bound and `Self` is a trait object, it is possible that
115 // something which derefs to `Self` actually implements the trait and the caller
116 // wanted to make a static dispatch on it but forgot to import the trait.
117 // See test `src/test/ui/issue-35976.rs`.
119 // In that case, we'll error anyway, but we'll also re-run the search with all traits
120 // in scope, and if we find another method which can be used, we'll output an
121 // appropriate hint suggesting to import the trait.
122 let illegal_sized_bound = self.predicates_require_illegal_sized_bound(&method_predicates);
124 // Add any trait/regions obligations specified on the method's type parameters.
125 // We won't add these if we encountered an illegal sized bound, so that we can use
126 // a custom error in that case.
127 if !illegal_sized_bound {
128 let method_ty = self.tcx.mk_fn_ptr(ty::Binder::bind(method_sig));
129 self.add_obligations(method_ty, all_substs, &method_predicates);
132 // Create the final `MethodCallee`.
133 let callee = MethodCallee {
134 def_id: pick.item.def_id,
139 if let Some(hir::MutMutable) = pick.autoref {
140 self.convert_place_derefs_to_mutable();
143 ConfirmResult { callee, illegal_sized_bound }
146 ///////////////////////////////////////////////////////////////////////////
149 fn adjust_self_ty(&mut self,
150 unadjusted_self_ty: Ty<'tcx>,
151 pick: &probe::Pick<'tcx>)
153 // Commit the autoderefs by calling `autoderef` again, but this
154 // time writing the results into the various tables.
155 let mut autoderef = self.autoderef(self.span, unadjusted_self_ty);
156 let (_, n) = autoderef.nth(pick.autoderefs).unwrap();
157 assert_eq!(n, pick.autoderefs);
159 let mut adjustments = autoderef.adjust_steps(Needs::None);
161 let mut target = autoderef.unambiguous_final_ty();
163 if let Some(mutbl) = pick.autoref {
164 let region = self.next_region_var(infer::Autoref(self.span));
165 target = self.tcx.mk_ref(region, ty::TypeAndMut {
169 let mutbl = match mutbl {
170 hir::MutImmutable => AutoBorrowMutability::Immutable,
171 hir::MutMutable => AutoBorrowMutability::Mutable {
172 // Method call receivers are the primary use case
173 // for two-phase borrows.
174 allow_two_phase_borrow: AllowTwoPhase::Yes,
177 adjustments.push(Adjustment {
178 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
182 if let Some(unsize_target) = pick.unsize {
183 target = self.tcx.mk_ref(region, ty::TypeAndMut {
187 adjustments.push(Adjustment {
188 kind: Adjust::Unsize,
193 // No unsizing should be performed without autoref (at
194 // least during method dispach). This is because we
195 // currently only unsize `[T;N]` to `[T]`, and naturally
196 // that must occur being a reference.
197 assert!(pick.unsize.is_none());
200 autoderef.finalize();
202 // Write out the final adjustments.
203 self.apply_adjustments(self.self_expr, adjustments);
208 ///////////////////////////////////////////////////////////////////////////
211 /// Returns a set of substitutions for the method *receiver* where all type and region
212 /// parameters are instantiated with fresh variables. This substitution does not include any
213 /// parameters declared on the method itself.
215 /// Note that this substitution may include late-bound regions from the impl level. If so,
216 /// these are instantiated later in the `instantiate_method_sig` routine.
217 fn fresh_receiver_substs(&mut self,
219 pick: &probe::Pick<'tcx>)
220 -> &'tcx Substs<'tcx> {
222 probe::InherentImplPick => {
223 let impl_def_id = pick.item.container.id();
224 assert!(self.tcx.impl_trait_ref(impl_def_id).is_none(),
225 "impl {:?} is not an inherent impl",
227 self.impl_self_ty(self.span, impl_def_id).substs
230 probe::ObjectPick => {
231 let trait_def_id = pick.item.container.id();
232 self.extract_existential_trait_ref(self_ty, |this, object_ty, principal| {
233 // The object data has no entry for the Self
234 // Type. For the purposes of this method call, we
235 // substitute the object type itself. This
236 // wouldn't be a sound substitution in all cases,
237 // since each instance of the object type is a
238 // different existential and hence could match
239 // distinct types (e.g., if `Self` appeared as an
240 // argument type), but those cases have already
241 // been ruled out when we deemed the trait to be
243 let original_poly_trait_ref = principal.with_self_ty(this.tcx, object_ty);
244 let upcast_poly_trait_ref = this.upcast(original_poly_trait_ref, trait_def_id);
245 let upcast_trait_ref =
246 this.replace_late_bound_regions_with_fresh_var(&upcast_poly_trait_ref);
247 debug!("original_poly_trait_ref={:?} upcast_trait_ref={:?} target_trait={:?}",
248 original_poly_trait_ref,
251 upcast_trait_ref.substs
255 probe::TraitPick => {
256 let trait_def_id = pick.item.container.id();
258 // Make a trait reference `$0 : Trait<$1...$n>`
259 // consisting entirely of type variables. Later on in
260 // the process we will unify the transformed-self-type
261 // of the method with the actual type in order to
262 // unify some of these variables.
263 self.fresh_substs_for_item(self.span, trait_def_id)
266 probe::WhereClausePick(ref poly_trait_ref) => {
267 // Where clauses can have bound regions in them. We need to instantiate
268 // those to convert from a poly-trait-ref to a trait-ref.
269 self.replace_late_bound_regions_with_fresh_var(&poly_trait_ref).substs
274 fn extract_existential_trait_ref<R, F>(&mut self, self_ty: Ty<'tcx>, mut closure: F) -> R
275 where F: FnMut(&mut ConfirmContext<'a, 'gcx, 'tcx>,
277 ty::PolyExistentialTraitRef<'tcx>)
280 // If we specified that this is an object method, then the
281 // self-type ought to be something that can be dereferenced to
282 // yield an object-type (e.g., `&Object` or `Box<Object>`
285 // FIXME: this feels, like, super dubious
287 .autoderef(self.span, self_ty)
288 .include_raw_pointers()
289 .filter_map(|(ty, _)| {
291 ty::TyDynamic(ref data, ..) => data.principal().map(|p| closure(self, ty, p)),
298 "self-type `{}` for ObjectPick never dereferenced to an object",
303 fn instantiate_method_substs(&mut self,
304 pick: &probe::Pick<'tcx>,
305 segment: &hir::PathSegment,
306 parent_substs: &Substs<'tcx>)
307 -> &'tcx Substs<'tcx> {
308 // Determine the values for the generic parameters of the method.
309 // If they were not explicitly supplied, just construct fresh
311 let method_generics = self.tcx.generics_of(pick.item.def_id);
312 let mut fn_segment = Some((segment, method_generics));
313 self.fcx.check_path_parameter_count(self.span, &mut fn_segment, true, false);
315 // Create subst for early-bound lifetime parameters, combining
316 // parameters from the type and those from the method.
317 assert_eq!(method_generics.parent_count(), parent_substs.len());
318 let provided = &segment.parameters;
319 Substs::for_item(self.tcx, pick.item.def_id, |def, _| {
320 let i = def.index as usize;
321 if i < parent_substs.len() {
322 parent_substs.region_at(i)
323 } else if let Some(lifetime)
324 = provided.as_ref().and_then(|p| p.lifetimes.get(i - parent_substs.len())) {
325 AstConv::ast_region_to_region(self.fcx, lifetime, Some(def))
327 self.region_var_for_def(self.span, def)
329 }, |def, _cur_substs| {
330 let i = def.index as usize;
331 if i < parent_substs.len() {
332 parent_substs.type_at(i)
333 } else if let Some(ast_ty)
334 = provided.as_ref().and_then(|p| {
335 p.types.get(i - parent_substs.len() - method_generics.regions.len())
340 self.type_var_for_def(self.span, def)
345 fn unify_receivers(&mut self, self_ty: Ty<'tcx>, method_self_ty: Ty<'tcx>) {
346 match self.at(&self.misc(self.span), self.param_env).sup(method_self_ty, self_ty) {
347 Ok(InferOk { obligations, value: () }) => {
348 self.register_predicates(obligations);
352 "{} was a subtype of {} but now is not?",
359 ///////////////////////////////////////////////////////////////////////////
362 // NOTE: this returns the *unnormalized* predicates and method sig. Because of
363 // inference guessing, the predicates and method signature can't be normalized
364 // until we unify the `Self` type.
365 fn instantiate_method_sig(&mut self,
366 pick: &probe::Pick<'tcx>,
367 all_substs: &'tcx Substs<'tcx>)
368 -> (ty::FnSig<'tcx>, ty::InstantiatedPredicates<'tcx>) {
369 debug!("instantiate_method_sig(pick={:?}, all_substs={:?})",
373 // Instantiate the bounds on the method with the
374 // type/early-bound-regions substitutions performed. There can
375 // be no late-bound regions appearing here.
376 let def_id = pick.item.def_id;
377 let method_predicates = self.tcx.predicates_of(def_id)
378 .instantiate(self.tcx, all_substs);
380 debug!("method_predicates after subst = {:?}", method_predicates);
382 let sig = self.tcx.fn_sig(def_id);
384 // Instantiate late-bound regions and substitute the trait
385 // parameters into the method type to get the actual method type.
387 // NB: Instantiate late-bound regions first so that
388 // `instantiate_type_scheme` can normalize associated types that
389 // may reference those regions.
390 let method_sig = self.replace_late_bound_regions_with_fresh_var(&sig);
391 debug!("late-bound lifetimes from method instantiated, method_sig={:?}",
394 let method_sig = method_sig.subst(self.tcx, all_substs);
395 debug!("type scheme substituted, method_sig={:?}", method_sig);
397 (method_sig, method_predicates)
400 fn add_obligations(&mut self,
402 all_substs: &Substs<'tcx>,
403 method_predicates: &ty::InstantiatedPredicates<'tcx>) {
404 debug!("add_obligations: fty={:?} all_substs={:?} method_predicates={:?}",
409 self.add_obligations_for_parameters(traits::ObligationCause::misc(self.span, self.body_id),
412 // this is a projection from a trait reference, so we have to
413 // make sure that the trait reference inputs are well-formed.
414 self.add_wf_bounds(all_substs, self.call_expr);
416 // the function type must also be well-formed (this is not
417 // implied by the substs being well-formed because of inherent
418 // impls and late-bound regions - see issue #28609).
419 self.register_wf_obligation(fty, self.span, traits::MiscObligation);
422 ///////////////////////////////////////////////////////////////////////////
425 /// When we select a method with a mutable autoref, we have to go convert any
426 /// auto-derefs, indices, etc from `Deref` and `Index` into `DerefMut` and `IndexMut`
428 fn convert_place_derefs_to_mutable(&self) {
429 // Gather up expressions we want to munge.
430 let mut exprs = Vec::new();
431 exprs.push(self.self_expr);
433 let last = exprs[exprs.len() - 1];
435 hir::ExprField(ref expr, _) |
436 hir::ExprIndex(ref expr, _) |
437 hir::ExprUnary(hir::UnDeref, ref expr) => exprs.push(&expr),
442 debug!("convert_place_derefs_to_mutable: exprs={:?}", exprs);
444 // Fix up autoderefs and derefs.
445 for (i, &expr) in exprs.iter().rev().enumerate() {
446 debug!("convert_place_derefs_to_mutable: i={} expr={:?}", i, expr);
448 // Fix up the autoderefs. Autorefs can only occur immediately preceding
449 // overloaded place ops, and will be fixed by them in order to get
450 // the correct region.
451 let mut source = self.node_ty(expr.hir_id);
452 // Do not mutate adjustments in place, but rather take them,
453 // and replace them after mutating them, to avoid having the
454 // tables borrowed during (`deref_mut`) method resolution.
455 let previous_adjustments = self.tables
458 .remove(expr.hir_id);
459 if let Some(mut adjustments) = previous_adjustments {
460 let needs = Needs::MutPlace;
461 for adjustment in &mut adjustments {
462 if let Adjust::Deref(Some(ref mut deref)) = adjustment.kind {
463 if let Some(ok) = self.try_overloaded_deref(expr.span, source, needs) {
464 let method = self.register_infer_ok_obligations(ok);
465 if let ty::TyRef(region, _, mutbl) = method.sig.output().sty {
466 *deref = OverloadedDeref {
473 source = adjustment.target;
475 self.tables.borrow_mut().adjustments_mut().insert(expr.hir_id, adjustments);
479 hir::ExprIndex(ref base_expr, ref index_expr) => {
480 let index_expr_ty = self.node_ty(index_expr.hir_id);
481 self.convert_place_op_to_mutable(
482 PlaceOp::Index, expr, base_expr, &[index_expr_ty]);
484 hir::ExprUnary(hir::UnDeref, ref base_expr) => {
485 self.convert_place_op_to_mutable(
486 PlaceOp::Deref, expr, base_expr, &[]);
493 fn convert_place_op_to_mutable(&self,
496 base_expr: &hir::Expr,
497 arg_tys: &[Ty<'tcx>])
499 debug!("convert_place_op_to_mutable({:?}, {:?}, {:?}, {:?})",
500 op, expr, base_expr, arg_tys);
501 if !self.tables.borrow().is_method_call(expr) {
502 debug!("convert_place_op_to_mutable - builtin, nothing to do");
506 let base_ty = self.tables.borrow().expr_adjustments(base_expr).last()
507 .map_or_else(|| self.node_ty(expr.hir_id), |adj| adj.target);
508 let base_ty = self.resolve_type_vars_if_possible(&base_ty);
510 // Need to deref because overloaded place ops take self by-reference.
511 let base_ty = base_ty.builtin_deref(false)
512 .expect("place op takes something that is not a ref")
515 let method = self.try_overloaded_place_op(
516 expr.span, base_ty, arg_tys, Needs::MutPlace, op);
517 let method = match method {
518 Some(ok) => self.register_infer_ok_obligations(ok),
519 None => return self.tcx.sess.delay_span_bug(expr.span, "re-trying op failed")
521 debug!("convert_place_op_to_mutable: method={:?}", method);
522 self.write_method_call(expr.hir_id, method);
524 let (region, mutbl) = if let ty::TyRef(r, _, mutbl) = method.sig.inputs()[0].sty {
527 span_bug!(expr.span, "input to place op is not a ref?");
530 // Convert the autoref in the base expr to mutable with the correct
531 // region and mutability.
532 let base_expr_ty = self.node_ty(base_expr.hir_id);
533 if let Some(adjustments) = self.tables
536 .get_mut(base_expr.hir_id) {
537 let mut source = base_expr_ty;
538 for adjustment in &mut adjustments[..] {
539 if let Adjust::Borrow(AutoBorrow::Ref(..)) = adjustment.kind {
540 debug!("convert_place_op_to_mutable: converting autoref {:?}", adjustment);
541 let mutbl = match mutbl {
542 hir::MutImmutable => AutoBorrowMutability::Immutable,
543 hir::MutMutable => AutoBorrowMutability::Mutable {
544 // For initial two-phase borrow
545 // deployment, conservatively omit
546 // overloaded operators.
547 allow_two_phase_borrow: AllowTwoPhase::No,
550 adjustment.kind = Adjust::Borrow(AutoBorrow::Ref(region, mutbl));
551 adjustment.target = self.tcx.mk_ref(region, ty::TypeAndMut {
556 source = adjustment.target;
559 // If we have an autoref followed by unsizing at the end, fix the unsize target.
560 match adjustments[..] {
561 [.., Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
562 Adjustment { kind: Adjust::Unsize, ref mut target }] => {
563 *target = method.sig.inputs()[0];
570 ///////////////////////////////////////////////////////////////////////////
573 fn predicates_require_illegal_sized_bound(&self,
574 predicates: &ty::InstantiatedPredicates<'tcx>)
576 let sized_def_id = match self.tcx.lang_items().sized_trait() {
577 Some(def_id) => def_id,
578 None => return false,
581 traits::elaborate_predicates(self.tcx, predicates.predicates.clone())
582 .filter_map(|predicate| {
584 ty::Predicate::Trait(trait_pred) if trait_pred.def_id() == sized_def_id =>
590 match trait_pred.skip_binder().self_ty().sty {
591 ty::TyDynamic(..) => true,
597 fn enforce_illegal_method_limitations(&self, pick: &probe::Pick) {
598 // Disallow calls to the method `drop` defined in the `Drop` trait.
599 match pick.item.container {
600 ty::TraitContainer(trait_def_id) => {
601 callee::check_legal_trait_for_method_call(self.tcx, self.span, trait_def_id)
603 ty::ImplContainer(..) => {}
608 source_trait_ref: ty::PolyTraitRef<'tcx>,
609 target_trait_def_id: DefId)
610 -> ty::PolyTraitRef<'tcx> {
611 let upcast_trait_refs = self.tcx
612 .upcast_choices(source_trait_ref.clone(), target_trait_def_id);
614 // must be exactly one trait ref or we'd get an ambig error etc
615 if upcast_trait_refs.len() != 1 {
617 "cannot uniquely upcast `{:?}` to `{:?}`: `{:?}`",
623 upcast_trait_refs.into_iter().next().unwrap()
626 fn replace_late_bound_regions_with_fresh_var<T>(&self, value: &ty::Binder<T>) -> T
627 where T: TypeFoldable<'tcx>
630 .replace_late_bound_regions_with_fresh_var(self.span, infer::FnCall, value)