]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/collect/type_of.rs
Rollup merge of #96035 - Gumichocopengin8:feature/update-github-action-version, r...
[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 }
454                         | hir::InlineAsmOperand::SymFn { anon_const } => anon_const.hir_id == hir_id,
455                         _ => false,
456                     }) =>
457                 {
458                     tcx.typeck(def_id).node_type(hir_id)
459                 }
460
461                 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => tcx
462                     .adt_def(tcx.hir().get_parent_item(hir_id))
463                     .repr()
464                     .discr_type()
465                     .to_ty(tcx),
466
467                 Node::TraitRef(trait_ref @ &TraitRef {
468                   path, ..
469                 }) if let Some((binding, seg)) =
470                   path
471                       .segments
472                       .iter()
473                       .find_map(|seg| {
474                           seg.args?.bindings
475                               .iter()
476                               .find_map(|binding| if binding.opt_const()?.hir_id == hir_id {
477                                 Some((binding, seg))
478                               } else {
479                                 None
480                               })
481                       }) =>
482                 {
483                   let Some(trait_def_id) = trait_ref.trait_def_id() else {
484                     return tcx.ty_error_with_message(DUMMY_SP, "Could not find trait");
485                   };
486                   let assoc_items = tcx.associated_items(trait_def_id);
487                   let assoc_item = assoc_items.find_by_name_and_kind(
488                     tcx, binding.ident, ty::AssocKind::Const, def_id.to_def_id(),
489                   );
490                   if let Some(assoc_item) = assoc_item {
491                     tcx.type_of(assoc_item.def_id)
492                   } else {
493                       // FIXME(associated_const_equality): add a useful error message here.
494                       tcx.ty_error_with_message(
495                         DUMMY_SP,
496                         "Could not find associated const on trait",
497                     )
498                   }
499                 }
500
501                 Node::GenericParam(&GenericParam {
502                     hir_id: param_hir_id,
503                     kind: GenericParamKind::Const { default: Some(ct), .. },
504                     ..
505                 }) if ct.hir_id == hir_id => tcx.type_of(tcx.hir().local_def_id(param_hir_id)),
506
507                 x =>
508                   tcx.ty_error_with_message(
509                     DUMMY_SP,
510                     &format!("unexpected const parent in type_of(): {x:?}"),
511                 ),
512             }
513         }
514
515         Node::GenericParam(param) => match &param.kind {
516             GenericParamKind::Type { default: Some(ty), .. }
517             | GenericParamKind::Const { ty, .. } => icx.to_ty(ty),
518             x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
519         },
520
521         x => {
522             bug!("unexpected sort of node in type_of(): {:?}", x);
523         }
524     }
525 }
526
527 #[instrument(skip(tcx), level = "debug")]
528 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
529 /// laid for "higher-order pattern unification".
530 /// This ensures that inference is tractable.
531 /// In particular, definitions of opaque types can only use other generics as arguments,
532 /// and they cannot repeat an argument. Example:
533 ///
534 /// ```rust
535 /// type Foo<A, B> = impl Bar<A, B>;
536 ///
537 /// // Okay -- `Foo` is applied to two distinct, generic types.
538 /// fn a<T, U>() -> Foo<T, U> { .. }
539 ///
540 /// // Not okay -- `Foo` is applied to `T` twice.
541 /// fn b<T>() -> Foo<T, T> { .. }
542 ///
543 /// // Not okay -- `Foo` is applied to a non-generic type.
544 /// fn b<T>() -> Foo<T, u32> { .. }
545 /// ```
546 ///
547 fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
548     use rustc_hir::{Expr, ImplItem, Item, TraitItem};
549
550     struct ConstraintLocator<'tcx> {
551         tcx: TyCtxt<'tcx>,
552
553         /// def_id of the opaque type whose defining uses are being checked
554         def_id: DefId,
555
556         /// as we walk the defining uses, we are checking that all of them
557         /// define the same hidden type. This variable is set to `Some`
558         /// with the first type that we find, and then later types are
559         /// checked against it (we also carry the span of that first
560         /// type).
561         found: Option<ty::OpaqueHiddenType<'tcx>>,
562     }
563
564     impl ConstraintLocator<'_> {
565         #[instrument(skip(self), level = "debug")]
566         fn check(&mut self, def_id: LocalDefId) {
567             // Don't try to check items that cannot possibly constrain the type.
568             if !self.tcx.has_typeck_results(def_id) {
569                 debug!("no constraint: no typeck results");
570                 return;
571             }
572             // Calling `mir_borrowck` can lead to cycle errors through
573             // const-checking, avoid calling it if we don't have to.
574             // ```rust
575             // type Foo = impl Fn() -> usize; // when computing type for this
576             // const fn bar() -> Foo {
577             //     || 0usize
578             // }
579             // const BAZR: Foo = bar(); // we would mir-borrowck this, causing cycles
580             // // because we again need to reveal `Foo` so we can check whether the
581             // // constant does not contain interior mutability.
582             // ```
583             let tables = self.tcx.typeck(def_id);
584             if let Some(_) = tables.tainted_by_errors {
585                 self.found = Some(ty::OpaqueHiddenType { span: DUMMY_SP, ty: self.tcx.ty_error() });
586                 return;
587             }
588             if tables.concrete_opaque_types.get(&self.def_id).is_none() {
589                 debug!("no constraints in typeck results");
590                 return;
591             }
592             // Use borrowck to get the type with unerased regions.
593             let concrete_opaque_types = &self.tcx.mir_borrowck(def_id).concrete_opaque_types;
594             debug!(?concrete_opaque_types);
595             for &(def_id, concrete_type) in concrete_opaque_types {
596                 if def_id != self.def_id {
597                     // Ignore constraints for other opaque types.
598                     continue;
599                 }
600
601                 debug!(?concrete_type, "found constraint");
602
603                 if let Some(prev) = self.found {
604                     if concrete_type.ty != prev.ty && !(concrete_type, prev).references_error() {
605                         prev.report_mismatch(&concrete_type, self.tcx);
606                     }
607                 } else {
608                     self.found = Some(concrete_type);
609                 }
610             }
611         }
612     }
613
614     impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
615         type NestedFilter = nested_filter::All;
616
617         fn nested_visit_map(&mut self) -> Self::Map {
618             self.tcx.hir()
619         }
620         fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
621             if let hir::ExprKind::Closure(..) = ex.kind {
622                 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
623                 self.check(def_id);
624             }
625             intravisit::walk_expr(self, ex);
626         }
627         fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
628             trace!(?it.def_id);
629             // The opaque type itself or its children are not within its reveal scope.
630             if it.def_id.to_def_id() != self.def_id {
631                 self.check(it.def_id);
632                 intravisit::walk_item(self, it);
633             }
634         }
635         fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
636             trace!(?it.def_id);
637             // The opaque type itself or its children are not within its reveal scope.
638             if it.def_id.to_def_id() != self.def_id {
639                 self.check(it.def_id);
640                 intravisit::walk_impl_item(self, it);
641             }
642         }
643         fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
644             trace!(?it.def_id);
645             self.check(it.def_id);
646             intravisit::walk_trait_item(self, it);
647         }
648     }
649
650     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
651     let scope = tcx.hir().get_defining_scope(hir_id);
652     let mut locator = ConstraintLocator { def_id: def_id.to_def_id(), tcx, found: None };
653
654     debug!(?scope);
655
656     if scope == hir::CRATE_HIR_ID {
657         tcx.hir().walk_toplevel_module(&mut locator);
658     } else {
659         trace!("scope={:#?}", tcx.hir().get(scope));
660         match tcx.hir().get(scope) {
661             // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
662             // This allows our visitor to process the defining item itself, causing
663             // it to pick up any 'sibling' defining uses.
664             //
665             // For example, this code:
666             // ```
667             // fn foo() {
668             //     type Blah = impl Debug;
669             //     let my_closure = || -> Blah { true };
670             // }
671             // ```
672             //
673             // requires us to explicitly process `foo()` in order
674             // to notice the defining usage of `Blah`.
675             Node::Item(it) => locator.visit_item(it),
676             Node::ImplItem(it) => locator.visit_impl_item(it),
677             Node::TraitItem(it) => locator.visit_trait_item(it),
678             other => bug!("{:?} is not a valid scope for an opaque type item", other),
679         }
680     }
681
682     match locator.found {
683         Some(hidden) => hidden.ty,
684         None => {
685             let span = tcx.def_span(def_id);
686             let name = tcx.item_name(tcx.parent(def_id.to_def_id()).unwrap());
687             let label = format!(
688                 "`{}` must be used in combination with a concrete type within the same module",
689                 name
690             );
691             tcx.sess.struct_span_err(span, "unconstrained opaque type").note(&label).emit();
692             tcx.ty_error()
693         }
694     }
695 }
696
697 fn infer_placeholder_type<'a>(
698     tcx: TyCtxt<'a>,
699     def_id: LocalDefId,
700     body_id: hir::BodyId,
701     span: Span,
702     item_ident: Ident,
703     kind: &'static str,
704 ) -> Ty<'a> {
705     // Attempts to make the type nameable by turning FnDefs into FnPtrs.
706     struct MakeNameable<'tcx> {
707         success: bool,
708         tcx: TyCtxt<'tcx>,
709     }
710
711     impl<'tcx> MakeNameable<'tcx> {
712         fn new(tcx: TyCtxt<'tcx>) -> Self {
713             MakeNameable { success: true, tcx }
714         }
715     }
716
717     impl<'tcx> TypeFolder<'tcx> for MakeNameable<'tcx> {
718         fn tcx(&self) -> TyCtxt<'tcx> {
719             self.tcx
720         }
721
722         fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
723             if !self.success {
724                 return ty;
725             }
726
727             match ty.kind() {
728                 ty::FnDef(def_id, _) => self.tcx.mk_fn_ptr(self.tcx.fn_sig(*def_id)),
729                 // FIXME: non-capturing closures should also suggest a function pointer
730                 ty::Closure(..) | ty::Generator(..) => {
731                     self.success = false;
732                     ty
733                 }
734                 _ => ty.super_fold_with(self),
735             }
736         }
737     }
738
739     let ty = tcx.diagnostic_only_typeck(def_id).node_type(body_id.hir_id);
740
741     // If this came from a free `const` or `static mut?` item,
742     // then the user may have written e.g. `const A = 42;`.
743     // In this case, the parser has stashed a diagnostic for
744     // us to improve in typeck so we do that now.
745     match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
746         Some(mut err) => {
747             if !ty.references_error() {
748                 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
749                 // We are typeck and have the real type, so remove that and suggest the actual type.
750                 // FIXME(eddyb) this looks like it should be functionality on `Diagnostic`.
751                 if let Ok(suggestions) = &mut err.suggestions {
752                     suggestions.clear();
753                 }
754
755                 // Suggesting unnameable types won't help.
756                 let mut mk_nameable = MakeNameable::new(tcx);
757                 let ty = mk_nameable.fold_ty(ty);
758                 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
759                 if let Some(sugg_ty) = sugg_ty {
760                     err.span_suggestion(
761                         span,
762                         &format!("provide a type for the {item}", item = kind),
763                         format!("{}: {}", item_ident, sugg_ty),
764                         Applicability::MachineApplicable,
765                     );
766                 } else {
767                     err.span_note(
768                         tcx.hir().body(body_id).value.span,
769                         &format!("however, the inferred type `{}` cannot be named", ty),
770                     );
771                 }
772             }
773
774             err.emit();
775         }
776         None => {
777             let mut diag = bad_placeholder(tcx, vec![span], kind);
778
779             if !ty.references_error() {
780                 let mut mk_nameable = MakeNameable::new(tcx);
781                 let ty = mk_nameable.fold_ty(ty);
782                 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
783                 if let Some(sugg_ty) = sugg_ty {
784                     diag.span_suggestion(
785                         span,
786                         "replace with the correct type",
787                         sugg_ty.to_string(),
788                         Applicability::MaybeIncorrect,
789                     );
790                 } else {
791                     diag.span_note(
792                         tcx.hir().body(body_id).value.span,
793                         &format!("however, the inferred type `{}` cannot be named", ty),
794                     );
795                 }
796             }
797
798             diag.emit();
799         }
800     }
801
802     // Typeck doesn't expect erased regions to be returned from `type_of`.
803     tcx.fold_regions(ty, &mut false, |r, _| match *r {
804         ty::ReErased => tcx.lifetimes.re_static,
805         _ => r,
806     })
807 }
808
809 fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) {
810     if !tcx.features().inherent_associated_types {
811         use rustc_session::parse::feature_err;
812         use rustc_span::symbol::sym;
813         feature_err(
814             &tcx.sess.parse_sess,
815             sym::inherent_associated_types,
816             span,
817             "inherent associated types are unstable",
818         )
819         .emit();
820     }
821 }