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