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};
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;
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;
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::Fn(..) => {
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::Fn(..) => {
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)
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 | Res::Def(DefKind::AssocTy, def_id) => {
261 tcx.generics_of(tcx.parent(def_id).unwrap())
263 Res::Def(_, def_id) => tcx.generics_of(def_id),
265 tcx.sess.delay_span_bug(
268 "unexpected const parent path def, parent: {:?}, def: {:?}",
272 return tcx.types.err;
280 if let ty::GenericParamDefKind::Const = param.kind {
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.
291 tcx.sess.delay_span_bug(
294 "missing generic parameter for `AnonConst`, parent {:?}",
301 tcx.sess.delay_span_bug(
303 &format!("unexpected const parent path {:?}", parent_node,),
310 tcx.sess.delay_span_bug(
312 &format!("unexpected const parent in type_of_def_id(): {:?}", x),
319 Node::GenericParam(param) => match ¶m.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"),
329 if let Some(unsupported_type) = err {
331 &tcx.sess.parse_sess,
332 sym::const_compare_raw_pointers,
335 "using {} as const generic parameters is unstable",
342 if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
349 "the types of const generic parameters must derive `PartialEq` and `Eq`",
353 format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
359 x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
363 bug!("unexpected sort of node in type_of_def_id(): {:?}", x);
368 fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
369 use rustc_hir::{Expr, ImplItem, Item, TraitItem};
371 debug!("find_opaque_ty_constraints({:?})", def_id);
373 struct ConstraintLocator<'tcx> {
376 // (first found type span, actual type, mapping from the opaque type's generic
377 // parameters to the concrete type's generic parameters)
379 // The mapping is an index for each use site of a generic parameter in the concrete type
381 // The indices index into the generic parameters on the opaque type.
382 found: Option<(Span, Ty<'tcx>, Vec<usize>)>,
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) {
390 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`: no tables",
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) {
399 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
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 {
408 "find_opaque_ty_constraints: found constraint for `{:?}` at `{:?}`: {:?}",
409 self.def_id, def_id, ty,
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
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
424 self.tcx.sess.span_err(
427 "defining opaque type use restricts opaque \
428 type by using the generic parameter `{}` twice",
435 self.tcx.sess.delay_span_bug(
438 "non-defining opaque ty use in defining scope: {:?}, {:?}",
439 concrete_type, substs,
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)
450 .filter_map(|t| match &t.kind {
451 ty::Param(p) => Some(*index_map.get(p).unwrap()),
455 let is_param = |ty: Ty<'_>| match ty.kind {
456 ty::Param(_) => true,
459 let bad_substs: Vec<_> = substs
462 .filter_map(|(i, k)| {
463 if let GenericArgKind::Type(ty) = k.unpack() { Some((i, ty)) } else { None }
465 .filter(|(_, ty)| !is_param(ty))
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(
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),
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,
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(
495 "concrete type differs from previous defining opaque type use",
499 format!("expected `{}`, got `{}`", prev_ty, concrete_type),
501 err.span_note(prev_span, "previous use here");
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(
507 "concrete type's generic parameters differ from previous defining use",
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();
517 write!(s, ", `{}`", substs[i]).unwrap();
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");
530 self.found = Some((span, concrete_type, indices));
534 "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`",
541 impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
542 type Map = Map<'tcx>;
544 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
545 intravisit::NestedVisitorMap::All(self.tcx.hir())
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);
552 intravisit::walk_expr(self, ex);
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 {
560 intravisit::walk_item(self, it);
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 {
569 intravisit::walk_impl_item(self, it);
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);
576 intravisit::walk_trait_item(self, it);
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 };
584 debug!("find_opaque_ty_constraints: scope={:?}", scope);
586 if scope == hir::CRATE_HIR_ID {
587 intravisit::walk_crate(&mut locator, tcx.hir().krate());
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.
595 // For example, this code:
598 // type Blah = impl Debug;
599 // let my_closure = || -> Blah { true };
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),
612 match locator.found {
613 Some((_, ty, _)) => ty,
615 let span = tcx.def_span(def_id);
616 tcx.sess.span_err(span, "could not find defining uses");
622 fn infer_placeholder_type(
625 body_id: hir::BodyId,
629 let ty = tcx.diagnostic_only_typeck_tables_of(def_id).node_type(body_id.hir_id);
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) {
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();
642 "provide a type for the item",
643 format!("{}: {}", item_ident, ty),
644 Applicability::MachineApplicable,
649 let mut diag = bad_placeholder_type(tcx, vec![span]);
650 if ty != tcx.types.err {
651 diag.span_suggestion(
653 "replace `_` with the correct type",
655 Applicability::MaybeIncorrect,
665 fn report_assoc_ty_on_inherent_impl(tcx: TyCtxt<'_>, span: Span) {
670 "associated types are not yet supported in inherent impls (see #8995)"