Skip to main content

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