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