]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/collect/type_of.rs
Auto merge of #95435 - cjgillot:one-name, r=oli-obk
[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, TypeFoldable, TypeFolder};
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
18 /// Computes the relevant generic parameter for a potential generic const argument.
19 ///
20 /// This should be called using the query `tcx.opt_const_param_of`.
21 #[instrument(level = "debug", skip(tcx))]
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::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 const args here as a
70             // 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::Projection(projection) = ty.kind() {
73                 let generics = tcx.generics_of(projection.item_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.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().local_def_id(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.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().local_def_id(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 filtered = path.segments.iter().find_map(|seg| {
164                 seg.args?
165                     .args
166                     .iter()
167                     .filter(|arg| arg.is_ty_or_const())
168                     .position(|arg| arg.id() == hir_id)
169                     .map(|index| (index, seg))
170             });
171
172             // FIXME(associated_const_generics): can we blend this with iteration above?
173             let (arg_index, segment) = match filtered {
174                 None => {
175                     let binding_filtered = path.segments.iter().find_map(|seg| {
176                         seg.args?
177                             .bindings
178                             .iter()
179                             .filter_map(TypeBinding::opt_const)
180                             .position(|ct| ct.hir_id == hir_id)
181                             .map(|idx| (idx, seg))
182                     });
183                     match binding_filtered {
184                         Some(inner) => inner,
185                         None => {
186                             tcx.sess.delay_span_bug(
187                                 tcx.def_span(def_id),
188                                 "no arg matching AnonConst in path",
189                             );
190                             return None;
191                         }
192                     }
193                 }
194                 Some(inner) => inner,
195             };
196
197             // Try to use the segment resolution if it is valid, otherwise we
198             // default to the path resolution.
199             let res = segment.res.filter(|&r| r != Res::Err).unwrap_or(path.res);
200             let generics = match tcx.res_generics_def_id(res) {
201                 Some(def_id) => tcx.generics_of(def_id),
202                 None => {
203                     tcx.sess.delay_span_bug(
204                         tcx.def_span(def_id),
205                         &format!("unexpected anon const res {:?} in path: {:?}", res, path),
206                     );
207                     return None;
208                 }
209             };
210
211             (generics, arg_index)
212         }
213         _ => return None,
214     };
215
216     debug!(?parent_node);
217     debug!(?generics, ?arg_idx);
218     generics
219         .params
220         .iter()
221         .filter(|param| param.kind.is_ty_or_const())
222         .nth(match generics.has_self && generics.parent.is_none() {
223             true => arg_idx + 1,
224             false => arg_idx,
225         })
226         .and_then(|param| match param.kind {
227             ty::GenericParamDefKind::Const { .. } => {
228                 debug!(?param);
229                 Some(param.def_id)
230             }
231             _ => None,
232         })
233 }
234
235 fn get_path_containing_arg_in_pat<'hir>(
236     pat: &'hir hir::Pat<'hir>,
237     arg_id: HirId,
238 ) -> Option<&'hir hir::Path<'hir>> {
239     use hir::*;
240
241     let is_arg_in_path = |p: &hir::Path<'_>| {
242         p.segments
243             .iter()
244             .filter_map(|seg| seg.args)
245             .flat_map(|args| args.args)
246             .any(|arg| arg.id() == arg_id)
247     };
248     let mut arg_path = None;
249     pat.walk(|pat| match pat.kind {
250         PatKind::Struct(QPath::Resolved(_, path), _, _)
251         | PatKind::TupleStruct(QPath::Resolved(_, path), _, _)
252         | PatKind::Path(QPath::Resolved(_, path))
253             if is_arg_in_path(path) =>
254         {
255             arg_path = Some(path);
256             false
257         }
258         _ => true,
259     });
260     arg_path
261 }
262
263 pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
264     let def_id = def_id.expect_local();
265     use rustc_hir::*;
266
267     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
268
269     let icx = ItemCtxt::new(tcx, def_id.to_def_id());
270
271     match tcx.hir().get(hir_id) {
272         Node::TraitItem(item) => match item.kind {
273             TraitItemKind::Fn(..) => {
274                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
275                 tcx.mk_fn_def(def_id.to_def_id(), substs)
276             }
277             TraitItemKind::Const(ty, body_id) => body_id
278                 .and_then(|body_id| {
279                     if is_suggestable_infer_ty(ty) {
280                         Some(infer_placeholder_type(
281                             tcx, def_id, body_id, ty.span, item.ident, "constant",
282                         ))
283                     } else {
284                         None
285                     }
286                 })
287                 .unwrap_or_else(|| icx.to_ty(ty)),
288             TraitItemKind::Type(_, Some(ty)) => icx.to_ty(ty),
289             TraitItemKind::Type(_, None) => {
290                 span_bug!(item.span, "associated type missing default");
291             }
292         },
293
294         Node::ImplItem(item) => match item.kind {
295             ImplItemKind::Fn(..) => {
296                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
297                 tcx.mk_fn_def(def_id.to_def_id(), substs)
298             }
299             ImplItemKind::Const(ty, body_id) => {
300                 if is_suggestable_infer_ty(ty) {
301                     infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident, "constant")
302                 } else {
303                     icx.to_ty(ty)
304                 }
305             }
306             ImplItemKind::TyAlias(ty) => {
307                 if tcx.impl_trait_ref(tcx.hir().get_parent_item(hir_id)).is_none() {
308                     check_feature_inherent_assoc_ty(tcx, item.span);
309                 }
310
311                 icx.to_ty(ty)
312             }
313         },
314
315         Node::Item(item) => {
316             match item.kind {
317                 ItemKind::Static(ty, .., body_id) => {
318                     if is_suggestable_infer_ty(ty) {
319                         infer_placeholder_type(
320                             tcx,
321                             def_id,
322                             body_id,
323                             ty.span,
324                             item.ident,
325                             "static variable",
326                         )
327                     } else {
328                         icx.to_ty(ty)
329                     }
330                 }
331                 ItemKind::Const(ty, body_id) => {
332                     if is_suggestable_infer_ty(ty) {
333                         infer_placeholder_type(
334                             tcx, def_id, body_id, ty.span, item.ident, "constant",
335                         )
336                     } else {
337                         icx.to_ty(ty)
338                     }
339                 }
340                 ItemKind::TyAlias(self_ty, _)
341                 | ItemKind::Impl(hir::Impl { self_ty, .. }) => icx.to_ty(self_ty),
342                 ItemKind::Fn(..) => {
343                     let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
344                     tcx.mk_fn_def(def_id.to_def_id(), substs)
345                 }
346                 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
347                     let def = tcx.adt_def(def_id);
348                     let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
349                     tcx.mk_adt(def, substs)
350                 }
351                 ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias, .. }) => {
352                     find_opaque_ty_constraints(tcx, def_id)
353                 }
354                 // Opaque types desugared from `impl Trait`.
355                 ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn(owner) | hir::OpaqueTyOrigin::AsyncFn(owner), .. }) => {
356                     let concrete_ty = tcx
357                         .mir_borrowck(owner)
358                         .concrete_opaque_types
359                         .get(&def_id.to_def_id())
360                         .copied()
361                         .map(|concrete| concrete.ty)
362                         .unwrap_or_else(|| {
363                             let table = tcx.typeck(owner);
364                             if let Some(_) = table.tainted_by_errors {
365                                 // Some error in the
366                                 // owner fn prevented us from populating
367                                 // the `concrete_opaque_types` table.
368                                 tcx.ty_error()
369                             } else {
370                                 table.concrete_opaque_types.get(&def_id.to_def_id()).copied().unwrap_or_else(|| {
371                                     // We failed to resolve the opaque type or it
372                                     // resolves to itself. We interpret this as the
373                                     // no values of the hidden type ever being constructed,
374                                     // so we can just make the hidden type be `!`.
375                                     // For backwards compatibility reasons, we fall back to
376                                     // `()` until we the diverging default is changed.
377                                     Some(tcx.mk_diverging_default())
378                                 }).expect("RPIT always have a hidden type from typeck")
379                             }
380                         });
381                     debug!("concrete_ty = {:?}", concrete_ty);
382                     concrete_ty
383                 }
384                 ItemKind::Trait(..)
385                 | ItemKind::TraitAlias(..)
386                 | ItemKind::Macro(..)
387                 | ItemKind::Mod(..)
388                 | ItemKind::ForeignMod { .. }
389                 | ItemKind::GlobalAsm(..)
390                 | ItemKind::ExternCrate(..)
391                 | ItemKind::Use(..) => {
392                     span_bug!(
393                         item.span,
394                         "compute_type_of_item: unexpected item type: {:?}",
395                         item.kind
396                     );
397                 }
398             }
399         }
400
401         Node::ForeignItem(foreign_item) => match foreign_item.kind {
402             ForeignItemKind::Fn(..) => {
403                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
404                 tcx.mk_fn_def(def_id.to_def_id(), substs)
405             }
406             ForeignItemKind::Static(t, _) => icx.to_ty(t),
407             ForeignItemKind::Type => tcx.mk_foreign(def_id.to_def_id()),
408         },
409
410         Node::Ctor(&ref def) | Node::Variant(Variant { data: ref def, .. }) => match *def {
411             VariantData::Unit(..) | VariantData::Struct(..) => {
412                 tcx.type_of(tcx.hir().get_parent_item(hir_id))
413             }
414             VariantData::Tuple(..) => {
415                 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
416                 tcx.mk_fn_def(def_id.to_def_id(), substs)
417             }
418         },
419
420         Node::Field(field) => icx.to_ty(field.ty),
421
422         Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => tcx.typeck(def_id).node_type(hir_id),
423
424         Node::AnonConst(_) if let Some(param) = tcx.opt_const_param_of(def_id) => {
425             // We defer to `type_of` of the corresponding parameter
426             // for generic arguments.
427             tcx.type_of(param)
428         }
429
430         Node::AnonConst(_) => {
431             let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
432             match parent_node {
433                 Node::Ty(&Ty { kind: TyKind::Array(_, ref constant), .. })
434                 | Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
435                     if constant.hir_id() == hir_id =>
436                 {
437                     tcx.types.usize
438                 }
439                 Node::Ty(&Ty { kind: TyKind::Typeof(ref e), .. }) if e.hir_id == hir_id => {
440                     tcx.typeck(def_id).node_type(e.hir_id)
441                 }
442
443                 Node::Expr(&Expr { kind: ExprKind::ConstBlock(ref anon_const), .. })
444                     if anon_const.hir_id == hir_id =>
445                 {
446                     let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
447                     substs.as_inline_const().ty()
448                 }
449
450                 Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. })
451                 | Node::Item(&Item { kind: ItemKind::GlobalAsm(asm), .. })
452                     if asm.operands.iter().any(|(op, _op_sp)| match op {
453                         hir::InlineAsmOperand::Const { anon_const } => anon_const.hir_id == hir_id,
454                         _ => false,
455                     }) =>
456                 {
457                     tcx.typeck(def_id).node_type(hir_id)
458                 }
459
460                 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => tcx
461                     .adt_def(tcx.hir().get_parent_item(hir_id))
462                     .repr()
463                     .discr_type()
464                     .to_ty(tcx),
465
466                 Node::TraitRef(trait_ref @ &TraitRef {
467                   path, ..
468                 }) if let Some((binding, seg)) =
469                   path
470                       .segments
471                       .iter()
472                       .find_map(|seg| {
473                           seg.args?.bindings
474                               .iter()
475                               .find_map(|binding| if binding.opt_const()?.hir_id == hir_id {
476                                 Some((binding, seg))
477                               } else {
478                                 None
479                               })
480                       }) =>
481                 {
482                   let Some(trait_def_id) = trait_ref.trait_def_id() else {
483                     return tcx.ty_error_with_message(DUMMY_SP, "Could not find trait");
484                   };
485                   let assoc_items = tcx.associated_items(trait_def_id);
486                   let assoc_item = assoc_items.find_by_name_and_kind(
487                     tcx, binding.ident, ty::AssocKind::Const, def_id.to_def_id(),
488                   );
489                   if let Some(assoc_item) = assoc_item {
490                     tcx.type_of(assoc_item.def_id)
491                   } else {
492                       // FIXME(associated_const_equality): add a useful error message here.
493                       tcx.ty_error_with_message(
494                         DUMMY_SP,
495                         "Could not find associated const on trait",
496                     )
497                   }
498                 }
499
500                 Node::GenericParam(&GenericParam {
501                     hir_id: param_hir_id,
502                     kind: GenericParamKind::Const { default: Some(ct), .. },
503                     ..
504                 }) if ct.hir_id == hir_id => tcx.type_of(tcx.hir().local_def_id(param_hir_id)),
505
506                 x =>
507                   tcx.ty_error_with_message(
508                     DUMMY_SP,
509                     &format!("unexpected const parent in type_of(): {x:?}"),
510                 ),
511             }
512         }
513
514         Node::GenericParam(param) => match &param.kind {
515             GenericParamKind::Type { default: Some(ty), .. }
516             | GenericParamKind::Const { ty, .. } => icx.to_ty(ty),
517             x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
518         },
519
520         x => {
521             bug!("unexpected sort of node in type_of(): {:?}", x);
522         }
523     }
524 }
525
526 #[instrument(skip(tcx), level = "debug")]
527 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
528 /// laid for "higher-order pattern unification".
529 /// This ensures that inference is tractable.
530 /// In particular, definitions of opaque types can only use other generics as arguments,
531 /// and they cannot repeat an argument. Example:
532 ///
533 /// ```rust
534 /// type Foo<A, B> = impl Bar<A, B>;
535 ///
536 /// // Okay -- `Foo` is applied to two distinct, generic types.
537 /// fn a<T, U>() -> Foo<T, U> { .. }
538 ///
539 /// // Not okay -- `Foo` is applied to `T` twice.
540 /// fn b<T>() -> Foo<T, T> { .. }
541 ///
542 /// // Not okay -- `Foo` is applied to a non-generic type.
543 /// fn b<T>() -> Foo<T, u32> { .. }
544 /// ```
545 ///
546 fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
547     use rustc_hir::{Expr, ImplItem, Item, TraitItem};
548
549     struct ConstraintLocator<'tcx> {
550         tcx: TyCtxt<'tcx>,
551
552         /// def_id of the opaque type whose defining uses are being checked
553         def_id: DefId,
554
555         /// as we walk the defining uses, we are checking that all of them
556         /// define the same hidden type. This variable is set to `Some`
557         /// with the first type that we find, and then later types are
558         /// checked against it (we also carry the span of that first
559         /// type).
560         found: Option<ty::OpaqueHiddenType<'tcx>>,
561     }
562
563     impl ConstraintLocator<'_> {
564         #[instrument(skip(self), level = "debug")]
565         fn check(&mut self, def_id: LocalDefId) {
566             // Don't try to check items that cannot possibly constrain the type.
567             if !self.tcx.has_typeck_results(def_id) {
568                 debug!("no constraint: no typeck results");
569                 return;
570             }
571             // Calling `mir_borrowck` can lead to cycle errors through
572             // const-checking, avoid calling it if we don't have to.
573             // ```rust
574             // type Foo = impl Fn() -> usize; // when computing type for this
575             // const fn bar() -> Foo {
576             //     || 0usize
577             // }
578             // const BAZR: Foo = bar(); // we would mir-borrowck this, causing cycles
579             // // because we again need to reveal `Foo` so we can check whether the
580             // // constant does not contain interior mutability.
581             // ```
582             let tables = self.tcx.typeck(def_id);
583             if let Some(_) = tables.tainted_by_errors {
584                 self.found = Some(ty::OpaqueHiddenType { span: DUMMY_SP, ty: self.tcx.ty_error() });
585                 return;
586             }
587             if tables.concrete_opaque_types.get(&self.def_id).is_none() {
588                 debug!("no constraints in typeck results");
589                 return;
590             }
591             // Use borrowck to get the type with unerased regions.
592             let concrete_opaque_types = &self.tcx.mir_borrowck(def_id).concrete_opaque_types;
593             debug!(?concrete_opaque_types);
594             for &(def_id, concrete_type) in concrete_opaque_types {
595                 if def_id != self.def_id {
596                     // Ignore constraints for other opaque types.
597                     continue;
598                 }
599
600                 debug!(?concrete_type, "found constraint");
601
602                 if let Some(prev) = self.found {
603                     if concrete_type.ty != prev.ty && !(concrete_type, prev).references_error() {
604                         prev.report_mismatch(&concrete_type, self.tcx);
605                     }
606                 } else {
607                     self.found = Some(concrete_type);
608                 }
609             }
610         }
611     }
612
613     impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
614         type NestedFilter = nested_filter::All;
615
616         fn nested_visit_map(&mut self) -> Self::Map {
617             self.tcx.hir()
618         }
619         fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
620             if let hir::ExprKind::Closure(..) = ex.kind {
621                 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
622                 self.check(def_id);
623             }
624             intravisit::walk_expr(self, ex);
625         }
626         fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
627             trace!(?it.def_id);
628             // The opaque type itself or its children are not within its reveal scope.
629             if it.def_id.to_def_id() != self.def_id {
630                 self.check(it.def_id);
631                 intravisit::walk_item(self, it);
632             }
633         }
634         fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
635             trace!(?it.def_id);
636             // The opaque type itself or its children are not within its reveal scope.
637             if it.def_id.to_def_id() != self.def_id {
638                 self.check(it.def_id);
639                 intravisit::walk_impl_item(self, it);
640             }
641         }
642         fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
643             trace!(?it.def_id);
644             self.check(it.def_id);
645             intravisit::walk_trait_item(self, it);
646         }
647     }
648
649     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
650     let scope = tcx.hir().get_defining_scope(hir_id);
651     let mut locator = ConstraintLocator { def_id: def_id.to_def_id(), tcx, found: None };
652
653     debug!(?scope);
654
655     if scope == hir::CRATE_HIR_ID {
656         tcx.hir().walk_toplevel_module(&mut locator);
657     } else {
658         trace!("scope={:#?}", tcx.hir().get(scope));
659         match tcx.hir().get(scope) {
660             // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
661             // This allows our visitor to process the defining item itself, causing
662             // it to pick up any 'sibling' defining uses.
663             //
664             // For example, this code:
665             // ```
666             // fn foo() {
667             //     type Blah = impl Debug;
668             //     let my_closure = || -> Blah { true };
669             // }
670             // ```
671             //
672             // requires us to explicitly process `foo()` in order
673             // to notice the defining usage of `Blah`.
674             Node::Item(it) => locator.visit_item(it),
675             Node::ImplItem(it) => locator.visit_impl_item(it),
676             Node::TraitItem(it) => locator.visit_trait_item(it),
677             other => bug!("{:?} is not a valid scope for an opaque type item", other),
678         }
679     }
680
681     match locator.found {
682         Some(hidden) => hidden.ty,
683         None => {
684             let span = tcx.def_span(def_id);
685             let name = tcx.item_name(tcx.parent(def_id.to_def_id()).unwrap());
686             let label = format!(
687                 "`{}` must be used in combination with a concrete type within the same module",
688                 name
689             );
690             tcx.sess.struct_span_err(span, "unconstrained opaque type").note(&label).emit();
691             tcx.ty_error()
692         }
693     }
694 }
695
696 fn infer_placeholder_type<'a>(
697     tcx: TyCtxt<'a>,
698     def_id: LocalDefId,
699     body_id: hir::BodyId,
700     span: Span,
701     item_ident: Ident,
702     kind: &'static str,
703 ) -> Ty<'a> {
704     // Attempts to make the type nameable by turning FnDefs into FnPtrs.
705     struct MakeNameable<'tcx> {
706         success: bool,
707         tcx: TyCtxt<'tcx>,
708     }
709
710     impl<'tcx> MakeNameable<'tcx> {
711         fn new(tcx: TyCtxt<'tcx>) -> Self {
712             MakeNameable { success: true, tcx }
713         }
714     }
715
716     impl<'tcx> TypeFolder<'tcx> for MakeNameable<'tcx> {
717         fn tcx(&self) -> TyCtxt<'tcx> {
718             self.tcx
719         }
720
721         fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
722             if !self.success {
723                 return ty;
724             }
725
726             match ty.kind() {
727                 ty::FnDef(def_id, _) => self.tcx.mk_fn_ptr(self.tcx.fn_sig(*def_id)),
728                 // FIXME: non-capturing closures should also suggest a function pointer
729                 ty::Closure(..) | ty::Generator(..) => {
730                     self.success = false;
731                     ty
732                 }
733                 _ => ty.super_fold_with(self),
734             }
735         }
736     }
737
738     let ty = tcx.diagnostic_only_typeck(def_id).node_type(body_id.hir_id);
739
740     // If this came from a free `const` or `static mut?` item,
741     // then the user may have written e.g. `const A = 42;`.
742     // In this case, the parser has stashed a diagnostic for
743     // us to improve in typeck so we do that now.
744     match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
745         Some(mut err) => {
746             if !ty.references_error() {
747                 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
748                 // We are typeck and have the real type, so remove that and suggest the actual type.
749                 // FIXME(eddyb) this looks like it should be functionality on `Diagnostic`.
750                 if let Ok(suggestions) = &mut err.suggestions {
751                     suggestions.clear();
752                 }
753
754                 // Suggesting unnameable types won't help.
755                 let mut mk_nameable = MakeNameable::new(tcx);
756                 let ty = mk_nameable.fold_ty(ty);
757                 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
758                 if let Some(sugg_ty) = sugg_ty {
759                     err.span_suggestion(
760                         span,
761                         &format!("provide a type for the {item}", item = kind),
762                         format!("{}: {}", item_ident, sugg_ty),
763                         Applicability::MachineApplicable,
764                     );
765                 } else {
766                     err.span_note(
767                         tcx.hir().body(body_id).value.span,
768                         &format!("however, the inferred type `{}` cannot be named", ty),
769                     );
770                 }
771             }
772
773             err.emit();
774         }
775         None => {
776             let mut diag = bad_placeholder(tcx, vec![span], kind);
777
778             if !ty.references_error() {
779                 let mut mk_nameable = MakeNameable::new(tcx);
780                 let ty = mk_nameable.fold_ty(ty);
781                 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
782                 if let Some(sugg_ty) = sugg_ty {
783                     diag.span_suggestion(
784                         span,
785                         "replace with the correct type",
786                         sugg_ty.to_string(),
787                         Applicability::MaybeIncorrect,
788                     );
789                 } else {
790                     diag.span_note(
791                         tcx.hir().body(body_id).value.span,
792                         &format!("however, the inferred type `{}` cannot be named", ty),
793                     );
794                 }
795             }
796
797             diag.emit();
798         }
799     }
800
801     // Typeck doesn't expect erased regions to be returned from `type_of`.
802     tcx.fold_regions(ty, &mut false, |r, _| match *r {
803         ty::ReErased => tcx.lifetimes.re_static,
804         _ => r,
805     })
806 }
807
808 fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) {
809     if !tcx.features().inherent_associated_types {
810         use rustc_session::parse::feature_err;
811         use rustc_span::symbol::sym;
812         feature_err(
813             &tcx.sess.parse_sess,
814             sym::inherent_associated_types,
815             span,
816             "inherent associated types are unstable",
817         )
818         .emit();
819     }
820 }