1 use rustc::hir::map::Map;
2 use rustc::session::parse::feature_err;
4 use rustc::ty::subst::{GenericArgKind, InternalSubsts, Subst};
5 use rustc::ty::util::IntTypeExt;
6 use rustc::ty::{self, DefIdTree, Ty, TyCtxt, TypeFoldable};
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_errors::{struct_span_err, Applicability, StashKey};
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit;
13 use rustc_hir::intravisit::Visitor;
15 use rustc_span::symbol::{sym, Ident};
16 use rustc_span::{Span, DUMMY_SP};
19 use super::{bad_placeholder_type, is_suggestable_infer_ty};
21 pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
24 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
26 let icx = ItemCtxt::new(tcx, def_id);
28 match tcx.hir().get(hir_id) {
29 Node::TraitItem(item) => match item.kind {
30 TraitItemKind::Method(..) => {
31 let substs = InternalSubsts::identity_for_item(tcx, def_id);
32 tcx.mk_fn_def(def_id, substs)
34 TraitItemKind::Const(ref ty, body_id) => body_id
36 if is_suggestable_infer_ty(ty) {
37 Some(infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident))
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");
49 Node::ImplItem(item) => match item.kind {
50 ImplItemKind::Method(..) => {
51 let substs = InternalSubsts::identity_for_item(tcx, def_id);
52 tcx.mk_fn_def(def_id, substs)
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)
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);
66 find_opaque_ty_constraints(tcx, def_id)
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);
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)
86 ItemKind::TyAlias(ref self_ty, _) | ItemKind::Impl { ref self_ty, .. } => {
90 let substs = InternalSubsts::identity_for_item(tcx, def_id);
91 tcx.mk_fn_def(def_id, substs)
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)
98 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {
99 find_opaque_ty_constraints(tcx, def_id)
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
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
113 OpaqueTyOrigin::TypeAlias => {
114 span_bug!(item.span, "Type alias impl trait shouldn't have an owner")
117 let concrete_ty = concrete_types
119 .map(|opaque| opaque.concrete_type)
121 tcx.sess.delay_span_bug(
124 "owner {:?} has no opaque type for {:?} in its tables",
128 if tcx.typeck_tables_of(owner).tainted_by_errors {
130 // owner fn prevented us from populating
131 // the `concrete_opaque_types` table.
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.
139 InternalSubsts::identity_for_item(tcx, def_id),
143 debug!("concrete_ty = {:?}", concrete_ty);
144 if concrete_ty.has_erased_regions() {
145 // FIXME(impl_trait_in_bindings) Handle this case.
148 "lifetimes in impl Trait types in bindings are not currently supported",
154 | ItemKind::TraitAlias(..)
156 | ItemKind::ForeignMod(..)
157 | ItemKind::GlobalAsm(..)
158 | ItemKind::ExternCrate(..)
159 | ItemKind::Use(..) => {
162 "compute_type_of_item: unexpected item type: {:?}",
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)
174 ForeignItemKind::Static(ref t, _) => icx.to_ty(t),
175 ForeignItemKind::Type => tcx.mk_foreign(def_id),
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))
182 VariantData::Tuple(..) => {
183 let substs = InternalSubsts::identity_for_item(tcx, def_id);
184 tcx.mk_fn_def(def_id, substs)
188 Node::Field(field) => icx.to_ty(&field.ty),
190 Node::Expr(&Expr { kind: ExprKind::Closure(.., gen), .. }) => {
192 return tcx.typeck_tables_of(def_id).node_type(hir_id);
195 let substs = InternalSubsts::identity_for_item(tcx, def_id);
196 tcx.mk_closure(def_id, substs)
199 Node::AnonConst(_) => {
200 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
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 =>
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)
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 {
220 kind: TyKind::Path(QPath::Resolved(_, ref path)), ..
223 kind: ExprKind::Path(QPath::Resolved(_, ref path)),
226 Node::Expr(&Expr { kind: ExprKind::Struct(ref path, ..), .. }) => {
227 if let QPath::Resolved(_, ref path) = **path {
233 Node::TraitRef(&TraitRef { ref path, .. }) => Some(&**path),
237 if let Some(path) = path {
241 .filter_map(|seg| seg.args.as_ref())
242 .map(|generic_args| generic_args.args.as_ref())
245 .filter(|arg| arg.is_const())
247 .filter(|(_, arg)| arg.id() == hir_id)
248 .map(|(index, _)| index)
252 bug!("no arg matching AnonConst in path");
255 // We've encountered an `AnonConst` in some path, so we need to
256 // figure out which generic parameter it corresponds to and return
257 // the relevant type.
258 let generics = match path.res {
259 Res::Def(DefKind::Ctor(..), def_id) => {
260 tcx.generics_of(tcx.parent(def_id).unwrap())
262 Res::Def(_, def_id) => tcx.generics_of(def_id),
263 Res::Err => return tcx.types.err,
265 tcx.sess.delay_span_bug(
267 &format!("unexpected const parent path def {:?}", res,),
269 return tcx.types.err;
277 if let ty::GenericParamDefKind::Const = param.kind {
284 .map(|param| tcx.type_of(param.def_id))
285 // This is no generic parameter associated with the arg. This is
286 // probably from an extra arg where one is not needed.
287 .unwrap_or(tcx.types.err)
289 tcx.sess.delay_span_bug(
291 &format!("unexpected const parent path {:?}", parent_node,),
293 return tcx.types.err;
298 tcx.sess.delay_span_bug(
300 &format!("unexpected const parent in type_of_def_id(): {:?}", x),
307 Node::GenericParam(param) => match ¶m.kind {
308 GenericParamKind::Type { default: Some(ref ty), .. } => icx.to_ty(ty),
309 GenericParamKind::Const { ty: ref hir_ty, .. } => {
310 let ty = icx.to_ty(hir_ty);
311 if !tcx.features().const_compare_raw_pointers {
312 let err = match ty.peel_refs().kind {
313 ty::FnPtr(_) => Some("function pointers"),
314 ty::RawPtr(_) => Some("raw pointers"),
317 if let Some(unsupported_type) = err {
319 &tcx.sess.parse_sess,
320 sym::const_compare_raw_pointers,
323 "using {} as const generic parameters is unstable",
330 if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
337 "the types of const generic parameters must derive `PartialEq` and `Eq`",
341 format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
347 x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
351 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
356 fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
357 use rustc_hir::{Expr, ImplItem, Item, TraitItem};
359 debug!("find_opaque_ty_constraints({:?})", def_id);
361 struct ConstraintLocator<'tcx> {
364 // (first found type span, actual type, mapping from the opaque type's generic
365 // parameters to the concrete type's generic parameters)
367 // The mapping is an index for each use site of a generic parameter in the concrete type
369 // The indices index into the generic parameters on the opaque type.
370 found: Option<(Span, Ty<'tcx>, Vec<usize>)>,
373 impl ConstraintLocator<'_> {
374 fn check(&mut self, def_id: DefId) {
375 // Don't try to check items that cannot possibly constrain the type.
376 if !self.tcx.has_typeck_tables(def_id) {
378 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`: no tables",
383 // Calling `mir_borrowck` can lead to cycle errors through
384 // const-checking, avoid calling it if we don't have to.
385 if !self.tcx.typeck_tables_of(def_id).concrete_opaque_types.contains_key(&self.def_id) {
387 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
392 // Use borrowck to get the type with unerased regions.
393 let ty = self.tcx.mir_borrowck(def_id).concrete_opaque_types.get(&self.def_id);
394 if let Some(ty::ResolvedOpaqueTy { concrete_type, substs }) = ty {
396 "find_opaque_ty_constraints: found constraint for `{:?}` at `{:?}`: {:?}",
397 self.def_id, def_id, ty,
400 // FIXME(oli-obk): trace the actual span from inference to improve errors.
401 let span = self.tcx.def_span(def_id);
402 // used to quickly look up the position of a generic parameter
403 let mut index_map: FxHashMap<ty::ParamTy, usize> = FxHashMap::default();
404 // Skipping binder is ok, since we only use this to find generic parameters and
406 for (idx, subst) in substs.iter().enumerate() {
407 if let GenericArgKind::Type(ty) = subst.unpack() {
408 if let ty::Param(p) = ty.kind {
409 if index_map.insert(p, idx).is_some() {
410 // There was already an entry for `p`, meaning a generic parameter
412 self.tcx.sess.span_err(
415 "defining opaque type use restricts opaque \
416 type by using the generic parameter `{}` twice",
423 self.tcx.sess.delay_span_bug(
426 "non-defining opaque ty use in defining scope: {:?}, {:?}",
427 concrete_type, substs,
433 // Compute the index within the opaque type for each generic parameter used in
434 // the concrete type.
435 let indices = concrete_type
436 .subst(self.tcx, substs)
438 .filter_map(|t| match &t.kind {
439 ty::Param(p) => Some(*index_map.get(p).unwrap()),
443 let is_param = |ty: Ty<'_>| match ty.kind {
444 ty::Param(_) => true,
447 let bad_substs: Vec<_> = substs
450 .filter_map(|(i, k)| {
451 if let GenericArgKind::Type(ty) = k.unpack() { Some((i, ty)) } else { None }
453 .filter(|(_, ty)| !is_param(ty))
455 if !bad_substs.is_empty() {
456 let identity_substs = InternalSubsts::identity_for_item(self.tcx, self.def_id);
457 for (i, bad_subst) in bad_substs {
458 self.tcx.sess.span_err(
461 "defining opaque type use does not fully define opaque type: \
462 generic parameter `{}` is specified as concrete type `{}`",
463 identity_substs.type_at(i),
468 } else if let Some((prev_span, prev_ty, ref prev_indices)) = self.found {
469 let mut ty = concrete_type.walk().fuse();
470 let mut p_ty = prev_ty.walk().fuse();
471 let iter_eq = (&mut ty).zip(&mut p_ty).all(|(t, p)| match (&t.kind, &p.kind) {
472 // Type parameters are equal to any other type parameter for the purpose of
473 // concrete type equality, as it is possible to obtain the same type just
474 // by passing matching parameters to a function.
475 (ty::Param(_), ty::Param(_)) => true,
478 if !iter_eq || ty.next().is_some() || p_ty.next().is_some() {
479 debug!("find_opaque_ty_constraints: span={:?}", span);
480 // Found different concrete types for the opaque type.
481 let mut err = self.tcx.sess.struct_span_err(
483 "concrete type differs from previous defining opaque type use",
487 format!("expected `{}`, got `{}`", prev_ty, concrete_type),
489 err.span_note(prev_span, "previous use here");
491 } else if indices != *prev_indices {
492 // Found "same" concrete types, but the generic parameter order differs.
493 let mut err = self.tcx.sess.struct_span_err(
495 "concrete type's generic parameters differ from previous defining use",
498 let mut s = String::new();
499 write!(s, "expected [").unwrap();
500 let list = |s: &mut String, indices: &Vec<usize>| {
501 let mut indices = indices.iter().cloned();
502 if let Some(first) = indices.next() {
503 write!(s, "`{}`", substs[first]).unwrap();
505 write!(s, ", `{}`", substs[i]).unwrap();
509 list(&mut s, prev_indices);
510 write!(s, "], got [").unwrap();
511 list(&mut s, &indices);
512 write!(s, "]").unwrap();
513 err.span_label(span, s);
514 err.span_note(prev_span, "previous use here");
518 self.found = Some((span, concrete_type, indices));
522 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
529 impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
530 type Map = Map<'tcx>;
532 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
533 intravisit::NestedVisitorMap::All(&self.tcx.hir())
535 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
536 if let hir::ExprKind::Closure(..) = ex.kind {
537 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
540 intravisit::walk_expr(self, ex);
542 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
543 debug!("find_existential_constraints: visiting {:?}", it);
544 let def_id = self.tcx.hir().local_def_id(it.hir_id);
545 // The opaque type itself or its children are not within its reveal scope.
546 if def_id != self.def_id {
548 intravisit::walk_item(self, it);
551 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
552 debug!("find_existential_constraints: visiting {:?}", it);
553 let def_id = self.tcx.hir().local_def_id(it.hir_id);
554 // The opaque type itself or its children are not within its reveal scope.
555 if def_id != self.def_id {
557 intravisit::walk_impl_item(self, it);
560 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
561 debug!("find_existential_constraints: visiting {:?}", it);
562 let def_id = self.tcx.hir().local_def_id(it.hir_id);
564 intravisit::walk_trait_item(self, it);
568 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
569 let scope = tcx.hir().get_defining_scope(hir_id);
570 let mut locator = ConstraintLocator { def_id, tcx, found: None };
572 debug!("find_opaque_ty_constraints: scope={:?}", scope);
574 if scope == hir::CRATE_HIR_ID {
575 intravisit::walk_crate(&mut locator, tcx.hir().krate());
577 debug!("find_opaque_ty_constraints: scope={:?}", tcx.hir().get(scope));
578 match tcx.hir().get(scope) {
579 // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
580 // This allows our visitor to process the defining item itself, causing
581 // it to pick up any 'sibling' defining uses.
583 // For example, this code:
586 // type Blah = impl Debug;
587 // let my_closure = || -> Blah { true };
591 // requires us to explicitly process `foo()` in order
592 // to notice the defining usage of `Blah`.
593 Node::Item(ref it) => locator.visit_item(it),
594 Node::ImplItem(ref it) => locator.visit_impl_item(it),
595 Node::TraitItem(ref it) => locator.visit_trait_item(it),
596 other => bug!("{:?} is not a valid scope for an opaque type item", other),
600 match locator.found {
601 Some((_, ty, _)) => ty,
603 let span = tcx.def_span(def_id);
604 tcx.sess.span_err(span, "could not find defining uses");
610 fn infer_placeholder_type(
613 body_id: hir::BodyId,
617 let ty = tcx.diagnostic_only_typeck_tables_of(def_id).node_type(body_id.hir_id);
619 // If this came from a free `const` or `static mut?` item,
620 // then the user may have written e.g. `const A = 42;`.
621 // In this case, the parser has stashed a diagnostic for
622 // us to improve in typeck so we do that now.
623 match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
625 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
626 // We are typeck and have the real type, so remove that and suggest the actual type.
627 err.suggestions.clear();
630 "provide a type for the item",
631 format!("{}: {}", item_ident, ty),
632 Applicability::MachineApplicable,
637 let mut diag = bad_placeholder_type(tcx, vec![span]);
638 if ty != tcx.types.err {
639 diag.span_suggestion(
641 "replace `_` with the correct type",
643 Applicability::MaybeIncorrect,
653 fn report_assoc_ty_on_inherent_impl(tcx: TyCtxt<'_>, span: Span) {
658 "associated types are not yet supported in inherent impls (see #8995)"