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