1 use rustc_errors::{Applicability, StashKey};
3 use rustc_hir::def::Res;
4 use rustc_hir::def_id::{DefId, LocalDefId};
5 use rustc_hir::intravisit;
6 use rustc_hir::intravisit::Visitor;
7 use rustc_hir::{HirId, Node};
8 use rustc_middle::hir::nested_filter;
9 use rustc_middle::ty::subst::InternalSubsts;
10 use rustc_middle::ty::util::IntTypeExt;
11 use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt, TypeFolder, TypeSuperFoldable, TypeVisitable};
12 use rustc_span::symbol::Ident;
13 use rustc_span::{Span, DUMMY_SP};
16 use super::{bad_placeholder, is_suggestable_infer_ty};
17 use crate::errors::UnconstrainedOpaqueType;
19 /// Computes the relevant generic parameter for a potential generic const argument.
21 /// This should be called using the query `tcx.opt_const_param_of`.
22 #[instrument(level = "debug", skip(tcx))]
23 pub(super) fn opt_const_param_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DefId> {
25 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
27 match tcx.hir().get(hir_id) {
28 Node::AnonConst(_) => (),
32 let parent_node_id = tcx.hir().get_parent_node(hir_id);
33 let parent_node = tcx.hir().get(parent_node_id);
35 let (generics, arg_idx) = match parent_node {
36 // This match arm is for when the def_id appears in a GAT whose
37 // path can't be resolved without typechecking e.g.
40 // type Assoc<const N: usize>;
41 // fn foo() -> Self::Assoc<3>;
44 // In the above code we would call this query with the def_id of 3 and
45 // the parent_node we match on would be the hir node for Self::Assoc<3>
47 // `Self::Assoc<3>` cant be resolved without typechecking here as we
48 // didnt write <Self as Foo>::Assoc<3>. If we did then another match
49 // arm would handle this.
51 // I believe this match arm is only needed for GAT but I am not 100% sure - BoxyUwU
52 Node::Ty(hir_ty @ Ty { kind: TyKind::Path(QPath::TypeRelative(_, segment)), .. }) => {
53 // Find the Item containing the associated type so we can create an ItemCtxt.
54 // Using the ItemCtxt convert the HIR for the unresolved assoc type into a
55 // ty which is a fully resolved projection.
56 // For the code example above, this would mean converting Self::Assoc<3>
57 // into a ty::Projection(<Self as Foo>::Assoc<3>)
61 .filter(|(_, node)| matches!(node, Node::Item(_)))
65 let item_did = tcx.hir().local_def_id(item_hir_id).to_def_id();
66 let item_ctxt = &ItemCtxt::new(tcx, item_did) as &dyn crate::astconv::AstConv<'_>;
67 let ty = item_ctxt.ast_ty_to_ty(hir_ty);
69 // Iterate through the generics of the projection to find the one that corresponds to
70 // the def_id that this query was called with. We filter to only const args here as a
71 // precaution for if it's ever allowed to elide lifetimes in GAT's. It currently isn't
72 // but it can't hurt to be safe ^^
73 if let ty::Projection(projection) = ty.kind() {
74 let generics = tcx.generics_of(projection.item_def_id);
76 let arg_index = segment
81 .filter(|arg| arg.is_ty_or_const())
82 .position(|arg| arg.id() == hir_id)
85 bug!("no arg matching AnonConst in segment");
90 // I dont think it's possible to reach this but I'm not 100% sure - BoxyUwU
91 tcx.sess.delay_span_bug(
93 "unexpected non-GAT usage of an anon const",
100 ExprKind::MethodCall(segment, ..) | ExprKind::Path(QPath::TypeRelative(_, segment)),
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
108 let type_dependent_def = tables.type_dependent_def_id(parent_node_id)?;
114 .filter(|arg| arg.is_ty_or_const())
115 .position(|arg| arg.id() == hir_id)
118 bug!("no arg matching AnonConst in segment");
121 (tcx.generics_of(type_dependent_def), idx)
124 Node::Ty(&Ty { kind: TyKind::Path(_), .. })
125 | Node::Expr(&Expr { kind: ExprKind::Path(_) | ExprKind::Struct(..), .. })
128 let path = match parent_node {
129 Node::Ty(&Ty { kind: TyKind::Path(QPath::Resolved(_, path)), .. })
130 | Node::TraitRef(&TraitRef { path, .. }) => &*path,
133 ExprKind::Path(QPath::Resolved(_, path))
134 | ExprKind::Struct(&QPath::Resolved(_, path), ..),
137 let body_owner = tcx.hir().local_def_id(tcx.hir().enclosing_body_owner(hir_id));
138 let _tables = tcx.typeck(body_owner);
142 if let Some(path) = get_path_containing_arg_in_pat(pat, hir_id) {
145 tcx.sess.delay_span_bug(
146 tcx.def_span(def_id),
147 &format!("unable to find const parent for {} in pat {:?}", hir_id, pat),
153 tcx.sess.delay_span_bug(
154 tcx.def_span(def_id),
155 &format!("unexpected const parent path {:?}", parent_node),
161 // We've encountered an `AnonConst` in some path, so we need to
162 // figure out which generic parameter it corresponds to and return
163 // the relevant type.
164 let Some((arg_index, segment)) = path.segments.iter().find_map(|seg| {
165 let args = seg.args?;
168 .filter(|arg| arg.is_ty_or_const())
169 .position(|arg| arg.id() == hir_id)
170 .map(|index| (index, seg)).or_else(|| args.bindings
172 .filter_map(TypeBinding::opt_const)
173 .position(|ct| ct.hir_id == hir_id)
174 .map(|idx| (idx, seg)))
176 tcx.sess.delay_span_bug(
177 tcx.def_span(def_id),
178 "no arg matching AnonConst in path",
183 // Try to use the segment resolution if it is valid, otherwise we
184 // default to the path resolution.
185 let res = segment.res.filter(|&r| r != Res::Err).unwrap_or(path.res);
186 let generics = match tcx.res_generics_def_id(res) {
187 Some(def_id) => tcx.generics_of(def_id),
189 tcx.sess.delay_span_bug(
190 tcx.def_span(def_id),
191 &format!("unexpected anon const res {:?} in path: {:?}", res, path),
197 (generics, arg_index)
202 debug!(?parent_node);
203 debug!(?generics, ?arg_idx);
207 .filter(|param| param.kind.is_ty_or_const())
208 .nth(match generics.has_self && generics.parent.is_none() {
212 .and_then(|param| match param.kind {
213 ty::GenericParamDefKind::Const { .. } => {
221 fn get_path_containing_arg_in_pat<'hir>(
222 pat: &'hir hir::Pat<'hir>,
224 ) -> Option<&'hir hir::Path<'hir>> {
227 let is_arg_in_path = |p: &hir::Path<'_>| {
230 .filter_map(|seg| seg.args)
231 .flat_map(|args| args.args)
232 .any(|arg| arg.id() == arg_id)
234 let mut arg_path = None;
235 pat.walk(|pat| match pat.kind {
236 PatKind::Struct(QPath::Resolved(_, path), _, _)
237 | PatKind::TupleStruct(QPath::Resolved(_, path), _, _)
238 | PatKind::Path(QPath::Resolved(_, path))
239 if is_arg_in_path(path) =>
241 arg_path = Some(path);
249 pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
250 let def_id = def_id.expect_local();
253 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
255 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
257 match tcx.hir().get(hir_id) {
258 Node::TraitItem(item) => match item.kind {
259 TraitItemKind::Fn(..) => {
260 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
261 tcx.mk_fn_def(def_id.to_def_id(), substs)
263 TraitItemKind::Const(ty, body_id) => body_id
264 .and_then(|body_id| {
265 if is_suggestable_infer_ty(ty) {
266 Some(infer_placeholder_type(
267 tcx, def_id, body_id, ty.span, item.ident, "constant",
273 .unwrap_or_else(|| icx.to_ty(ty)),
274 TraitItemKind::Type(_, Some(ty)) => icx.to_ty(ty),
275 TraitItemKind::Type(_, None) => {
276 span_bug!(item.span, "associated type missing default");
280 Node::ImplItem(item) => match item.kind {
281 ImplItemKind::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)
285 ImplItemKind::Const(ty, body_id) => {
286 if is_suggestable_infer_ty(ty) {
287 infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident, "constant")
292 ImplItemKind::TyAlias(ty) => {
293 if tcx.impl_trait_ref(tcx.hir().get_parent_item(hir_id)).is_none() {
294 check_feature_inherent_assoc_ty(tcx, item.span);
301 Node::Item(item) => {
303 ItemKind::Static(ty, .., body_id) => {
304 if is_suggestable_infer_ty(ty) {
305 infer_placeholder_type(
317 ItemKind::Const(ty, body_id) => {
318 if is_suggestable_infer_ty(ty) {
319 infer_placeholder_type(
320 tcx, def_id, body_id, ty.span, item.ident, "constant",
326 ItemKind::TyAlias(self_ty, _) => icx.to_ty(self_ty),
327 ItemKind::Impl(hir::Impl { self_ty, .. }) => icx.to_ty(*self_ty),
328 ItemKind::Fn(..) => {
329 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
330 tcx.mk_fn_def(def_id.to_def_id(), substs)
332 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
333 let def = tcx.adt_def(def_id);
334 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
335 tcx.mk_adt(def, substs)
337 ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias, .. }) => {
338 find_opaque_ty_constraints_for_tait(tcx, def_id)
340 // Opaque types desugared from `impl Trait`.
341 ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn(owner) | hir::OpaqueTyOrigin::AsyncFn(owner), .. }) => {
342 find_opaque_ty_constraints_for_rpit(tcx, def_id, owner)
345 | ItemKind::TraitAlias(..)
346 | ItemKind::Macro(..)
348 | ItemKind::ForeignMod { .. }
349 | ItemKind::GlobalAsm(..)
350 | ItemKind::ExternCrate(..)
351 | ItemKind::Use(..) => {
354 "compute_type_of_item: unexpected item type: {:?}",
361 Node::ForeignItem(foreign_item) => match foreign_item.kind {
362 ForeignItemKind::Fn(..) => {
363 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
364 tcx.mk_fn_def(def_id.to_def_id(), substs)
366 ForeignItemKind::Static(t, _) => icx.to_ty(t),
367 ForeignItemKind::Type => tcx.mk_foreign(def_id.to_def_id()),
370 Node::Ctor(&ref def) | Node::Variant(Variant { data: ref def, .. }) => match *def {
371 VariantData::Unit(..) | VariantData::Struct(..) => {
372 tcx.type_of(tcx.hir().get_parent_item(hir_id))
374 VariantData::Tuple(..) => {
375 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
376 tcx.mk_fn_def(def_id.to_def_id(), substs)
380 Node::Field(field) => icx.to_ty(field.ty),
382 Node::Expr(&Expr { kind: ExprKind::Closure{..}, .. }) => tcx.typeck(def_id).node_type(hir_id),
384 Node::AnonConst(_) if let Some(param) = tcx.opt_const_param_of(def_id) => {
385 // We defer to `type_of` of the corresponding parameter
386 // for generic arguments.
390 Node::AnonConst(_) => {
391 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
393 Node::Ty(&Ty { kind: TyKind::Array(_, ref constant), .. })
394 | Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
395 if constant.hir_id() == hir_id =>
399 Node::Ty(&Ty { kind: TyKind::Typeof(ref e), .. }) if e.hir_id == hir_id => {
400 tcx.typeck(def_id).node_type(e.hir_id)
403 Node::Expr(&Expr { kind: ExprKind::ConstBlock(ref anon_const), .. })
404 if anon_const.hir_id == hir_id =>
406 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
407 substs.as_inline_const().ty()
410 Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. })
411 | Node::Item(&Item { kind: ItemKind::GlobalAsm(asm), .. })
412 if asm.operands.iter().any(|(op, _op_sp)| match op {
413 hir::InlineAsmOperand::Const { anon_const }
414 | hir::InlineAsmOperand::SymFn { anon_const } => anon_const.hir_id == hir_id,
418 tcx.typeck(def_id).node_type(hir_id)
421 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => tcx
422 .adt_def(tcx.hir().get_parent_item(hir_id))
427 Node::TypeBinding(binding @ &TypeBinding { hir_id: binding_id, .. })
428 if let Node::TraitRef(trait_ref) = tcx.hir().get(
429 tcx.hir().get_parent_node(binding_id)
432 let Some(trait_def_id) = trait_ref.trait_def_id() else {
433 return tcx.ty_error_with_message(DUMMY_SP, "Could not find trait");
435 let assoc_items = tcx.associated_items(trait_def_id);
436 let assoc_item = assoc_items.find_by_name_and_kind(
437 tcx, binding.ident, ty::AssocKind::Const, def_id.to_def_id(),
439 if let Some(assoc_item) = assoc_item {
440 tcx.type_of(assoc_item.def_id)
442 // FIXME(associated_const_equality): add a useful error message here.
443 tcx.ty_error_with_message(
445 "Could not find associated const on trait",
450 Node::GenericParam(&GenericParam {
451 hir_id: param_hir_id,
452 kind: GenericParamKind::Const { default: Some(ct), .. },
454 }) if ct.hir_id == hir_id => tcx.type_of(tcx.hir().local_def_id(param_hir_id)),
457 tcx.ty_error_with_message(
459 &format!("unexpected const parent in type_of(): {x:?}"),
464 Node::GenericParam(param) => match ¶m.kind {
465 GenericParamKind::Type { default: Some(ty), .. }
466 | GenericParamKind::Const { ty, .. } => icx.to_ty(ty),
467 x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
471 bug!("unexpected sort of node in type_of(): {:?}", x);
476 #[instrument(skip(tcx), level = "debug")]
477 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
478 /// laid for "higher-order pattern unification".
479 /// This ensures that inference is tractable.
480 /// In particular, definitions of opaque types can only use other generics as arguments,
481 /// and they cannot repeat an argument. Example:
483 /// ```ignore (illustrative)
484 /// type Foo<A, B> = impl Bar<A, B>;
486 /// // Okay -- `Foo` is applied to two distinct, generic types.
487 /// fn a<T, U>() -> Foo<T, U> { .. }
489 /// // Not okay -- `Foo` is applied to `T` twice.
490 /// fn b<T>() -> Foo<T, T> { .. }
492 /// // Not okay -- `Foo` is applied to a non-generic type.
493 /// fn b<T>() -> Foo<T, u32> { .. }
496 fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
497 use rustc_hir::{Expr, ImplItem, Item, TraitItem};
499 struct ConstraintLocator<'tcx> {
502 /// def_id of the opaque type whose defining uses are being checked
505 /// as we walk the defining uses, we are checking that all of them
506 /// define the same hidden type. This variable is set to `Some`
507 /// with the first type that we find, and then later types are
508 /// checked against it (we also carry the span of that first
510 found: Option<ty::OpaqueHiddenType<'tcx>>,
513 impl ConstraintLocator<'_> {
514 #[instrument(skip(self), level = "debug")]
515 fn check(&mut self, item_def_id: LocalDefId) {
516 // Don't try to check items that cannot possibly constrain the type.
517 if !self.tcx.has_typeck_results(item_def_id) {
518 debug!("no constraint: no typeck results");
521 // Calling `mir_borrowck` can lead to cycle errors through
522 // const-checking, avoid calling it if we don't have to.
524 // type Foo = impl Fn() -> usize; // when computing type for this
525 // const fn bar() -> Foo {
528 // const BAZR: Foo = bar(); // we would mir-borrowck this, causing cycles
529 // // because we again need to reveal `Foo` so we can check whether the
530 // // constant does not contain interior mutability.
532 let tables = self.tcx.typeck(item_def_id);
533 if let Some(_) = tables.tainted_by_errors {
534 self.found = Some(ty::OpaqueHiddenType { span: DUMMY_SP, ty: self.tcx.ty_error() });
537 if !tables.concrete_opaque_types.contains_key(&self.def_id) {
538 debug!("no constraints in typeck results");
541 // Use borrowck to get the type with unerased regions.
542 let concrete_opaque_types = &self.tcx.mir_borrowck(item_def_id).concrete_opaque_types;
543 debug!(?concrete_opaque_types);
544 if let Some(&concrete_type) = concrete_opaque_types.get(&self.def_id) {
545 debug!(?concrete_type, "found constraint");
546 if let Some(prev) = self.found {
547 if concrete_type.ty != prev.ty && !(concrete_type, prev).references_error() {
548 prev.report_mismatch(&concrete_type, self.tcx);
551 self.found = Some(concrete_type);
557 impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
558 type NestedFilter = nested_filter::All;
560 fn nested_visit_map(&mut self) -> Self::Map {
563 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
564 if let hir::ExprKind::Closure { .. } = ex.kind {
565 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
568 intravisit::walk_expr(self, ex);
570 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
572 // The opaque type itself or its children are not within its reveal scope.
573 if it.def_id != self.def_id {
574 self.check(it.def_id);
575 intravisit::walk_item(self, it);
578 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
580 // The opaque type itself or its children are not within its reveal scope.
581 if it.def_id != self.def_id {
582 self.check(it.def_id);
583 intravisit::walk_impl_item(self, it);
586 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
588 self.check(it.def_id);
589 intravisit::walk_trait_item(self, it);
593 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
594 let scope = tcx.hir().get_defining_scope(hir_id);
595 let mut locator = ConstraintLocator { def_id: def_id, tcx, found: None };
599 if scope == hir::CRATE_HIR_ID {
600 tcx.hir().walk_toplevel_module(&mut locator);
602 trace!("scope={:#?}", tcx.hir().get(scope));
603 match tcx.hir().get(scope) {
604 // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
605 // This allows our visitor to process the defining item itself, causing
606 // it to pick up any 'sibling' defining uses.
608 // For example, this code:
611 // type Blah = impl Debug;
612 // let my_closure = || -> Blah { true };
616 // requires us to explicitly process `foo()` in order
617 // to notice the defining usage of `Blah`.
618 Node::Item(it) => locator.visit_item(it),
619 Node::ImplItem(it) => locator.visit_impl_item(it),
620 Node::TraitItem(it) => locator.visit_trait_item(it),
621 other => bug!("{:?} is not a valid scope for an opaque type item", other),
625 match locator.found {
626 Some(hidden) => hidden.ty,
628 tcx.sess.emit_err(UnconstrainedOpaqueType {
629 span: tcx.def_span(def_id),
630 name: tcx.item_name(tcx.local_parent(def_id).to_def_id()),
637 fn find_opaque_ty_constraints_for_rpit(
640 owner_def_id: LocalDefId,
642 use rustc_hir::{Expr, ImplItem, Item, TraitItem};
644 struct ConstraintChecker<'tcx> {
647 /// def_id of the opaque type whose defining uses are being checked
650 found: ty::OpaqueHiddenType<'tcx>,
653 impl ConstraintChecker<'_> {
654 #[instrument(skip(self), level = "debug")]
655 fn check(&self, def_id: LocalDefId) {
656 // Use borrowck to get the type with unerased regions.
657 let concrete_opaque_types = &self.tcx.mir_borrowck(def_id).concrete_opaque_types;
658 debug!(?concrete_opaque_types);
659 for &(def_id, concrete_type) in concrete_opaque_types {
660 if def_id != self.def_id {
661 // Ignore constraints for other opaque types.
665 debug!(?concrete_type, "found constraint");
667 if concrete_type.ty != self.found.ty
668 && !(concrete_type, self.found).references_error()
670 self.found.report_mismatch(&concrete_type, self.tcx);
676 impl<'tcx> intravisit::Visitor<'tcx> for ConstraintChecker<'tcx> {
677 type NestedFilter = nested_filter::OnlyBodies;
679 fn nested_visit_map(&mut self) -> Self::Map {
682 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
683 if let hir::ExprKind::Closure { .. } = ex.kind {
684 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
687 intravisit::walk_expr(self, ex);
689 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
691 // The opaque type itself or its children are not within its reveal scope.
692 if it.def_id != self.def_id {
693 self.check(it.def_id);
694 intravisit::walk_item(self, it);
697 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
699 // The opaque type itself or its children are not within its reveal scope.
700 if it.def_id != self.def_id {
701 self.check(it.def_id);
702 intravisit::walk_impl_item(self, it);
705 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
707 self.check(it.def_id);
708 intravisit::walk_trait_item(self, it);
712 let concrete = tcx.mir_borrowck(owner_def_id).concrete_opaque_types.get(&def_id).copied();
714 if let Some(concrete) = concrete {
715 let scope = tcx.hir().local_def_id_to_hir_id(owner_def_id);
717 let mut locator = ConstraintChecker { def_id: def_id, tcx, found: concrete };
719 match tcx.hir().get(scope) {
720 Node::Item(it) => intravisit::walk_item(&mut locator, it),
721 Node::ImplItem(it) => intravisit::walk_impl_item(&mut locator, it),
722 Node::TraitItem(it) => intravisit::walk_trait_item(&mut locator, it),
723 other => bug!("{:?} is not a valid scope for an opaque type item", other),
727 concrete.map(|concrete| concrete.ty).unwrap_or_else(|| {
728 let table = tcx.typeck(owner_def_id);
729 if let Some(_) = table.tainted_by_errors {
731 // owner fn prevented us from populating
732 // the `concrete_opaque_types` table.
736 .concrete_opaque_types
740 // We failed to resolve the opaque type or it
741 // resolves to itself. We interpret this as the
742 // no values of the hidden type ever being constructed,
743 // so we can just make the hidden type be `!`.
744 // For backwards compatibility reasons, we fall back to
745 // `()` until we the diverging default is changed.
746 Some(tcx.mk_diverging_default())
748 .expect("RPIT always have a hidden type from typeck")
753 fn infer_placeholder_type<'a>(
756 body_id: hir::BodyId,
761 // Attempts to make the type nameable by turning FnDefs into FnPtrs.
762 struct MakeNameable<'tcx> {
767 impl<'tcx> MakeNameable<'tcx> {
768 fn new(tcx: TyCtxt<'tcx>) -> Self {
769 MakeNameable { success: true, tcx }
773 impl<'tcx> TypeFolder<'tcx> for MakeNameable<'tcx> {
774 fn tcx(&self) -> TyCtxt<'tcx> {
778 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
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;
790 _ => ty.super_fold_with(self),
795 let ty = tcx.diagnostic_only_typeck(def_id).node_type(body_id.hir_id);
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) {
803 if !ty.references_error() {
804 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
805 // We are typeck and have the real type, so remove that and suggest the actual type.
806 // FIXME(eddyb) this looks like it should be functionality on `Diagnostic`.
807 if let Ok(suggestions) = &mut err.suggestions {
811 // Suggesting unnameable types won't help.
812 let mut mk_nameable = MakeNameable::new(tcx);
813 let ty = mk_nameable.fold_ty(ty);
814 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
815 if let Some(sugg_ty) = sugg_ty {
818 &format!("provide a type for the {item}", item = kind),
819 format!("{}: {}", item_ident, sugg_ty),
820 Applicability::MachineApplicable,
824 tcx.hir().body(body_id).value.span,
825 &format!("however, the inferred type `{}` cannot be named", ty),
833 let mut diag = bad_placeholder(tcx, vec![span], kind);
835 if !ty.references_error() {
836 let mut mk_nameable = MakeNameable::new(tcx);
837 let ty = mk_nameable.fold_ty(ty);
838 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
839 if let Some(sugg_ty) = sugg_ty {
840 diag.span_suggestion(
842 "replace with the correct type",
844 Applicability::MaybeIncorrect,
848 tcx.hir().body(body_id).value.span,
849 &format!("however, the inferred type `{}` cannot be named", ty),
858 // Typeck doesn't expect erased regions to be returned from `type_of`.
859 tcx.fold_regions(ty, |r, _| match *r {
860 ty::ReErased => tcx.lifetimes.re_static,
865 fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) {
866 if !tcx.features().inherent_associated_types {
867 use rustc_session::parse::feature_err;
868 use rustc_span::symbol::sym;
870 &tcx.sess.parse_sess,
871 sym::inherent_associated_types,
873 "inherent associated types are unstable",