]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/confirm.rs
introduce PredicateAtom
[rust.git] / src / librustc_typeck / check / method / confirm.rs
1 use super::{probe, MethodCallee};
2
3 use crate::astconv::AstConv;
4 use crate::check::{callee, FnCtxt};
5 use crate::hir::def_id::DefId;
6 use crate::hir::GenericArg;
7 use rustc_hir as hir;
8 use rustc_infer::infer::{self, InferOk};
9 use rustc_middle::traits::{ObligationCauseCode, UnifyReceiverContext};
10 use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCast};
11 use rustc_middle::ty::adjustment::{AllowTwoPhase, AutoBorrow, AutoBorrowMutability};
12 use rustc_middle::ty::fold::TypeFoldable;
13 use rustc_middle::ty::subst::{Subst, SubstsRef};
14 use rustc_middle::ty::{self, GenericParamDefKind, Ty};
15 use rustc_span::Span;
16 use rustc_trait_selection::traits;
17
18 use std::ops::Deref;
19
20 struct ConfirmContext<'a, 'tcx> {
21     fcx: &'a FnCtxt<'a, 'tcx>,
22     span: Span,
23     self_expr: &'tcx hir::Expr<'tcx>,
24     call_expr: &'tcx hir::Expr<'tcx>,
25 }
26
27 impl<'a, 'tcx> Deref for ConfirmContext<'a, 'tcx> {
28     type Target = FnCtxt<'a, 'tcx>;
29     fn deref(&self) -> &Self::Target {
30         &self.fcx
31     }
32 }
33
34 pub struct ConfirmResult<'tcx> {
35     pub callee: MethodCallee<'tcx>,
36     pub illegal_sized_bound: Option<Span>,
37 }
38
39 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40     pub fn confirm_method(
41         &self,
42         span: Span,
43         self_expr: &'tcx hir::Expr<'tcx>,
44         call_expr: &'tcx hir::Expr<'tcx>,
45         unadjusted_self_ty: Ty<'tcx>,
46         pick: probe::Pick<'tcx>,
47         segment: &hir::PathSegment<'_>,
48     ) -> ConfirmResult<'tcx> {
49         debug!(
50             "confirm(unadjusted_self_ty={:?}, pick={:?}, generic_args={:?})",
51             unadjusted_self_ty, pick, segment.args,
52         );
53
54         let mut confirm_cx = ConfirmContext::new(self, span, self_expr, call_expr);
55         confirm_cx.confirm(unadjusted_self_ty, pick, segment)
56     }
57 }
58
59 impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
60     fn new(
61         fcx: &'a FnCtxt<'a, 'tcx>,
62         span: Span,
63         self_expr: &'tcx hir::Expr<'tcx>,
64         call_expr: &'tcx hir::Expr<'tcx>,
65     ) -> ConfirmContext<'a, 'tcx> {
66         ConfirmContext { fcx, span, self_expr, call_expr }
67     }
68
69     fn confirm(
70         &mut self,
71         unadjusted_self_ty: Ty<'tcx>,
72         pick: probe::Pick<'tcx>,
73         segment: &hir::PathSegment<'_>,
74     ) -> ConfirmResult<'tcx> {
75         // Adjust the self expression the user provided and obtain the adjusted type.
76         let self_ty = self.adjust_self_ty(unadjusted_self_ty, &pick);
77
78         // Create substitutions for the method's type parameters.
79         let rcvr_substs = self.fresh_receiver_substs(self_ty, &pick);
80         let all_substs = self.instantiate_method_substs(&pick, segment, rcvr_substs);
81
82         debug!("all_substs={:?}", all_substs);
83
84         // Create the final signature for the method, replacing late-bound regions.
85         let (method_sig, method_predicates) = self.instantiate_method_sig(&pick, all_substs);
86
87         // Unify the (adjusted) self type with what the method expects.
88         //
89         // SUBTLE: if we want good error messages, because of "guessing" while matching
90         // traits, no trait system method can be called before this point because they
91         // could alter our Self-type, except for normalizing the receiver from the
92         // signature (which is also done during probing).
93         let method_sig_rcvr =
94             self.normalize_associated_types_in(self.span, &method_sig.inputs()[0]);
95         debug!(
96             "confirm: self_ty={:?} method_sig_rcvr={:?} method_sig={:?} method_predicates={:?}",
97             self_ty, method_sig_rcvr, method_sig, method_predicates
98         );
99         self.unify_receivers(self_ty, method_sig_rcvr, &pick, all_substs);
100
101         let (method_sig, method_predicates) =
102             self.normalize_associated_types_in(self.span, &(method_sig, method_predicates));
103
104         // Make sure nobody calls `drop()` explicitly.
105         self.enforce_illegal_method_limitations(&pick);
106
107         // If there is a `Self: Sized` bound and `Self` is a trait object, it is possible that
108         // something which derefs to `Self` actually implements the trait and the caller
109         // wanted to make a static dispatch on it but forgot to import the trait.
110         // See test `src/test/ui/issue-35976.rs`.
111         //
112         // In that case, we'll error anyway, but we'll also re-run the search with all traits
113         // in scope, and if we find another method which can be used, we'll output an
114         // appropriate hint suggesting to import the trait.
115         let illegal_sized_bound = self.predicates_require_illegal_sized_bound(&method_predicates);
116
117         // Add any trait/regions obligations specified on the method's type parameters.
118         // We won't add these if we encountered an illegal sized bound, so that we can use
119         // a custom error in that case.
120         if illegal_sized_bound.is_none() {
121             let method_ty = self.tcx.mk_fn_ptr(ty::Binder::bind(method_sig));
122             self.add_obligations(method_ty, all_substs, method_predicates);
123         }
124
125         // Create the final `MethodCallee`.
126         let callee = MethodCallee { def_id: pick.item.def_id, substs: all_substs, sig: method_sig };
127         ConfirmResult { callee, illegal_sized_bound }
128     }
129
130     ///////////////////////////////////////////////////////////////////////////
131     // ADJUSTMENTS
132
133     fn adjust_self_ty(
134         &mut self,
135         unadjusted_self_ty: Ty<'tcx>,
136         pick: &probe::Pick<'tcx>,
137     ) -> Ty<'tcx> {
138         // Commit the autoderefs by calling `autoderef` again, but this
139         // time writing the results into the various typeck results.
140         let mut autoderef = self.autoderef(self.span, unadjusted_self_ty);
141         let (_, n) = match autoderef.nth(pick.autoderefs) {
142             Some(n) => n,
143             None => {
144                 return self.tcx.ty_error_with_message(
145                     rustc_span::DUMMY_SP,
146                     &format!("failed autoderef {}", pick.autoderefs),
147                 );
148             }
149         };
150         assert_eq!(n, pick.autoderefs);
151
152         let mut adjustments = self.adjust_steps(&autoderef);
153
154         let mut target =
155             self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false));
156
157         if let Some(mutbl) = pick.autoref {
158             let region = self.next_region_var(infer::Autoref(self.span, pick.item));
159             target = self.tcx.mk_ref(region, ty::TypeAndMut { mutbl, ty: target });
160             let mutbl = match mutbl {
161                 hir::Mutability::Not => AutoBorrowMutability::Not,
162                 hir::Mutability::Mut => AutoBorrowMutability::Mut {
163                     // Method call receivers are the primary use case
164                     // for two-phase borrows.
165                     allow_two_phase_borrow: AllowTwoPhase::Yes,
166                 },
167             };
168             adjustments
169                 .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)), target });
170
171             if let Some(unsize_target) = pick.unsize {
172                 target = self
173                     .tcx
174                     .mk_ref(region, ty::TypeAndMut { mutbl: mutbl.into(), ty: unsize_target });
175                 adjustments.push(Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target });
176             }
177         } else {
178             // No unsizing should be performed without autoref (at
179             // least during method dispach). This is because we
180             // currently only unsize `[T;N]` to `[T]`, and naturally
181             // that must occur being a reference.
182             assert!(pick.unsize.is_none());
183         }
184
185         self.register_predicates(autoderef.into_obligations());
186
187         // Write out the final adjustments.
188         self.apply_adjustments(self.self_expr, adjustments);
189
190         target
191     }
192
193     /// Returns a set of substitutions for the method *receiver* where all type and region
194     /// parameters are instantiated with fresh variables. This substitution does not include any
195     /// parameters declared on the method itself.
196     ///
197     /// Note that this substitution may include late-bound regions from the impl level. If so,
198     /// these are instantiated later in the `instantiate_method_sig` routine.
199     fn fresh_receiver_substs(
200         &mut self,
201         self_ty: Ty<'tcx>,
202         pick: &probe::Pick<'tcx>,
203     ) -> SubstsRef<'tcx> {
204         match pick.kind {
205             probe::InherentImplPick => {
206                 let impl_def_id = pick.item.container.id();
207                 assert!(
208                     self.tcx.impl_trait_ref(impl_def_id).is_none(),
209                     "impl {:?} is not an inherent impl",
210                     impl_def_id
211                 );
212                 self.fresh_substs_for_item(self.span, impl_def_id)
213             }
214
215             probe::ObjectPick => {
216                 let trait_def_id = pick.item.container.id();
217                 self.extract_existential_trait_ref(self_ty, |this, object_ty, principal| {
218                     // The object data has no entry for the Self
219                     // Type. For the purposes of this method call, we
220                     // substitute the object type itself. This
221                     // wouldn't be a sound substitution in all cases,
222                     // since each instance of the object type is a
223                     // different existential and hence could match
224                     // distinct types (e.g., if `Self` appeared as an
225                     // argument type), but those cases have already
226                     // been ruled out when we deemed the trait to be
227                     // "object safe".
228                     let original_poly_trait_ref = principal.with_self_ty(this.tcx, object_ty);
229                     let upcast_poly_trait_ref = this.upcast(original_poly_trait_ref, trait_def_id);
230                     let upcast_trait_ref =
231                         this.replace_bound_vars_with_fresh_vars(&upcast_poly_trait_ref);
232                     debug!(
233                         "original_poly_trait_ref={:?} upcast_trait_ref={:?} target_trait={:?}",
234                         original_poly_trait_ref, upcast_trait_ref, trait_def_id
235                     );
236                     upcast_trait_ref.substs
237                 })
238             }
239
240             probe::TraitPick => {
241                 let trait_def_id = pick.item.container.id();
242
243                 // Make a trait reference `$0 : Trait<$1...$n>`
244                 // consisting entirely of type variables. Later on in
245                 // the process we will unify the transformed-self-type
246                 // of the method with the actual type in order to
247                 // unify some of these variables.
248                 self.fresh_substs_for_item(self.span, trait_def_id)
249             }
250
251             probe::WhereClausePick(ref poly_trait_ref) => {
252                 // Where clauses can have bound regions in them. We need to instantiate
253                 // those to convert from a poly-trait-ref to a trait-ref.
254                 self.replace_bound_vars_with_fresh_vars(&poly_trait_ref).substs
255             }
256         }
257     }
258
259     fn extract_existential_trait_ref<R, F>(&mut self, self_ty: Ty<'tcx>, mut closure: F) -> R
260     where
261         F: FnMut(&mut ConfirmContext<'a, 'tcx>, Ty<'tcx>, ty::PolyExistentialTraitRef<'tcx>) -> R,
262     {
263         // If we specified that this is an object method, then the
264         // self-type ought to be something that can be dereferenced to
265         // yield an object-type (e.g., `&Object` or `Box<Object>`
266         // etc).
267
268         // FIXME: this feels, like, super dubious
269         self.fcx
270             .autoderef(self.span, self_ty)
271             .include_raw_pointers()
272             .find_map(|(ty, _)| match ty.kind {
273                 ty::Dynamic(ref data, ..) => Some(closure(
274                     self,
275                     ty,
276                     data.principal().unwrap_or_else(|| {
277                         span_bug!(self.span, "calling trait method on empty object?")
278                     }),
279                 )),
280                 _ => None,
281             })
282             .unwrap_or_else(|| {
283                 span_bug!(
284                     self.span,
285                     "self-type `{}` for ObjectPick never dereferenced to an object",
286                     self_ty
287                 )
288             })
289     }
290
291     fn instantiate_method_substs(
292         &mut self,
293         pick: &probe::Pick<'tcx>,
294         seg: &hir::PathSegment<'_>,
295         parent_substs: SubstsRef<'tcx>,
296     ) -> SubstsRef<'tcx> {
297         // Determine the values for the generic parameters of the method.
298         // If they were not explicitly supplied, just construct fresh
299         // variables.
300         let generics = self.tcx.generics_of(pick.item.def_id);
301         let arg_count_correct = AstConv::check_generic_arg_count_for_call(
302             self.tcx, self.span, &generics, &seg, true, // `is_method_call`
303         );
304
305         // Create subst for early-bound lifetime parameters, combining
306         // parameters from the type and those from the method.
307         assert_eq!(generics.parent_count, parent_substs.len());
308
309         AstConv::create_substs_for_generic_args(
310             self.tcx,
311             pick.item.def_id,
312             parent_substs,
313             false,
314             None,
315             arg_count_correct,
316             // Provide the generic args, and whether types should be inferred.
317             |def_id| {
318                 // The last component of the returned tuple here is unimportant.
319                 if def_id == pick.item.def_id {
320                     if let Some(ref data) = seg.args {
321                         return (Some(data), false);
322                     }
323                 }
324                 (None, false)
325             },
326             // Provide substitutions for parameters for which (valid) arguments have been provided.
327             |param, arg| match (&param.kind, arg) {
328                 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
329                     AstConv::ast_region_to_region(self.fcx, lt, Some(param)).into()
330                 }
331                 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => self.to_ty(ty).into(),
332                 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
333                     self.const_arg_to_const(&ct.value, param.def_id).into()
334                 }
335                 _ => unreachable!(),
336             },
337             // Provide substitutions for parameters for which arguments are inferred.
338             |_, param, _| self.var_for_def(self.span, param),
339         )
340     }
341
342     fn unify_receivers(
343         &mut self,
344         self_ty: Ty<'tcx>,
345         method_self_ty: Ty<'tcx>,
346         pick: &probe::Pick<'tcx>,
347         substs: SubstsRef<'tcx>,
348     ) {
349         debug!(
350             "unify_receivers: self_ty={:?} method_self_ty={:?} span={:?} pick={:?}",
351             self_ty, method_self_ty, self.span, pick
352         );
353         let cause = self.cause(
354             self.span,
355             ObligationCauseCode::UnifyReceiver(Box::new(UnifyReceiverContext {
356                 assoc_item: pick.item,
357                 param_env: self.param_env,
358                 substs,
359             })),
360         );
361         match self.at(&cause, self.param_env).sup(method_self_ty, self_ty) {
362             Ok(InferOk { obligations, value: () }) => {
363                 self.register_predicates(obligations);
364             }
365             Err(_) => {
366                 span_bug!(
367                     self.span,
368                     "{} was a subtype of {} but now is not?",
369                     self_ty,
370                     method_self_ty
371                 );
372             }
373         }
374     }
375
376     // NOTE: this returns the *unnormalized* predicates and method sig. Because of
377     // inference guessing, the predicates and method signature can't be normalized
378     // until we unify the `Self` type.
379     fn instantiate_method_sig(
380         &mut self,
381         pick: &probe::Pick<'tcx>,
382         all_substs: SubstsRef<'tcx>,
383     ) -> (ty::FnSig<'tcx>, ty::InstantiatedPredicates<'tcx>) {
384         debug!("instantiate_method_sig(pick={:?}, all_substs={:?})", pick, all_substs);
385
386         // Instantiate the bounds on the method with the
387         // type/early-bound-regions substitutions performed. There can
388         // be no late-bound regions appearing here.
389         let def_id = pick.item.def_id;
390         let method_predicates = self.tcx.predicates_of(def_id).instantiate(self.tcx, all_substs);
391
392         debug!("method_predicates after subst = {:?}", method_predicates);
393
394         let sig = self.tcx.fn_sig(def_id);
395
396         // Instantiate late-bound regions and substitute the trait
397         // parameters into the method type to get the actual method type.
398         //
399         // N.B., instantiate late-bound regions first so that
400         // `instantiate_type_scheme` can normalize associated types that
401         // may reference those regions.
402         let method_sig = self.replace_bound_vars_with_fresh_vars(&sig);
403         debug!("late-bound lifetimes from method instantiated, method_sig={:?}", method_sig);
404
405         let method_sig = method_sig.subst(self.tcx, all_substs);
406         debug!("type scheme substituted, method_sig={:?}", method_sig);
407
408         (method_sig, method_predicates)
409     }
410
411     fn add_obligations(
412         &mut self,
413         fty: Ty<'tcx>,
414         all_substs: SubstsRef<'tcx>,
415         method_predicates: ty::InstantiatedPredicates<'tcx>,
416     ) {
417         debug!(
418             "add_obligations: fty={:?} all_substs={:?} method_predicates={:?}",
419             fty, all_substs, method_predicates
420         );
421
422         self.add_obligations_for_parameters(
423             traits::ObligationCause::misc(self.span, self.body_id),
424             method_predicates,
425         );
426
427         // this is a projection from a trait reference, so we have to
428         // make sure that the trait reference inputs are well-formed.
429         self.add_wf_bounds(all_substs, self.call_expr);
430
431         // the function type must also be well-formed (this is not
432         // implied by the substs being well-formed because of inherent
433         // impls and late-bound regions - see issue #28609).
434         self.register_wf_obligation(fty.into(), self.span, traits::MiscObligation);
435     }
436
437     ///////////////////////////////////////////////////////////////////////////
438     // MISCELLANY
439
440     fn predicates_require_illegal_sized_bound(
441         &self,
442         predicates: &ty::InstantiatedPredicates<'tcx>,
443     ) -> Option<Span> {
444         let sized_def_id = match self.tcx.lang_items().sized_trait() {
445             Some(def_id) => def_id,
446             None => return None,
447         };
448
449         traits::elaborate_predicates(self.tcx, predicates.predicates.iter().copied())
450             // We don't care about regions here.
451             .filter_map(|obligation| match obligation.predicate.skip_binders() {
452                 ty::PredicateAtom::Trait(trait_pred, _) if trait_pred.def_id() == sized_def_id => {
453                     let span = predicates
454                         .predicates
455                         .iter()
456                         .zip(predicates.spans.iter())
457                         .find_map(
458                             |(p, span)| {
459                                 if *p == obligation.predicate { Some(*span) } else { None }
460                             },
461                         )
462                         .unwrap_or(rustc_span::DUMMY_SP);
463                     Some((trait_pred, span))
464                 }
465                 _ => None,
466             })
467             .find_map(|(trait_pred, span)| match trait_pred.self_ty().kind {
468                 ty::Dynamic(..) => Some(span),
469                 _ => None,
470             })
471     }
472
473     fn enforce_illegal_method_limitations(&self, pick: &probe::Pick<'_>) {
474         // Disallow calls to the method `drop` defined in the `Drop` trait.
475         match pick.item.container {
476             ty::TraitContainer(trait_def_id) => callee::check_legal_trait_for_method_call(
477                 self.tcx,
478                 self.span,
479                 Some(self.self_expr.span),
480                 trait_def_id,
481             ),
482             ty::ImplContainer(..) => {}
483         }
484     }
485
486     fn upcast(
487         &mut self,
488         source_trait_ref: ty::PolyTraitRef<'tcx>,
489         target_trait_def_id: DefId,
490     ) -> ty::PolyTraitRef<'tcx> {
491         let upcast_trait_refs =
492             traits::upcast_choices(self.tcx, source_trait_ref, target_trait_def_id);
493
494         // must be exactly one trait ref or we'd get an ambig error etc
495         if upcast_trait_refs.len() != 1 {
496             span_bug!(
497                 self.span,
498                 "cannot uniquely upcast `{:?}` to `{:?}`: `{:?}`",
499                 source_trait_ref,
500                 target_trait_def_id,
501                 upcast_trait_refs
502             );
503         }
504
505         upcast_trait_refs.into_iter().next().unwrap()
506     }
507
508     fn replace_bound_vars_with_fresh_vars<T>(&self, value: &ty::Binder<T>) -> T
509     where
510         T: TypeFoldable<'tcx>,
511     {
512         self.fcx.replace_bound_vars_with_fresh_vars(self.span, infer::FnCall, value).0
513     }
514 }