]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/cx/mod.rs
Auto merge of #107443 - cjgillot:generator-less-query, r=compiler-errors
[rust.git] / compiler / rustc_mir_build / src / 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
5 use crate::thir::pattern::pat_from_hir;
6 use crate::thir::util::UserAnnotatedTyHelpers;
7
8 use rustc_data_structures::steal::Steal;
9 use rustc_errors::ErrorGuaranteed;
10 use rustc_hir as hir;
11 use rustc_hir::def::DefKind;
12 use rustc_hir::def_id::{DefId, LocalDefId};
13 use rustc_hir::lang_items::LangItem;
14 use rustc_hir::HirId;
15 use rustc_hir::Node;
16 use rustc_middle::middle::region;
17 use rustc_middle::thir::*;
18 use rustc_middle::ty::{self, RvalueScopes, TyCtxt};
19 use rustc_span::Span;
20
21 pub(crate) fn thir_body(
22     tcx: TyCtxt<'_>,
23     owner_def: ty::WithOptConstParam<LocalDefId>,
24 ) -> Result<(&Steal<Thir<'_>>, ExprId), ErrorGuaranteed> {
25     let hir = tcx.hir();
26     let body = hir.body(hir.body_owned_by(owner_def.did));
27     let mut cx = Cx::new(tcx, owner_def);
28     if let Some(reported) = cx.typeck_results.tainted_by_errors {
29         return Err(reported);
30     }
31     let expr = cx.mirror_expr(&body.value);
32
33     let owner_id = hir.local_def_id_to_hir_id(owner_def.did);
34     if let Some(ref fn_decl) = hir.fn_decl_by_hir_id(owner_id) {
35         let closure_env_param = cx.closure_env_param(owner_def.did, owner_id);
36         let explicit_params = cx.explicit_params(owner_id, fn_decl, body);
37         cx.thir.params = closure_env_param.into_iter().chain(explicit_params).collect();
38
39         // The resume argument may be missing, in that case we need to provide it here.
40         // It will always be `()` in this case.
41         if tcx.def_kind(owner_def.did) == DefKind::Generator && body.params.is_empty() {
42             cx.thir.params.push(Param {
43                 ty: tcx.mk_unit(),
44                 pat: None,
45                 ty_span: None,
46                 self_kind: None,
47                 hir_id: None,
48             });
49         }
50     }
51
52     Ok((tcx.alloc_steal_thir(cx.thir), expr))
53 }
54
55 pub(crate) fn thir_tree(tcx: TyCtxt<'_>, owner_def: ty::WithOptConstParam<LocalDefId>) -> String {
56     match thir_body(tcx, owner_def) {
57         Ok((thir, _)) => {
58             let thir = thir.steal();
59             tcx.thir_tree_representation(&thir)
60         }
61         Err(_) => "error".into(),
62     }
63 }
64
65 pub(crate) fn thir_flat(tcx: TyCtxt<'_>, owner_def: ty::WithOptConstParam<LocalDefId>) -> String {
66     match thir_body(tcx, owner_def) {
67         Ok((thir, _)) => format!("{:#?}", thir.steal()),
68         Err(_) => "error".into(),
69     }
70 }
71
72 struct Cx<'tcx> {
73     tcx: TyCtxt<'tcx>,
74     thir: Thir<'tcx>,
75
76     param_env: ty::ParamEnv<'tcx>,
77
78     region_scope_tree: &'tcx region::ScopeTree,
79     typeck_results: &'tcx ty::TypeckResults<'tcx>,
80     rvalue_scopes: &'tcx RvalueScopes,
81
82     /// When applying adjustments to the expression
83     /// with the given `HirId`, use the given `Span`,
84     /// instead of the usual span. This is used to
85     /// assign the span of an overall method call
86     /// (e.g. `my_val.foo()`) to the adjustment expressions
87     /// for the receiver.
88     adjustment_span: Option<(HirId, Span)>,
89
90     /// False to indicate that adjustments should not be applied. Only used for `custom_mir`
91     apply_adjustments: bool,
92
93     /// The `DefId` of the owner of this body.
94     body_owner: DefId,
95 }
96
97 impl<'tcx> Cx<'tcx> {
98     fn new(tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>) -> Cx<'tcx> {
99         let typeck_results = tcx.typeck_opt_const_arg(def);
100         let did = def.did;
101         let hir = tcx.hir();
102         Cx {
103             tcx,
104             thir: Thir::new(),
105             param_env: tcx.param_env(def.did),
106             region_scope_tree: tcx.region_scope_tree(def.did),
107             typeck_results,
108             rvalue_scopes: &typeck_results.rvalue_scopes,
109             body_owner: did.to_def_id(),
110             adjustment_span: None,
111             apply_adjustments: hir
112                 .attrs(hir.local_def_id_to_hir_id(did))
113                 .iter()
114                 .all(|attr| attr.name_or_empty() != rustc_span::sym::custom_mir),
115         }
116     }
117
118     #[instrument(level = "debug", skip(self))]
119     fn pattern_from_hir(&mut self, p: &hir::Pat<'_>) -> Box<Pat<'tcx>> {
120         let p = match self.tcx.hir().get(p.hir_id) {
121             Node::Pat(p) => p,
122             node => bug!("pattern became {:?}", node),
123         };
124         pat_from_hir(self.tcx, self.param_env, self.typeck_results(), p)
125     }
126
127     fn closure_env_param(&self, owner_def: LocalDefId, owner_id: HirId) -> Option<Param<'tcx>> {
128         match self.tcx.def_kind(owner_def) {
129             DefKind::Closure => {
130                 let closure_ty = self.typeck_results.node_type(owner_id);
131
132                 let ty::Closure(closure_def_id, closure_substs) = *closure_ty.kind() else {
133                     bug!("closure expr does not have closure type: {:?}", closure_ty);
134                 };
135
136                 let bound_vars = self.tcx.mk_bound_variable_kinds(std::iter::once(
137                     ty::BoundVariableKind::Region(ty::BrEnv),
138                 ));
139                 let br = ty::BoundRegion {
140                     var: ty::BoundVar::from_usize(bound_vars.len() - 1),
141                     kind: ty::BrEnv,
142                 };
143                 let env_region = ty::ReLateBound(ty::INNERMOST, br);
144                 let closure_env_ty =
145                     self.tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap();
146                 let liberated_closure_env_ty = self.tcx.erase_late_bound_regions(
147                     ty::Binder::bind_with_vars(closure_env_ty, bound_vars),
148                 );
149                 let env_param = Param {
150                     ty: liberated_closure_env_ty,
151                     pat: None,
152                     ty_span: None,
153                     self_kind: None,
154                     hir_id: None,
155                 };
156
157                 Some(env_param)
158             }
159             DefKind::Generator => {
160                 let gen_ty = self.typeck_results.node_type(owner_id);
161                 let gen_param =
162                     Param { ty: gen_ty, pat: None, ty_span: None, self_kind: None, hir_id: None };
163                 Some(gen_param)
164             }
165             _ => None,
166         }
167     }
168
169     fn explicit_params<'a>(
170         &'a mut self,
171         owner_id: HirId,
172         fn_decl: &'tcx hir::FnDecl<'tcx>,
173         body: &'tcx hir::Body<'tcx>,
174     ) -> impl Iterator<Item = Param<'tcx>> + 'a {
175         let fn_sig = self.typeck_results.liberated_fn_sigs()[owner_id];
176
177         body.params.iter().enumerate().map(move |(index, param)| {
178             let ty_span = fn_decl
179                 .inputs
180                 .get(index)
181                 // Make sure that inferred closure args have no type span
182                 .and_then(|ty| if param.pat.span != ty.span { Some(ty.span) } else { None });
183
184             let self_kind = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
185                 Some(fn_decl.implicit_self)
186             } else {
187                 None
188             };
189
190             // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
191             // (as it's created inside the body itself, not passed in from outside).
192             let ty = if fn_decl.c_variadic && index == fn_decl.inputs.len() {
193                 let va_list_did = self.tcx.require_lang_item(LangItem::VaList, Some(param.span));
194
195                 self.tcx
196                     .bound_type_of(va_list_did)
197                     .subst(self.tcx, &[self.tcx.lifetimes.re_erased.into()])
198             } else {
199                 fn_sig.inputs()[index]
200             };
201
202             let pat = self.pattern_from_hir(param.pat);
203             Param { pat: Some(pat), ty, ty_span, self_kind, hir_id: Some(param.hir_id) }
204         })
205     }
206 }
207
208 impl<'tcx> UserAnnotatedTyHelpers<'tcx> for Cx<'tcx> {
209     fn tcx(&self) -> TyCtxt<'tcx> {
210         self.tcx
211     }
212
213     fn typeck_results(&self) -> &ty::TypeckResults<'tcx> {
214         self.typeck_results
215     }
216 }
217
218 mod block;
219 mod expr;