rustc_hir_analysis/collect/
type_of.rs

1use core::ops::ControlFlow;
2
3use rustc_errors::{Applicability, StashKey, Suggestions};
4use rustc_hir::def_id::{DefId, LocalDefId};
5use rustc_hir::intravisit::VisitorExt;
6use rustc_hir::{self as hir, AmbigArg, HirId};
7use rustc_middle::query::plumbing::CyclePlaceholder;
8use rustc_middle::ty::fold::fold_regions;
9use rustc_middle::ty::print::with_forced_trimmed_paths;
10use rustc_middle::ty::util::IntTypeExt;
11use rustc_middle::ty::{self, Article, IsSuggestable, Ty, TyCtxt, TypeVisitableExt};
12use rustc_middle::{bug, span_bug};
13use rustc_span::{DUMMY_SP, Ident, Span};
14
15use super::{HirPlaceholderCollector, ItemCtxt, bad_placeholder};
16use crate::errors::TypeofReservedKeywordUsed;
17use crate::hir_ty_lowering::HirTyLowerer;
18
19mod opaque;
20
21fn anon_const_type_of<'tcx>(icx: &ItemCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> {
22    use hir::*;
23    use rustc_middle::ty::Ty;
24    let tcx = icx.tcx;
25    let hir_id = tcx.local_def_id_to_hir_id(def_id);
26
27    let node = tcx.hir_node(hir_id);
28    let Node::AnonConst(&AnonConst { span, .. }) = node else {
29        span_bug!(
30            tcx.def_span(def_id),
31            "expected anon const in `anon_const_type_of`, got {node:?}"
32        );
33    };
34
35    let parent_node_id = tcx.parent_hir_id(hir_id);
36    let parent_node = tcx.hir_node(parent_node_id);
37
38    let find_sym_fn = |&(op, op_sp)| match op {
39        hir::InlineAsmOperand::SymFn { anon_const } if anon_const.hir_id == hir_id => {
40            Some((anon_const, op_sp))
41        }
42        _ => None,
43    };
44
45    let find_const = |&(op, op_sp)| match op {
46        hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == hir_id => {
47            Some((anon_const, op_sp))
48        }
49        _ => None,
50    };
51
52    match parent_node {
53        // Anon consts "inside" the type system.
54        Node::ConstArg(&ConstArg {
55            hir_id: arg_hir_id,
56            kind: ConstArgKind::Anon(&AnonConst { hir_id: anon_hir_id, .. }),
57            ..
58        }) if anon_hir_id == hir_id => const_arg_anon_type_of(icx, arg_hir_id, span),
59
60        // Anon consts outside the type system.
61        Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. })
62        | Node::Item(&Item { kind: ItemKind::GlobalAsm(asm), .. })
63            if let Some((anon_const, op_sp)) = asm.operands.iter().find_map(find_sym_fn) =>
64        {
65            let ty = tcx.typeck(def_id).node_type(hir_id);
66
67            match ty.kind() {
68                ty::Error(_) => ty,
69                ty::FnDef(..) => ty,
70                _ => {
71                    let guar = tcx
72                        .dcx()
73                        .struct_span_err(op_sp, "invalid `sym` operand")
74                        .with_span_label(
75                            tcx.def_span(anon_const.def_id),
76                            format!("is {} `{}`", ty.kind().article(), ty),
77                        )
78                        .with_help("`sym` operands must refer to either a function or a static")
79                        .emit();
80
81                    Ty::new_error(tcx, guar)
82                }
83            }
84        }
85        Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. })
86        | Node::Item(&Item { kind: ItemKind::GlobalAsm(asm), .. })
87            if let Some((anon_const, op_sp)) = asm.operands.iter().find_map(find_const) =>
88        {
89            let ty = tcx.typeck(def_id).node_type(hir_id);
90
91            match ty.kind() {
92                ty::Error(_) => ty,
93                ty::Int(_) | ty::Uint(_) => ty,
94                _ => {
95                    let guar = tcx
96                        .dcx()
97                        .struct_span_err(op_sp, "invalid type for `const` operand")
98                        .with_span_label(
99                            tcx.def_span(anon_const.def_id),
100                            format!("is {} `{}`", ty.kind().article(), ty),
101                        )
102                        .with_help("`const` operands must be of an integer type")
103                        .emit();
104
105                    Ty::new_error(tcx, guar)
106                }
107            }
108        }
109        Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => {
110            tcx.adt_def(tcx.hir().get_parent_item(hir_id)).repr().discr_type().to_ty(tcx)
111        }
112        // Sort of affects the type system, but only for the purpose of diagnostics
113        // so no need for ConstArg.
114        Node::Ty(&hir::Ty { kind: TyKind::Typeof(ref e), span, .. }) if e.hir_id == hir_id => {
115            let ty = tcx.typeck(def_id).node_type(tcx.local_def_id_to_hir_id(def_id));
116            let ty = fold_regions(tcx, ty, |r, _| {
117                if r.is_erased() { ty::Region::new_error_misc(tcx) } else { r }
118            });
119            let (ty, opt_sugg) = if let Some(ty) = ty.make_suggestable(tcx, false, None) {
120                (ty, Some((span, Applicability::MachineApplicable)))
121            } else {
122                (ty, None)
123            };
124            tcx.dcx().emit_err(TypeofReservedKeywordUsed { span, ty, opt_sugg });
125            return ty;
126        }
127
128        Node::Field(&hir::FieldDef { default: Some(c), def_id: field_def_id, .. })
129            if c.hir_id == hir_id =>
130        {
131            tcx.type_of(field_def_id).instantiate_identity()
132        }
133
134        _ => Ty::new_error_with_message(
135            tcx,
136            span,
137            format!("unexpected anon const parent in type_of(): {parent_node:?}"),
138        ),
139    }
140}
141
142fn const_arg_anon_type_of<'tcx>(icx: &ItemCtxt<'tcx>, arg_hir_id: HirId, span: Span) -> Ty<'tcx> {
143    use hir::*;
144    use rustc_middle::ty::Ty;
145
146    let tcx = icx.tcx;
147
148    match tcx.parent_hir_node(arg_hir_id) {
149        // Array length const arguments do not have `type_of` fed as there is never a corresponding
150        // generic parameter definition.
151        Node::Ty(&hir::Ty { kind: TyKind::Array(_, ref constant), .. })
152        | Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
153            if constant.hir_id == arg_hir_id =>
154        {
155            tcx.types.usize
156        }
157
158        Node::TyPat(pat) => {
159            let hir::TyKind::Pat(ty, p) = tcx.parent_hir_node(pat.hir_id).expect_ty().kind else {
160                bug!()
161            };
162            assert_eq!(p.hir_id, pat.hir_id);
163            icx.lower_ty(ty)
164        }
165
166        // This is not a `bug!` as const arguments in path segments that did not resolve to anything
167        // will result in `type_of` never being fed.
168        _ => Ty::new_error_with_message(
169            tcx,
170            span,
171            "`type_of` called on const argument's anon const before the const argument was lowered",
172        ),
173    }
174}
175
176pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_, Ty<'_>> {
177    use rustc_hir::*;
178    use rustc_middle::ty::Ty;
179
180    // If we are computing `type_of` the synthesized associated type for an RPITIT in the impl
181    // side, use `collect_return_position_impl_trait_in_trait_tys` to infer the value of the
182    // associated type in the impl.
183    match tcx.opt_rpitit_info(def_id.to_def_id()) {
184        Some(ty::ImplTraitInTraitData::Impl { fn_def_id }) => {
185            match tcx.collect_return_position_impl_trait_in_trait_tys(fn_def_id) {
186                Ok(map) => {
187                    let assoc_item = tcx.associated_item(def_id);
188                    return map[&assoc_item.trait_item_def_id.unwrap()];
189                }
190                Err(_) => {
191                    return ty::EarlyBinder::bind(Ty::new_error_with_message(
192                        tcx,
193                        DUMMY_SP,
194                        "Could not collect return position impl trait in trait tys",
195                    ));
196                }
197            }
198        }
199        // For an RPITIT in a trait, just return the corresponding opaque.
200        Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
201            return ty::EarlyBinder::bind(Ty::new_opaque(
202                tcx,
203                opaque_def_id,
204                ty::GenericArgs::identity_for_item(tcx, opaque_def_id),
205            ));
206        }
207        None => {}
208    }
209
210    let hir_id = tcx.local_def_id_to_hir_id(def_id);
211
212    let icx = ItemCtxt::new(tcx, def_id);
213
214    let output = match tcx.hir_node(hir_id) {
215        Node::TraitItem(item) => match item.kind {
216            TraitItemKind::Fn(..) => {
217                let args = ty::GenericArgs::identity_for_item(tcx, def_id);
218                Ty::new_fn_def(tcx, def_id.to_def_id(), args)
219            }
220            TraitItemKind::Const(ty, body_id) => body_id
221                .and_then(|body_id| {
222                    ty.is_suggestable_infer_ty().then(|| {
223                        infer_placeholder_type(
224                            icx.lowerer(),
225                            def_id,
226                            body_id,
227                            ty.span,
228                            item.ident,
229                            "associated constant",
230                        )
231                    })
232                })
233                .unwrap_or_else(|| icx.lower_ty(ty)),
234            TraitItemKind::Type(_, Some(ty)) => icx.lower_ty(ty),
235            TraitItemKind::Type(_, None) => {
236                span_bug!(item.span, "associated type missing default");
237            }
238        },
239
240        Node::ImplItem(item) => match item.kind {
241            ImplItemKind::Fn(..) => {
242                let args = ty::GenericArgs::identity_for_item(tcx, def_id);
243                Ty::new_fn_def(tcx, def_id.to_def_id(), args)
244            }
245            ImplItemKind::Const(ty, body_id) => {
246                if ty.is_suggestable_infer_ty() {
247                    infer_placeholder_type(
248                        icx.lowerer(),
249                        def_id,
250                        body_id,
251                        ty.span,
252                        item.ident,
253                        "associated constant",
254                    )
255                } else {
256                    icx.lower_ty(ty)
257                }
258            }
259            ImplItemKind::Type(ty) => {
260                if tcx.impl_trait_ref(tcx.hir().get_parent_item(hir_id)).is_none() {
261                    check_feature_inherent_assoc_ty(tcx, item.span);
262                }
263
264                icx.lower_ty(ty)
265            }
266        },
267
268        Node::Item(item) => match item.kind {
269            ItemKind::Static(ty, .., body_id) => {
270                if ty.is_suggestable_infer_ty() {
271                    infer_placeholder_type(
272                        icx.lowerer(),
273                        def_id,
274                        body_id,
275                        ty.span,
276                        item.ident,
277                        "static variable",
278                    )
279                } else {
280                    icx.lower_ty(ty)
281                }
282            }
283            ItemKind::Const(ty, _, body_id) => {
284                if ty.is_suggestable_infer_ty() {
285                    infer_placeholder_type(
286                        icx.lowerer(),
287                        def_id,
288                        body_id,
289                        ty.span,
290                        item.ident,
291                        "constant",
292                    )
293                } else {
294                    icx.lower_ty(ty)
295                }
296            }
297            ItemKind::TyAlias(self_ty, _) => icx.lower_ty(self_ty),
298            ItemKind::Impl(hir::Impl { self_ty, .. }) => match self_ty.find_self_aliases() {
299                spans if spans.len() > 0 => {
300                    let guar = tcx
301                        .dcx()
302                        .emit_err(crate::errors::SelfInImplSelf { span: spans.into(), note: () });
303                    Ty::new_error(tcx, guar)
304                }
305                _ => icx.lower_ty(*self_ty),
306            },
307            ItemKind::Fn { .. } => {
308                let args = ty::GenericArgs::identity_for_item(tcx, def_id);
309                Ty::new_fn_def(tcx, def_id.to_def_id(), args)
310            }
311            ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
312                let def = tcx.adt_def(def_id);
313                let args = ty::GenericArgs::identity_for_item(tcx, def_id);
314                Ty::new_adt(tcx, def, args)
315            }
316            ItemKind::Trait(..)
317            | ItemKind::TraitAlias(..)
318            | ItemKind::Macro(..)
319            | ItemKind::Mod(..)
320            | ItemKind::ForeignMod { .. }
321            | ItemKind::GlobalAsm(..)
322            | ItemKind::ExternCrate(..)
323            | ItemKind::Use(..) => {
324                span_bug!(item.span, "compute_type_of_item: unexpected item type: {:?}", item.kind);
325            }
326        },
327
328        Node::OpaqueTy(..) => tcx.type_of_opaque(def_id).map_or_else(
329            |CyclePlaceholder(guar)| Ty::new_error(tcx, guar),
330            |ty| ty.instantiate_identity(),
331        ),
332
333        Node::ForeignItem(foreign_item) => match foreign_item.kind {
334            ForeignItemKind::Fn(..) => {
335                let args = ty::GenericArgs::identity_for_item(tcx, def_id);
336                Ty::new_fn_def(tcx, def_id.to_def_id(), args)
337            }
338            ForeignItemKind::Static(t, _, _) => icx.lower_ty(t),
339            ForeignItemKind::Type => Ty::new_foreign(tcx, def_id.to_def_id()),
340        },
341
342        Node::Ctor(def) | Node::Variant(Variant { data: def, .. }) => match def {
343            VariantData::Unit(..) | VariantData::Struct { .. } => {
344                tcx.type_of(tcx.hir().get_parent_item(hir_id)).instantiate_identity()
345            }
346            VariantData::Tuple(_, _, ctor) => {
347                let args = ty::GenericArgs::identity_for_item(tcx, def_id);
348                Ty::new_fn_def(tcx, ctor.to_def_id(), args)
349            }
350        },
351
352        Node::Field(field) => icx.lower_ty(field.ty),
353
354        Node::Expr(&Expr { kind: ExprKind::Closure { .. }, .. }) => {
355            tcx.typeck(def_id).node_type(hir_id)
356        }
357
358        Node::AnonConst(_) => anon_const_type_of(&icx, def_id),
359
360        Node::ConstBlock(_) => {
361            let args = ty::GenericArgs::identity_for_item(tcx, def_id.to_def_id());
362            args.as_inline_const().ty()
363        }
364
365        Node::GenericParam(param) => match &param.kind {
366            GenericParamKind::Type { default: Some(ty), .. }
367            | GenericParamKind::Const { ty, .. } => icx.lower_ty(ty),
368            x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
369        },
370
371        x => {
372            bug!("unexpected sort of node in type_of(): {:?}", x);
373        }
374    };
375    if let Err(e) = icx.check_tainted_by_errors()
376        && !output.references_error()
377    {
378        ty::EarlyBinder::bind(Ty::new_error(tcx, e))
379    } else {
380        ty::EarlyBinder::bind(output)
381    }
382}
383
384pub(super) fn type_of_opaque(
385    tcx: TyCtxt<'_>,
386    def_id: DefId,
387) -> Result<ty::EarlyBinder<'_, Ty<'_>>, CyclePlaceholder> {
388    if let Some(def_id) = def_id.as_local() {
389        Ok(ty::EarlyBinder::bind(match tcx.hir_node_by_def_id(def_id).expect_opaque_ty().origin {
390            hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
391                opaque::find_opaque_ty_constraints_for_tait(tcx, def_id)
392            }
393            hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: true, .. } => {
394                opaque::find_opaque_ty_constraints_for_impl_trait_in_assoc_type(tcx, def_id)
395            }
396            // Opaque types desugared from `impl Trait`.
397            hir::OpaqueTyOrigin::FnReturn { parent: owner, in_trait_or_impl }
398            | hir::OpaqueTyOrigin::AsyncFn { parent: owner, in_trait_or_impl } => {
399                if in_trait_or_impl == Some(hir::RpitContext::Trait)
400                    && !tcx.defaultness(owner).has_value()
401                {
402                    span_bug!(
403                        tcx.def_span(def_id),
404                        "tried to get type of this RPITIT with no definition"
405                    );
406                }
407                opaque::find_opaque_ty_constraints_for_rpit(tcx, def_id, owner)
408            }
409        }))
410    } else {
411        // Foreign opaque type will go through the foreign provider
412        // and load the type from metadata.
413        Ok(tcx.type_of(def_id))
414    }
415}
416
417fn infer_placeholder_type<'tcx>(
418    cx: &dyn HirTyLowerer<'tcx>,
419    def_id: LocalDefId,
420    body_id: hir::BodyId,
421    span: Span,
422    item_ident: Ident,
423    kind: &'static str,
424) -> Ty<'tcx> {
425    let tcx = cx.tcx();
426    let ty = tcx.typeck(def_id).node_type(body_id.hir_id);
427
428    // If this came from a free `const` or `static mut?` item,
429    // then the user may have written e.g. `const A = 42;`.
430    // In this case, the parser has stashed a diagnostic for
431    // us to improve in typeck so we do that now.
432    let guar = cx
433        .dcx()
434        .try_steal_modify_and_emit_err(span, StashKey::ItemNoType, |err| {
435            if !ty.references_error() {
436                // Only suggest adding `:` if it was missing (and suggested by parsing diagnostic).
437                let colon = if span == item_ident.span.shrink_to_hi() { ":" } else { "" };
438
439                // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
440                // We are typeck and have the real type, so remove that and suggest the actual type.
441                if let Suggestions::Enabled(suggestions) = &mut err.suggestions {
442                    suggestions.clear();
443                }
444
445                if let Some(ty) = ty.make_suggestable(tcx, false, None) {
446                    err.span_suggestion(
447                        span,
448                        format!("provide a type for the {kind}"),
449                        format!("{colon} {ty}"),
450                        Applicability::MachineApplicable,
451                    );
452                } else {
453                    with_forced_trimmed_paths!(err.span_note(
454                        tcx.hir().body(body_id).value.span,
455                        format!("however, the inferred type `{ty}` cannot be named"),
456                    ));
457                }
458            }
459        })
460        .unwrap_or_else(|| {
461            let mut visitor = HirPlaceholderCollector::default();
462            let node = tcx.hir_node_by_def_id(def_id);
463            if let Some(ty) = node.ty() {
464                visitor.visit_ty_unambig(ty);
465            }
466            // If we have just one span, let's try to steal a const `_` feature error.
467            let try_steal_span = if !tcx.features().generic_arg_infer() && visitor.spans.len() == 1
468            {
469                visitor.spans.first().copied()
470            } else {
471                None
472            };
473            // If we didn't find any infer tys, then just fallback to `span`.
474            if visitor.spans.is_empty() {
475                visitor.spans.push(span);
476            }
477            let mut diag = bad_placeholder(cx, visitor.spans, kind);
478
479            // HACK(#69396): Stashing and stealing diagnostics does not interact
480            // well with macros which may delay more than one diagnostic on the
481            // same span. If this happens, we will fall through to this arm, so
482            // we need to suppress the suggestion since it's invalid. Ideally we
483            // would suppress the duplicated error too, but that's really hard.
484            if span.is_empty() && span.from_expansion() {
485                // An approximately better primary message + no suggestion...
486                diag.primary_message("missing type for item");
487            } else if !ty.references_error() {
488                if let Some(ty) = ty.make_suggestable(tcx, false, None) {
489                    diag.span_suggestion_verbose(
490                        span,
491                        "replace this with a fully-specified type",
492                        ty,
493                        Applicability::MachineApplicable,
494                    );
495                } else {
496                    with_forced_trimmed_paths!(diag.span_note(
497                        tcx.hir().body(body_id).value.span,
498                        format!("however, the inferred type `{ty}` cannot be named"),
499                    ));
500                }
501            }
502
503            if let Some(try_steal_span) = try_steal_span {
504                cx.dcx().try_steal_replace_and_emit_err(
505                    try_steal_span,
506                    StashKey::UnderscoreForArrayLengths,
507                    diag,
508                )
509            } else {
510                diag.emit()
511            }
512        });
513    Ty::new_error(tcx, guar)
514}
515
516fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) {
517    if !tcx.features().inherent_associated_types() {
518        use rustc_session::parse::feature_err;
519        use rustc_span::sym;
520        feature_err(
521            &tcx.sess,
522            sym::inherent_associated_types,
523            span,
524            "inherent associated types are unstable",
525        )
526        .emit();
527    }
528}
529
530pub(crate) fn type_alias_is_lazy<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> bool {
531    use hir::intravisit::Visitor;
532    if tcx.features().lazy_type_alias() {
533        return true;
534    }
535    struct HasTait;
536    impl<'tcx> Visitor<'tcx> for HasTait {
537        type Result = ControlFlow<()>;
538        fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
539            if let hir::TyKind::OpaqueDef(..) = t.kind {
540                ControlFlow::Break(())
541            } else {
542                hir::intravisit::walk_ty(self, t)
543            }
544        }
545    }
546    HasTait.visit_ty_unambig(tcx.hir().expect_item(def_id).expect_ty_alias().0).is_break()
547}