]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_typeck/src/collect/type_of.rs
Merge tag 'debian/1.52.1+dfsg1-1_exp2' into proxmox/buster
[rustc.git] / compiler / rustc_typeck / src / collect / type_of.rs
CommitLineData
ba9703b0 1use rustc_data_structures::fx::FxHashSet;
1b1a35ee 2use rustc_errors::{Applicability, ErrorReported, StashKey};
74b04a01
XL
3use rustc_hir as hir;
4use rustc_hir::def::{DefKind, Res};
f9f354fc 5use rustc_hir::def_id::{DefId, LocalDefId};
74b04a01
XL
6use rustc_hir::intravisit;
7use rustc_hir::intravisit::Visitor;
5869c6ff 8use rustc_hir::{HirId, Node};
ba9703b0
XL
9use rustc_middle::hir::map::Map;
10use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts};
11use rustc_middle::ty::util::IntTypeExt;
12use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt, TypeFoldable};
f035d41b 13use rustc_span::symbol::Ident;
74b04a01
XL
14use rustc_span::{Span, DUMMY_SP};
15
16use super::ItemCtxt;
17use super::{bad_placeholder_type, is_suggestable_infer_ty};
18
3dfed10e
XL
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`.
22pub(super) fn opt_const_param_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DefId> {
23 use hir::*;
3dfed10e
XL
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 {
6a06907d
XL
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 }
3dfed10e
XL
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(_), .. })
5869c6ff
XL
130 | Node::Expr(&Expr { kind: ExprKind::Path(_) | ExprKind::Struct(..), .. })
131 | Node::TraitRef(..)
132 | Node::Pat(_) => {
3dfed10e
XL
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 }
5869c6ff
XL
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 }
1b1a35ee
XL
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 }
3dfed10e
XL
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.
3dfed10e
XL
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 Res::Def(_, def_id) => tcx.generics_of(def_id),
195 Res::Err => {
196 tcx.sess.delay_span_bug(tcx.def_span(def_id), "anon const with Res::Err");
197 return None;
198 }
29967ef6
XL
199 _ => {
200 // If the user tries to specify generics on a type that does not take them,
201 // e.g. `usize<T>`, we may hit this branch, in which case we treat it as if
202 // no arguments have been passed. An error should already have been emitted.
203 tcx.sess.delay_span_bug(
204 tcx.def_span(def_id),
205 &format!("unexpected anon const res {:?} in path: {:?}", res, path),
206 );
207 return None;
208 }
3dfed10e
XL
209 };
210
211 generics
212 .params
213 .iter()
214 .filter(|param| matches!(param.kind, ty::GenericParamDefKind::Const))
215 .nth(arg_index)
216 .map(|param| param.def_id)
217 }
218 _ => None,
219 }
220 } else {
221 None
222 }
223}
224
5869c6ff
XL
225fn get_path_containing_arg_in_pat<'hir>(
226 pat: &'hir hir::Pat<'hir>,
227 arg_id: HirId,
228) -> Option<&'hir hir::Path<'hir>> {
229 use hir::*;
230
231 let is_arg_in_path = |p: &hir::Path<'_>| {
232 p.segments
233 .iter()
234 .filter_map(|seg| seg.args)
235 .flat_map(|args| args.args)
236 .any(|arg| arg.id() == arg_id)
237 };
238 let mut arg_path = None;
239 pat.walk(|pat| match pat.kind {
240 PatKind::Struct(QPath::Resolved(_, path), _, _)
241 | PatKind::TupleStruct(QPath::Resolved(_, path), _, _)
242 | PatKind::Path(QPath::Resolved(_, path))
243 if is_arg_in_path(path) =>
244 {
245 arg_path = Some(path);
246 false
247 }
248 _ => true,
249 });
250 arg_path
251}
252
74b04a01 253pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
3dfed10e 254 let def_id = def_id.expect_local();
74b04a01
XL
255 use rustc_hir::*;
256
3dfed10e 257 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
74b04a01 258
3dfed10e 259 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
74b04a01
XL
260
261 match tcx.hir().get(hir_id) {
262 Node::TraitItem(item) => match item.kind {
ba9703b0 263 TraitItemKind::Fn(..) => {
3dfed10e
XL
264 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
265 tcx.mk_fn_def(def_id.to_def_id(), substs)
74b04a01
XL
266 }
267 TraitItemKind::Const(ref ty, body_id) => body_id
268 .and_then(|body_id| {
269 if is_suggestable_infer_ty(ty) {
3dfed10e 270 Some(infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident))
74b04a01
XL
271 } else {
272 None
273 }
274 })
275 .unwrap_or_else(|| icx.to_ty(ty)),
276 TraitItemKind::Type(_, Some(ref ty)) => icx.to_ty(ty),
277 TraitItemKind::Type(_, None) => {
278 span_bug!(item.span, "associated type missing default");
279 }
280 },
281
282 Node::ImplItem(item) => match item.kind {
ba9703b0 283 ImplItemKind::Fn(..) => {
3dfed10e
XL
284 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
285 tcx.mk_fn_def(def_id.to_def_id(), substs)
74b04a01
XL
286 }
287 ImplItemKind::Const(ref ty, body_id) => {
288 if is_suggestable_infer_ty(ty) {
3dfed10e 289 infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)
74b04a01
XL
290 } else {
291 icx.to_ty(ty)
292 }
293 }
74b04a01 294 ImplItemKind::TyAlias(ref ty) => {
ba9703b0 295 if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id).to_def_id()).is_none() {
6a06907d 296 check_feature_inherent_assoc_ty(tcx, item.span);
74b04a01
XL
297 }
298
299 icx.to_ty(ty)
300 }
301 },
302
303 Node::Item(item) => {
304 match item.kind {
305 ItemKind::Static(ref ty, .., body_id) | ItemKind::Const(ref ty, body_id) => {
306 if is_suggestable_infer_ty(ty) {
3dfed10e 307 infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident)
74b04a01
XL
308 } else {
309 icx.to_ty(ty)
310 }
311 }
5869c6ff
XL
312 ItemKind::TyAlias(ref self_ty, _)
313 | ItemKind::Impl(hir::Impl { ref self_ty, .. }) => icx.to_ty(self_ty),
74b04a01 314 ItemKind::Fn(..) => {
3dfed10e
XL
315 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
316 tcx.mk_fn_def(def_id.to_def_id(), substs)
74b04a01
XL
317 }
318 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
319 let def = tcx.adt_def(def_id);
3dfed10e 320 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
74b04a01
XL
321 tcx.mk_adt(def, substs)
322 }
f035d41b 323 ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::Binding, .. }) => {
3dfed10e 324 let_position_impl_trait_type(tcx, def_id)
f035d41b 325 }
74b04a01 326 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {
3dfed10e 327 find_opaque_ty_constraints(tcx, def_id)
74b04a01
XL
328 }
329 // Opaque types desugared from `impl Trait`.
f035d41b
XL
330 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: Some(owner), .. }) => {
331 let concrete_ty = tcx
332 .mir_borrowck(owner.expect_local())
333 .concrete_opaque_types
3dfed10e 334 .get(&def_id.to_def_id())
74b04a01
XL
335 .map(|opaque| opaque.concrete_type)
336 .unwrap_or_else(|| {
337 tcx.sess.delay_span_bug(
338 DUMMY_SP,
339 &format!(
3dfed10e 340 "owner {:?} has no opaque type for {:?} in its typeck results",
74b04a01
XL
341 owner, def_id,
342 ),
343 );
ba9703b0 344 if let Some(ErrorReported) =
3dfed10e 345 tcx.typeck(owner.expect_local()).tainted_by_errors
ba9703b0 346 {
74b04a01
XL
347 // Some error in the
348 // owner fn prevented us from populating
349 // the `concrete_opaque_types` table.
f035d41b 350 tcx.ty_error()
74b04a01
XL
351 } else {
352 // We failed to resolve the opaque type or it
353 // resolves to itself. Return the non-revealed
354 // type, which should result in E0720.
355 tcx.mk_opaque(
3dfed10e
XL
356 def_id.to_def_id(),
357 InternalSubsts::identity_for_item(tcx, def_id.to_def_id()),
74b04a01
XL
358 )
359 }
360 });
361 debug!("concrete_ty = {:?}", concrete_ty);
74b04a01
XL
362 concrete_ty
363 }
364 ItemKind::Trait(..)
365 | ItemKind::TraitAlias(..)
366 | ItemKind::Mod(..)
fc512014 367 | ItemKind::ForeignMod { .. }
74b04a01
XL
368 | ItemKind::GlobalAsm(..)
369 | ItemKind::ExternCrate(..)
370 | ItemKind::Use(..) => {
371 span_bug!(
372 item.span,
373 "compute_type_of_item: unexpected item type: {:?}",
374 item.kind
375 );
376 }
377 }
378 }
379
380 Node::ForeignItem(foreign_item) => match foreign_item.kind {
381 ForeignItemKind::Fn(..) => {
3dfed10e
XL
382 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
383 tcx.mk_fn_def(def_id.to_def_id(), substs)
74b04a01
XL
384 }
385 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
3dfed10e 386 ForeignItemKind::Type => tcx.mk_foreign(def_id.to_def_id()),
74b04a01
XL
387 },
388
389 Node::Ctor(&ref def) | Node::Variant(Variant { data: ref def, .. }) => match *def {
390 VariantData::Unit(..) | VariantData::Struct(..) => {
ba9703b0 391 tcx.type_of(tcx.hir().get_parent_did(hir_id).to_def_id())
74b04a01
XL
392 }
393 VariantData::Tuple(..) => {
3dfed10e
XL
394 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
395 tcx.mk_fn_def(def_id.to_def_id(), substs)
74b04a01
XL
396 }
397 },
398
399 Node::Field(field) => icx.to_ty(&field.ty),
400
401 Node::Expr(&Expr { kind: ExprKind::Closure(.., gen), .. }) => {
3dfed10e 402 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
ba9703b0 403 if let Some(movability) = gen {
3dfed10e 404 tcx.mk_generator(def_id.to_def_id(), substs, movability)
ba9703b0 405 } else {
3dfed10e 406 tcx.mk_closure(def_id.to_def_id(), substs)
ba9703b0 407 }
74b04a01
XL
408 }
409
410 Node::AnonConst(_) => {
3dfed10e
XL
411 if let Some(param) = tcx.opt_const_param_of(def_id) {
412 // We defer to `type_of` of the corresponding parameter
413 // for generic arguments.
414 return tcx.type_of(param);
415 }
416
74b04a01
XL
417 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
418 match parent_node {
419 Node::Ty(&Ty { kind: TyKind::Array(_, ref constant), .. })
420 | Node::Ty(&Ty { kind: TyKind::Typeof(ref constant), .. })
421 | Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
422 if constant.hir_id == hir_id =>
423 {
424 tcx.types.usize
425 }
426
29967ef6
XL
427 Node::Expr(&Expr { kind: ExprKind::ConstBlock(ref anon_const), .. })
428 if anon_const.hir_id == hir_id =>
429 {
430 tcx.typeck(def_id).node_type(anon_const.hir_id)
431 }
432
ba9703b0
XL
433 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => tcx
434 .adt_def(tcx.hir().get_parent_did(hir_id).to_def_id())
435 .repr
436 .discr_type()
437 .to_ty(tcx),
74b04a01 438
f035d41b
XL
439 x => tcx.ty_error_with_message(
440 DUMMY_SP,
441 &format!("unexpected const parent in type_of_def_id(): {:?}", x),
442 ),
74b04a01
XL
443 }
444 }
445
446 Node::GenericParam(param) => match &param.kind {
3dfed10e
XL
447 GenericParamKind::Type { default: Some(ty), .. }
448 | GenericParamKind::Const { ty, .. } => icx.to_ty(ty),
74b04a01
XL
449 x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
450 },
451
452 x => {
453 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
454 }
455 }
456}
457
f9f354fc 458fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
74b04a01
XL
459 use rustc_hir::{Expr, ImplItem, Item, TraitItem};
460
461 debug!("find_opaque_ty_constraints({:?})", def_id);
462
463 struct ConstraintLocator<'tcx> {
464 tcx: TyCtxt<'tcx>,
465 def_id: DefId,
ba9703b0
XL
466 // (first found type span, actual type)
467 found: Option<(Span, Ty<'tcx>)>,
74b04a01
XL
468 }
469
470 impl ConstraintLocator<'_> {
f9f354fc 471 fn check(&mut self, def_id: LocalDefId) {
74b04a01 472 // Don't try to check items that cannot possibly constrain the type.
3dfed10e 473 if !self.tcx.has_typeck_results(def_id) {
74b04a01 474 debug!(
3dfed10e 475 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`: no typeck results",
74b04a01
XL
476 self.def_id, def_id,
477 );
478 return;
479 }
480 // Calling `mir_borrowck` can lead to cycle errors through
481 // const-checking, avoid calling it if we don't have to.
3dfed10e 482 if !self.tcx.typeck(def_id).concrete_opaque_types.contains_key(&self.def_id) {
74b04a01
XL
483 debug!(
484 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
485 self.def_id, def_id,
486 );
487 return;
488 }
489 // Use borrowck to get the type with unerased regions.
490 let ty = self.tcx.mir_borrowck(def_id).concrete_opaque_types.get(&self.def_id);
491 if let Some(ty::ResolvedOpaqueTy { concrete_type, substs }) = ty {
492 debug!(
493 "find_opaque_ty_constraints: found constraint for `{:?}` at `{:?}`: {:?}",
494 self.def_id, def_id, ty,
495 );
496
497 // FIXME(oli-obk): trace the actual span from inference to improve errors.
498 let span = self.tcx.def_span(def_id);
ba9703b0
XL
499
500 // HACK(eddyb) this check shouldn't be needed, as `wfcheck`
501 // performs the same checks, in theory, but I've kept it here
502 // using `delay_span_bug`, just in case `wfcheck` slips up.
503 let opaque_generics = self.tcx.generics_of(self.def_id);
504 let mut used_params: FxHashSet<_> = FxHashSet::default();
505 for (i, arg) in substs.iter().enumerate() {
506 let arg_is_param = match arg.unpack() {
1b1a35ee 507 GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Param(_)),
ba9703b0
XL
508 GenericArgKind::Lifetime(lt) => {
509 matches!(lt, ty::ReEarlyBound(_) | ty::ReFree(_))
510 }
511 GenericArgKind::Const(ct) => matches!(ct.val, ty::ConstKind::Param(_)),
512 };
513
514 if arg_is_param {
515 if !used_params.insert(arg) {
516 // There was already an entry for `arg`, meaning a generic parameter
517 // was used twice.
74b04a01
XL
518 self.tcx.sess.delay_span_bug(
519 span,
520 &format!(
ba9703b0
XL
521 "defining opaque type use restricts opaque \
522 type by using the generic parameter `{}` twice",
523 arg,
74b04a01
XL
524 ),
525 );
526 }
ba9703b0
XL
527 } else {
528 let param = opaque_generics.param_at(i, self.tcx);
529 self.tcx.sess.delay_span_bug(
74b04a01
XL
530 span,
531 &format!(
532 "defining opaque type use does not fully define opaque type: \
ba9703b0
XL
533 generic parameter `{}` is specified as concrete {} `{}`",
534 param.name,
535 param.kind.descr(),
536 arg,
74b04a01
XL
537 ),
538 );
539 }
ba9703b0
XL
540 }
541
542 if let Some((prev_span, prev_ty)) = self.found {
543 if *concrete_type != prev_ty {
74b04a01
XL
544 debug!("find_opaque_ty_constraints: span={:?}", span);
545 // Found different concrete types for the opaque type.
546 let mut err = self.tcx.sess.struct_span_err(
547 span,
548 "concrete type differs from previous defining opaque type use",
549 );
550 err.span_label(
551 span,
552 format!("expected `{}`, got `{}`", prev_ty, concrete_type),
553 );
554 err.span_note(prev_span, "previous use here");
555 err.emit();
74b04a01
XL
556 }
557 } else {
ba9703b0 558 self.found = Some((span, concrete_type));
74b04a01
XL
559 }
560 } else {
561 debug!(
562 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
563 self.def_id, def_id,
564 );
565 }
566 }
567 }
568
569 impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
570 type Map = Map<'tcx>;
571
ba9703b0
XL
572 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
573 intravisit::NestedVisitorMap::All(self.tcx.hir())
74b04a01
XL
574 }
575 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
576 if let hir::ExprKind::Closure(..) = ex.kind {
577 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
578 self.check(def_id);
579 }
580 intravisit::walk_expr(self, ex);
581 }
582 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
583 debug!("find_existential_constraints: visiting {:?}", it);
74b04a01 584 // The opaque type itself or its children are not within its reveal scope.
6a06907d
XL
585 if it.def_id.to_def_id() != self.def_id {
586 self.check(it.def_id);
74b04a01
XL
587 intravisit::walk_item(self, it);
588 }
589 }
590 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
591 debug!("find_existential_constraints: visiting {:?}", it);
74b04a01 592 // The opaque type itself or its children are not within its reveal scope.
6a06907d
XL
593 if it.def_id.to_def_id() != self.def_id {
594 self.check(it.def_id);
74b04a01
XL
595 intravisit::walk_impl_item(self, it);
596 }
597 }
598 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
599 debug!("find_existential_constraints: visiting {:?}", it);
6a06907d 600 self.check(it.def_id);
74b04a01
XL
601 intravisit::walk_trait_item(self, it);
602 }
603 }
604
3dfed10e 605 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
74b04a01 606 let scope = tcx.hir().get_defining_scope(hir_id);
f9f354fc 607 let mut locator = ConstraintLocator { def_id: def_id.to_def_id(), tcx, found: None };
74b04a01
XL
608
609 debug!("find_opaque_ty_constraints: scope={:?}", scope);
610
611 if scope == hir::CRATE_HIR_ID {
612 intravisit::walk_crate(&mut locator, tcx.hir().krate());
613 } else {
614 debug!("find_opaque_ty_constraints: scope={:?}", tcx.hir().get(scope));
615 match tcx.hir().get(scope) {
616 // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
617 // This allows our visitor to process the defining item itself, causing
618 // it to pick up any 'sibling' defining uses.
619 //
620 // For example, this code:
621 // ```
622 // fn foo() {
623 // type Blah = impl Debug;
624 // let my_closure = || -> Blah { true };
625 // }
626 // ```
627 //
628 // requires us to explicitly process `foo()` in order
629 // to notice the defining usage of `Blah`.
630 Node::Item(ref it) => locator.visit_item(it),
631 Node::ImplItem(ref it) => locator.visit_impl_item(it),
632 Node::TraitItem(ref it) => locator.visit_trait_item(it),
633 other => bug!("{:?} is not a valid scope for an opaque type item", other),
634 }
635 }
636
637 match locator.found {
ba9703b0 638 Some((_, ty)) => ty,
74b04a01
XL
639 None => {
640 let span = tcx.def_span(def_id);
641 tcx.sess.span_err(span, "could not find defining uses");
f035d41b 642 tcx.ty_error()
74b04a01
XL
643 }
644 }
645}
646
f035d41b
XL
647/// Retrieve the inferred concrete type for let position impl trait.
648///
649/// This is different to other kinds of impl trait because:
650///
651/// 1. We know which function contains the defining use (the function that
652/// contains the let statement)
653/// 2. We do not currently allow (free) lifetimes in the return type. `let`
654/// statements in some statically unreachable code are removed from the MIR
655/// by the time we borrow check, and it's not clear how we should handle
656/// those.
657fn let_position_impl_trait_type(tcx: TyCtxt<'_>, opaque_ty_id: LocalDefId) -> Ty<'_> {
3dfed10e 658 let scope = tcx.hir().get_defining_scope(tcx.hir().local_def_id_to_hir_id(opaque_ty_id));
f035d41b
XL
659 let scope_def_id = tcx.hir().local_def_id(scope);
660
661 let opaque_ty_def_id = opaque_ty_id.to_def_id();
662
3dfed10e
XL
663 let owner_typeck_results = tcx.typeck(scope_def_id);
664 let concrete_ty = owner_typeck_results
f035d41b
XL
665 .concrete_opaque_types
666 .get(&opaque_ty_def_id)
667 .map(|opaque| opaque.concrete_type)
668 .unwrap_or_else(|| {
669 tcx.sess.delay_span_bug(
670 DUMMY_SP,
671 &format!(
3dfed10e 672 "owner {:?} has no opaque type for {:?} in its typeck results",
f035d41b
XL
673 scope_def_id, opaque_ty_id
674 ),
675 );
3dfed10e 676 if let Some(ErrorReported) = owner_typeck_results.tainted_by_errors {
f035d41b
XL
677 // Some error in the owner fn prevented us from populating the
678 // `concrete_opaque_types` table.
679 tcx.ty_error()
680 } else {
681 // We failed to resolve the opaque type or it resolves to
682 // itself. Return the non-revealed type, which should result in
683 // E0720.
684 tcx.mk_opaque(
685 opaque_ty_def_id,
686 InternalSubsts::identity_for_item(tcx, opaque_ty_def_id),
687 )
688 }
689 });
690 debug!("concrete_ty = {:?}", concrete_ty);
691 if concrete_ty.has_erased_regions() {
692 // FIXME(impl_trait_in_bindings) Handle this case.
693 tcx.sess.span_fatal(
3dfed10e 694 tcx.hir().span(tcx.hir().local_def_id_to_hir_id(opaque_ty_id)),
f035d41b
XL
695 "lifetimes in impl Trait types in bindings are not currently supported",
696 );
697 }
698 concrete_ty
699}
700
74b04a01
XL
701fn infer_placeholder_type(
702 tcx: TyCtxt<'_>,
f9f354fc 703 def_id: LocalDefId,
74b04a01
XL
704 body_id: hir::BodyId,
705 span: Span,
706 item_ident: Ident,
707) -> Ty<'_> {
3dfed10e 708 let ty = tcx.diagnostic_only_typeck(def_id).node_type(body_id.hir_id);
74b04a01
XL
709
710 // If this came from a free `const` or `static mut?` item,
711 // then the user may have written e.g. `const A = 42;`.
712 // In this case, the parser has stashed a diagnostic for
713 // us to improve in typeck so we do that now.
714 match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
715 Some(mut err) => {
716 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
717 // We are typeck and have the real type, so remove that and suggest the actual type.
718 err.suggestions.clear();
719 err.span_suggestion(
720 span,
721 "provide a type for the item",
722 format!("{}: {}", item_ident, ty),
723 Applicability::MachineApplicable,
724 )
6a06907d 725 .emit_unless(ty.references_error());
74b04a01
XL
726 }
727 None => {
728 let mut diag = bad_placeholder_type(tcx, vec![span]);
6a06907d
XL
729
730 if !ty.references_error() {
74b04a01
XL
731 diag.span_suggestion(
732 span,
733 "replace `_` with the correct type",
734 ty.to_string(),
735 Applicability::MaybeIncorrect,
736 );
737 }
6a06907d 738
74b04a01
XL
739 diag.emit();
740 }
741 }
742
ba9703b0 743 // Typeck doesn't expect erased regions to be returned from `type_of`.
fc512014 744 tcx.fold_regions(ty, &mut false, |r, _| match r {
ba9703b0
XL
745 ty::ReErased => tcx.lifetimes.re_static,
746 _ => r,
747 })
74b04a01
XL
748}
749
6a06907d
XL
750fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) {
751 if !tcx.features().inherent_associated_types {
752 use rustc_session::parse::feature_err;
753 use rustc_span::symbol::sym;
754 feature_err(
755 &tcx.sess.parse_sess,
756 sym::inherent_associated_types,
757 span,
758 "inherent associated types are unstable",
759 )
760 .emit();
761 }
74b04a01 762}