rustc_mir_build/thir/cx/
mod.rs

1//! This module contains the functionality to convert from the wacky tcx data
2//! structures into the THIR. The `builder` is generally ignorant of the tcx,
3//! etc., and instead goes through the `Cx` for most of its work.
4
5use rustc_data_structures::steal::Steal;
6use rustc_errors::ErrorGuaranteed;
7use rustc_hir::attrs::AttributeKind;
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::{DefId, LocalDefId};
10use rustc_hir::lang_items::LangItem;
11use rustc_hir::{self as hir, HirId, find_attr};
12use rustc_middle::bug;
13use rustc_middle::thir::*;
14use rustc_middle::ty::{self, TyCtxt};
15use tracing::instrument;
16
17use crate::thir::pattern::pat_from_hir;
18
19/// Query implementation for [`TyCtxt::thir_body`].
20pub(crate) fn thir_body(
21    tcx: TyCtxt<'_>,
22    owner_def: LocalDefId,
23) -> Result<(&Steal<Thir<'_>>, ExprId), ErrorGuaranteed> {
24    let body = tcx.hir_body_owned_by(owner_def);
25    let mut cx = ThirBuildCx::new(tcx, owner_def);
26    if let Some(reported) = cx.typeck_results.tainted_by_errors {
27        return Err(reported);
28    }
29
30    // Lower the params before the body's expression so errors from params are shown first.
31    let owner_id = tcx.local_def_id_to_hir_id(owner_def);
32    if let Some(fn_decl) = tcx.hir_fn_decl_by_hir_id(owner_id) {
33        let closure_env_param = cx.closure_env_param(owner_def, owner_id);
34        let explicit_params = cx.explicit_params(owner_id, fn_decl, &body);
35        cx.thir.params = closure_env_param.into_iter().chain(explicit_params).collect();
36
37        // The resume argument may be missing, in that case we need to provide it here.
38        // It will always be `()` in this case.
39        if tcx.is_coroutine(owner_def.to_def_id()) && body.params.is_empty() {
40            cx.thir.params.push(Param {
41                ty: tcx.types.unit,
42                pat: None,
43                ty_span: None,
44                self_kind: None,
45                hir_id: None,
46            });
47        }
48    }
49
50    let expr = cx.mirror_expr(body.value);
51    Ok((tcx.alloc_steal_thir(cx.thir), expr))
52}
53
54/// Context for lowering HIR to THIR for a single function body (or other kind of body).
55struct ThirBuildCx<'tcx> {
56    tcx: TyCtxt<'tcx>,
57    /// The THIR data that this context is building.
58    thir: Thir<'tcx>,
59
60    typing_env: ty::TypingEnv<'tcx>,
61
62    typeck_results: &'tcx ty::TypeckResults<'tcx>,
63
64    /// False to indicate that adjustments should not be applied. Only used for `custom_mir`
65    apply_adjustments: bool,
66
67    /// The `DefId` of the owner of this body.
68    body_owner: DefId,
69}
70
71impl<'tcx> ThirBuildCx<'tcx> {
72    fn new(tcx: TyCtxt<'tcx>, def: LocalDefId) -> Self {
73        let typeck_results = tcx.typeck(def);
74        let hir_id = tcx.local_def_id_to_hir_id(def);
75
76        let body_type = match tcx.hir_body_owner_kind(def) {
77            rustc_hir::BodyOwnerKind::Fn | rustc_hir::BodyOwnerKind::Closure => {
78                // fetch the fully liberated fn signature (that is, all bound
79                // types/lifetimes replaced)
80                BodyTy::Fn(typeck_results.liberated_fn_sigs()[hir_id])
81            }
82            rustc_hir::BodyOwnerKind::Const { .. } | rustc_hir::BodyOwnerKind::Static(_) => {
83                // Get the revealed type of this const. This is *not* the adjusted
84                // type of its body, which may be a subtype of this type. For
85                // example:
86                //
87                // fn foo(_: &()) {}
88                // static X: fn(&'static ()) = foo;
89                //
90                // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
91                // is not the same as the type of X. We need the type of the return
92                // place to be the type of the constant because NLL typeck will
93                // equate them.
94                BodyTy::Const(typeck_results.node_type(hir_id))
95            }
96            rustc_hir::BodyOwnerKind::GlobalAsm => {
97                BodyTy::GlobalAsm(typeck_results.node_type(hir_id))
98            }
99        };
100
101        Self {
102            tcx,
103            thir: Thir::new(body_type),
104            // FIXME(#132279): We're in a body, we should use a typing
105            // mode which reveals the opaque types defined by that body.
106            typing_env: ty::TypingEnv::non_body_analysis(tcx, def),
107            typeck_results,
108            body_owner: def.to_def_id(),
109            apply_adjustments:
110                !find_attr!(tcx.hir_attrs(hir_id), AttributeKind::CustomMir(..) => ()).is_some(),
111        }
112    }
113
114    #[instrument(level = "debug", skip(self))]
115    fn pattern_from_hir(&mut self, p: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
116        pat_from_hir(self.tcx, self.typing_env, self.typeck_results, p)
117    }
118
119    fn closure_env_param(&self, owner_def: LocalDefId, expr_id: HirId) -> Option<Param<'tcx>> {
120        if self.tcx.def_kind(owner_def) != DefKind::Closure {
121            return None;
122        }
123
124        let closure_ty = self.typeck_results.node_type(expr_id);
125        Some(match *closure_ty.kind() {
126            ty::Coroutine(..) => {
127                Param { ty: closure_ty, pat: None, ty_span: None, self_kind: None, hir_id: None }
128            }
129            ty::Closure(_, args) => {
130                let closure_env_ty = self.tcx.closure_env_ty(
131                    closure_ty,
132                    args.as_closure().kind(),
133                    self.tcx.lifetimes.re_erased,
134                );
135                Param {
136                    ty: closure_env_ty,
137                    pat: None,
138                    ty_span: None,
139                    self_kind: None,
140                    hir_id: None,
141                }
142            }
143            ty::CoroutineClosure(_, args) => {
144                let closure_env_ty = self.tcx.closure_env_ty(
145                    closure_ty,
146                    args.as_coroutine_closure().kind(),
147                    self.tcx.lifetimes.re_erased,
148                );
149                Param {
150                    ty: closure_env_ty,
151                    pat: None,
152                    ty_span: None,
153                    self_kind: None,
154                    hir_id: None,
155                }
156            }
157            _ => bug!("unexpected closure type: {closure_ty}"),
158        })
159    }
160
161    fn explicit_params(
162        &mut self,
163        owner_id: HirId,
164        fn_decl: &'tcx hir::FnDecl<'tcx>,
165        body: &'tcx hir::Body<'tcx>,
166    ) -> impl Iterator<Item = Param<'tcx>> {
167        let fn_sig = self.typeck_results.liberated_fn_sigs()[owner_id];
168
169        body.params.iter().enumerate().map(move |(index, param)| {
170            let ty_span = fn_decl
171                .inputs
172                .get(index)
173                // Make sure that inferred closure args have no type span
174                .and_then(|ty| if param.pat.span != ty.span { Some(ty.span) } else { None });
175
176            let self_kind = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
177                Some(fn_decl.implicit_self)
178            } else {
179                None
180            };
181
182            // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
183            // (as it's created inside the body itself, not passed in from outside).
184            let ty = if fn_decl.c_variadic && index == fn_decl.inputs.len() {
185                let va_list_did = self.tcx.require_lang_item(LangItem::VaList, param.span);
186
187                self.tcx
188                    .type_of(va_list_did)
189                    .instantiate(self.tcx, &[self.tcx.lifetimes.re_erased.into()])
190            } else {
191                fn_sig.inputs()[index]
192            };
193
194            let pat = self.pattern_from_hir(param.pat);
195            Param { pat: Some(pat), ty, ty_span, self_kind, hir_id: Some(param.hir_id) }
196        })
197    }
198
199    fn user_args_applied_to_ty_of_hir_id(
200        &self,
201        hir_id: HirId,
202    ) -> Option<ty::CanonicalUserType<'tcx>> {
203        crate::thir::util::user_args_applied_to_ty_of_hir_id(self.tcx, self.typeck_results, hir_id)
204    }
205}
206
207mod block;
208mod expr;