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