]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/cx/mod.rs
Merge commit 'f4850f7292efa33759b4f7f9b7621268979e9914' into clippyup
[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<'tcx>(
22     tcx: TyCtxt<'tcx>,
23     owner_def: ty::WithOptConstParam<LocalDefId>,
24 ) -> Result<(&'tcx Steal<Thir<'tcx>>, 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>(
56     tcx: TyCtxt<'tcx>,
57     owner_def: ty::WithOptConstParam<LocalDefId>,
58 ) -> String {
59     match thir_body(tcx, owner_def) {
60         Ok((thir, _)) => format!("{:#?}", thir.steal()),
61         Err(_) => "error".into(),
62     }
63 }
64
65 struct Cx<'tcx> {
66     tcx: TyCtxt<'tcx>,
67     thir: Thir<'tcx>,
68
69     param_env: ty::ParamEnv<'tcx>,
70
71     region_scope_tree: &'tcx region::ScopeTree,
72     typeck_results: &'tcx ty::TypeckResults<'tcx>,
73     rvalue_scopes: &'tcx RvalueScopes,
74
75     /// When applying adjustments to the expression
76     /// with the given `HirId`, use the given `Span`,
77     /// instead of the usual span. This is used to
78     /// assign the span of an overall method call
79     /// (e.g. `my_val.foo()`) to the adjustment expressions
80     /// for the receiver.
81     adjustment_span: Option<(HirId, Span)>,
82
83     /// False to indicate that adjustments should not be applied. Only used for `custom_mir`
84     apply_adjustments: bool,
85
86     /// The `DefId` of the owner of this body.
87     body_owner: DefId,
88 }
89
90 impl<'tcx> Cx<'tcx> {
91     fn new(tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam<LocalDefId>) -> Cx<'tcx> {
92         let typeck_results = tcx.typeck_opt_const_arg(def);
93         let did = def.did;
94         let hir = tcx.hir();
95         Cx {
96             tcx,
97             thir: Thir::new(),
98             param_env: tcx.param_env(def.did),
99             region_scope_tree: tcx.region_scope_tree(def.did),
100             typeck_results,
101             rvalue_scopes: &typeck_results.rvalue_scopes,
102             body_owner: did.to_def_id(),
103             adjustment_span: None,
104             apply_adjustments: hir
105                 .attrs(hir.local_def_id_to_hir_id(did))
106                 .iter()
107                 .all(|attr| attr.name_or_empty() != rustc_span::sym::custom_mir),
108         }
109     }
110
111     #[instrument(level = "debug", skip(self))]
112     fn pattern_from_hir(&mut self, p: &hir::Pat<'_>) -> Box<Pat<'tcx>> {
113         let p = match self.tcx.hir().get(p.hir_id) {
114             Node::Pat(p) => p,
115             node => bug!("pattern became {:?}", node),
116         };
117         pat_from_hir(self.tcx, self.param_env, self.typeck_results(), p)
118     }
119
120     fn closure_env_param(&self, owner_def: LocalDefId, owner_id: HirId) -> Option<Param<'tcx>> {
121         match self.tcx.def_kind(owner_def) {
122             DefKind::Closure => {
123                 let closure_ty = self.typeck_results.node_type(owner_id);
124
125                 let ty::Closure(closure_def_id, closure_substs) = *closure_ty.kind() else {
126                     bug!("closure expr does not have closure type: {:?}", closure_ty);
127                 };
128
129                 let bound_vars = self.tcx.mk_bound_variable_kinds(std::iter::once(
130                     ty::BoundVariableKind::Region(ty::BrEnv),
131                 ));
132                 let br = ty::BoundRegion {
133                     var: ty::BoundVar::from_usize(bound_vars.len() - 1),
134                     kind: ty::BrEnv,
135                 };
136                 let env_region = ty::ReLateBound(ty::INNERMOST, br);
137                 let closure_env_ty =
138                     self.tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap();
139                 let liberated_closure_env_ty = self.tcx.erase_late_bound_regions(
140                     ty::Binder::bind_with_vars(closure_env_ty, bound_vars),
141                 );
142                 let env_param = Param {
143                     ty: liberated_closure_env_ty,
144                     pat: None,
145                     ty_span: None,
146                     self_kind: None,
147                     hir_id: None,
148                 };
149
150                 Some(env_param)
151             }
152             DefKind::Generator => {
153                 let gen_ty = self.typeck_results.node_type(owner_id);
154                 let gen_param =
155                     Param { ty: gen_ty, pat: None, ty_span: None, self_kind: None, hir_id: None };
156                 Some(gen_param)
157             }
158             _ => None,
159         }
160     }
161
162     fn explicit_params<'a>(
163         &'a mut self,
164         owner_id: HirId,
165         fn_decl: &'tcx hir::FnDecl<'tcx>,
166         body: &'tcx hir::Body<'tcx>,
167     ) -> impl Iterator<Item = Param<'tcx>> + 'a {
168         let fn_sig = self.typeck_results.liberated_fn_sigs()[owner_id];
169
170         body.params.iter().enumerate().map(move |(index, param)| {
171             let ty_span = fn_decl
172                 .inputs
173                 .get(index)
174                 // Make sure that inferred closure args have no type span
175                 .and_then(|ty| if param.pat.span != ty.span { Some(ty.span) } else { None });
176
177             let self_kind = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
178                 Some(fn_decl.implicit_self)
179             } else {
180                 None
181             };
182
183             // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
184             // (as it's created inside the body itself, not passed in from outside).
185             let ty = if fn_decl.c_variadic && index == fn_decl.inputs.len() {
186                 let va_list_did = self.tcx.require_lang_item(LangItem::VaList, Some(param.span));
187
188                 self.tcx
189                     .bound_type_of(va_list_did)
190                     .subst(self.tcx, &[self.tcx.lifetimes.re_erased.into()])
191             } else {
192                 fn_sig.inputs()[index]
193             };
194
195             let pat = self.pattern_from_hir(param.pat);
196             Param { pat: Some(pat), ty, ty_span, self_kind, hir_id: Some(param.hir_id) }
197         })
198     }
199 }
200
201 impl<'tcx> UserAnnotatedTyHelpers<'tcx> for Cx<'tcx> {
202     fn tcx(&self) -> TyCtxt<'tcx> {
203         self.tcx
204     }
205
206     fn typeck_results(&self) -> &ty::TypeckResults<'tcx> {
207         self.typeck_results
208     }
209 }
210
211 mod block;
212 mod expr;