1 use rustc_errors::{Applicability, StashKey};
3 use rustc_hir::def_id::{DefId, LocalDefId};
4 use rustc_hir::intravisit;
5 use rustc_hir::intravisit::Visitor;
6 use rustc_hir::{HirId, Node};
7 use rustc_middle::hir::nested_filter;
8 use rustc_middle::ty::subst::InternalSubsts;
9 use rustc_middle::ty::util::IntTypeExt;
10 use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt, TypeFolder, TypeSuperFoldable, TypeVisitable};
11 use rustc_span::symbol::Ident;
12 use rustc_span::{Span, DUMMY_SP};
15 use super::{bad_placeholder, is_suggestable_infer_ty};
16 use crate::errors::UnconstrainedOpaqueType;
18 /// Computes the relevant generic parameter for a potential generic const argument.
20 /// This should be called using the query `tcx.opt_const_param_of`.
21 pub(super) fn opt_const_param_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DefId> {
23 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
25 match tcx.hir().get(hir_id) {
26 Node::AnonConst(_) => (),
30 let parent_node_id = tcx.hir().get_parent_node(hir_id);
31 let parent_node = tcx.hir().get(parent_node_id);
33 let (generics, arg_idx) = match parent_node {
34 // This match arm is for when the def_id appears in a GAT whose
35 // path can't be resolved without typechecking e.g.
38 // type Assoc<const N: usize>;
39 // fn foo() -> Self::Assoc<3>;
42 // In the above code we would call this query with the def_id of 3 and
43 // the parent_node we match on would be the hir node for Self::Assoc<3>
45 // `Self::Assoc<3>` cant be resolved without typechecking here as we
46 // didnt write <Self as Foo>::Assoc<3>. If we did then another match
47 // arm would handle this.
49 // I believe this match arm is only needed for GAT but I am not 100% sure - BoxyUwU
50 Node::Ty(hir_ty @ Ty { kind: TyKind::Path(QPath::TypeRelative(_, segment)), .. }) => {
51 // Find the Item containing the associated type so we can create an ItemCtxt.
52 // Using the ItemCtxt convert the HIR for the unresolved assoc type into a
53 // ty which is a fully resolved projection.
54 // For the code example above, this would mean converting Self::Assoc<3>
55 // into a ty::Projection(<Self as Foo>::Assoc<3>)
59 .filter(|(_, node)| matches!(node, Node::Item(_)))
63 let item_did = tcx.hir().local_def_id(item_hir_id).to_def_id();
64 let item_ctxt = &ItemCtxt::new(tcx, item_did) as &dyn crate::astconv::AstConv<'_>;
65 let ty = item_ctxt.ast_ty_to_ty(hir_ty);
67 // Iterate through the generics of the projection to find the one that corresponds to
68 // the def_id that this query was called with. We filter to only type and const args here
69 // as a precaution for if it's ever allowed to elide lifetimes in GAT's. It currently isn't
70 // but it can't hurt to be safe ^^
71 if let ty::Projection(projection) = ty.kind() {
72 let generics = tcx.generics_of(projection.item_def_id);
74 let arg_index = segment
79 .filter(|arg| arg.is_ty_or_const())
80 .position(|arg| arg.hir_id() == hir_id)
83 bug!("no arg matching AnonConst in segment");
88 // I dont think it's possible to reach this but I'm not 100% sure - BoxyUwU
89 tcx.sess.delay_span_bug(
91 "unexpected non-GAT usage of an anon const",
98 ExprKind::MethodCall(segment, ..) | ExprKind::Path(QPath::TypeRelative(_, segment)),
101 let body_owner = tcx.hir().enclosing_body_owner(hir_id);
102 let tables = tcx.typeck(body_owner);
103 // This may fail in case the method/path does not actually exist.
104 // As there is no relevant param for `def_id`, we simply return
106 let type_dependent_def = tables.type_dependent_def_id(parent_node_id)?;
112 .filter(|arg| arg.is_ty_or_const())
113 .position(|arg| arg.hir_id() == hir_id)
116 bug!("no arg matching AnonConst in segment");
119 (tcx.generics_of(type_dependent_def), idx)
122 Node::Ty(&Ty { kind: TyKind::Path(_), .. })
123 | Node::Expr(&Expr { kind: ExprKind::Path(_) | ExprKind::Struct(..), .. })
126 let path = match parent_node {
127 Node::Ty(&Ty { kind: TyKind::Path(QPath::Resolved(_, path)), .. })
128 | Node::TraitRef(&TraitRef { path, .. }) => &*path,
131 ExprKind::Path(QPath::Resolved(_, path))
132 | ExprKind::Struct(&QPath::Resolved(_, path), ..),
135 let body_owner = tcx.hir().enclosing_body_owner(hir_id);
136 let _tables = tcx.typeck(body_owner);
140 if let Some(path) = get_path_containing_arg_in_pat(pat, hir_id) {
143 tcx.sess.delay_span_bug(
144 tcx.def_span(def_id),
145 &format!("unable to find const parent for {} in pat {:?}", hir_id, pat),
151 tcx.sess.delay_span_bug(
152 tcx.def_span(def_id),
153 &format!("unexpected const parent path {:?}", parent_node),
159 // We've encountered an `AnonConst` in some path, so we need to
160 // figure out which generic parameter it corresponds to and return
161 // the relevant type.
162 let Some((arg_index, segment)) = path.segments.iter().find_map(|seg| {
163 let args = seg.args?;
166 .filter(|arg| arg.is_ty_or_const())
167 .position(|arg| arg.hir_id() == hir_id)
168 .map(|index| (index, seg)).or_else(|| args.bindings
170 .filter_map(TypeBinding::opt_const)
171 .position(|ct| ct.hir_id == hir_id)
172 .map(|idx| (idx, seg)))
174 tcx.sess.delay_span_bug(
175 tcx.def_span(def_id),
176 "no arg matching AnonConst in path",
181 let generics = match tcx.res_generics_def_id(segment.res) {
182 Some(def_id) => tcx.generics_of(def_id),
184 tcx.sess.delay_span_bug(
185 tcx.def_span(def_id),
186 &format!("unexpected anon const res {:?} in path: {:?}", segment.res, path),
192 (generics, arg_index)
197 debug!(?parent_node);
198 debug!(?generics, ?arg_idx);
202 .filter(|param| param.kind.is_ty_or_const())
203 .nth(match generics.has_self && generics.parent.is_none() {
207 .and_then(|param| match param.kind {
208 ty::GenericParamDefKind::Const { .. } => {
216 fn get_path_containing_arg_in_pat<'hir>(
217 pat: &'hir hir::Pat<'hir>,
219 ) -> Option<&'hir hir::Path<'hir>> {
222 let is_arg_in_path = |p: &hir::Path<'_>| {
225 .filter_map(|seg| seg.args)
226 .flat_map(|args| args.args)
227 .any(|arg| arg.hir_id() == arg_id)
229 let mut arg_path = None;
230 pat.walk(|pat| match pat.kind {
231 PatKind::Struct(QPath::Resolved(_, path), _, _)
232 | PatKind::TupleStruct(QPath::Resolved(_, path), _, _)
233 | PatKind::Path(QPath::Resolved(_, path))
234 if is_arg_in_path(path) =>
236 arg_path = Some(path);
244 pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
245 let def_id = def_id.expect_local();
248 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
250 let icx = ItemCtxt::new(tcx, def_id.to_def_id());
252 match tcx.hir().get(hir_id) {
253 Node::TraitItem(item) => match item.kind {
254 TraitItemKind::Fn(..) => {
255 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
256 tcx.mk_fn_def(def_id.to_def_id(), substs)
258 TraitItemKind::Const(ty, body_id) => body_id
259 .and_then(|body_id| {
260 if is_suggestable_infer_ty(ty) {
261 Some(infer_placeholder_type(
262 tcx, def_id, body_id, ty.span, item.ident, "constant",
268 .unwrap_or_else(|| icx.to_ty(ty)),
269 TraitItemKind::Type(_, Some(ty)) => icx.to_ty(ty),
270 TraitItemKind::Type(_, None) => {
271 span_bug!(item.span, "associated type missing default");
275 Node::ImplItem(item) => match item.kind {
276 ImplItemKind::Fn(..) => {
277 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
278 tcx.mk_fn_def(def_id.to_def_id(), substs)
280 ImplItemKind::Const(ty, body_id) => {
281 if is_suggestable_infer_ty(ty) {
282 infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident, "constant")
287 ImplItemKind::TyAlias(ty) => {
288 if tcx.impl_trait_ref(tcx.hir().get_parent_item(hir_id)).is_none() {
289 check_feature_inherent_assoc_ty(tcx, item.span);
296 Node::Item(item) => {
298 ItemKind::Static(ty, .., body_id) => {
299 if is_suggestable_infer_ty(ty) {
300 infer_placeholder_type(
312 ItemKind::Const(ty, body_id) => {
313 if is_suggestable_infer_ty(ty) {
314 infer_placeholder_type(
315 tcx, def_id, body_id, ty.span, item.ident, "constant",
321 ItemKind::TyAlias(self_ty, _) => icx.to_ty(self_ty),
322 ItemKind::Impl(hir::Impl { self_ty, .. }) => icx.to_ty(*self_ty),
323 ItemKind::Fn(..) => {
324 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
325 tcx.mk_fn_def(def_id.to_def_id(), substs)
327 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
328 let def = tcx.adt_def(def_id);
329 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
330 tcx.mk_adt(def, substs)
332 ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias, .. }) => {
333 find_opaque_ty_constraints_for_tait(tcx, def_id)
335 // Opaque types desugared from `impl Trait`.
336 ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn(owner) | hir::OpaqueTyOrigin::AsyncFn(owner), in_trait, .. }) => {
338 span_bug!(item.span, "impl-trait in trait has no default")
340 find_opaque_ty_constraints_for_rpit(tcx, def_id, owner)
344 | ItemKind::TraitAlias(..)
345 | ItemKind::Macro(..)
347 | ItemKind::ForeignMod { .. }
348 | ItemKind::GlobalAsm(..)
349 | ItemKind::ExternCrate(..)
350 | ItemKind::Use(..) => {
353 "compute_type_of_item: unexpected item type: {:?}",
360 Node::ForeignItem(foreign_item) => match foreign_item.kind {
361 ForeignItemKind::Fn(..) => {
362 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
363 tcx.mk_fn_def(def_id.to_def_id(), substs)
365 ForeignItemKind::Static(t, _) => icx.to_ty(t),
366 ForeignItemKind::Type => tcx.mk_foreign(def_id.to_def_id()),
369 Node::Ctor(&ref def) | Node::Variant(Variant { data: ref def, .. }) => match *def {
370 VariantData::Unit(..) | VariantData::Struct(..) => {
371 tcx.type_of(tcx.hir().get_parent_item(hir_id))
373 VariantData::Tuple(..) => {
374 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
375 tcx.mk_fn_def(def_id.to_def_id(), substs)
379 Node::Field(field) => icx.to_ty(field.ty),
381 Node::Expr(&Expr { kind: ExprKind::Closure{..}, .. }) => tcx.typeck(def_id).node_type(hir_id),
383 Node::AnonConst(_) if let Some(param) = tcx.opt_const_param_of(def_id) => {
384 // We defer to `type_of` of the corresponding parameter
385 // for generic arguments.
389 Node::AnonConst(_) => {
390 let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
392 Node::Ty(&Ty { kind: TyKind::Array(_, ref constant), .. })
393 | Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
394 if constant.hir_id() == hir_id =>
398 Node::Ty(&Ty { kind: TyKind::Typeof(ref e), .. }) if e.hir_id == hir_id => {
399 tcx.typeck(def_id).node_type(e.hir_id)
402 Node::Expr(&Expr { kind: ExprKind::ConstBlock(ref anon_const), .. })
403 if anon_const.hir_id == hir_id =>
405 let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
406 substs.as_inline_const().ty()
409 Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. })
410 | Node::Item(&Item { kind: ItemKind::GlobalAsm(asm), .. })
411 if asm.operands.iter().any(|(op, _op_sp)| match op {
412 hir::InlineAsmOperand::Const { anon_const }
413 | hir::InlineAsmOperand::SymFn { anon_const } => anon_const.hir_id == hir_id,
417 tcx.typeck(def_id).node_type(hir_id)
420 Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => tcx
421 .adt_def(tcx.hir().get_parent_item(hir_id))
426 Node::TypeBinding(binding @ &TypeBinding { hir_id: binding_id, .. })
427 if let Node::TraitRef(trait_ref) = tcx.hir().get(
428 tcx.hir().get_parent_node(binding_id)
431 let Some(trait_def_id) = trait_ref.trait_def_id() else {
432 return tcx.ty_error_with_message(DUMMY_SP, "Could not find trait");
434 let assoc_items = tcx.associated_items(trait_def_id);
435 let assoc_item = assoc_items.find_by_name_and_kind(
436 tcx, binding.ident, ty::AssocKind::Const, def_id.to_def_id(),
438 if let Some(assoc_item) = assoc_item {
439 tcx.type_of(assoc_item.def_id)
441 // FIXME(associated_const_equality): add a useful error message here.
442 tcx.ty_error_with_message(
444 "Could not find associated const on trait",
449 Node::GenericParam(&GenericParam {
450 hir_id: param_hir_id,
451 kind: GenericParamKind::Const { default: Some(ct), .. },
453 }) if ct.hir_id == hir_id => tcx.type_of(tcx.hir().local_def_id(param_hir_id)),
456 tcx.ty_error_with_message(
458 &format!("unexpected const parent in type_of(): {x:?}"),
463 Node::GenericParam(param) => match ¶m.kind {
464 GenericParamKind::Type { default: Some(ty), .. }
465 | GenericParamKind::Const { ty, .. } => icx.to_ty(ty),
466 x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
470 bug!("unexpected sort of node in type_of(): {:?}", x);
475 #[instrument(skip(tcx), level = "debug")]
476 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
477 /// laid for "higher-order pattern unification".
478 /// This ensures that inference is tractable.
479 /// In particular, definitions of opaque types can only use other generics as arguments,
480 /// and they cannot repeat an argument. Example:
482 /// ```ignore (illustrative)
483 /// type Foo<A, B> = impl Bar<A, B>;
485 /// // Okay -- `Foo` is applied to two distinct, generic types.
486 /// fn a<T, U>() -> Foo<T, U> { .. }
488 /// // Not okay -- `Foo` is applied to `T` twice.
489 /// fn b<T>() -> Foo<T, T> { .. }
491 /// // Not okay -- `Foo` is applied to a non-generic type.
492 /// fn b<T>() -> Foo<T, u32> { .. }
495 fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
496 use rustc_hir::{Expr, ImplItem, Item, TraitItem};
498 struct ConstraintLocator<'tcx> {
501 /// def_id of the opaque type whose defining uses are being checked
504 /// as we walk the defining uses, we are checking that all of them
505 /// define the same hidden type. This variable is set to `Some`
506 /// with the first type that we find, and then later types are
507 /// checked against it (we also carry the span of that first
509 found: Option<ty::OpaqueHiddenType<'tcx>>,
512 impl ConstraintLocator<'_> {
513 #[instrument(skip(self), level = "debug")]
514 fn check(&mut self, item_def_id: LocalDefId) {
515 // Don't try to check items that cannot possibly constrain the type.
516 if !self.tcx.has_typeck_results(item_def_id) {
517 debug!("no constraint: no typeck results");
520 // Calling `mir_borrowck` can lead to cycle errors through
521 // const-checking, avoid calling it if we don't have to.
523 // type Foo = impl Fn() -> usize; // when computing type for this
524 // const fn bar() -> Foo {
527 // const BAZR: Foo = bar(); // we would mir-borrowck this, causing cycles
528 // // because we again need to reveal `Foo` so we can check whether the
529 // // constant does not contain interior mutability.
531 let tables = self.tcx.typeck(item_def_id);
532 if let Some(_) = tables.tainted_by_errors {
533 self.found = Some(ty::OpaqueHiddenType { span: DUMMY_SP, ty: self.tcx.ty_error() });
536 if !tables.concrete_opaque_types.contains_key(&self.def_id) {
537 debug!("no constraints in typeck results");
540 // Use borrowck to get the type with unerased regions.
541 let concrete_opaque_types = &self.tcx.mir_borrowck(item_def_id).concrete_opaque_types;
542 debug!(?concrete_opaque_types);
543 if let Some(&concrete_type) = concrete_opaque_types.get(&self.def_id) {
544 debug!(?concrete_type, "found constraint");
545 if let Some(prev) = self.found {
546 if concrete_type.ty != prev.ty && !(concrete_type, prev).references_error() {
547 prev.report_mismatch(&concrete_type, self.tcx);
550 self.found = Some(concrete_type);
556 impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
557 type NestedFilter = nested_filter::All;
559 fn nested_visit_map(&mut self) -> Self::Map {
562 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
563 if let hir::ExprKind::Closure { .. } = ex.kind {
564 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
567 intravisit::walk_expr(self, ex);
569 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
571 // The opaque type itself or its children are not within its reveal scope.
572 if it.def_id != self.def_id {
573 self.check(it.def_id);
574 intravisit::walk_item(self, it);
577 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
579 // The opaque type itself or its children are not within its reveal scope.
580 if it.def_id != self.def_id {
581 self.check(it.def_id);
582 intravisit::walk_impl_item(self, it);
585 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
587 self.check(it.def_id);
588 intravisit::walk_trait_item(self, it);
592 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
593 let scope = tcx.hir().get_defining_scope(hir_id);
594 let mut locator = ConstraintLocator { def_id: def_id, tcx, found: None };
598 if scope == hir::CRATE_HIR_ID {
599 tcx.hir().walk_toplevel_module(&mut locator);
601 trace!("scope={:#?}", tcx.hir().get(scope));
602 match tcx.hir().get(scope) {
603 // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
604 // This allows our visitor to process the defining item itself, causing
605 // it to pick up any 'sibling' defining uses.
607 // For example, this code:
610 // type Blah = impl Debug;
611 // let my_closure = || -> Blah { true };
615 // requires us to explicitly process `foo()` in order
616 // to notice the defining usage of `Blah`.
617 Node::Item(it) => locator.visit_item(it),
618 Node::ImplItem(it) => locator.visit_impl_item(it),
619 Node::TraitItem(it) => locator.visit_trait_item(it),
620 other => bug!("{:?} is not a valid scope for an opaque type item", other),
624 match locator.found {
625 Some(hidden) => hidden.ty,
627 tcx.sess.emit_err(UnconstrainedOpaqueType {
628 span: tcx.def_span(def_id),
629 name: tcx.item_name(tcx.local_parent(def_id).to_def_id()),
636 fn find_opaque_ty_constraints_for_rpit(
639 owner_def_id: LocalDefId,
641 use rustc_hir::{Expr, ImplItem, Item, TraitItem};
643 struct ConstraintChecker<'tcx> {
646 /// def_id of the opaque type whose defining uses are being checked
649 found: ty::OpaqueHiddenType<'tcx>,
652 impl ConstraintChecker<'_> {
653 #[instrument(skip(self), level = "debug")]
654 fn check(&self, def_id: LocalDefId) {
655 // Use borrowck to get the type with unerased regions.
656 let concrete_opaque_types = &self.tcx.mir_borrowck(def_id).concrete_opaque_types;
657 debug!(?concrete_opaque_types);
658 for &(def_id, concrete_type) in concrete_opaque_types {
659 if def_id != self.def_id {
660 // Ignore constraints for other opaque types.
664 debug!(?concrete_type, "found constraint");
666 if concrete_type.ty != self.found.ty
667 && !(concrete_type, self.found).references_error()
669 self.found.report_mismatch(&concrete_type, self.tcx);
675 impl<'tcx> intravisit::Visitor<'tcx> for ConstraintChecker<'tcx> {
676 type NestedFilter = nested_filter::OnlyBodies;
678 fn nested_visit_map(&mut self) -> Self::Map {
681 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
682 if let hir::ExprKind::Closure { .. } = ex.kind {
683 let def_id = self.tcx.hir().local_def_id(ex.hir_id);
686 intravisit::walk_expr(self, ex);
688 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
690 // The opaque type itself or its children are not within its reveal scope.
691 if it.def_id != self.def_id {
692 self.check(it.def_id);
693 intravisit::walk_item(self, it);
696 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
698 // The opaque type itself or its children are not within its reveal scope.
699 if it.def_id != self.def_id {
700 self.check(it.def_id);
701 intravisit::walk_impl_item(self, it);
704 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
706 self.check(it.def_id);
707 intravisit::walk_trait_item(self, it);
711 let concrete = tcx.mir_borrowck(owner_def_id).concrete_opaque_types.get(&def_id).copied();
713 if let Some(concrete) = concrete {
714 let scope = tcx.hir().local_def_id_to_hir_id(owner_def_id);
716 let mut locator = ConstraintChecker { def_id: def_id, tcx, found: concrete };
718 match tcx.hir().get(scope) {
719 Node::Item(it) => intravisit::walk_item(&mut locator, it),
720 Node::ImplItem(it) => intravisit::walk_impl_item(&mut locator, it),
721 Node::TraitItem(it) => intravisit::walk_trait_item(&mut locator, it),
722 other => bug!("{:?} is not a valid scope for an opaque type item", other),
726 concrete.map(|concrete| concrete.ty).unwrap_or_else(|| {
727 let table = tcx.typeck(owner_def_id);
728 if let Some(_) = table.tainted_by_errors {
730 // owner fn prevented us from populating
731 // the `concrete_opaque_types` table.
735 .concrete_opaque_types
739 // We failed to resolve the opaque type or it
740 // resolves to itself. We interpret this as the
741 // no values of the hidden type ever being constructed,
742 // so we can just make the hidden type be `!`.
743 // For backwards compatibility reasons, we fall back to
744 // `()` until we the diverging default is changed.
745 Some(tcx.mk_diverging_default())
747 .expect("RPIT always have a hidden type from typeck")
752 fn infer_placeholder_type<'a>(
755 body_id: hir::BodyId,
760 // Attempts to make the type nameable by turning FnDefs into FnPtrs.
761 struct MakeNameable<'tcx> {
766 impl<'tcx> MakeNameable<'tcx> {
767 fn new(tcx: TyCtxt<'tcx>) -> Self {
768 MakeNameable { success: true, tcx }
772 impl<'tcx> TypeFolder<'tcx> for MakeNameable<'tcx> {
773 fn tcx(&self) -> TyCtxt<'tcx> {
777 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
783 ty::FnDef(def_id, _) => self.tcx.mk_fn_ptr(self.tcx.fn_sig(*def_id)),
784 // FIXME: non-capturing closures should also suggest a function pointer
785 ty::Closure(..) | ty::Generator(..) => {
786 self.success = false;
789 _ => ty.super_fold_with(self),
794 let ty = tcx.diagnostic_only_typeck(def_id).node_type(body_id.hir_id);
796 // If this came from a free `const` or `static mut?` item,
797 // then the user may have written e.g. `const A = 42;`.
798 // In this case, the parser has stashed a diagnostic for
799 // us to improve in typeck so we do that now.
800 match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
802 if !ty.references_error() {
803 // Only suggest adding `:` if it was missing (and suggested by parsing diagnostic)
804 let colon = if span == item_ident.span.shrink_to_hi() { ":" } else { "" };
806 // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
807 // We are typeck and have the real type, so remove that and suggest the actual type.
808 // FIXME(eddyb) this looks like it should be functionality on `Diagnostic`.
809 if let Ok(suggestions) = &mut err.suggestions {
813 // Suggesting unnameable types won't help.
814 let mut mk_nameable = MakeNameable::new(tcx);
815 let ty = mk_nameable.fold_ty(ty);
816 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
817 if let Some(sugg_ty) = sugg_ty {
820 &format!("provide a type for the {item}", item = kind),
821 format!("{colon} {sugg_ty}"),
822 Applicability::MachineApplicable,
826 tcx.hir().body(body_id).value.span,
827 &format!("however, the inferred type `{}` cannot be named", ty),
835 let mut diag = bad_placeholder(tcx, vec![span], kind);
837 if !ty.references_error() {
838 let mut mk_nameable = MakeNameable::new(tcx);
839 let ty = mk_nameable.fold_ty(ty);
840 let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
841 if let Some(sugg_ty) = sugg_ty {
842 diag.span_suggestion(
844 "replace with the correct type",
846 Applicability::MaybeIncorrect,
850 tcx.hir().body(body_id).value.span,
851 &format!("however, the inferred type `{}` cannot be named", ty),
860 // Typeck doesn't expect erased regions to be returned from `type_of`.
861 tcx.fold_regions(ty, |r, _| match *r {
862 ty::ReErased => tcx.lifetimes.re_static,
867 fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) {
868 if !tcx.features().inherent_associated_types {
869 use rustc_session::parse::feature_err;
870 use rustc_span::symbol::sym;
872 &tcx.sess.parse_sess,
873 sym::inherent_associated_types,
875 "inherent associated types are unstable",