]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/collect/type_of.rs
Auto merge of #97313 - cjgillot:ast-lifetimes-anon, r=petrochenkov
[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(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                     let concrete_ty = tcx
343                         .mir_borrowck(owner)
344                         .concrete_opaque_types
345                         .get(&def_id)
346                         .copied()
347                         .map(|concrete| concrete.ty)
348                         .unwrap_or_else(|| {
349                             let table = tcx.typeck(owner);
350                             if let Some(_) = table.tainted_by_errors {
351                                 // Some error in the
352                                 // owner fn prevented us from populating
353                                 // the `concrete_opaque_types` table.
354                                 tcx.ty_error()
355                             } else {
356                                 table.concrete_opaque_types.get(&def_id).copied().unwrap_or_else(|| {
357                                     // We failed to resolve the opaque type or it
358                                     // resolves to itself. We interpret this as the
359                                     // no values of the hidden type ever being constructed,
360                                     // so we can just make the hidden type be `!`.
361                                     // For backwards compatibility reasons, we fall back to
362                                     // `()` until we the diverging default is changed.
363                                     Some(tcx.mk_diverging_default())
364                                 }).expect("RPIT always have a hidden type from typeck")
365                             }
366                         });
367                     debug!("concrete_ty = {:?}", concrete_ty);
368                     concrete_ty
369                 }
370                 ItemKind::Trait(..)
371                 | ItemKind::TraitAlias(..)
372                 | ItemKind::Macro(..)
373                 | ItemKind::Mod(..)
374                 | ItemKind::ForeignMod { .. }
375                 | ItemKind::GlobalAsm(..)
376                 | ItemKind::ExternCrate(..)
377                 | ItemKind::Use(..) => {
378                     span_bug!(
379                         item.span,
380                         "compute_type_of_item: unexpected item type: {:?}",
381                         item.kind
382                     );
383                 }
384             }
385         }
386
387         Node::ForeignItem(foreign_item) => match foreign_item.kind {
388             ForeignItemKind::Fn(..) => {
389                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
390                 tcx.mk_fn_def(def_id.to_def_id(), substs)
391             }
392             ForeignItemKind::Static(t, _) => icx.to_ty(t),
393             ForeignItemKind::Type => tcx.mk_foreign(def_id.to_def_id()),
394         },
395
396         Node::Ctor(&ref def) | Node::Variant(Variant { data: ref def, .. }) => match *def {
397             VariantData::Unit(..) | VariantData::Struct(..) => {
398                 tcx.type_of(tcx.hir().get_parent_item(hir_id))
399             }
400             VariantData::Tuple(..) => {
401                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
402                 tcx.mk_fn_def(def_id.to_def_id(), substs)
403             }
404         },
405
406         Node::Field(field) => icx.to_ty(field.ty),
407
408         Node::Expr(&Expr { kind: ExprKind::Closure{..}, .. }) => tcx.typeck(def_id).node_type(hir_id),
409
410         Node::AnonConst(_) if let Some(param) = tcx.opt_const_param_of(def_id) => {
411             // We defer to `type_of` of the corresponding parameter
412             // for generic arguments.
413             tcx.type_of(param)
414         }
415
416         Node::AnonConst(_) => {
417             let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
418             match parent_node {
419                 Node::Ty(&Ty { kind: TyKind::Array(_, ref constant), .. })
420                 | Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
421                     if constant.hir_id() == hir_id =>
422                 {
423                     tcx.types.usize
424                 }
425                 Node::Ty(&Ty { kind: TyKind::Typeof(ref e), .. }) if e.hir_id == hir_id => {
426                     tcx.typeck(def_id).node_type(e.hir_id)
427                 }
428
429                 Node::Expr(&Expr { kind: ExprKind::ConstBlock(ref anon_const), .. })
430                     if anon_const.hir_id == hir_id =>
431                 {
432                     let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
433                     substs.as_inline_const().ty()
434                 }
435
436                 Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. })
437                 | Node::Item(&Item { kind: ItemKind::GlobalAsm(asm), .. })
438                     if asm.operands.iter().any(|(op, _op_sp)| match op {
439                         hir::InlineAsmOperand::Const { anon_const }
440                         | hir::InlineAsmOperand::SymFn { anon_const } => anon_const.hir_id == hir_id,
441                         _ => false,
442                     }) =>
443                 {
444                     tcx.typeck(def_id).node_type(hir_id)
445                 }
446
447                 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => tcx
448                     .adt_def(tcx.hir().get_parent_item(hir_id))
449                     .repr()
450                     .discr_type()
451                     .to_ty(tcx),
452
453                 Node::TypeBinding(binding @ &TypeBinding { hir_id: binding_id, ..  })
454                     if let Node::TraitRef(trait_ref) = tcx.hir().get(
455                         tcx.hir().get_parent_node(binding_id)
456                     ) =>
457                 {
458                   let Some(trait_def_id) = trait_ref.trait_def_id() else {
459                     return tcx.ty_error_with_message(DUMMY_SP, "Could not find trait");
460                   };
461                   let assoc_items = tcx.associated_items(trait_def_id);
462                   let assoc_item = assoc_items.find_by_name_and_kind(
463                     tcx, binding.ident, ty::AssocKind::Const, def_id.to_def_id(),
464                   );
465                   if let Some(assoc_item) = assoc_item {
466                     tcx.type_of(assoc_item.def_id)
467                   } else {
468                       // FIXME(associated_const_equality): add a useful error message here.
469                       tcx.ty_error_with_message(
470                         DUMMY_SP,
471                         "Could not find associated const on trait",
472                     )
473                   }
474                 }
475
476                 Node::GenericParam(&GenericParam {
477                     hir_id: param_hir_id,
478                     kind: GenericParamKind::Const { default: Some(ct), .. },
479                     ..
480                 }) if ct.hir_id == hir_id => tcx.type_of(tcx.hir().local_def_id(param_hir_id)),
481
482                 x =>
483                   tcx.ty_error_with_message(
484                     DUMMY_SP,
485                     &format!("unexpected const parent in type_of(): {x:?}"),
486                 ),
487             }
488         }
489
490         Node::GenericParam(param) => match &param.kind {
491             GenericParamKind::Type { default: Some(ty), .. }
492             | GenericParamKind::Const { ty, .. } => icx.to_ty(ty),
493             x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
494         },
495
496         x => {
497             bug!("unexpected sort of node in type_of(): {:?}", x);
498         }
499     }
500 }
501
502 #[instrument(skip(tcx), level = "debug")]
503 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
504 /// laid for "higher-order pattern unification".
505 /// This ensures that inference is tractable.
506 /// In particular, definitions of opaque types can only use other generics as arguments,
507 /// and they cannot repeat an argument. Example:
508 ///
509 /// ```ignore (illustrative)
510 /// type Foo<A, B> = impl Bar<A, B>;
511 ///
512 /// // Okay -- `Foo` is applied to two distinct, generic types.
513 /// fn a<T, U>() -> Foo<T, U> { .. }
514 ///
515 /// // Not okay -- `Foo` is applied to `T` twice.
516 /// fn b<T>() -> Foo<T, T> { .. }
517 ///
518 /// // Not okay -- `Foo` is applied to a non-generic type.
519 /// fn b<T>() -> Foo<T, u32> { .. }
520 /// ```
521 ///
522 fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
523     use rustc_hir::{Expr, ImplItem, Item, TraitItem};
524
525     struct ConstraintLocator<'tcx> {
526         tcx: TyCtxt<'tcx>,
527
528         /// def_id of the opaque type whose defining uses are being checked
529         def_id: LocalDefId,
530
531         /// as we walk the defining uses, we are checking that all of them
532         /// define the same hidden type. This variable is set to `Some`
533         /// with the first type that we find, and then later types are
534         /// checked against it (we also carry the span of that first
535         /// type).
536         found: Option<ty::OpaqueHiddenType<'tcx>>,
537     }
538
539     impl ConstraintLocator<'_> {
540         #[instrument(skip(self), level = "debug")]
541         fn check(&mut self, item_def_id: LocalDefId) {
542             // Don't try to check items that cannot possibly constrain the type.
543             if !self.tcx.has_typeck_results(item_def_id) {
544                 debug!("no constraint: no typeck results");
545                 return;
546             }
547             // Calling `mir_borrowck` can lead to cycle errors through
548             // const-checking, avoid calling it if we don't have to.
549             // ```rust
550             // type Foo = impl Fn() -> usize; // when computing type for this
551             // const fn bar() -> Foo {
552             //     || 0usize
553             // }
554             // const BAZR: Foo = bar(); // we would mir-borrowck this, causing cycles
555             // // because we again need to reveal `Foo` so we can check whether the
556             // // constant does not contain interior mutability.
557             // ```
558             let tables = self.tcx.typeck(item_def_id);
559             if let Some(_) = tables.tainted_by_errors {
560                 self.found = Some(ty::OpaqueHiddenType { span: DUMMY_SP, ty: self.tcx.ty_error() });
561                 return;
562             }
563             if !tables.concrete_opaque_types.contains_key(&self.def_id) {
564                 debug!("no constraints in typeck results");
565                 return;
566             }
567             // Use borrowck to get the type with unerased regions.
568             let concrete_opaque_types = &self.tcx.mir_borrowck(item_def_id).concrete_opaque_types;
569             debug!(?concrete_opaque_types);
570             if let Some(&concrete_type) = concrete_opaque_types.get(&self.def_id) {
571                 debug!(?concrete_type, "found constraint");
572                 if let Some(prev) = self.found {
573                     if concrete_type.ty != prev.ty && !(concrete_type, prev).references_error() {
574                         prev.report_mismatch(&concrete_type, self.tcx);
575                     }
576                 } else {
577                     self.found = Some(concrete_type);
578                 }
579             }
580         }
581     }
582
583     impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
584         type NestedFilter = nested_filter::All;
585
586         fn nested_visit_map(&mut self) -> Self::Map {
587             self.tcx.hir()
588         }
589         fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
590             if let hir::ExprKind::Closure { .. } = ex.kind {
591                 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
592                 self.check(def_id);
593             }
594             intravisit::walk_expr(self, ex);
595         }
596         fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
597             trace!(?it.def_id);
598             // The opaque type itself or its children are not within its reveal scope.
599             if it.def_id != self.def_id {
600                 self.check(it.def_id);
601                 intravisit::walk_item(self, it);
602             }
603         }
604         fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
605             trace!(?it.def_id);
606             // The opaque type itself or its children are not within its reveal scope.
607             if it.def_id != self.def_id {
608                 self.check(it.def_id);
609                 intravisit::walk_impl_item(self, it);
610             }
611         }
612         fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
613             trace!(?it.def_id);
614             self.check(it.def_id);
615             intravisit::walk_trait_item(self, it);
616         }
617     }
618
619     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
620     let scope = tcx.hir().get_defining_scope(hir_id);
621     let mut locator = ConstraintLocator { def_id: def_id, tcx, found: None };
622
623     debug!(?scope);
624
625     if scope == hir::CRATE_HIR_ID {
626         tcx.hir().walk_toplevel_module(&mut locator);
627     } else {
628         trace!("scope={:#?}", tcx.hir().get(scope));
629         match tcx.hir().get(scope) {
630             // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
631             // This allows our visitor to process the defining item itself, causing
632             // it to pick up any 'sibling' defining uses.
633             //
634             // For example, this code:
635             // ```
636             // fn foo() {
637             //     type Blah = impl Debug;
638             //     let my_closure = || -> Blah { true };
639             // }
640             // ```
641             //
642             // requires us to explicitly process `foo()` in order
643             // to notice the defining usage of `Blah`.
644             Node::Item(it) => locator.visit_item(it),
645             Node::ImplItem(it) => locator.visit_impl_item(it),
646             Node::TraitItem(it) => locator.visit_trait_item(it),
647             other => bug!("{:?} is not a valid scope for an opaque type item", other),
648         }
649     }
650
651     match locator.found {
652         Some(hidden) => hidden.ty,
653         None => {
654             tcx.sess.emit_err(UnconstrainedOpaqueType {
655                 span: tcx.def_span(def_id),
656                 name: tcx.item_name(tcx.local_parent(def_id).to_def_id()),
657             });
658             tcx.ty_error()
659         }
660     }
661 }
662
663 fn infer_placeholder_type<'a>(
664     tcx: TyCtxt<'a>,
665     def_id: LocalDefId,
666     body_id: hir::BodyId,
667     span: Span,
668     item_ident: Ident,
669     kind: &'static str,
670 ) -> Ty<'a> {
671     // Attempts to make the type nameable by turning FnDefs into FnPtrs.
672     struct MakeNameable<'tcx> {
673         success: bool,
674         tcx: TyCtxt<'tcx>,
675     }
676
677     impl<'tcx> MakeNameable<'tcx> {
678         fn new(tcx: TyCtxt<'tcx>) -> Self {
679             MakeNameable { success: true, tcx }
680         }
681     }
682
683     impl<'tcx> TypeFolder<'tcx> for MakeNameable<'tcx> {
684         fn tcx(&self) -> TyCtxt<'tcx> {
685             self.tcx
686         }
687
688         fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
689             if !self.success {
690                 return ty;
691             }
692
693             match ty.kind() {
694                 ty::FnDef(def_id, _) => self.tcx.mk_fn_ptr(self.tcx.fn_sig(*def_id)),
695                 // FIXME: non-capturing closures should also suggest a function pointer
696                 ty::Closure(..) | ty::Generator(..) => {
697                     self.success = false;
698                     ty
699                 }
700                 _ => ty.super_fold_with(self),
701             }
702         }
703     }
704
705     let ty = tcx.diagnostic_only_typeck(def_id).node_type(body_id.hir_id);
706
707     // If this came from a free `const` or `static mut?` item,
708     // then the user may have written e.g. `const A = 42;`.
709     // In this case, the parser has stashed a diagnostic for
710     // us to improve in typeck so we do that now.
711     match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
712         Some(mut err) => {
713             if !ty.references_error() {
714                 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
715                 // We are typeck and have the real type, so remove that and suggest the actual type.
716                 // FIXME(eddyb) this looks like it should be functionality on `Diagnostic`.
717                 if let Ok(suggestions) = &mut err.suggestions {
718                     suggestions.clear();
719                 }
720
721                 // Suggesting unnameable types won't help.
722                 let mut mk_nameable = MakeNameable::new(tcx);
723                 let ty = mk_nameable.fold_ty(ty);
724                 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
725                 if let Some(sugg_ty) = sugg_ty {
726                     err.span_suggestion(
727                         span,
728                         &format!("provide a type for the {item}", item = kind),
729                         format!("{}: {}", item_ident, sugg_ty),
730                         Applicability::MachineApplicable,
731                     );
732                 } else {
733                     err.span_note(
734                         tcx.hir().body(body_id).value.span,
735                         &format!("however, the inferred type `{}` cannot be named", ty),
736                     );
737                 }
738             }
739
740             err.emit();
741         }
742         None => {
743             let mut diag = bad_placeholder(tcx, vec![span], kind);
744
745             if !ty.references_error() {
746                 let mut mk_nameable = MakeNameable::new(tcx);
747                 let ty = mk_nameable.fold_ty(ty);
748                 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
749                 if let Some(sugg_ty) = sugg_ty {
750                     diag.span_suggestion(
751                         span,
752                         "replace with the correct type",
753                         sugg_ty,
754                         Applicability::MaybeIncorrect,
755                     );
756                 } else {
757                     diag.span_note(
758                         tcx.hir().body(body_id).value.span,
759                         &format!("however, the inferred type `{}` cannot be named", ty),
760                     );
761                 }
762             }
763
764             diag.emit();
765         }
766     }
767
768     // Typeck doesn't expect erased regions to be returned from `type_of`.
769     tcx.fold_regions(ty, |r, _| match *r {
770         ty::ReErased => tcx.lifetimes.re_static,
771         _ => r,
772     })
773 }
774
775 fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) {
776     if !tcx.features().inherent_associated_types {
777         use rustc_session::parse::feature_err;
778         use rustc_span::symbol::sym;
779         feature_err(
780             &tcx.sess.parse_sess,
781             sym::inherent_associated_types,
782             span,
783             "inherent associated types are unstable",
784         )
785         .emit();
786     }
787 }