]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs
New upstream version 1.62.1+dfsg1
[rustc.git] / compiler / rustc_typeck / src / check / fn_ctxt / _impl.rs
1 use crate::astconv::{
2 AstConv, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch,
3 GenericArgCountResult, IsMethodCall, PathSeg,
4 };
5 use crate::check::callee::{self, DeferredCallResolution};
6 use crate::check::method::{self, MethodCallee, SelfSource};
7 use crate::check::{BreakableCtxt, Diverges, Expectation, FnCtxt, LocalTy};
8
9 use rustc_data_structures::captures::Captures;
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_errors::{Applicability, Diagnostic, ErrorGuaranteed, MultiSpan};
12 use rustc_hir as hir;
13 use rustc_hir::def::{CtorOf, DefKind, Res};
14 use rustc_hir::def_id::DefId;
15 use rustc_hir::lang_items::LangItem;
16 use rustc_hir::{ExprKind, GenericArg, Node, QPath};
17 use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse};
18 use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
19 use rustc_infer::infer::{InferOk, InferResult};
20 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
21 use rustc_middle::ty::fold::TypeFoldable;
22 use rustc_middle::ty::subst::{
23 self, GenericArgKind, InternalSubsts, Subst, SubstsRef, UserSelfTy, UserSubsts,
24 };
25 use rustc_middle::ty::{
26 self, AdtKind, CanonicalUserType, DefIdTree, EarlyBinder, GenericParamDefKind, ToPolyTraitRef,
27 ToPredicate, Ty, UserType,
28 };
29 use rustc_session::lint;
30 use rustc_span::hygiene::DesugaringKind;
31 use rustc_span::source_map::{original_sp, DUMMY_SP};
32 use rustc_span::symbol::{kw, sym, Ident};
33 use rustc_span::{self, BytePos, Span};
34 use rustc_trait_selection::infer::InferCtxtExt as _;
35 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
36 use rustc_trait_selection::traits::{
37 self, ObligationCause, ObligationCauseCode, StatementAsExpression, TraitEngine, TraitEngineExt,
38 WellFormedLoc,
39 };
40
41 use std::collections::hash_map::Entry;
42 use std::iter;
43 use std::slice;
44
45 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
46 /// Produces warning on the given node, if the current point in the
47 /// function is unreachable, and there hasn't been another warning.
48 pub(in super::super) fn warn_if_unreachable(&self, id: hir::HirId, span: Span, kind: &str) {
49 // FIXME: Combine these two 'if' expressions into one once
50 // let chains are implemented
51 if let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() {
52 // If span arose from a desugaring of `if` or `while`, then it is the condition itself,
53 // which diverges, that we are about to lint on. This gives suboptimal diagnostics.
54 // Instead, stop here so that the `if`- or `while`-expression's block is linted instead.
55 if !span.is_desugaring(DesugaringKind::CondTemporary)
56 && !span.is_desugaring(DesugaringKind::Async)
57 && !orig_span.is_desugaring(DesugaringKind::Await)
58 {
59 self.diverges.set(Diverges::WarnedAlways);
60
61 debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
62
63 self.tcx().struct_span_lint_hir(lint::builtin::UNREACHABLE_CODE, id, span, |lint| {
64 let msg = format!("unreachable {}", kind);
65 lint.build(&msg)
66 .span_label(span, &msg)
67 .span_label(
68 orig_span,
69 custom_note
70 .unwrap_or("any code following this expression is unreachable"),
71 )
72 .emit();
73 })
74 }
75 }
76 }
77
78 /// Resolves type and const variables in `ty` if possible. Unlike the infcx
79 /// version (resolve_vars_if_possible), this version will
80 /// also select obligations if it seems useful, in an effort
81 /// to get more type information.
82 pub(in super::super) fn resolve_vars_with_obligations(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
83 self.resolve_vars_with_obligations_and_mutate_fulfillment(ty, |_| {})
84 }
85
86 #[instrument(skip(self, mutate_fulfillment_errors), level = "debug")]
87 pub(in super::super) fn resolve_vars_with_obligations_and_mutate_fulfillment(
88 &self,
89 mut ty: Ty<'tcx>,
90 mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
91 ) -> Ty<'tcx> {
92 // No Infer()? Nothing needs doing.
93 if !ty.has_infer_types_or_consts() {
94 debug!("no inference var, nothing needs doing");
95 return ty;
96 }
97
98 // If `ty` is a type variable, see whether we already know what it is.
99 ty = self.resolve_vars_if_possible(ty);
100 if !ty.has_infer_types_or_consts() {
101 debug!(?ty);
102 return ty;
103 }
104
105 // If not, try resolving pending obligations as much as
106 // possible. This can help substantially when there are
107 // indirect dependencies that don't seem worth tracking
108 // precisely.
109 self.select_obligations_where_possible(false, mutate_fulfillment_errors);
110 ty = self.resolve_vars_if_possible(ty);
111
112 debug!(?ty);
113 ty
114 }
115
116 pub(in super::super) fn record_deferred_call_resolution(
117 &self,
118 closure_def_id: DefId,
119 r: DeferredCallResolution<'tcx>,
120 ) {
121 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
122 deferred_call_resolutions.entry(closure_def_id).or_default().push(r);
123 }
124
125 pub(in super::super) fn remove_deferred_call_resolutions(
126 &self,
127 closure_def_id: DefId,
128 ) -> Vec<DeferredCallResolution<'tcx>> {
129 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
130 deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default()
131 }
132
133 pub fn tag(&self) -> String {
134 format!("{:p}", self)
135 }
136
137 pub fn local_ty(&self, span: Span, nid: hir::HirId) -> LocalTy<'tcx> {
138 self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| {
139 span_bug!(span, "no type for local variable {}", self.tcx.hir().node_to_string(nid))
140 })
141 }
142
143 #[inline]
144 pub fn write_ty(&self, id: hir::HirId, ty: Ty<'tcx>) {
145 debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(ty), self.tag());
146 self.typeck_results.borrow_mut().node_types_mut().insert(id, ty);
147
148 if ty.references_error() {
149 self.has_errors.set(true);
150 self.set_tainted_by_errors();
151 }
152 }
153
154 pub fn write_field_index(&self, hir_id: hir::HirId, index: usize) {
155 self.typeck_results.borrow_mut().field_indices_mut().insert(hir_id, index);
156 }
157
158 pub(in super::super) fn write_resolution(
159 &self,
160 hir_id: hir::HirId,
161 r: Result<(DefKind, DefId), ErrorGuaranteed>,
162 ) {
163 self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id, r);
164 }
165
166 pub fn write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>) {
167 debug!("write_method_call(hir_id={:?}, method={:?})", hir_id, method);
168 self.write_resolution(hir_id, Ok((DefKind::AssocFn, method.def_id)));
169 self.write_substs(hir_id, method.substs);
170
171 // When the method is confirmed, the `method.substs` includes
172 // parameters from not just the method, but also the impl of
173 // the method -- in particular, the `Self` type will be fully
174 // resolved. However, those are not something that the "user
175 // specified" -- i.e., those types come from the inferred type
176 // of the receiver, not something the user wrote. So when we
177 // create the user-substs, we want to replace those earlier
178 // types with just the types that the user actually wrote --
179 // that is, those that appear on the *method itself*.
180 //
181 // As an example, if the user wrote something like
182 // `foo.bar::<u32>(...)` -- the `Self` type here will be the
183 // type of `foo` (possibly adjusted), but we don't want to
184 // include that. We want just the `[_, u32]` part.
185 if !method.substs.is_empty() {
186 let method_generics = self.tcx.generics_of(method.def_id);
187 if !method_generics.params.is_empty() {
188 let user_type_annotation = self.infcx.probe(|_| {
189 let user_substs = UserSubsts {
190 substs: InternalSubsts::for_item(self.tcx, method.def_id, |param, _| {
191 let i = param.index as usize;
192 if i < method_generics.parent_count {
193 self.infcx.var_for_def(DUMMY_SP, param)
194 } else {
195 method.substs[i]
196 }
197 }),
198 user_self_ty: None, // not relevant here
199 };
200
201 self.infcx.canonicalize_user_type_annotation(UserType::TypeOf(
202 method.def_id,
203 user_substs,
204 ))
205 });
206
207 debug!("write_method_call: user_type_annotation={:?}", user_type_annotation);
208 self.write_user_type_annotation(hir_id, user_type_annotation);
209 }
210 }
211 }
212
213 pub fn write_substs(&self, node_id: hir::HirId, substs: SubstsRef<'tcx>) {
214 if !substs.is_empty() {
215 debug!("write_substs({:?}, {:?}) in fcx {}", node_id, substs, self.tag());
216
217 self.typeck_results.borrow_mut().node_substs_mut().insert(node_id, substs);
218 }
219 }
220
221 /// Given the substs that we just converted from the HIR, try to
222 /// canonicalize them and store them as user-given substitutions
223 /// (i.e., substitutions that must be respected by the NLL check).
224 ///
225 /// This should be invoked **before any unifications have
226 /// occurred**, so that annotations like `Vec<_>` are preserved
227 /// properly.
228 #[instrument(skip(self), level = "debug")]
229 pub fn write_user_type_annotation_from_substs(
230 &self,
231 hir_id: hir::HirId,
232 def_id: DefId,
233 substs: SubstsRef<'tcx>,
234 user_self_ty: Option<UserSelfTy<'tcx>>,
235 ) {
236 debug!("fcx {}", self.tag());
237
238 if Self::can_contain_user_lifetime_bounds((substs, user_self_ty)) {
239 let canonicalized = self.infcx.canonicalize_user_type_annotation(UserType::TypeOf(
240 def_id,
241 UserSubsts { substs, user_self_ty },
242 ));
243 debug!(?canonicalized);
244 self.write_user_type_annotation(hir_id, canonicalized);
245 }
246 }
247
248 #[instrument(skip(self), level = "debug")]
249 pub fn write_user_type_annotation(
250 &self,
251 hir_id: hir::HirId,
252 canonical_user_type_annotation: CanonicalUserType<'tcx>,
253 ) {
254 debug!("fcx {}", self.tag());
255
256 if !canonical_user_type_annotation.is_identity() {
257 self.typeck_results
258 .borrow_mut()
259 .user_provided_types_mut()
260 .insert(hir_id, canonical_user_type_annotation);
261 } else {
262 debug!("skipping identity substs");
263 }
264 }
265
266 #[instrument(skip(self, expr), level = "debug")]
267 pub fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec<Adjustment<'tcx>>) {
268 debug!("expr = {:#?}", expr);
269
270 if adj.is_empty() {
271 return;
272 }
273
274 for a in &adj {
275 if let Adjust::NeverToAny = a.kind {
276 if a.target.is_ty_var() {
277 self.diverging_type_vars.borrow_mut().insert(a.target);
278 debug!("apply_adjustments: adding `{:?}` as diverging type var", a.target);
279 }
280 }
281 }
282
283 let autoborrow_mut = adj.iter().any(|adj| {
284 matches!(
285 adj,
286 &Adjustment {
287 kind: Adjust::Borrow(AutoBorrow::Ref(_, AutoBorrowMutability::Mut { .. })),
288 ..
289 }
290 )
291 });
292
293 match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) {
294 Entry::Vacant(entry) => {
295 entry.insert(adj);
296 }
297 Entry::Occupied(mut entry) => {
298 debug!(" - composing on top of {:?}", entry.get());
299 match (&entry.get()[..], &adj[..]) {
300 // Applying any adjustment on top of a NeverToAny
301 // is a valid NeverToAny adjustment, because it can't
302 // be reached.
303 (&[Adjustment { kind: Adjust::NeverToAny, .. }], _) => return,
304 (
305 &[
306 Adjustment { kind: Adjust::Deref(_), .. },
307 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
308 ],
309 &[
310 Adjustment { kind: Adjust::Deref(_), .. },
311 .., // Any following adjustments are allowed.
312 ],
313 ) => {
314 // A reborrow has no effect before a dereference.
315 }
316 // FIXME: currently we never try to compose autoderefs
317 // and ReifyFnPointer/UnsafeFnPointer, but we could.
318 _ => {
319 self.tcx.sess.delay_span_bug(
320 expr.span,
321 &format!(
322 "while adjusting {:?}, can't compose {:?} and {:?}",
323 expr,
324 entry.get(),
325 adj
326 ),
327 );
328 }
329 }
330 *entry.get_mut() = adj;
331 }
332 }
333
334 // If there is an mutable auto-borrow, it is equivalent to `&mut <expr>`.
335 // In this case implicit use of `Deref` and `Index` within `<expr>` should
336 // instead be `DerefMut` and `IndexMut`, so fix those up.
337 if autoborrow_mut {
338 self.convert_place_derefs_to_mutable(expr);
339 }
340 }
341
342 /// Basically whenever we are converting from a type scheme into
343 /// the fn body space, we always want to normalize associated
344 /// types as well. This function combines the two.
345 fn instantiate_type_scheme<T>(&self, span: Span, substs: SubstsRef<'tcx>, value: T) -> T
346 where
347 T: TypeFoldable<'tcx>,
348 {
349 debug!("instantiate_type_scheme(value={:?}, substs={:?})", value, substs);
350 let value = EarlyBinder(value).subst(self.tcx, substs);
351 let result = self.normalize_associated_types_in(span, value);
352 debug!("instantiate_type_scheme = {:?}", result);
353 result
354 }
355
356 /// As `instantiate_type_scheme`, but for the bounds found in a
357 /// generic type scheme.
358 pub(in super::super) fn instantiate_bounds(
359 &self,
360 span: Span,
361 def_id: DefId,
362 substs: SubstsRef<'tcx>,
363 ) -> (ty::InstantiatedPredicates<'tcx>, Vec<Span>) {
364 let bounds = self.tcx.predicates_of(def_id);
365 let spans: Vec<Span> = bounds.predicates.iter().map(|(_, span)| *span).collect();
366 let result = bounds.instantiate(self.tcx, substs);
367 let result = self.normalize_associated_types_in(span, result);
368 debug!(
369 "instantiate_bounds(bounds={:?}, substs={:?}) = {:?}, {:?}",
370 bounds, substs, result, spans,
371 );
372 (result, spans)
373 }
374
375 /// Convenience method which tracks extra diagnostic information for normalization
376 /// that occurs as a result of WF checking. The `hir_id` is the `HirId` of the hir item
377 /// whose type is being wf-checked - this is used to construct a more precise span if
378 /// an error occurs.
379 ///
380 /// It is never necessary to call this method - calling `normalize_associated_types_in` will
381 /// just result in a slightly worse diagnostic span, and will still be sound.
382 pub(in super::super) fn normalize_associated_types_in_wf<T>(
383 &self,
384 span: Span,
385 value: T,
386 loc: WellFormedLoc,
387 ) -> T
388 where
389 T: TypeFoldable<'tcx>,
390 {
391 self.inh.normalize_associated_types_in_with_cause(
392 ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(Some(loc))),
393 self.param_env,
394 value,
395 )
396 }
397
398 pub(in super::super) fn normalize_associated_types_in<T>(&self, span: Span, value: T) -> T
399 where
400 T: TypeFoldable<'tcx>,
401 {
402 self.inh.normalize_associated_types_in(span, self.body_id, self.param_env, value)
403 }
404
405 pub(in super::super) fn normalize_associated_types_in_as_infer_ok<T>(
406 &self,
407 span: Span,
408 value: T,
409 ) -> InferOk<'tcx, T>
410 where
411 T: TypeFoldable<'tcx>,
412 {
413 self.inh.partially_normalize_associated_types_in(
414 ObligationCause::misc(span, self.body_id),
415 self.param_env,
416 value,
417 )
418 }
419
420 pub(in super::super) fn normalize_op_associated_types_in_as_infer_ok<T>(
421 &self,
422 span: Span,
423 value: T,
424 opt_input_expr: Option<&hir::Expr<'_>>,
425 ) -> InferOk<'tcx, T>
426 where
427 T: TypeFoldable<'tcx>,
428 {
429 self.inh.partially_normalize_associated_types_in(
430 ObligationCause::new(
431 span,
432 self.body_id,
433 traits::BinOp {
434 rhs_span: opt_input_expr.map(|expr| expr.span),
435 is_lit: opt_input_expr
436 .map_or(false, |expr| matches!(expr.kind, ExprKind::Lit(_))),
437 },
438 ),
439 self.param_env,
440 value,
441 )
442 }
443
444 pub fn require_type_meets(
445 &self,
446 ty: Ty<'tcx>,
447 span: Span,
448 code: traits::ObligationCauseCode<'tcx>,
449 def_id: DefId,
450 ) {
451 self.register_bound(ty, def_id, traits::ObligationCause::new(span, self.body_id, code));
452 }
453
454 pub fn require_type_is_sized(
455 &self,
456 ty: Ty<'tcx>,
457 span: Span,
458 code: traits::ObligationCauseCode<'tcx>,
459 ) {
460 if !ty.references_error() {
461 let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
462 self.require_type_meets(ty, span, code, lang_item);
463 }
464 }
465
466 pub fn require_type_is_sized_deferred(
467 &self,
468 ty: Ty<'tcx>,
469 span: Span,
470 code: traits::ObligationCauseCode<'tcx>,
471 ) {
472 if !ty.references_error() {
473 self.deferred_sized_obligations.borrow_mut().push((ty, span, code));
474 }
475 }
476
477 pub fn register_bound(
478 &self,
479 ty: Ty<'tcx>,
480 def_id: DefId,
481 cause: traits::ObligationCause<'tcx>,
482 ) {
483 if !ty.references_error() {
484 self.fulfillment_cx.borrow_mut().register_bound(
485 self,
486 self.param_env,
487 ty,
488 def_id,
489 cause,
490 );
491 }
492 }
493
494 pub fn to_ty(&self, ast_t: &hir::Ty<'_>) -> Ty<'tcx> {
495 let t = <dyn AstConv<'_>>::ast_ty_to_ty(self, ast_t);
496 self.register_wf_obligation(t.into(), ast_t.span, traits::MiscObligation);
497 t
498 }
499
500 pub fn to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
501 let ty = self.to_ty(ast_ty);
502 debug!("to_ty_saving_user_provided_ty: ty={:?}", ty);
503
504 if Self::can_contain_user_lifetime_bounds(ty) {
505 let c_ty = self.infcx.canonicalize_response(UserType::Ty(ty));
506 debug!("to_ty_saving_user_provided_ty: c_ty={:?}", c_ty);
507 self.typeck_results.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty);
508 }
509
510 ty
511 }
512
513 pub fn array_length_to_const(&self, length: &hir::ArrayLen) -> ty::Const<'tcx> {
514 match length {
515 &hir::ArrayLen::Infer(_, span) => self.ct_infer(self.tcx.types.usize, None, span),
516 hir::ArrayLen::Body(anon_const) => self.to_const(anon_const),
517 }
518 }
519
520 pub fn to_const(&self, ast_c: &hir::AnonConst) -> ty::Const<'tcx> {
521 let const_def_id = self.tcx.hir().local_def_id(ast_c.hir_id);
522 let c = ty::Const::from_anon_const(self.tcx, const_def_id);
523 self.register_wf_obligation(
524 c.into(),
525 self.tcx.hir().span(ast_c.hir_id),
526 ObligationCauseCode::MiscObligation,
527 );
528 c
529 }
530
531 pub fn const_arg_to_const(
532 &self,
533 ast_c: &hir::AnonConst,
534 param_def_id: DefId,
535 ) -> ty::Const<'tcx> {
536 let const_def = ty::WithOptConstParam {
537 did: self.tcx.hir().local_def_id(ast_c.hir_id),
538 const_param_did: Some(param_def_id),
539 };
540 let c = ty::Const::from_opt_const_arg_anon_const(self.tcx, const_def);
541 self.register_wf_obligation(
542 c.into(),
543 self.tcx.hir().span(ast_c.hir_id),
544 ObligationCauseCode::MiscObligation,
545 );
546 c
547 }
548
549 // If the type given by the user has free regions, save it for later, since
550 // NLL would like to enforce those. Also pass in types that involve
551 // projections, since those can resolve to `'static` bounds (modulo #54940,
552 // which hopefully will be fixed by the time you see this comment, dear
553 // reader, although I have my doubts). Also pass in types with inference
554 // types, because they may be repeated. Other sorts of things are already
555 // sufficiently enforced with erased regions. =)
556 fn can_contain_user_lifetime_bounds<T>(t: T) -> bool
557 where
558 T: TypeFoldable<'tcx>,
559 {
560 t.has_free_regions() || t.has_projections() || t.has_infer_types()
561 }
562
563 pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> {
564 match self.typeck_results.borrow().node_types().get(id) {
565 Some(&t) => t,
566 None if self.is_tainted_by_errors() => self.tcx.ty_error(),
567 None => {
568 bug!(
569 "no type for node {}: {} in fcx {}",
570 id,
571 self.tcx.hir().node_to_string(id),
572 self.tag()
573 );
574 }
575 }
576 }
577
578 pub fn node_ty_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
579 match self.typeck_results.borrow().node_types().get(id) {
580 Some(&t) => Some(t),
581 None if self.is_tainted_by_errors() => Some(self.tcx.ty_error()),
582 None => None,
583 }
584 }
585
586 /// Registers an obligation for checking later, during regionck, that `arg` is well-formed.
587 pub fn register_wf_obligation(
588 &self,
589 arg: subst::GenericArg<'tcx>,
590 span: Span,
591 code: traits::ObligationCauseCode<'tcx>,
592 ) {
593 // WF obligations never themselves fail, so no real need to give a detailed cause:
594 let cause = traits::ObligationCause::new(span, self.body_id, code);
595 self.register_predicate(traits::Obligation::new(
596 cause,
597 self.param_env,
598 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx),
599 ));
600 }
601
602 /// Registers obligations that all `substs` are well-formed.
603 pub fn add_wf_bounds(&self, substs: SubstsRef<'tcx>, expr: &hir::Expr<'_>) {
604 for arg in substs.iter().filter(|arg| {
605 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
606 }) {
607 self.register_wf_obligation(arg, expr.span, traits::MiscObligation);
608 }
609 }
610
611 // FIXME(arielb1): use this instead of field.ty everywhere
612 // Only for fields! Returns <none> for methods>
613 // Indifferent to privacy flags
614 pub fn field_ty(
615 &self,
616 span: Span,
617 field: &'tcx ty::FieldDef,
618 substs: SubstsRef<'tcx>,
619 ) -> Ty<'tcx> {
620 self.normalize_associated_types_in(span, field.ty(self.tcx, substs))
621 }
622
623 pub(in super::super) fn resolve_generator_interiors(&self, def_id: DefId) {
624 let mut generators = self.deferred_generator_interiors.borrow_mut();
625 for (body_id, interior, kind) in generators.drain(..) {
626 self.select_obligations_where_possible(false, |_| {});
627 crate::check::generator_interior::resolve_interior(
628 self, def_id, body_id, interior, kind,
629 );
630 }
631 }
632
633 #[instrument(skip(self), level = "debug")]
634 pub(in super::super) fn select_all_obligations_or_error(&self) {
635 let errors = self.fulfillment_cx.borrow_mut().select_all_or_error(&self);
636
637 if !errors.is_empty() {
638 self.report_fulfillment_errors(&errors, self.inh.body_id, false);
639 }
640 }
641
642 /// Select as many obligations as we can at present.
643 pub(in super::super) fn select_obligations_where_possible(
644 &self,
645 fallback_has_occurred: bool,
646 mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
647 ) {
648 let mut result = self.fulfillment_cx.borrow_mut().select_where_possible(self);
649 if !result.is_empty() {
650 mutate_fulfillment_errors(&mut result);
651 self.report_fulfillment_errors(&result, self.inh.body_id, fallback_has_occurred);
652 }
653 }
654
655 /// For the overloaded place expressions (`*x`, `x[3]`), the trait
656 /// returns a type of `&T`, but the actual type we assign to the
657 /// *expression* is `T`. So this function just peels off the return
658 /// type by one layer to yield `T`.
659 pub(in super::super) fn make_overloaded_place_return_type(
660 &self,
661 method: MethodCallee<'tcx>,
662 ) -> ty::TypeAndMut<'tcx> {
663 // extract method return type, which will be &T;
664 let ret_ty = method.sig.output();
665
666 // method returns &T, but the type as visible to user is T, so deref
667 ret_ty.builtin_deref(true).unwrap()
668 }
669
670 #[instrument(skip(self), level = "debug")]
671 fn self_type_matches_expected_vid(
672 &self,
673 trait_ref: ty::PolyTraitRef<'tcx>,
674 expected_vid: ty::TyVid,
675 ) -> bool {
676 let self_ty = self.shallow_resolve(trait_ref.skip_binder().self_ty());
677 debug!(?self_ty);
678
679 match *self_ty.kind() {
680 ty::Infer(ty::TyVar(found_vid)) => {
681 // FIXME: consider using `sub_root_var` here so we
682 // can see through subtyping.
683 let found_vid = self.root_var(found_vid);
684 debug!("self_type_matches_expected_vid - found_vid={:?}", found_vid);
685 expected_vid == found_vid
686 }
687 _ => false,
688 }
689 }
690
691 #[instrument(skip(self), level = "debug")]
692 pub(in super::super) fn obligations_for_self_ty<'b>(
693 &'b self,
694 self_ty: ty::TyVid,
695 ) -> impl Iterator<Item = (ty::PolyTraitRef<'tcx>, traits::PredicateObligation<'tcx>)>
696 + Captures<'tcx>
697 + 'b {
698 // FIXME: consider using `sub_root_var` here so we
699 // can see through subtyping.
700 let ty_var_root = self.root_var(self_ty);
701 trace!("pending_obligations = {:#?}", self.fulfillment_cx.borrow().pending_obligations());
702
703 self.fulfillment_cx
704 .borrow()
705 .pending_obligations()
706 .into_iter()
707 .filter_map(move |obligation| {
708 let bound_predicate = obligation.predicate.kind();
709 match bound_predicate.skip_binder() {
710 ty::PredicateKind::Projection(data) => Some((
711 bound_predicate.rebind(data).required_poly_trait_ref(self.tcx),
712 obligation,
713 )),
714 ty::PredicateKind::Trait(data) => {
715 Some((bound_predicate.rebind(data).to_poly_trait_ref(), obligation))
716 }
717 ty::PredicateKind::Subtype(..) => None,
718 ty::PredicateKind::Coerce(..) => None,
719 ty::PredicateKind::RegionOutlives(..) => None,
720 ty::PredicateKind::TypeOutlives(..) => None,
721 ty::PredicateKind::WellFormed(..) => None,
722 ty::PredicateKind::ObjectSafe(..) => None,
723 ty::PredicateKind::ConstEvaluatable(..) => None,
724 ty::PredicateKind::ConstEquate(..) => None,
725 // N.B., this predicate is created by breaking down a
726 // `ClosureType: FnFoo()` predicate, where
727 // `ClosureType` represents some `Closure`. It can't
728 // possibly be referring to the current closure,
729 // because we haven't produced the `Closure` for
730 // this closure yet; this is exactly why the other
731 // code is looking for a self type of an unresolved
732 // inference variable.
733 ty::PredicateKind::ClosureKind(..) => None,
734 ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
735 }
736 })
737 .filter(move |(tr, _)| self.self_type_matches_expected_vid(*tr, ty_var_root))
738 }
739
740 pub(in super::super) fn type_var_is_sized(&self, self_ty: ty::TyVid) -> bool {
741 self.obligations_for_self_ty(self_ty)
742 .any(|(tr, _)| Some(tr.def_id()) == self.tcx.lang_items().sized_trait())
743 }
744
745 pub(in super::super) fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
746 vec![self.tcx.ty_error(); len]
747 }
748
749 /// Unifies the output type with the expected type early, for more coercions
750 /// and forward type information on the input expressions.
751 #[instrument(skip(self, call_span), level = "debug")]
752 pub(in super::super) fn expected_inputs_for_expected_output(
753 &self,
754 call_span: Span,
755 expected_ret: Expectation<'tcx>,
756 formal_ret: Ty<'tcx>,
757 formal_args: &[Ty<'tcx>],
758 ) -> Vec<Ty<'tcx>> {
759 let formal_ret = self.resolve_vars_with_obligations(formal_ret);
760 let Some(ret_ty) = expected_ret.only_has_type(self) else { return vec![]; };
761
762 // HACK(oli-obk): This is a hack to keep RPIT and TAIT in sync wrt their behaviour.
763 // Without it, the inference
764 // variable will get instantiated with the opaque type. The inference variable often
765 // has various helpful obligations registered for it that help closures figure out their
766 // signature. If we infer the inference var to the opaque type, the closure won't be able
767 // to find those obligations anymore, and it can't necessarily find them from the opaque
768 // type itself. We could be more powerful with inference if we *combined* the obligations
769 // so that we got both the obligations from the opaque type and the ones from the inference
770 // variable. That will accept more code than we do right now, so we need to carefully consider
771 // the implications.
772 // Note: this check is pessimistic, as the inference type could be matched with something other
773 // than the opaque type, but then we need a new `TypeRelation` just for this specific case and
774 // can't re-use `sup` below.
775 // See src/test/ui/impl-trait/hidden-type-is-opaque.rs and
776 // src/test/ui/impl-trait/hidden-type-is-opaque-2.rs for examples that hit this path.
777 if formal_ret.has_infer_types() {
778 for ty in ret_ty.walk() {
779 if let ty::subst::GenericArgKind::Type(ty) = ty.unpack() {
780 if let ty::Opaque(def_id, _) = *ty.kind() {
781 if self.infcx.opaque_type_origin(def_id, DUMMY_SP).is_some() {
782 return vec![];
783 }
784 }
785 }
786 }
787 }
788
789 let expect_args = self
790 .fudge_inference_if_ok(|| {
791 // Attempt to apply a subtyping relationship between the formal
792 // return type (likely containing type variables if the function
793 // is polymorphic) and the expected return type.
794 // No argument expectations are produced if unification fails.
795 let origin = self.misc(call_span);
796 let ures = self.at(&origin, self.param_env).sup(ret_ty, formal_ret);
797
798 // FIXME(#27336) can't use ? here, Try::from_error doesn't default
799 // to identity so the resulting type is not constrained.
800 match ures {
801 Ok(ok) => {
802 // Process any obligations locally as much as
803 // we can. We don't care if some things turn
804 // out unconstrained or ambiguous, as we're
805 // just trying to get hints here.
806 let errors = self.save_and_restore_in_snapshot_flag(|_| {
807 let mut fulfill = <dyn TraitEngine<'_>>::new(self.tcx);
808 for obligation in ok.obligations {
809 fulfill.register_predicate_obligation(self, obligation);
810 }
811 fulfill.select_where_possible(self)
812 });
813
814 if !errors.is_empty() {
815 return Err(());
816 }
817 }
818 Err(_) => return Err(()),
819 }
820
821 // Record all the argument types, with the substitutions
822 // produced from the above subtyping unification.
823 Ok(formal_args.iter().map(|&ty| self.resolve_vars_if_possible(ty)).collect())
824 })
825 .unwrap_or_default();
826 debug!(?formal_args, ?formal_ret, ?expect_args, ?expected_ret);
827 expect_args
828 }
829
830 pub(in super::super) fn resolve_lang_item_path(
831 &self,
832 lang_item: hir::LangItem,
833 span: Span,
834 hir_id: hir::HirId,
835 expr_hir_id: Option<hir::HirId>,
836 ) -> (Res, Ty<'tcx>) {
837 let def_id = self.tcx.require_lang_item(lang_item, Some(span));
838 let def_kind = self.tcx.def_kind(def_id);
839
840 let item_ty = if let DefKind::Variant = def_kind {
841 self.tcx.bound_type_of(self.tcx.parent(def_id))
842 } else {
843 self.tcx.bound_type_of(def_id)
844 };
845 let substs = self.infcx.fresh_substs_for_item(span, def_id);
846 let ty = item_ty.subst(self.tcx, substs);
847
848 self.write_resolution(hir_id, Ok((def_kind, def_id)));
849 self.add_required_obligations_with_code(
850 span,
851 def_id,
852 &substs,
853 match lang_item {
854 hir::LangItem::IntoFutureIntoFuture => {
855 ObligationCauseCode::AwaitableExpr(expr_hir_id)
856 }
857 hir::LangItem::IteratorNext | hir::LangItem::IntoIterIntoIter => {
858 ObligationCauseCode::ForLoopIterator
859 }
860 hir::LangItem::TryTraitFromOutput
861 | hir::LangItem::TryTraitFromResidual
862 | hir::LangItem::TryTraitBranch => ObligationCauseCode::QuestionMark,
863 _ => traits::ItemObligation(def_id),
864 },
865 );
866 (Res::Def(def_kind, def_id), ty)
867 }
868
869 /// Resolves an associated value path into a base type and associated constant, or method
870 /// resolution. The newly resolved definition is written into `type_dependent_defs`.
871 pub fn resolve_ty_and_res_fully_qualified_call(
872 &self,
873 qpath: &'tcx QPath<'tcx>,
874 hir_id: hir::HirId,
875 span: Span,
876 ) -> (Res, Option<Ty<'tcx>>, &'tcx [hir::PathSegment<'tcx>]) {
877 debug!(
878 "resolve_ty_and_res_fully_qualified_call: qpath={:?} hir_id={:?} span={:?}",
879 qpath, hir_id, span
880 );
881 let (ty, qself, item_segment) = match *qpath {
882 QPath::Resolved(ref opt_qself, ref path) => {
883 return (
884 path.res,
885 opt_qself.as_ref().map(|qself| self.to_ty(qself)),
886 path.segments,
887 );
888 }
889 QPath::TypeRelative(ref qself, ref segment) => {
890 // Don't use `self.to_ty`, since this will register a WF obligation.
891 // If we're trying to call a non-existent method on a trait
892 // (e.g. `MyTrait::missing_method`), then resolution will
893 // give us a `QPath::TypeRelative` with a trait object as
894 // `qself`. In that case, we want to avoid registering a WF obligation
895 // for `dyn MyTrait`, since we don't actually need the trait
896 // to be object-safe.
897 // We manually call `register_wf_obligation` in the success path
898 // below.
899 (<dyn AstConv<'_>>::ast_ty_to_ty_in_path(self, qself), qself, segment)
900 }
901 QPath::LangItem(..) => {
902 bug!("`resolve_ty_and_res_fully_qualified_call` called on `LangItem`")
903 }
904 };
905 if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id)
906 {
907 self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
908 // Return directly on cache hit. This is useful to avoid doubly reporting
909 // errors with default match binding modes. See #44614.
910 let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id));
911 return (def, Some(ty), slice::from_ref(&**item_segment));
912 }
913 let item_name = item_segment.ident;
914 let result = self
915 .resolve_fully_qualified_call(span, item_name, ty, qself.span, hir_id)
916 .or_else(|error| {
917 let result = match error {
918 method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)),
919 _ => Err(ErrorGuaranteed::unchecked_claim_error_was_emitted()),
920 };
921
922 // If we have a path like `MyTrait::missing_method`, then don't register
923 // a WF obligation for `dyn MyTrait` when method lookup fails. Otherwise,
924 // register a WF obligation so that we can detect any additional
925 // errors in the self type.
926 if !(matches!(error, method::MethodError::NoMatch(_)) && ty.is_trait()) {
927 self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
928 }
929 if item_name.name != kw::Empty {
930 if let Some(mut e) = self.report_method_error(
931 span,
932 ty,
933 item_name,
934 SelfSource::QPath(qself),
935 error,
936 None,
937 ) {
938 e.emit();
939 }
940 }
941 result
942 });
943
944 if result.is_ok() {
945 self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None));
946 }
947
948 // Write back the new resolution.
949 self.write_resolution(hir_id, result);
950 (
951 result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
952 Some(ty),
953 slice::from_ref(&**item_segment),
954 )
955 }
956
957 /// Given a function `Node`, return its `FnDecl` if it exists, or `None` otherwise.
958 pub(in super::super) fn get_node_fn_decl(
959 &self,
960 node: Node<'tcx>,
961 ) -> Option<(&'tcx hir::FnDecl<'tcx>, Ident, bool)> {
962 match node {
963 Node::Item(&hir::Item { ident, kind: hir::ItemKind::Fn(ref sig, ..), .. }) => {
964 // This is less than ideal, it will not suggest a return type span on any
965 // method called `main`, regardless of whether it is actually the entry point,
966 // but it will still present it as the reason for the expected type.
967 Some((&sig.decl, ident, ident.name != sym::main))
968 }
969 Node::TraitItem(&hir::TraitItem {
970 ident,
971 kind: hir::TraitItemKind::Fn(ref sig, ..),
972 ..
973 }) => Some((&sig.decl, ident, true)),
974 Node::ImplItem(&hir::ImplItem {
975 ident,
976 kind: hir::ImplItemKind::Fn(ref sig, ..),
977 ..
978 }) => Some((&sig.decl, ident, false)),
979 _ => None,
980 }
981 }
982
983 /// Given a `HirId`, return the `FnDecl` of the method it is enclosed by and whether a
984 /// suggestion can be made, `None` otherwise.
985 pub fn get_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, bool)> {
986 // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or
987 // `while` before reaching it, as block tail returns are not available in them.
988 self.tcx.hir().get_return_block(blk_id).and_then(|blk_id| {
989 let parent = self.tcx.hir().get(blk_id);
990 self.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main))
991 })
992 }
993
994 pub(in super::super) fn note_internal_mutation_in_method(
995 &self,
996 err: &mut Diagnostic,
997 expr: &hir::Expr<'_>,
998 expected: Ty<'tcx>,
999 found: Ty<'tcx>,
1000 ) {
1001 if found != self.tcx.types.unit {
1002 return;
1003 }
1004 if let ExprKind::MethodCall(path_segment, [rcvr, ..], _) = expr.kind {
1005 if self
1006 .typeck_results
1007 .borrow()
1008 .expr_ty_adjusted_opt(rcvr)
1009 .map_or(true, |ty| expected.peel_refs() != ty.peel_refs())
1010 {
1011 return;
1012 }
1013 let mut sp = MultiSpan::from_span(path_segment.ident.span);
1014 sp.push_span_label(
1015 path_segment.ident.span,
1016 format!(
1017 "this call modifies {} in-place",
1018 match rcvr.kind {
1019 ExprKind::Path(QPath::Resolved(
1020 None,
1021 hir::Path { segments: [segment], .. },
1022 )) => format!("`{}`", segment.ident),
1023 _ => "its receiver".to_string(),
1024 }
1025 ),
1026 );
1027 sp.push_span_label(
1028 rcvr.span,
1029 "you probably want to use this value after calling the method...".to_string(),
1030 );
1031 err.span_note(
1032 sp,
1033 &format!("method `{}` modifies its receiver in-place", path_segment.ident),
1034 );
1035 err.note(&format!("...instead of the `()` output of method `{}`", path_segment.ident));
1036 }
1037 }
1038
1039 pub(in super::super) fn note_need_for_fn_pointer(
1040 &self,
1041 err: &mut Diagnostic,
1042 expected: Ty<'tcx>,
1043 found: Ty<'tcx>,
1044 ) {
1045 let (sig, did, substs) = match (&expected.kind(), &found.kind()) {
1046 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1047 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1048 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1049 if sig1 != sig2 {
1050 return;
1051 }
1052 err.note(
1053 "different `fn` items always have unique types, even if their signatures are \
1054 the same",
1055 );
1056 (sig1, *did1, substs1)
1057 }
1058 (ty::FnDef(did, substs), ty::FnPtr(sig2)) => {
1059 let sig1 = self.tcx.bound_fn_sig(*did).subst(self.tcx, substs);
1060 if sig1 != *sig2 {
1061 return;
1062 }
1063 (sig1, *did, substs)
1064 }
1065 _ => return,
1066 };
1067 err.help(&format!("change the expected type to be function pointer `{}`", sig));
1068 err.help(&format!(
1069 "if the expected type is due to type inference, cast the expected `fn` to a function \
1070 pointer: `{} as {}`",
1071 self.tcx.def_path_str_with_substs(did, substs),
1072 sig
1073 ));
1074 }
1075
1076 pub(in super::super) fn could_remove_semicolon(
1077 &self,
1078 blk: &'tcx hir::Block<'tcx>,
1079 expected_ty: Ty<'tcx>,
1080 ) -> Option<(Span, StatementAsExpression)> {
1081 // Be helpful when the user wrote `{... expr;}` and
1082 // taking the `;` off is enough to fix the error.
1083 let last_stmt = blk.stmts.last()?;
1084 let hir::StmtKind::Semi(ref last_expr) = last_stmt.kind else {
1085 return None;
1086 };
1087 let last_expr_ty = self.node_ty(last_expr.hir_id);
1088 let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) {
1089 (ty::Opaque(last_def_id, _), ty::Opaque(exp_def_id, _))
1090 if last_def_id == exp_def_id =>
1091 {
1092 StatementAsExpression::CorrectType
1093 }
1094 (ty::Opaque(last_def_id, last_bounds), ty::Opaque(exp_def_id, exp_bounds)) => {
1095 debug!(
1096 "both opaque, likely future {:?} {:?} {:?} {:?}",
1097 last_def_id, last_bounds, exp_def_id, exp_bounds
1098 );
1099
1100 let last_local_id = last_def_id.as_local()?;
1101 let exp_local_id = exp_def_id.as_local()?;
1102
1103 match (
1104 &self.tcx.hir().expect_item(last_local_id).kind,
1105 &self.tcx.hir().expect_item(exp_local_id).kind,
1106 ) {
1107 (
1108 hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: last_bounds, .. }),
1109 hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: exp_bounds, .. }),
1110 ) if iter::zip(*last_bounds, *exp_bounds).all(|(left, right)| {
1111 match (left, right) {
1112 (
1113 hir::GenericBound::Trait(tl, ml),
1114 hir::GenericBound::Trait(tr, mr),
1115 ) if tl.trait_ref.trait_def_id() == tr.trait_ref.trait_def_id()
1116 && ml == mr =>
1117 {
1118 true
1119 }
1120 (
1121 hir::GenericBound::LangItemTrait(langl, _, _, argsl),
1122 hir::GenericBound::LangItemTrait(langr, _, _, argsr),
1123 ) if langl == langr => {
1124 // FIXME: consider the bounds!
1125 debug!("{:?} {:?}", argsl, argsr);
1126 true
1127 }
1128 _ => false,
1129 }
1130 }) =>
1131 {
1132 StatementAsExpression::NeedsBoxing
1133 }
1134 _ => StatementAsExpression::CorrectType,
1135 }
1136 }
1137 _ => StatementAsExpression::CorrectType,
1138 };
1139 if (matches!(last_expr_ty.kind(), ty::Error(_))
1140 || self.can_sub(self.param_env, last_expr_ty, expected_ty).is_err())
1141 && matches!(needs_box, StatementAsExpression::CorrectType)
1142 {
1143 return None;
1144 }
1145 let span = if last_stmt.span.from_expansion() {
1146 let mac_call = original_sp(last_stmt.span, blk.span);
1147 self.tcx.sess.source_map().mac_call_stmt_semi_span(mac_call)?
1148 } else {
1149 last_stmt.span.with_lo(last_stmt.span.hi() - BytePos(1))
1150 };
1151 Some((span, needs_box))
1152 }
1153
1154 // Instantiates the given path, which must refer to an item with the given
1155 // number of type parameters and type.
1156 #[instrument(skip(self, span), level = "debug")]
1157 pub fn instantiate_value_path(
1158 &self,
1159 segments: &[hir::PathSegment<'_>],
1160 self_ty: Option<Ty<'tcx>>,
1161 res: Res,
1162 span: Span,
1163 hir_id: hir::HirId,
1164 ) -> (Ty<'tcx>, Res) {
1165 let tcx = self.tcx;
1166
1167 let path_segs = match res {
1168 Res::Local(_) | Res::SelfCtor(_) => vec![],
1169 Res::Def(kind, def_id) => <dyn AstConv<'_>>::def_ids_for_value_path_segments(
1170 self, segments, self_ty, kind, def_id,
1171 ),
1172 _ => bug!("instantiate_value_path on {:?}", res),
1173 };
1174
1175 let mut user_self_ty = None;
1176 let mut is_alias_variant_ctor = false;
1177 match res {
1178 Res::Def(DefKind::Ctor(CtorOf::Variant, _), _)
1179 if let Some(self_ty) = self_ty =>
1180 {
1181 let adt_def = self_ty.ty_adt_def().unwrap();
1182 user_self_ty = Some(UserSelfTy { impl_def_id: adt_def.did(), self_ty });
1183 is_alias_variant_ctor = true;
1184 }
1185 Res::Def(DefKind::AssocFn | DefKind::AssocConst, def_id) => {
1186 let container = tcx.associated_item(def_id).container;
1187 debug!(?def_id, ?container);
1188 match container {
1189 ty::TraitContainer(trait_did) => {
1190 callee::check_legal_trait_for_method_call(tcx, span, None, span, trait_did)
1191 }
1192 ty::ImplContainer(impl_def_id) => {
1193 if segments.len() == 1 {
1194 // `<T>::assoc` will end up here, and so
1195 // can `T::assoc`. It this came from an
1196 // inherent impl, we need to record the
1197 // `T` for posterity (see `UserSelfTy` for
1198 // details).
1199 let self_ty = self_ty.expect("UFCS sugared assoc missing Self");
1200 user_self_ty = Some(UserSelfTy { impl_def_id, self_ty });
1201 }
1202 }
1203 }
1204 }
1205 _ => {}
1206 }
1207
1208 // Now that we have categorized what space the parameters for each
1209 // segment belong to, let's sort out the parameters that the user
1210 // provided (if any) into their appropriate spaces. We'll also report
1211 // errors if type parameters are provided in an inappropriate place.
1212
1213 let generic_segs: FxHashSet<_> = path_segs.iter().map(|PathSeg(_, index)| index).collect();
1214 let generics_has_err = <dyn AstConv<'_>>::prohibit_generics(
1215 self,
1216 segments.iter().enumerate().filter_map(|(index, seg)| {
1217 if !generic_segs.contains(&index) || is_alias_variant_ctor {
1218 Some(seg)
1219 } else {
1220 None
1221 }
1222 }),
1223 );
1224
1225 if let Res::Local(hid) = res {
1226 let ty = self.local_ty(span, hid).decl_ty;
1227 let ty = self.normalize_associated_types_in(span, ty);
1228 self.write_ty(hir_id, ty);
1229 return (ty, res);
1230 }
1231
1232 if generics_has_err {
1233 // Don't try to infer type parameters when prohibited generic arguments were given.
1234 user_self_ty = None;
1235 }
1236
1237 // Now we have to compare the types that the user *actually*
1238 // provided against the types that were *expected*. If the user
1239 // did not provide any types, then we want to substitute inference
1240 // variables. If the user provided some types, we may still need
1241 // to add defaults. If the user provided *too many* types, that's
1242 // a problem.
1243
1244 let mut infer_args_for_err = FxHashSet::default();
1245
1246 let mut explicit_late_bound = ExplicitLateBound::No;
1247 for &PathSeg(def_id, index) in &path_segs {
1248 let seg = &segments[index];
1249 let generics = tcx.generics_of(def_id);
1250
1251 // Argument-position `impl Trait` is treated as a normal generic
1252 // parameter internally, but we don't allow users to specify the
1253 // parameter's value explicitly, so we have to do some error-
1254 // checking here.
1255 let arg_count = <dyn AstConv<'_>>::check_generic_arg_count_for_call(
1256 tcx,
1257 span,
1258 def_id,
1259 &generics,
1260 seg,
1261 IsMethodCall::No,
1262 );
1263
1264 if let ExplicitLateBound::Yes = arg_count.explicit_late_bound {
1265 explicit_late_bound = ExplicitLateBound::Yes;
1266 }
1267
1268 if let Err(GenericArgCountMismatch { reported: Some(_), .. }) = arg_count.correct {
1269 infer_args_for_err.insert(index);
1270 self.set_tainted_by_errors(); // See issue #53251.
1271 }
1272 }
1273
1274 let has_self = path_segs
1275 .last()
1276 .map(|PathSeg(def_id, _)| tcx.generics_of(*def_id).has_self)
1277 .unwrap_or(false);
1278
1279 let (res, self_ctor_substs) = if let Res::SelfCtor(impl_def_id) = res {
1280 let ty = self.normalize_ty(span, tcx.at(span).type_of(impl_def_id));
1281 match *ty.kind() {
1282 ty::Adt(adt_def, substs) if adt_def.has_ctor() => {
1283 let variant = adt_def.non_enum_variant();
1284 let ctor_def_id = variant.ctor_def_id.unwrap();
1285 (
1286 Res::Def(DefKind::Ctor(CtorOf::Struct, variant.ctor_kind), ctor_def_id),
1287 Some(substs),
1288 )
1289 }
1290 _ => {
1291 let mut err = tcx.sess.struct_span_err(
1292 span,
1293 "the `Self` constructor can only be used with tuple or unit structs",
1294 );
1295 if let Some(adt_def) = ty.ty_adt_def() {
1296 match adt_def.adt_kind() {
1297 AdtKind::Enum => {
1298 err.help("did you mean to use one of the enum's variants?");
1299 }
1300 AdtKind::Struct | AdtKind::Union => {
1301 err.span_suggestion(
1302 span,
1303 "use curly brackets",
1304 String::from("Self { /* fields */ }"),
1305 Applicability::HasPlaceholders,
1306 );
1307 }
1308 }
1309 }
1310 err.emit();
1311
1312 return (tcx.ty_error(), res);
1313 }
1314 }
1315 } else {
1316 (res, None)
1317 };
1318 let def_id = res.def_id();
1319
1320 // The things we are substituting into the type should not contain
1321 // escaping late-bound regions, and nor should the base type scheme.
1322 let ty = tcx.type_of(def_id);
1323
1324 let arg_count = GenericArgCountResult {
1325 explicit_late_bound,
1326 correct: if infer_args_for_err.is_empty() {
1327 Ok(())
1328 } else {
1329 Err(GenericArgCountMismatch::default())
1330 },
1331 };
1332
1333 struct CreateCtorSubstsContext<'a, 'tcx> {
1334 fcx: &'a FnCtxt<'a, 'tcx>,
1335 span: Span,
1336 path_segs: &'a [PathSeg],
1337 infer_args_for_err: &'a FxHashSet<usize>,
1338 segments: &'a [hir::PathSegment<'a>],
1339 }
1340 impl<'tcx, 'a> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for CreateCtorSubstsContext<'a, 'tcx> {
1341 fn args_for_def_id(
1342 &mut self,
1343 def_id: DefId,
1344 ) -> (Option<&'a hir::GenericArgs<'a>>, bool) {
1345 if let Some(&PathSeg(_, index)) =
1346 self.path_segs.iter().find(|&PathSeg(did, _)| *did == def_id)
1347 {
1348 // If we've encountered an `impl Trait`-related error, we're just
1349 // going to infer the arguments for better error messages.
1350 if !self.infer_args_for_err.contains(&index) {
1351 // Check whether the user has provided generic arguments.
1352 if let Some(ref data) = self.segments[index].args {
1353 return (Some(data), self.segments[index].infer_args);
1354 }
1355 }
1356 return (None, self.segments[index].infer_args);
1357 }
1358
1359 (None, true)
1360 }
1361
1362 fn provided_kind(
1363 &mut self,
1364 param: &ty::GenericParamDef,
1365 arg: &GenericArg<'_>,
1366 ) -> subst::GenericArg<'tcx> {
1367 match (&param.kind, arg) {
1368 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
1369 <dyn AstConv<'_>>::ast_region_to_region(self.fcx, lt, Some(param)).into()
1370 }
1371 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
1372 self.fcx.to_ty(ty).into()
1373 }
1374 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
1375 self.fcx.const_arg_to_const(&ct.value, param.def_id).into()
1376 }
1377 (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => {
1378 self.fcx.ty_infer(Some(param), inf.span).into()
1379 }
1380 (GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
1381 let tcx = self.fcx.tcx();
1382 self.fcx.ct_infer(tcx.type_of(param.def_id), Some(param), inf.span).into()
1383 }
1384 _ => unreachable!(),
1385 }
1386 }
1387
1388 fn inferred_kind(
1389 &mut self,
1390 substs: Option<&[subst::GenericArg<'tcx>]>,
1391 param: &ty::GenericParamDef,
1392 infer_args: bool,
1393 ) -> subst::GenericArg<'tcx> {
1394 let tcx = self.fcx.tcx();
1395 match param.kind {
1396 GenericParamDefKind::Lifetime => {
1397 self.fcx.re_infer(Some(param), self.span).unwrap().into()
1398 }
1399 GenericParamDefKind::Type { has_default, .. } => {
1400 if !infer_args && has_default {
1401 // If we have a default, then we it doesn't matter that we're not
1402 // inferring the type arguments: we provide the default where any
1403 // is missing.
1404 let default = tcx.bound_type_of(param.def_id);
1405 self.fcx
1406 .normalize_ty(self.span, default.subst(tcx, substs.unwrap()))
1407 .into()
1408 } else {
1409 // If no type arguments were provided, we have to infer them.
1410 // This case also occurs as a result of some malformed input, e.g.
1411 // a lifetime argument being given instead of a type parameter.
1412 // Using inference instead of `Error` gives better error messages.
1413 self.fcx.var_for_def(self.span, param)
1414 }
1415 }
1416 GenericParamDefKind::Const { has_default } => {
1417 if !infer_args && has_default {
1418 EarlyBinder(tcx.const_param_default(param.def_id))
1419 .subst(tcx, substs.unwrap())
1420 .into()
1421 } else {
1422 self.fcx.var_for_def(self.span, param)
1423 }
1424 }
1425 }
1426 }
1427 }
1428
1429 let substs = self_ctor_substs.unwrap_or_else(|| {
1430 <dyn AstConv<'_>>::create_substs_for_generic_args(
1431 tcx,
1432 def_id,
1433 &[],
1434 has_self,
1435 self_ty,
1436 &arg_count,
1437 &mut CreateCtorSubstsContext {
1438 fcx: self,
1439 span,
1440 path_segs: &path_segs,
1441 infer_args_for_err: &infer_args_for_err,
1442 segments,
1443 },
1444 )
1445 });
1446 assert!(!substs.has_escaping_bound_vars());
1447 assert!(!ty.has_escaping_bound_vars());
1448
1449 // First, store the "user substs" for later.
1450 self.write_user_type_annotation_from_substs(hir_id, def_id, substs, user_self_ty);
1451
1452 self.add_required_obligations(span, def_id, &substs);
1453
1454 // Substitute the values for the type parameters into the type of
1455 // the referenced item.
1456 let ty_substituted = self.instantiate_type_scheme(span, &substs, ty);
1457
1458 if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
1459 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
1460 // is inherent, there is no `Self` parameter; instead, the impl needs
1461 // type parameters, which we can infer by unifying the provided `Self`
1462 // with the substituted impl type.
1463 // This also occurs for an enum variant on a type alias.
1464 let ty = tcx.type_of(impl_def_id);
1465
1466 let impl_ty = self.instantiate_type_scheme(span, &substs, ty);
1467 match self.at(&self.misc(span), self.param_env).eq(impl_ty, self_ty) {
1468 Ok(ok) => self.register_infer_ok_obligations(ok),
1469 Err(_) => {
1470 self.tcx.sess.delay_span_bug(
1471 span,
1472 &format!(
1473 "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
1474 self_ty,
1475 impl_ty,
1476 ),
1477 );
1478 }
1479 }
1480 }
1481
1482 debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_substituted);
1483 self.write_substs(hir_id, substs);
1484
1485 (ty_substituted, res)
1486 }
1487
1488 /// Add all the obligations that are required, substituting and normalized appropriately.
1489 crate fn add_required_obligations(&self, span: Span, def_id: DefId, substs: &SubstsRef<'tcx>) {
1490 self.add_required_obligations_with_code(
1491 span,
1492 def_id,
1493 substs,
1494 traits::ItemObligation(def_id),
1495 )
1496 }
1497
1498 #[tracing::instrument(level = "debug", skip(self, span, def_id, substs))]
1499 fn add_required_obligations_with_code(
1500 &self,
1501 span: Span,
1502 def_id: DefId,
1503 substs: &SubstsRef<'tcx>,
1504 code: ObligationCauseCode<'tcx>,
1505 ) {
1506 let (bounds, _) = self.instantiate_bounds(span, def_id, &substs);
1507
1508 for obligation in traits::predicates_for_generics(
1509 traits::ObligationCause::new(span, self.body_id, code),
1510 self.param_env,
1511 bounds,
1512 ) {
1513 self.register_predicate(obligation);
1514 }
1515 }
1516
1517 /// Resolves `typ` by a single level if `typ` is a type variable.
1518 /// If no resolution is possible, then an error is reported.
1519 /// Numeric inference variables may be left unresolved.
1520 pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1521 let ty = self.resolve_vars_with_obligations(ty);
1522 if !ty.is_ty_var() {
1523 ty
1524 } else {
1525 if !self.is_tainted_by_errors() {
1526 self.emit_inference_failure_err((**self).body_id, sp, ty.into(), vec![], E0282)
1527 .note("type must be known at this point")
1528 .emit();
1529 }
1530 let err = self.tcx.ty_error();
1531 self.demand_suptype(sp, err, ty);
1532 err
1533 }
1534 }
1535
1536 pub(in super::super) fn with_breakable_ctxt<F: FnOnce() -> R, R>(
1537 &self,
1538 id: hir::HirId,
1539 ctxt: BreakableCtxt<'tcx>,
1540 f: F,
1541 ) -> (BreakableCtxt<'tcx>, R) {
1542 let index;
1543 {
1544 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1545 index = enclosing_breakables.stack.len();
1546 enclosing_breakables.by_id.insert(id, index);
1547 enclosing_breakables.stack.push(ctxt);
1548 }
1549 let result = f();
1550 let ctxt = {
1551 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1552 debug_assert!(enclosing_breakables.stack.len() == index + 1);
1553 enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
1554 enclosing_breakables.stack.pop().expect("missing breakable context")
1555 };
1556 (ctxt, result)
1557 }
1558
1559 /// Instantiate a QueryResponse in a probe context, without a
1560 /// good ObligationCause.
1561 pub(in super::super) fn probe_instantiate_query_response(
1562 &self,
1563 span: Span,
1564 original_values: &OriginalQueryValues<'tcx>,
1565 query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>,
1566 ) -> InferResult<'tcx, Ty<'tcx>> {
1567 self.instantiate_query_response_and_region_obligations(
1568 &traits::ObligationCause::misc(span, self.body_id),
1569 self.param_env,
1570 original_values,
1571 query_result,
1572 )
1573 }
1574
1575 /// Returns `true` if an expression is contained inside the LHS of an assignment expression.
1576 pub(in super::super) fn expr_in_place(&self, mut expr_id: hir::HirId) -> bool {
1577 let mut contained_in_place = false;
1578
1579 while let hir::Node::Expr(parent_expr) =
1580 self.tcx.hir().get(self.tcx.hir().get_parent_node(expr_id))
1581 {
1582 match &parent_expr.kind {
1583 hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => {
1584 if lhs.hir_id == expr_id {
1585 contained_in_place = true;
1586 break;
1587 }
1588 }
1589 _ => (),
1590 }
1591 expr_id = parent_expr.hir_id;
1592 }
1593
1594 contained_in_place
1595 }
1596 }