]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/collect/type_of.rs
Rollup merge of #69565 - RalfJung:assert, r=eddyb
[rust.git] / src / librustc_typeck / collect / type_of.rs
1 use rustc::hir::map::Map;
2 use rustc::session::parse::feature_err;
3 use rustc::ty::subst::{GenericArgKind, InternalSubsts, Subst};
4 use rustc::ty::util::IntTypeExt;
5 use rustc::ty::{self, DefIdTree, Ty, TyCtxt, TypeFoldable};
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_errors::{struct_span_err, Applicability, StashKey};
8 use rustc_hir as hir;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::intravisit;
12 use rustc_hir::intravisit::Visitor;
13 use rustc_hir::Node;
14 use rustc_infer::traits;
15 use rustc_span::symbol::{sym, Ident};
16 use rustc_span::{Span, DUMMY_SP};
17
18 use super::ItemCtxt;
19 use super::{bad_placeholder_type, is_suggestable_infer_ty};
20
21 pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
22     use rustc_hir::*;
23
24     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
25
26     let icx = ItemCtxt::new(tcx, def_id);
27
28     match tcx.hir().get(hir_id) {
29         Node::TraitItem(item) => match item.kind {
30             TraitItemKind::Method(..) => {
31                 let substs = InternalSubsts::identity_for_item(tcx, def_id);
32                 tcx.mk_fn_def(def_id, substs)
33             }
34             TraitItemKind::Const(ref ty, body_id) => body_id
35                 .and_then(|body_id| {
36                     if is_suggestable_infer_ty(ty) {
37                         Some(infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident))
38                     } else {
39                         None
40                     }
41                 })
42                 .unwrap_or_else(|| icx.to_ty(ty)),
43             TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
44             TraitItemKind::Type(_, None) => {
45                 span_bug!(item.span, "associated type missing default");
46             }
47         },
48
49         Node::ImplItem(item) => match item.kind {
50             ImplItemKind::Method(..) => {
51                 let substs = InternalSubsts::identity_for_item(tcx, def_id);
52                 tcx.mk_fn_def(def_id, substs)
53             }
54             ImplItemKind::Const(ref ty, body_id) => {
55                 if is_suggestable_infer_ty(ty) {
56                     infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)
57                 } else {
58                     icx.to_ty(ty)
59                 }
60             }
61             ImplItemKind::OpaqueTy(_) => {
62                 if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id)).is_none() {
63                     report_assoc_ty_on_inherent_impl(tcx, item.span);
64                 }
65
66                 find_opaque_ty_constraints(tcx, def_id)
67             }
68             ImplItemKind::TyAlias(ref ty) => {
69                 if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id)).is_none() {
70                     report_assoc_ty_on_inherent_impl(tcx, item.span);
71                 }
72
73                 icx.to_ty(ty)
74             }
75         },
76
77         Node::Item(item) => {
78             match item.kind {
79                 ItemKind::Static(ref ty, .., body_id) | ItemKind::Const(ref ty, body_id) => {
80                     if is_suggestable_infer_ty(ty) {
81                         infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)
82                     } else {
83                         icx.to_ty(ty)
84                     }
85                 }
86                 ItemKind::TyAlias(ref self_ty, _) | ItemKind::Impl { ref self_ty, .. } => {
87                     icx.to_ty(self_ty)
88                 }
89                 ItemKind::Fn(..) => {
90                     let substs = InternalSubsts::identity_for_item(tcx, def_id);
91                     tcx.mk_fn_def(def_id, substs)
92                 }
93                 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
94                     let def = tcx.adt_def(def_id);
95                     let substs = InternalSubsts::identity_for_item(tcx, def_id);
96                     tcx.mk_adt(def, substs)
97                 }
98                 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {
99                     find_opaque_ty_constraints(tcx, def_id)
100                 }
101                 // Opaque types desugared from `impl Trait`.
102                 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: Some(owner), origin, .. }) => {
103                     let concrete_types = match origin {
104                         OpaqueTyOrigin::FnReturn | OpaqueTyOrigin::AsyncFn => {
105                             &tcx.mir_borrowck(owner).concrete_opaque_types
106                         }
107                         OpaqueTyOrigin::Misc => {
108                             // We shouldn't leak borrowck results through impl trait in bindings.
109                             // For example, we shouldn't be able to tell if `x` in
110                             // `let x: impl Sized + 'a = &()` has type `&'static ()` or `&'a ()`.
111                             &tcx.typeck_tables_of(owner).concrete_opaque_types
112                         }
113                         OpaqueTyOrigin::TypeAlias => {
114                             span_bug!(item.span, "Type alias impl trait shouldn't have an owner")
115                         }
116                     };
117                     let concrete_ty = concrete_types
118                         .get(&def_id)
119                         .map(|opaque| opaque.concrete_type)
120                         .unwrap_or_else(|| {
121                             tcx.sess.delay_span_bug(
122                                 DUMMY_SP,
123                                 &format!(
124                                     "owner {:?} has no opaque type for {:?} in its tables",
125                                     owner, def_id,
126                                 ),
127                             );
128                             if tcx.typeck_tables_of(owner).tainted_by_errors {
129                                 // Some error in the
130                                 // owner fn prevented us from populating
131                                 // the `concrete_opaque_types` table.
132                                 tcx.types.err
133                             } else {
134                                 // We failed to resolve the opaque type or it
135                                 // resolves to itself. Return the non-revealed
136                                 // type, which should result in E0720.
137                                 tcx.mk_opaque(
138                                     def_id,
139                                     InternalSubsts::identity_for_item(tcx, def_id),
140                                 )
141                             }
142                         });
143                     debug!("concrete_ty = {:?}", concrete_ty);
144                     if concrete_ty.has_erased_regions() {
145                         // FIXME(impl_trait_in_bindings) Handle this case.
146                         tcx.sess.span_fatal(
147                             item.span,
148                             "lifetimes in impl Trait types in bindings are not currently supported",
149                         );
150                     }
151                     concrete_ty
152                 }
153                 ItemKind::Trait(..)
154                 | ItemKind::TraitAlias(..)
155                 | ItemKind::Mod(..)
156                 | ItemKind::ForeignMod(..)
157                 | ItemKind::GlobalAsm(..)
158                 | ItemKind::ExternCrate(..)
159                 | ItemKind::Use(..) => {
160                     span_bug!(
161                         item.span,
162                         "compute_type_of_item: unexpected item type: {:?}",
163                         item.kind
164                     );
165                 }
166             }
167         }
168
169         Node::ForeignItem(foreign_item) => match foreign_item.kind {
170             ForeignItemKind::Fn(..) => {
171                 let substs = InternalSubsts::identity_for_item(tcx, def_id);
172                 tcx.mk_fn_def(def_id, substs)
173             }
174             ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
175             ForeignItemKind::Type => tcx.mk_foreign(def_id),
176         },
177
178         Node::Ctor(&ref def) | Node::Variant(Variant { data: ref def, .. }) => match *def {
179             VariantData::Unit(..) | VariantData::Struct(..) => {
180                 tcx.type_of(tcx.hir().get_parent_did(hir_id))
181             }
182             VariantData::Tuple(..) => {
183                 let substs = InternalSubsts::identity_for_item(tcx, def_id);
184                 tcx.mk_fn_def(def_id, substs)
185             }
186         },
187
188         Node::Field(field) => icx.to_ty(&field.ty),
189
190         Node::Expr(&Expr { kind: ExprKind::Closure(.., gen), .. }) => {
191             if gen.is_some() {
192                 return tcx.typeck_tables_of(def_id).node_type(hir_id);
193             }
194
195             let substs = InternalSubsts::identity_for_item(tcx, def_id);
196             tcx.mk_closure(def_id, substs)
197         }
198
199         Node::AnonConst(_) => {
200             let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
201             match parent_node {
202                 Node::Ty(&Ty { kind: TyKind::Array(_, ref constant), .. })
203                 | Node::Ty(&Ty { kind: TyKind::Typeof(ref constant), .. })
204                 | Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
205                     if constant.hir_id == hir_id =>
206                 {
207                     tcx.types.usize
208                 }
209
210                 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => {
211                     tcx.adt_def(tcx.hir().get_parent_did(hir_id)).repr.discr_type().to_ty(tcx)
212                 }
213
214                 Node::Ty(&Ty { kind: TyKind::Path(_), .. })
215                 | Node::Expr(&Expr { kind: ExprKind::Struct(..), .. })
216                 | Node::Expr(&Expr { kind: ExprKind::Path(_), .. })
217                 | Node::TraitRef(..) => {
218                     let path = match parent_node {
219                         Node::Ty(&Ty {
220                             kind: TyKind::Path(QPath::Resolved(_, ref path)), ..
221                         })
222                         | Node::Expr(&Expr {
223                             kind: ExprKind::Path(QPath::Resolved(_, ref path)),
224                             ..
225                         }) => Some(&**path),
226                         Node::Expr(&Expr { kind: ExprKind::Struct(ref path, ..), .. }) => {
227                             if let QPath::Resolved(_, ref path) = **path {
228                                 Some(&**path)
229                             } else {
230                                 None
231                             }
232                         }
233                         Node::TraitRef(&TraitRef { ref path, .. }) => Some(&**path),
234                         _ => None,
235                     };
236
237                     if let Some(path) = path {
238                         let arg_index = path
239                             .segments
240                             .iter()
241                             .filter_map(|seg| seg.args.as_ref())
242                             .map(|generic_args| generic_args.args)
243                             .find_map(|args| {
244                                 args.iter()
245                                     .filter(|arg| arg.is_const())
246                                     .enumerate()
247                                     .filter(|(_, arg)| arg.id() == hir_id)
248                                     .map(|(index, _)| index)
249                                     .next()
250                             })
251                             .unwrap_or_else(|| {
252                                 bug!("no arg matching AnonConst in path");
253                             });
254
255                         // We've encountered an `AnonConst` in some path, so we need to
256                         // figure out which generic parameter it corresponds to and return
257                         // the relevant type.
258                         let generics = match path.res {
259                             Res::Def(DefKind::Ctor(..), def_id) => {
260                                 tcx.generics_of(tcx.parent(def_id).unwrap())
261                             }
262                             Res::Def(_, def_id) => tcx.generics_of(def_id),
263                             Res::Err => return tcx.types.err,
264                             res => {
265                                 tcx.sess.delay_span_bug(
266                                     DUMMY_SP,
267                                     &format!("unexpected const parent path def {:?}", res,),
268                                 );
269                                 return tcx.types.err;
270                             }
271                         };
272
273                         generics
274                             .params
275                             .iter()
276                             .filter(|param| {
277                                 if let ty::GenericParamDefKind::Const = param.kind {
278                                     true
279                                 } else {
280                                     false
281                                 }
282                             })
283                             .nth(arg_index)
284                             .map(|param| tcx.type_of(param.def_id))
285                             // This is no generic parameter associated with the arg. This is
286                             // probably from an extra arg where one is not needed.
287                             .unwrap_or(tcx.types.err)
288                     } else {
289                         tcx.sess.delay_span_bug(
290                             DUMMY_SP,
291                             &format!("unexpected const parent path {:?}", parent_node,),
292                         );
293                         return tcx.types.err;
294                     }
295                 }
296
297                 x => {
298                     tcx.sess.delay_span_bug(
299                         DUMMY_SP,
300                         &format!("unexpected const parent in type_of_def_id(): {:?}", x),
301                     );
302                     tcx.types.err
303                 }
304             }
305         }
306
307         Node::GenericParam(param) => match &param.kind {
308             GenericParamKind::Type { default: Some(ref ty), .. } => icx.to_ty(ty),
309             GenericParamKind::Const { ty: ref hir_ty, .. } => {
310                 let ty = icx.to_ty(hir_ty);
311                 if !tcx.features().const_compare_raw_pointers {
312                     let err = match ty.peel_refs().kind {
313                         ty::FnPtr(_) => Some("function pointers"),
314                         ty::RawPtr(_) => Some("raw pointers"),
315                         _ => None,
316                     };
317                     if let Some(unsupported_type) = err {
318                         feature_err(
319                             &tcx.sess.parse_sess,
320                             sym::const_compare_raw_pointers,
321                             hir_ty.span,
322                             &format!(
323                                 "using {} as const generic parameters is unstable",
324                                 unsupported_type
325                             ),
326                         )
327                         .emit();
328                     };
329                 }
330                 if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
331                     .is_some()
332                 {
333                     struct_span_err!(
334                         tcx.sess,
335                         hir_ty.span,
336                         E0741,
337                         "the types of const generic parameters must derive `PartialEq` and `Eq`",
338                     )
339                     .span_label(
340                         hir_ty.span,
341                         format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
342                     )
343                     .emit();
344                 }
345                 ty
346             }
347             x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
348         },
349
350         x => {
351             bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
352         }
353     }
354 }
355
356 fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
357     use rustc_hir::{Expr, ImplItem, Item, TraitItem};
358
359     debug!("find_opaque_ty_constraints({:?})", def_id);
360
361     struct ConstraintLocator<'tcx> {
362         tcx: TyCtxt<'tcx>,
363         def_id: DefId,
364         // (first found type span, actual type, mapping from the opaque type's generic
365         // parameters to the concrete type's generic parameters)
366         //
367         // The mapping is an index for each use site of a generic parameter in the concrete type
368         //
369         // The indices index into the generic parameters on the opaque type.
370         found: Option<(Span, Ty<'tcx>, Vec<usize>)>,
371     }
372
373     impl ConstraintLocator<'_> {
374         fn check(&mut self, def_id: DefId) {
375             // Don't try to check items that cannot possibly constrain the type.
376             if !self.tcx.has_typeck_tables(def_id) {
377                 debug!(
378                     "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`: no tables",
379                     self.def_id, def_id,
380                 );
381                 return;
382             }
383             // Calling `mir_borrowck` can lead to cycle errors through
384             // const-checking, avoid calling it if we don't have to.
385             if !self.tcx.typeck_tables_of(def_id).concrete_opaque_types.contains_key(&self.def_id) {
386                 debug!(
387                     "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
388                     self.def_id, def_id,
389                 );
390                 return;
391             }
392             // Use borrowck to get the type with unerased regions.
393             let ty = self.tcx.mir_borrowck(def_id).concrete_opaque_types.get(&self.def_id);
394             if let Some(ty::ResolvedOpaqueTy { concrete_type, substs }) = ty {
395                 debug!(
396                     "find_opaque_ty_constraints: found constraint for `{:?}` at `{:?}`: {:?}",
397                     self.def_id, def_id, ty,
398                 );
399
400                 // FIXME(oli-obk): trace the actual span from inference to improve errors.
401                 let span = self.tcx.def_span(def_id);
402                 // used to quickly look up the position of a generic parameter
403                 let mut index_map: FxHashMap<ty::ParamTy, usize> = FxHashMap::default();
404                 // Skipping binder is ok, since we only use this to find generic parameters and
405                 // their positions.
406                 for (idx, subst) in substs.iter().enumerate() {
407                     if let GenericArgKind::Type(ty) = subst.unpack() {
408                         if let ty::Param(p) = ty.kind {
409                             if index_map.insert(p, idx).is_some() {
410                                 // There was already an entry for `p`, meaning a generic parameter
411                                 // was used twice.
412                                 self.tcx.sess.span_err(
413                                     span,
414                                     &format!(
415                                         "defining opaque type use restricts opaque \
416                                          type by using the generic parameter `{}` twice",
417                                         p,
418                                     ),
419                                 );
420                                 return;
421                             }
422                         } else {
423                             self.tcx.sess.delay_span_bug(
424                                 span,
425                                 &format!(
426                                     "non-defining opaque ty use in defining scope: {:?}, {:?}",
427                                     concrete_type, substs,
428                                 ),
429                             );
430                         }
431                     }
432                 }
433                 // Compute the index within the opaque type for each generic parameter used in
434                 // the concrete type.
435                 let indices = concrete_type
436                     .subst(self.tcx, substs)
437                     .walk()
438                     .filter_map(|t| match &t.kind {
439                         ty::Param(p) => Some(*index_map.get(p).unwrap()),
440                         _ => None,
441                     })
442                     .collect();
443                 let is_param = |ty: Ty<'_>| match ty.kind {
444                     ty::Param(_) => true,
445                     _ => false,
446                 };
447                 let bad_substs: Vec<_> = substs
448                     .iter()
449                     .enumerate()
450                     .filter_map(|(i, k)| {
451                         if let GenericArgKind::Type(ty) = k.unpack() { Some((i, ty)) } else { None }
452                     })
453                     .filter(|(_, ty)| !is_param(ty))
454                     .collect();
455                 if !bad_substs.is_empty() {
456                     let identity_substs = InternalSubsts::identity_for_item(self.tcx, self.def_id);
457                     for (i, bad_subst) in bad_substs {
458                         self.tcx.sess.span_err(
459                             span,
460                             &format!(
461                                 "defining opaque type use does not fully define opaque type: \
462                             generic parameter `{}` is specified as concrete type `{}`",
463                                 identity_substs.type_at(i),
464                                 bad_subst
465                             ),
466                         );
467                     }
468                 } else if let Some((prev_span, prev_ty, ref prev_indices)) = self.found {
469                     let mut ty = concrete_type.walk().fuse();
470                     let mut p_ty = prev_ty.walk().fuse();
471                     let iter_eq = (&mut ty).zip(&mut p_ty).all(|(t, p)| match (&t.kind, &p.kind) {
472                         // Type parameters are equal to any other type parameter for the purpose of
473                         // concrete type equality, as it is possible to obtain the same type just
474                         // by passing matching parameters to a function.
475                         (ty::Param(_), ty::Param(_)) => true,
476                         _ => t == p,
477                     });
478                     if !iter_eq || ty.next().is_some() || p_ty.next().is_some() {
479                         debug!("find_opaque_ty_constraints: span={:?}", span);
480                         // Found different concrete types for the opaque type.
481                         let mut err = self.tcx.sess.struct_span_err(
482                             span,
483                             "concrete type differs from previous defining opaque type use",
484                         );
485                         err.span_label(
486                             span,
487                             format!("expected `{}`, got `{}`", prev_ty, concrete_type),
488                         );
489                         err.span_note(prev_span, "previous use here");
490                         err.emit();
491                     } else if indices != *prev_indices {
492                         // Found "same" concrete types, but the generic parameter order differs.
493                         let mut err = self.tcx.sess.struct_span_err(
494                             span,
495                             "concrete type's generic parameters differ from previous defining use",
496                         );
497                         use std::fmt::Write;
498                         let mut s = String::new();
499                         write!(s, "expected [").unwrap();
500                         let list = |s: &mut String, indices: &Vec<usize>| {
501                             let mut indices = indices.iter().cloned();
502                             if let Some(first) = indices.next() {
503                                 write!(s, "`{}`", substs[first]).unwrap();
504                                 for i in indices {
505                                     write!(s, ", `{}`", substs[i]).unwrap();
506                                 }
507                             }
508                         };
509                         list(&mut s, prev_indices);
510                         write!(s, "], got [").unwrap();
511                         list(&mut s, &indices);
512                         write!(s, "]").unwrap();
513                         err.span_label(span, s);
514                         err.span_note(prev_span, "previous use here");
515                         err.emit();
516                     }
517                 } else {
518                     self.found = Some((span, concrete_type, indices));
519                 }
520             } else {
521                 debug!(
522                     "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
523                     self.def_id, def_id,
524                 );
525             }
526         }
527     }
528
529     impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
530         type Map = Map<'tcx>;
531
532         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
533             intravisit::NestedVisitorMap::All(&self.tcx.hir())
534         }
535         fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
536             if let hir::ExprKind::Closure(..) = ex.kind {
537                 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
538                 self.check(def_id);
539             }
540             intravisit::walk_expr(self, ex);
541         }
542         fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
543             debug!("find_existential_constraints: visiting {:?}", it);
544             let def_id = self.tcx.hir().local_def_id(it.hir_id);
545             // The opaque type itself or its children are not within its reveal scope.
546             if def_id != self.def_id {
547                 self.check(def_id);
548                 intravisit::walk_item(self, it);
549             }
550         }
551         fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
552             debug!("find_existential_constraints: visiting {:?}", it);
553             let def_id = self.tcx.hir().local_def_id(it.hir_id);
554             // The opaque type itself or its children are not within its reveal scope.
555             if def_id != self.def_id {
556                 self.check(def_id);
557                 intravisit::walk_impl_item(self, it);
558             }
559         }
560         fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
561             debug!("find_existential_constraints: visiting {:?}", it);
562             let def_id = self.tcx.hir().local_def_id(it.hir_id);
563             self.check(def_id);
564             intravisit::walk_trait_item(self, it);
565         }
566     }
567
568     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
569     let scope = tcx.hir().get_defining_scope(hir_id);
570     let mut locator = ConstraintLocator { def_id, tcx, found: None };
571
572     debug!("find_opaque_ty_constraints: scope={:?}", scope);
573
574     if scope == hir::CRATE_HIR_ID {
575         intravisit::walk_crate(&mut locator, tcx.hir().krate());
576     } else {
577         debug!("find_opaque_ty_constraints: scope={:?}", tcx.hir().get(scope));
578         match tcx.hir().get(scope) {
579             // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
580             // This allows our visitor to process the defining item itself, causing
581             // it to pick up any 'sibling' defining uses.
582             //
583             // For example, this code:
584             // ```
585             // fn foo() {
586             //     type Blah = impl Debug;
587             //     let my_closure = || -> Blah { true };
588             // }
589             // ```
590             //
591             // requires us to explicitly process `foo()` in order
592             // to notice the defining usage of `Blah`.
593             Node::Item(ref it) => locator.visit_item(it),
594             Node::ImplItem(ref it) => locator.visit_impl_item(it),
595             Node::TraitItem(ref it) => locator.visit_trait_item(it),
596             other => bug!("{:?} is not a valid scope for an opaque type item", other),
597         }
598     }
599
600     match locator.found {
601         Some((_, ty, _)) => ty,
602         None => {
603             let span = tcx.def_span(def_id);
604             tcx.sess.span_err(span, "could not find defining uses");
605             tcx.types.err
606         }
607     }
608 }
609
610 fn infer_placeholder_type(
611     tcx: TyCtxt<'_>,
612     def_id: DefId,
613     body_id: hir::BodyId,
614     span: Span,
615     item_ident: Ident,
616 ) -> Ty<'_> {
617     let ty = tcx.diagnostic_only_typeck_tables_of(def_id).node_type(body_id.hir_id);
618
619     // If this came from a free `const` or `static mut?` item,
620     // then the user may have written e.g. `const A = 42;`.
621     // In this case, the parser has stashed a diagnostic for
622     // us to improve in typeck so we do that now.
623     match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
624         Some(mut err) => {
625             // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
626             // We are typeck and have the real type, so remove that and suggest the actual type.
627             err.suggestions.clear();
628             err.span_suggestion(
629                 span,
630                 "provide a type for the item",
631                 format!("{}: {}", item_ident, ty),
632                 Applicability::MachineApplicable,
633             )
634             .emit();
635         }
636         None => {
637             let mut diag = bad_placeholder_type(tcx, vec![span]);
638             if ty != tcx.types.err {
639                 diag.span_suggestion(
640                     span,
641                     "replace `_` with the correct type",
642                     ty.to_string(),
643                     Applicability::MaybeIncorrect,
644                 );
645             }
646             diag.emit();
647         }
648     }
649
650     ty
651 }
652
653 fn report_assoc_ty_on_inherent_impl(tcx: TyCtxt<'_>, span: Span) {
654     struct_span_err!(
655         tcx.sess,
656         span,
657         E0202,
658         "associated types are not yet supported in inherent impls (see #8995)"
659     )
660     .emit();
661 }