]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/collect/type_of.rs
55642dfb4557b3f6c073180f0030809f86080861
[rust.git] / src / librustc_typeck / collect / type_of.rs
1 use rustc::hir::map::Map;
2 use rustc::ty::subst::{GenericArgKind, InternalSubsts, Subst};
3 use rustc::ty::util::IntTypeExt;
4 use rustc::ty::{self, DefIdTree, Ty, TyCtxt, TypeFoldable};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_errors::{struct_span_err, Applicability, StashKey};
7 use rustc_hir as hir;
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::DefId;
10 use rustc_hir::intravisit;
11 use rustc_hir::intravisit::Visitor;
12 use rustc_hir::Node;
13 use rustc_session::parse::feature_err;
14 use rustc_span::symbol::{sym, Ident};
15 use rustc_span::{Span, DUMMY_SP};
16 use rustc_trait_selection::traits;
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::Fn(..) => {
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::Fn(..) => {
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                             | Res::Def(DefKind::AssocTy, def_id) => {
261                                 tcx.generics_of(tcx.parent(def_id).unwrap())
262                             }
263                             Res::Def(_, def_id) => tcx.generics_of(def_id),
264                             res => {
265                                 tcx.sess.delay_span_bug(
266                                     DUMMY_SP,
267                                     &format!(
268                                         "unexpected const parent path def, parent: {:?}, def: {:?}",
269                                         parent_node, res
270                                     ),
271                                 );
272                                 return tcx.types.err;
273                             }
274                         };
275
276                         generics
277                             .params
278                             .iter()
279                             .filter(|param| {
280                                 if let ty::GenericParamDefKind::Const = param.kind {
281                                     true
282                                 } else {
283                                     false
284                                 }
285                             })
286                             .nth(arg_index)
287                             .map(|param| tcx.type_of(param.def_id))
288                             // This is no generic parameter associated with the arg. This is
289                             // probably from an extra arg where one is not needed.
290                             .unwrap_or_else(|| {
291                                 tcx.sess.delay_span_bug(
292                                     DUMMY_SP,
293                                     &format!(
294                                         "missing generic parameter for `AnonConst`, parent {:?}",
295                                         parent_node
296                                     ),
297                                 );
298                                 tcx.types.err
299                             })
300                     } else {
301                         tcx.sess.delay_span_bug(
302                             DUMMY_SP,
303                             &format!("unexpected const parent path {:?}", parent_node,),
304                         );
305                         tcx.types.err
306                     }
307                 }
308
309                 x => {
310                     tcx.sess.delay_span_bug(
311                         DUMMY_SP,
312                         &format!("unexpected const parent in type_of_def_id(): {:?}", x),
313                     );
314                     tcx.types.err
315                 }
316             }
317         }
318
319         Node::GenericParam(param) => match &param.kind {
320             GenericParamKind::Type { default: Some(ref ty), .. } => icx.to_ty(ty),
321             GenericParamKind::Const { ty: ref hir_ty, .. } => {
322                 let ty = icx.to_ty(hir_ty);
323                 if !tcx.features().const_compare_raw_pointers {
324                     let err = match ty.peel_refs().kind {
325                         ty::FnPtr(_) => Some("function pointers"),
326                         ty::RawPtr(_) => Some("raw pointers"),
327                         _ => None,
328                     };
329                     if let Some(unsupported_type) = err {
330                         feature_err(
331                             &tcx.sess.parse_sess,
332                             sym::const_compare_raw_pointers,
333                             hir_ty.span,
334                             &format!(
335                                 "using {} as const generic parameters is unstable",
336                                 unsupported_type
337                             ),
338                         )
339                         .emit();
340                     };
341                 }
342                 if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
343                     .is_some()
344                 {
345                     struct_span_err!(
346                         tcx.sess,
347                         hir_ty.span,
348                         E0741,
349                         "the types of const generic parameters must derive `PartialEq` and `Eq`",
350                     )
351                     .span_label(
352                         hir_ty.span,
353                         format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
354                     )
355                     .emit();
356                 }
357                 ty
358             }
359             x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
360         },
361
362         x => {
363             bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
364         }
365     }
366 }
367
368 fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
369     use rustc_hir::{Expr, ImplItem, Item, TraitItem};
370
371     debug!("find_opaque_ty_constraints({:?})", def_id);
372
373     struct ConstraintLocator<'tcx> {
374         tcx: TyCtxt<'tcx>,
375         def_id: DefId,
376         // (first found type span, actual type, mapping from the opaque type's generic
377         // parameters to the concrete type's generic parameters)
378         //
379         // The mapping is an index for each use site of a generic parameter in the concrete type
380         //
381         // The indices index into the generic parameters on the opaque type.
382         found: Option<(Span, Ty<'tcx>, Vec<usize>)>,
383     }
384
385     impl ConstraintLocator<'_> {
386         fn check(&mut self, def_id: DefId) {
387             // Don't try to check items that cannot possibly constrain the type.
388             if !self.tcx.has_typeck_tables(def_id) {
389                 debug!(
390                     "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`: no tables",
391                     self.def_id, def_id,
392                 );
393                 return;
394             }
395             // Calling `mir_borrowck` can lead to cycle errors through
396             // const-checking, avoid calling it if we don't have to.
397             if !self.tcx.typeck_tables_of(def_id).concrete_opaque_types.contains_key(&self.def_id) {
398                 debug!(
399                     "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
400                     self.def_id, def_id,
401                 );
402                 return;
403             }
404             // Use borrowck to get the type with unerased regions.
405             let ty = self.tcx.mir_borrowck(def_id).concrete_opaque_types.get(&self.def_id);
406             if let Some(ty::ResolvedOpaqueTy { concrete_type, substs }) = ty {
407                 debug!(
408                     "find_opaque_ty_constraints: found constraint for `{:?}` at `{:?}`: {:?}",
409                     self.def_id, def_id, ty,
410                 );
411
412                 // FIXME(oli-obk): trace the actual span from inference to improve errors.
413                 let span = self.tcx.def_span(def_id);
414                 // used to quickly look up the position of a generic parameter
415                 let mut index_map: FxHashMap<ty::ParamTy, usize> = FxHashMap::default();
416                 // Skipping binder is ok, since we only use this to find generic parameters and
417                 // their positions.
418                 for (idx, subst) in substs.iter().enumerate() {
419                     if let GenericArgKind::Type(ty) = subst.unpack() {
420                         if let ty::Param(p) = ty.kind {
421                             if index_map.insert(p, idx).is_some() {
422                                 // There was already an entry for `p`, meaning a generic parameter
423                                 // was used twice.
424                                 self.tcx.sess.span_err(
425                                     span,
426                                     &format!(
427                                         "defining opaque type use restricts opaque \
428                                          type by using the generic parameter `{}` twice",
429                                         p,
430                                     ),
431                                 );
432                                 return;
433                             }
434                         } else {
435                             self.tcx.sess.delay_span_bug(
436                                 span,
437                                 &format!(
438                                     "non-defining opaque ty use in defining scope: {:?}, {:?}",
439                                     concrete_type, substs,
440                                 ),
441                             );
442                         }
443                     }
444                 }
445                 // Compute the index within the opaque type for each generic parameter used in
446                 // the concrete type.
447                 let indices = concrete_type
448                     .subst(self.tcx, substs)
449                     .walk()
450                     .filter_map(|t| match &t.kind {
451                         ty::Param(p) => Some(*index_map.get(p).unwrap()),
452                         _ => None,
453                     })
454                     .collect();
455                 let is_param = |ty: Ty<'_>| match ty.kind {
456                     ty::Param(_) => true,
457                     _ => false,
458                 };
459                 let bad_substs: Vec<_> = substs
460                     .iter()
461                     .enumerate()
462                     .filter_map(|(i, k)| {
463                         if let GenericArgKind::Type(ty) = k.unpack() { Some((i, ty)) } else { None }
464                     })
465                     .filter(|(_, ty)| !is_param(ty))
466                     .collect();
467                 if !bad_substs.is_empty() {
468                     let identity_substs = InternalSubsts::identity_for_item(self.tcx, self.def_id);
469                     for (i, bad_subst) in bad_substs {
470                         self.tcx.sess.span_err(
471                             span,
472                             &format!(
473                                 "defining opaque type use does not fully define opaque type: \
474                             generic parameter `{}` is specified as concrete type `{}`",
475                                 identity_substs.type_at(i),
476                                 bad_subst
477                             ),
478                         );
479                     }
480                 } else if let Some((prev_span, prev_ty, ref prev_indices)) = self.found {
481                     let mut ty = concrete_type.walk().fuse();
482                     let mut p_ty = prev_ty.walk().fuse();
483                     let iter_eq = (&mut ty).zip(&mut p_ty).all(|(t, p)| match (&t.kind, &p.kind) {
484                         // Type parameters are equal to any other type parameter for the purpose of
485                         // concrete type equality, as it is possible to obtain the same type just
486                         // by passing matching parameters to a function.
487                         (ty::Param(_), ty::Param(_)) => true,
488                         _ => t == p,
489                     });
490                     if !iter_eq || ty.next().is_some() || p_ty.next().is_some() {
491                         debug!("find_opaque_ty_constraints: span={:?}", span);
492                         // Found different concrete types for the opaque type.
493                         let mut err = self.tcx.sess.struct_span_err(
494                             span,
495                             "concrete type differs from previous defining opaque type use",
496                         );
497                         err.span_label(
498                             span,
499                             format!("expected `{}`, got `{}`", prev_ty, concrete_type),
500                         );
501                         err.span_note(prev_span, "previous use here");
502                         err.emit();
503                     } else if indices != *prev_indices {
504                         // Found "same" concrete types, but the generic parameter order differs.
505                         let mut err = self.tcx.sess.struct_span_err(
506                             span,
507                             "concrete type's generic parameters differ from previous defining use",
508                         );
509                         use std::fmt::Write;
510                         let mut s = String::new();
511                         write!(s, "expected [").unwrap();
512                         let list = |s: &mut String, indices: &Vec<usize>| {
513                             let mut indices = indices.iter().cloned();
514                             if let Some(first) = indices.next() {
515                                 write!(s, "`{}`", substs[first]).unwrap();
516                                 for i in indices {
517                                     write!(s, ", `{}`", substs[i]).unwrap();
518                                 }
519                             }
520                         };
521                         list(&mut s, prev_indices);
522                         write!(s, "], got [").unwrap();
523                         list(&mut s, &indices);
524                         write!(s, "]").unwrap();
525                         err.span_label(span, s);
526                         err.span_note(prev_span, "previous use here");
527                         err.emit();
528                     }
529                 } else {
530                     self.found = Some((span, concrete_type, indices));
531                 }
532             } else {
533                 debug!(
534                     "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
535                     self.def_id, def_id,
536                 );
537             }
538         }
539     }
540
541     impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
542         type Map = Map<'tcx>;
543
544         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
545             intravisit::NestedVisitorMap::All(self.tcx.hir())
546         }
547         fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
548             if let hir::ExprKind::Closure(..) = ex.kind {
549                 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
550                 self.check(def_id);
551             }
552             intravisit::walk_expr(self, ex);
553         }
554         fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
555             debug!("find_existential_constraints: visiting {:?}", it);
556             let def_id = self.tcx.hir().local_def_id(it.hir_id);
557             // The opaque type itself or its children are not within its reveal scope.
558             if def_id != self.def_id {
559                 self.check(def_id);
560                 intravisit::walk_item(self, it);
561             }
562         }
563         fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
564             debug!("find_existential_constraints: visiting {:?}", it);
565             let def_id = self.tcx.hir().local_def_id(it.hir_id);
566             // The opaque type itself or its children are not within its reveal scope.
567             if def_id != self.def_id {
568                 self.check(def_id);
569                 intravisit::walk_impl_item(self, it);
570             }
571         }
572         fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
573             debug!("find_existential_constraints: visiting {:?}", it);
574             let def_id = self.tcx.hir().local_def_id(it.hir_id);
575             self.check(def_id);
576             intravisit::walk_trait_item(self, it);
577         }
578     }
579
580     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
581     let scope = tcx.hir().get_defining_scope(hir_id);
582     let mut locator = ConstraintLocator { def_id, tcx, found: None };
583
584     debug!("find_opaque_ty_constraints: scope={:?}", scope);
585
586     if scope == hir::CRATE_HIR_ID {
587         intravisit::walk_crate(&mut locator, tcx.hir().krate());
588     } else {
589         debug!("find_opaque_ty_constraints: scope={:?}", tcx.hir().get(scope));
590         match tcx.hir().get(scope) {
591             // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
592             // This allows our visitor to process the defining item itself, causing
593             // it to pick up any 'sibling' defining uses.
594             //
595             // For example, this code:
596             // ```
597             // fn foo() {
598             //     type Blah = impl Debug;
599             //     let my_closure = || -> Blah { true };
600             // }
601             // ```
602             //
603             // requires us to explicitly process `foo()` in order
604             // to notice the defining usage of `Blah`.
605             Node::Item(ref it) => locator.visit_item(it),
606             Node::ImplItem(ref it) => locator.visit_impl_item(it),
607             Node::TraitItem(ref it) => locator.visit_trait_item(it),
608             other => bug!("{:?} is not a valid scope for an opaque type item", other),
609         }
610     }
611
612     match locator.found {
613         Some((_, ty, _)) => ty,
614         None => {
615             let span = tcx.def_span(def_id);
616             tcx.sess.span_err(span, "could not find defining uses");
617             tcx.types.err
618         }
619     }
620 }
621
622 fn infer_placeholder_type(
623     tcx: TyCtxt<'_>,
624     def_id: DefId,
625     body_id: hir::BodyId,
626     span: Span,
627     item_ident: Ident,
628 ) -> Ty<'_> {
629     let ty = tcx.diagnostic_only_typeck_tables_of(def_id).node_type(body_id.hir_id);
630
631     // If this came from a free `const` or `static mut?` item,
632     // then the user may have written e.g. `const A = 42;`.
633     // In this case, the parser has stashed a diagnostic for
634     // us to improve in typeck so we do that now.
635     match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
636         Some(mut err) => {
637             // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
638             // We are typeck and have the real type, so remove that and suggest the actual type.
639             err.suggestions.clear();
640             err.span_suggestion(
641                 span,
642                 "provide a type for the item",
643                 format!("{}: {}", item_ident, ty),
644                 Applicability::MachineApplicable,
645             )
646             .emit();
647         }
648         None => {
649             let mut diag = bad_placeholder_type(tcx, vec![span]);
650             if ty != tcx.types.err {
651                 diag.span_suggestion(
652                     span,
653                     "replace `_` with the correct type",
654                     ty.to_string(),
655                     Applicability::MaybeIncorrect,
656                 );
657             }
658             diag.emit();
659         }
660     }
661
662     ty
663 }
664
665 fn report_assoc_ty_on_inherent_impl(tcx: TyCtxt<'_>, span: Span) {
666     struct_span_err!(
667         tcx.sess,
668         span,
669         E0202,
670         "associated types are not yet supported in inherent impls (see #8995)"
671     )
672     .emit();
673 }