]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/collect/type_of.rs
fix [type error] for error E0029 and E0277
[rust.git] / compiler / rustc_hir_analysis / src / collect / type_of.rs
1 use rustc_errors::{Applicability, StashKey};
2 use rustc_hir as hir;
3 use rustc_hir::def_id::{DefId, LocalDefId};
4 use rustc_hir::intravisit;
5 use rustc_hir::intravisit::Visitor;
6 use rustc_hir::{HirId, Node};
7 use rustc_middle::hir::nested_filter;
8 use rustc_middle::ty::print::with_forced_trimmed_paths;
9 use rustc_middle::ty::subst::InternalSubsts;
10 use rustc_middle::ty::util::IntTypeExt;
11 use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt, TypeFolder, TypeSuperFoldable, TypeVisitable};
12 use rustc_span::symbol::Ident;
13 use rustc_span::{Span, DUMMY_SP};
14
15 use super::ItemCtxt;
16 use super::{bad_placeholder, is_suggestable_infer_ty};
17 use crate::errors::UnconstrainedOpaqueType;
18
19 /// Computes the relevant generic parameter for a potential generic const argument.
20 ///
21 /// This should be called using the query `tcx.opt_const_param_of`.
22 pub(super) fn opt_const_param_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DefId> {
23     use hir::*;
24     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
25
26     match tcx.hir().get(hir_id) {
27         Node::AnonConst(_) => (),
28         _ => return None,
29     };
30
31     let parent_node_id = tcx.hir().get_parent_node(hir_id);
32     let parent_node = tcx.hir().get(parent_node_id);
33
34     let (generics, arg_idx) = match parent_node {
35         // This match arm is for when the def_id appears in a GAT whose
36         // path can't be resolved without typechecking e.g.
37         //
38         // trait Foo {
39         //   type Assoc<const N: usize>;
40         //   fn foo() -> Self::Assoc<3>;
41         // }
42         //
43         // In the above code we would call this query with the def_id of 3 and
44         // the parent_node we match on would be the hir node for Self::Assoc<3>
45         //
46         // `Self::Assoc<3>` cant be resolved without typechecking here as we
47         // didnt write <Self as Foo>::Assoc<3>. If we did then another match
48         // arm would handle this.
49         //
50         // I believe this match arm is only needed for GAT but I am not 100% sure - BoxyUwU
51         Node::Ty(hir_ty @ Ty { kind: TyKind::Path(QPath::TypeRelative(_, segment)), .. }) => {
52             // Find the Item containing the associated type so we can create an ItemCtxt.
53             // Using the ItemCtxt convert the HIR for the unresolved assoc type into a
54             // ty which is a fully resolved projection.
55             // For the code example above, this would mean converting Self::Assoc<3>
56             // into a ty::Alias(ty::Projection, <Self as Foo>::Assoc<3>)
57             let item_hir_id = tcx
58                 .hir()
59                 .parent_iter(hir_id)
60                 .filter(|(_, node)| matches!(node, Node::Item(_)))
61                 .map(|(id, _)| id)
62                 .next()
63                 .unwrap();
64             let item_did = tcx.hir().local_def_id(item_hir_id).to_def_id();
65             let item_ctxt = &ItemCtxt::new(tcx, item_did) as &dyn crate::astconv::AstConv<'_>;
66             let ty = item_ctxt.ast_ty_to_ty(hir_ty);
67
68             // Iterate through the generics of the projection to find the one that corresponds to
69             // the def_id that this query was called with. We filter to only type and const args here
70             // as a precaution for if it's ever allowed to elide lifetimes in GAT's. It currently isn't
71             // but it can't hurt to be safe ^^
72             if let ty::Alias(ty::Projection, projection) = ty.kind() {
73                 let generics = tcx.generics_of(projection.def_id);
74
75                 let arg_index = segment
76                     .args
77                     .and_then(|args| {
78                         args.args
79                             .iter()
80                             .filter(|arg| arg.is_ty_or_const())
81                             .position(|arg| arg.hir_id() == hir_id)
82                     })
83                     .unwrap_or_else(|| {
84                         bug!("no arg matching AnonConst in segment");
85                     });
86
87                 (generics, arg_index)
88             } else {
89                 // I dont think it's possible to reach this but I'm not 100% sure - BoxyUwU
90                 tcx.sess.delay_span_bug(
91                     tcx.def_span(def_id),
92                     "unexpected non-GAT usage of an anon const",
93                 );
94                 return None;
95             }
96         }
97         Node::Expr(&Expr {
98             kind:
99                 ExprKind::MethodCall(segment, ..) | ExprKind::Path(QPath::TypeRelative(_, segment)),
100             ..
101         }) => {
102             let body_owner = tcx.hir().enclosing_body_owner(hir_id);
103             let tables = tcx.typeck(body_owner);
104             // This may fail in case the method/path does not actually exist.
105             // As there is no relevant param for `def_id`, we simply return
106             // `None` here.
107             let type_dependent_def = tables.type_dependent_def_id(parent_node_id)?;
108             let idx = segment
109                 .args
110                 .and_then(|args| {
111                     args.args
112                         .iter()
113                         .filter(|arg| arg.is_ty_or_const())
114                         .position(|arg| arg.hir_id() == hir_id)
115                 })
116                 .unwrap_or_else(|| {
117                     bug!("no arg matching AnonConst in segment");
118                 });
119
120             (tcx.generics_of(type_dependent_def), idx)
121         }
122
123         Node::Ty(&Ty { kind: TyKind::Path(_), .. })
124         | Node::Expr(&Expr { kind: ExprKind::Path(_) | ExprKind::Struct(..), .. })
125         | Node::TraitRef(..)
126         | Node::Pat(_) => {
127             let path = match parent_node {
128                 Node::Ty(&Ty { kind: TyKind::Path(QPath::Resolved(_, path)), .. })
129                 | Node::TraitRef(&TraitRef { path, .. }) => &*path,
130                 Node::Expr(&Expr {
131                     kind:
132                         ExprKind::Path(QPath::Resolved(_, path))
133                         | ExprKind::Struct(&QPath::Resolved(_, path), ..),
134                     ..
135                 }) => {
136                     let body_owner = tcx.hir().enclosing_body_owner(hir_id);
137                     let _tables = tcx.typeck(body_owner);
138                     &*path
139                 }
140                 Node::Pat(pat) => {
141                     if let Some(path) = get_path_containing_arg_in_pat(pat, hir_id) {
142                         path
143                     } else {
144                         tcx.sess.delay_span_bug(
145                             tcx.def_span(def_id),
146                             &format!("unable to find const parent for {} in pat {:?}", hir_id, pat),
147                         );
148                         return None;
149                     }
150                 }
151                 _ => {
152                     tcx.sess.delay_span_bug(
153                         tcx.def_span(def_id),
154                         &format!("unexpected const parent path {:?}", parent_node),
155                     );
156                     return None;
157                 }
158             };
159
160             // We've encountered an `AnonConst` in some path, so we need to
161             // figure out which generic parameter it corresponds to and return
162             // the relevant type.
163             let Some((arg_index, segment)) = path.segments.iter().find_map(|seg| {
164                 let args = seg.args?;
165                 args.args
166                 .iter()
167                 .filter(|arg| arg.is_ty_or_const())
168                 .position(|arg| arg.hir_id() == hir_id)
169                 .map(|index| (index, seg)).or_else(|| args.bindings
170                     .iter()
171                     .filter_map(TypeBinding::opt_const)
172                     .position(|ct| ct.hir_id == hir_id)
173                     .map(|idx| (idx, seg)))
174             }) else {
175                 tcx.sess.delay_span_bug(
176                     tcx.def_span(def_id),
177                     "no arg matching AnonConst in path",
178                 );
179                 return None;
180             };
181
182             let generics = match tcx.res_generics_def_id(segment.res) {
183                 Some(def_id) => tcx.generics_of(def_id),
184                 None => {
185                     tcx.sess.delay_span_bug(
186                         tcx.def_span(def_id),
187                         &format!("unexpected anon const res {:?} in path: {:?}", segment.res, path),
188                     );
189                     return None;
190                 }
191             };
192
193             (generics, arg_index)
194         }
195         _ => return None,
196     };
197
198     debug!(?parent_node);
199     debug!(?generics, ?arg_idx);
200     generics
201         .params
202         .iter()
203         .filter(|param| param.kind.is_ty_or_const())
204         .nth(match generics.has_self && generics.parent.is_none() {
205             true => arg_idx + 1,
206             false => arg_idx,
207         })
208         .and_then(|param| match param.kind {
209             ty::GenericParamDefKind::Const { .. } => {
210                 debug!(?param);
211                 Some(param.def_id)
212             }
213             _ => None,
214         })
215 }
216
217 fn get_path_containing_arg_in_pat<'hir>(
218     pat: &'hir hir::Pat<'hir>,
219     arg_id: HirId,
220 ) -> Option<&'hir hir::Path<'hir>> {
221     use hir::*;
222
223     let is_arg_in_path = |p: &hir::Path<'_>| {
224         p.segments
225             .iter()
226             .filter_map(|seg| seg.args)
227             .flat_map(|args| args.args)
228             .any(|arg| arg.hir_id() == arg_id)
229     };
230     let mut arg_path = None;
231     pat.walk(|pat| match pat.kind {
232         PatKind::Struct(QPath::Resolved(_, path), _, _)
233         | PatKind::TupleStruct(QPath::Resolved(_, path), _, _)
234         | PatKind::Path(QPath::Resolved(_, path))
235             if is_arg_in_path(path) =>
236         {
237             arg_path = Some(path);
238             false
239         }
240         _ => true,
241     });
242     arg_path
243 }
244
245 pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
246     let def_id = def_id.expect_local();
247     use rustc_hir::*;
248
249     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
250
251     let icx = ItemCtxt::new(tcx, def_id.to_def_id());
252
253     match tcx.hir().get(hir_id) {
254         Node::TraitItem(item) => match item.kind {
255             TraitItemKind::Fn(..) => {
256                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
257                 tcx.mk_fn_def(def_id.to_def_id(), substs)
258             }
259             TraitItemKind::Const(ty, body_id) => body_id
260                 .and_then(|body_id| {
261                     if is_suggestable_infer_ty(ty) {
262                         Some(infer_placeholder_type(
263                             tcx, def_id, body_id, ty.span, item.ident, "constant",
264                         ))
265                     } else {
266                         None
267                     }
268                 })
269                 .unwrap_or_else(|| icx.to_ty(ty)),
270             TraitItemKind::Type(_, Some(ty)) => icx.to_ty(ty),
271             TraitItemKind::Type(_, None) => {
272                 span_bug!(item.span, "associated type missing default");
273             }
274         },
275
276         Node::ImplItem(item) => match item.kind {
277             ImplItemKind::Fn(..) => {
278                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
279                 tcx.mk_fn_def(def_id.to_def_id(), substs)
280             }
281             ImplItemKind::Const(ty, body_id) => {
282                 if is_suggestable_infer_ty(ty) {
283                     infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident, "constant")
284                 } else {
285                     icx.to_ty(ty)
286                 }
287             }
288             ImplItemKind::Type(ty) => {
289                 if tcx.impl_trait_ref(tcx.hir().get_parent_item(hir_id)).is_none() {
290                     check_feature_inherent_assoc_ty(tcx, item.span);
291                 }
292
293                 icx.to_ty(ty)
294             }
295         },
296
297         Node::Item(item) => {
298             match item.kind {
299                 ItemKind::Static(ty, .., body_id) => {
300                     if is_suggestable_infer_ty(ty) {
301                         infer_placeholder_type(
302                             tcx,
303                             def_id,
304                             body_id,
305                             ty.span,
306                             item.ident,
307                             "static variable",
308                         )
309                     } else {
310                         icx.to_ty(ty)
311                     }
312                 }
313                 ItemKind::Const(ty, body_id) => {
314                     if is_suggestable_infer_ty(ty) {
315                         infer_placeholder_type(
316                             tcx, def_id, body_id, ty.span, item.ident, "constant",
317                         )
318                     } else {
319                         icx.to_ty(ty)
320                     }
321                 }
322                 ItemKind::TyAlias(self_ty, _) => icx.to_ty(self_ty),
323                 ItemKind::Impl(hir::Impl { self_ty, .. }) => {
324                     match self_ty.find_self_aliases() {
325                         spans if spans.len() > 0 => {
326                             tcx.sess.emit_err(crate::errors::SelfInImplSelf { span: spans.into(), note: (), });
327                             tcx.ty_error()
328                         },
329                         _ => icx.to_ty(*self_ty),
330                     }
331                 },
332                 ItemKind::Fn(..) => {
333                     let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
334                     tcx.mk_fn_def(def_id.to_def_id(), substs)
335                 }
336                 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
337                     let def = tcx.adt_def(def_id);
338                     let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
339                     tcx.mk_adt(def, substs)
340                 }
341                 ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias, .. }) => {
342                     find_opaque_ty_constraints_for_tait(tcx, def_id)
343                 }
344                 // Opaque types desugared from `impl Trait`.
345                 ItemKind::OpaqueTy(OpaqueTy {
346                     origin:
347                         hir::OpaqueTyOrigin::FnReturn(owner) | hir::OpaqueTyOrigin::AsyncFn(owner),
348                     in_trait,
349                     ..
350                 }) => {
351                     if in_trait {
352                         assert!(tcx.impl_defaultness(owner).has_value());
353                     }
354                     find_opaque_ty_constraints_for_rpit(tcx, def_id, owner)
355                 }
356                 ItemKind::Trait(..)
357                 | ItemKind::TraitAlias(..)
358                 | ItemKind::Macro(..)
359                 | ItemKind::Mod(..)
360                 | ItemKind::ForeignMod { .. }
361                 | ItemKind::GlobalAsm(..)
362                 | ItemKind::ExternCrate(..)
363                 | ItemKind::Use(..) => {
364                     span_bug!(
365                         item.span,
366                         "compute_type_of_item: unexpected item type: {:?}",
367                         item.kind
368                     );
369                 }
370             }
371         }
372
373         Node::ForeignItem(foreign_item) => match foreign_item.kind {
374             ForeignItemKind::Fn(..) => {
375                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
376                 tcx.mk_fn_def(def_id.to_def_id(), substs)
377             }
378             ForeignItemKind::Static(t, _) => icx.to_ty(t),
379             ForeignItemKind::Type => tcx.mk_foreign(def_id.to_def_id()),
380         },
381
382         Node::Ctor(&ref def) | Node::Variant(Variant { data: ref def, .. }) => match *def {
383             VariantData::Unit(..) | VariantData::Struct(..) => {
384                 tcx.type_of(tcx.hir().get_parent_item(hir_id))
385             }
386             VariantData::Tuple(..) => {
387                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
388                 tcx.mk_fn_def(def_id.to_def_id(), substs)
389             }
390         },
391
392         Node::Field(field) => icx.to_ty(field.ty),
393
394         Node::Expr(&Expr { kind: ExprKind::Closure { .. }, .. }) => {
395             tcx.typeck(def_id).node_type(hir_id)
396         }
397
398         Node::AnonConst(_) if let Some(param) = tcx.opt_const_param_of(def_id) => {
399             // We defer to `type_of` of the corresponding parameter
400             // for generic arguments.
401             tcx.type_of(param)
402         }
403
404         Node::AnonConst(_) => {
405             let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
406             match parent_node {
407                 Node::Ty(&Ty { kind: TyKind::Array(_, ref constant), .. })
408                 | Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
409                     if constant.hir_id() == hir_id =>
410                 {
411                     tcx.types.usize
412                 }
413                 Node::Ty(&Ty { kind: TyKind::Typeof(ref e), .. }) if e.hir_id == hir_id => {
414                     tcx.typeck(def_id).node_type(e.hir_id)
415                 }
416
417                 Node::Expr(&Expr { kind: ExprKind::ConstBlock(ref anon_const), .. })
418                     if anon_const.hir_id == hir_id =>
419                 {
420                     let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
421                     substs.as_inline_const().ty()
422                 }
423
424                 Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. })
425                 | Node::Item(&Item { kind: ItemKind::GlobalAsm(asm), .. })
426                     if asm.operands.iter().any(|(op, _op_sp)| match op {
427                         hir::InlineAsmOperand::Const { anon_const }
428                         | hir::InlineAsmOperand::SymFn { anon_const } => {
429                             anon_const.hir_id == hir_id
430                         }
431                         _ => false,
432                     }) =>
433                 {
434                     tcx.typeck(def_id).node_type(hir_id)
435                 }
436
437                 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => {
438                     tcx.adt_def(tcx.hir().get_parent_item(hir_id)).repr().discr_type().to_ty(tcx)
439                 }
440
441                 Node::TypeBinding(
442                     binding @ &TypeBinding {
443                         hir_id: binding_id,
444                         kind: TypeBindingKind::Equality { term: Term::Const(ref e) },
445                         ..
446                     },
447                 ) if let Node::TraitRef(trait_ref) =
448                     tcx.hir().get(tcx.hir().get_parent_node(binding_id))
449                     && e.hir_id == hir_id =>
450                 {
451                     let Some(trait_def_id) = trait_ref.trait_def_id() else {
452                         return tcx.ty_error_with_message(DUMMY_SP, "Could not find trait");
453                     };
454                     let assoc_items = tcx.associated_items(trait_def_id);
455                     let assoc_item = assoc_items.find_by_name_and_kind(
456                         tcx,
457                         binding.ident,
458                         ty::AssocKind::Const,
459                         def_id.to_def_id(),
460                     );
461                     if let Some(assoc_item) = assoc_item {
462                         tcx.type_of(assoc_item.def_id)
463                     } else {
464                         // FIXME(associated_const_equality): add a useful error message here.
465                         tcx.ty_error_with_message(
466                             DUMMY_SP,
467                             "Could not find associated const on trait",
468                         )
469                     }
470                 }
471
472                 Node::TypeBinding(
473                     binding @ &TypeBinding { hir_id: binding_id, gen_args, ref kind, .. },
474                 ) if let Node::TraitRef(trait_ref) =
475                     tcx.hir().get(tcx.hir().get_parent_node(binding_id))
476                     && let Some((idx, _)) =
477                         gen_args.args.iter().enumerate().find(|(_, arg)| {
478                             if let GenericArg::Const(ct) = arg {
479                                 ct.value.hir_id == hir_id
480                             } else {
481                                 false
482                             }
483                         }) =>
484                 {
485                     let Some(trait_def_id) = trait_ref.trait_def_id() else {
486                         return tcx.ty_error_with_message(DUMMY_SP, "Could not find trait");
487                     };
488                     let assoc_items = tcx.associated_items(trait_def_id);
489                     let assoc_item = assoc_items.find_by_name_and_kind(
490                         tcx,
491                         binding.ident,
492                         match kind {
493                             // I think `<A: T>` type bindings requires that `A` is a type
494                             TypeBindingKind::Constraint { .. }
495                             | TypeBindingKind::Equality { term: Term::Ty(..) } => {
496                                 ty::AssocKind::Type
497                             }
498                             TypeBindingKind::Equality { term: Term::Const(..) } => {
499                                 ty::AssocKind::Const
500                             }
501                         },
502                         def_id.to_def_id(),
503                     );
504                     if let Some(param)
505                         = assoc_item.map(|item| &tcx.generics_of(item.def_id).params[idx]).filter(|param| param.kind.is_ty_or_const())
506                     {
507                         tcx.type_of(param.def_id)
508                     } else {
509                         // FIXME(associated_const_equality): add a useful error message here.
510                         tcx.ty_error_with_message(
511                             DUMMY_SP,
512                             "Could not find associated const on trait",
513                         )
514                     }
515                 }
516
517                 Node::GenericParam(&GenericParam {
518                     def_id: param_def_id,
519                     kind: GenericParamKind::Const { default: Some(ct), .. },
520                     ..
521                 }) if ct.hir_id == hir_id => tcx.type_of(param_def_id),
522
523                 x => tcx.ty_error_with_message(
524                     DUMMY_SP,
525                     &format!("unexpected const parent in type_of(): {x:?}"),
526                 ),
527             }
528         }
529
530         Node::GenericParam(param) => match &param.kind {
531             GenericParamKind::Type { default: Some(ty), .. }
532             | GenericParamKind::Const { ty, .. } => icx.to_ty(ty),
533             x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
534         },
535
536         x => {
537             bug!("unexpected sort of node in type_of(): {:?}", x);
538         }
539     }
540 }
541
542 #[instrument(skip(tcx), level = "debug")]
543 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
544 /// laid for "higher-order pattern unification".
545 /// This ensures that inference is tractable.
546 /// In particular, definitions of opaque types can only use other generics as arguments,
547 /// and they cannot repeat an argument. Example:
548 ///
549 /// ```ignore (illustrative)
550 /// type Foo<A, B> = impl Bar<A, B>;
551 ///
552 /// // Okay -- `Foo` is applied to two distinct, generic types.
553 /// fn a<T, U>() -> Foo<T, U> { .. }
554 ///
555 /// // Not okay -- `Foo` is applied to `T` twice.
556 /// fn b<T>() -> Foo<T, T> { .. }
557 ///
558 /// // Not okay -- `Foo` is applied to a non-generic type.
559 /// fn b<T>() -> Foo<T, u32> { .. }
560 /// ```
561 ///
562 fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
563     use rustc_hir::{Expr, ImplItem, Item, TraitItem};
564
565     struct ConstraintLocator<'tcx> {
566         tcx: TyCtxt<'tcx>,
567
568         /// def_id of the opaque type whose defining uses are being checked
569         def_id: LocalDefId,
570
571         /// as we walk the defining uses, we are checking that all of them
572         /// define the same hidden type. This variable is set to `Some`
573         /// with the first type that we find, and then later types are
574         /// checked against it (we also carry the span of that first
575         /// type).
576         found: Option<ty::OpaqueHiddenType<'tcx>>,
577
578         /// In the presence of dead code, typeck may figure out a hidden type
579         /// while borrowck will now. We collect these cases here and check at
580         /// the end that we actually found a type that matches (modulo regions).
581         typeck_types: Vec<ty::OpaqueHiddenType<'tcx>>,
582     }
583
584     impl ConstraintLocator<'_> {
585         #[instrument(skip(self), level = "debug")]
586         fn check(&mut self, item_def_id: LocalDefId) {
587             // Don't try to check items that cannot possibly constrain the type.
588             if !self.tcx.has_typeck_results(item_def_id) {
589                 debug!("no constraint: no typeck results");
590                 return;
591             }
592             // Calling `mir_borrowck` can lead to cycle errors through
593             // const-checking, avoid calling it if we don't have to.
594             // ```rust
595             // type Foo = impl Fn() -> usize; // when computing type for this
596             // const fn bar() -> Foo {
597             //     || 0usize
598             // }
599             // const BAZR: Foo = bar(); // we would mir-borrowck this, causing cycles
600             // // because we again need to reveal `Foo` so we can check whether the
601             // // constant does not contain interior mutability.
602             // ```
603             let tables = self.tcx.typeck(item_def_id);
604             if let Some(_) = tables.tainted_by_errors {
605                 self.found = Some(ty::OpaqueHiddenType { span: DUMMY_SP, ty: self.tcx.ty_error() });
606                 return;
607             }
608             let Some(&typeck_hidden_ty) = tables.concrete_opaque_types.get(&self.def_id) else {
609                 debug!("no constraints in typeck results");
610                 return;
611             };
612             if self.typeck_types.iter().all(|prev| prev.ty != typeck_hidden_ty.ty) {
613                 self.typeck_types.push(typeck_hidden_ty);
614             }
615
616             // Use borrowck to get the type with unerased regions.
617             let concrete_opaque_types = &self.tcx.mir_borrowck(item_def_id).concrete_opaque_types;
618             debug!(?concrete_opaque_types);
619             if let Some(&concrete_type) = concrete_opaque_types.get(&self.def_id) {
620                 debug!(?concrete_type, "found constraint");
621                 if let Some(prev) = &mut self.found {
622                     if concrete_type.ty != prev.ty && !(concrete_type, prev.ty).references_error() {
623                         prev.report_mismatch(&concrete_type, self.tcx);
624                         prev.ty = self.tcx.ty_error();
625                     }
626                 } else {
627                     self.found = Some(concrete_type);
628                 }
629             }
630         }
631     }
632
633     impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
634         type NestedFilter = nested_filter::All;
635
636         fn nested_visit_map(&mut self) -> Self::Map {
637             self.tcx.hir()
638         }
639         fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
640             if let hir::ExprKind::Closure(closure) = ex.kind {
641                 self.check(closure.def_id);
642             }
643             intravisit::walk_expr(self, ex);
644         }
645         fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
646             trace!(?it.owner_id);
647             // The opaque type itself or its children are not within its reveal scope.
648             if it.owner_id.def_id != self.def_id {
649                 self.check(it.owner_id.def_id);
650                 intravisit::walk_item(self, it);
651             }
652         }
653         fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
654             trace!(?it.owner_id);
655             // The opaque type itself or its children are not within its reveal scope.
656             if it.owner_id.def_id != self.def_id {
657                 self.check(it.owner_id.def_id);
658                 intravisit::walk_impl_item(self, it);
659             }
660         }
661         fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
662             trace!(?it.owner_id);
663             self.check(it.owner_id.def_id);
664             intravisit::walk_trait_item(self, it);
665         }
666     }
667
668     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
669     let scope = tcx.hir().get_defining_scope(hir_id);
670     let mut locator = ConstraintLocator { def_id, tcx, found: None, typeck_types: vec![] };
671
672     debug!(?scope);
673
674     if scope == hir::CRATE_HIR_ID {
675         tcx.hir().walk_toplevel_module(&mut locator);
676     } else {
677         trace!("scope={:#?}", tcx.hir().get(scope));
678         match tcx.hir().get(scope) {
679             // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
680             // This allows our visitor to process the defining item itself, causing
681             // it to pick up any 'sibling' defining uses.
682             //
683             // For example, this code:
684             // ```
685             // fn foo() {
686             //     type Blah = impl Debug;
687             //     let my_closure = || -> Blah { true };
688             // }
689             // ```
690             //
691             // requires us to explicitly process `foo()` in order
692             // to notice the defining usage of `Blah`.
693             Node::Item(it) => locator.visit_item(it),
694             Node::ImplItem(it) => locator.visit_impl_item(it),
695             Node::TraitItem(it) => locator.visit_trait_item(it),
696             other => bug!("{:?} is not a valid scope for an opaque type item", other),
697         }
698     }
699
700     let Some(hidden) = locator.found else {
701         let reported = tcx.sess.emit_err(UnconstrainedOpaqueType {
702             span: tcx.def_span(def_id),
703             name: tcx.item_name(tcx.local_parent(def_id).to_def_id()),
704             what: match tcx.hir().get(scope) {
705                 _ if scope == hir::CRATE_HIR_ID => "module",
706                 Node::Item(hir::Item { kind: hir::ItemKind::Mod(_), .. }) => "module",
707                 Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. }) => "impl",
708                 _ => "item",
709             },
710         });
711         return tcx.ty_error_with_guaranteed(reported);
712     };
713
714     // Only check against typeck if we didn't already error
715     if !hidden.ty.references_error() {
716         for concrete_type in locator.typeck_types {
717             if tcx.erase_regions(concrete_type.ty) != tcx.erase_regions(hidden.ty)
718                 && !(concrete_type, hidden).references_error()
719             {
720                 hidden.report_mismatch(&concrete_type, tcx);
721             }
722         }
723     }
724
725     hidden.ty
726 }
727
728 fn find_opaque_ty_constraints_for_rpit(
729     tcx: TyCtxt<'_>,
730     def_id: LocalDefId,
731     owner_def_id: LocalDefId,
732 ) -> Ty<'_> {
733     use rustc_hir::{Expr, ImplItem, Item, TraitItem};
734
735     struct ConstraintChecker<'tcx> {
736         tcx: TyCtxt<'tcx>,
737
738         /// def_id of the opaque type whose defining uses are being checked
739         def_id: LocalDefId,
740
741         found: ty::OpaqueHiddenType<'tcx>,
742     }
743
744     impl ConstraintChecker<'_> {
745         #[instrument(skip(self), level = "debug")]
746         fn check(&self, def_id: LocalDefId) {
747             // Use borrowck to get the type with unerased regions.
748             let concrete_opaque_types = &self.tcx.mir_borrowck(def_id).concrete_opaque_types;
749             debug!(?concrete_opaque_types);
750             for &(def_id, concrete_type) in concrete_opaque_types {
751                 if def_id != self.def_id {
752                     // Ignore constraints for other opaque types.
753                     continue;
754                 }
755
756                 debug!(?concrete_type, "found constraint");
757
758                 if concrete_type.ty != self.found.ty
759                     && !(concrete_type, self.found).references_error()
760                 {
761                     self.found.report_mismatch(&concrete_type, self.tcx);
762                 }
763             }
764         }
765     }
766
767     impl<'tcx> intravisit::Visitor<'tcx> for ConstraintChecker<'tcx> {
768         type NestedFilter = nested_filter::OnlyBodies;
769
770         fn nested_visit_map(&mut self) -> Self::Map {
771             self.tcx.hir()
772         }
773         fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
774             if let hir::ExprKind::Closure(closure) = ex.kind {
775                 self.check(closure.def_id);
776             }
777             intravisit::walk_expr(self, ex);
778         }
779         fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
780             trace!(?it.owner_id);
781             // The opaque type itself or its children are not within its reveal scope.
782             if it.owner_id.def_id != self.def_id {
783                 self.check(it.owner_id.def_id);
784                 intravisit::walk_item(self, it);
785             }
786         }
787         fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
788             trace!(?it.owner_id);
789             // The opaque type itself or its children are not within its reveal scope.
790             if it.owner_id.def_id != self.def_id {
791                 self.check(it.owner_id.def_id);
792                 intravisit::walk_impl_item(self, it);
793             }
794         }
795         fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
796             trace!(?it.owner_id);
797             self.check(it.owner_id.def_id);
798             intravisit::walk_trait_item(self, it);
799         }
800     }
801
802     let concrete = tcx.mir_borrowck(owner_def_id).concrete_opaque_types.get(&def_id).copied();
803
804     if let Some(concrete) = concrete {
805         let scope = tcx.hir().local_def_id_to_hir_id(owner_def_id);
806         debug!(?scope);
807         let mut locator = ConstraintChecker { def_id, tcx, found: concrete };
808
809         match tcx.hir().get(scope) {
810             Node::Item(it) => intravisit::walk_item(&mut locator, it),
811             Node::ImplItem(it) => intravisit::walk_impl_item(&mut locator, it),
812             Node::TraitItem(it) => intravisit::walk_trait_item(&mut locator, it),
813             other => bug!("{:?} is not a valid scope for an opaque type item", other),
814         }
815     }
816
817     concrete.map(|concrete| concrete.ty).unwrap_or_else(|| {
818         let table = tcx.typeck(owner_def_id);
819         if let Some(_) = table.tainted_by_errors {
820             // Some error in the
821             // owner fn prevented us from populating
822             // the `concrete_opaque_types` table.
823             tcx.ty_error()
824         } else {
825             table.concrete_opaque_types.get(&def_id).map(|ty| ty.ty).unwrap_or_else(|| {
826                 // We failed to resolve the opaque type or it
827                 // resolves to itself. We interpret this as the
828                 // no values of the hidden type ever being constructed,
829                 // so we can just make the hidden type be `!`.
830                 // For backwards compatibility reasons, we fall back to
831                 // `()` until we the diverging default is changed.
832                 tcx.mk_diverging_default()
833             })
834         }
835     })
836 }
837
838 fn infer_placeholder_type<'a>(
839     tcx: TyCtxt<'a>,
840     def_id: LocalDefId,
841     body_id: hir::BodyId,
842     span: Span,
843     item_ident: Ident,
844     kind: &'static str,
845 ) -> Ty<'a> {
846     // Attempts to make the type nameable by turning FnDefs into FnPtrs.
847     struct MakeNameable<'tcx> {
848         success: bool,
849         tcx: TyCtxt<'tcx>,
850     }
851
852     impl<'tcx> MakeNameable<'tcx> {
853         fn new(tcx: TyCtxt<'tcx>) -> Self {
854             MakeNameable { success: true, tcx }
855         }
856     }
857
858     impl<'tcx> TypeFolder<'tcx> for MakeNameable<'tcx> {
859         fn tcx(&self) -> TyCtxt<'tcx> {
860             self.tcx
861         }
862
863         fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
864             if !self.success {
865                 return ty;
866             }
867
868             match ty.kind() {
869                 ty::FnDef(def_id, _) => self.tcx.mk_fn_ptr(self.tcx.fn_sig(*def_id)),
870                 // FIXME: non-capturing closures should also suggest a function pointer
871                 ty::Closure(..) | ty::Generator(..) => {
872                     self.success = false;
873                     ty
874                 }
875                 _ => ty.super_fold_with(self),
876             }
877         }
878     }
879
880     let ty = tcx.diagnostic_only_typeck(def_id).node_type(body_id.hir_id);
881
882     // If this came from a free `const` or `static mut?` item,
883     // then the user may have written e.g. `const A = 42;`.
884     // In this case, the parser has stashed a diagnostic for
885     // us to improve in typeck so we do that now.
886     match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
887         Some(mut err) => {
888             if !ty.references_error() {
889                 // Only suggest adding `:` if it was missing (and suggested by parsing diagnostic)
890                 let colon = if span == item_ident.span.shrink_to_hi() { ":" } else { "" };
891
892                 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
893                 // We are typeck and have the real type, so remove that and suggest the actual type.
894                 // FIXME(eddyb) this looks like it should be functionality on `Diagnostic`.
895                 if let Ok(suggestions) = &mut err.suggestions {
896                     suggestions.clear();
897                 }
898
899                 // Suggesting unnameable types won't help.
900                 let mut mk_nameable = MakeNameable::new(tcx);
901                 let ty = mk_nameable.fold_ty(ty);
902                 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
903                 if let Some(sugg_ty) = sugg_ty {
904                     err.span_suggestion(
905                         span,
906                         &format!("provide a type for the {item}", item = kind),
907                         format!("{colon} {sugg_ty}"),
908                         Applicability::MachineApplicable,
909                     );
910                 } else {
911                     with_forced_trimmed_paths!(err.span_note(
912                         tcx.hir().body(body_id).value.span,
913                         &format!("however, the inferred type `{ty}` cannot be named"),
914                     ));
915                 }
916             }
917
918             err.emit();
919         }
920         None => {
921             let mut diag = bad_placeholder(tcx, vec![span], kind);
922
923             if !ty.references_error() {
924                 let mut mk_nameable = MakeNameable::new(tcx);
925                 let ty = mk_nameable.fold_ty(ty);
926                 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
927                 if let Some(sugg_ty) = sugg_ty {
928                     diag.span_suggestion(
929                         span,
930                         "replace with the correct type",
931                         sugg_ty,
932                         Applicability::MaybeIncorrect,
933                     );
934                 } else {
935                     with_forced_trimmed_paths!(diag.span_note(
936                         tcx.hir().body(body_id).value.span,
937                         &format!("however, the inferred type `{ty}` cannot be named"),
938                     ));
939                 }
940             }
941
942             diag.emit();
943         }
944     }
945
946     // Typeck doesn't expect erased regions to be returned from `type_of`.
947     tcx.fold_regions(ty, |r, _| match *r {
948         ty::ReErased => tcx.lifetimes.re_static,
949         _ => r,
950     })
951 }
952
953 fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) {
954     if !tcx.features().inherent_associated_types {
955         use rustc_session::parse::feature_err;
956         use rustc_span::symbol::sym;
957         feature_err(
958             &tcx.sess.parse_sess,
959             sym::inherent_associated_types,
960             span,
961             "inherent associated types are unstable",
962         )
963         .emit();
964     }
965 }