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