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