Skip to content

Commit af128b0

Browse files
committed
Also compute implicit params in THIR.
1 parent 445841c commit af128b0

File tree

3 files changed

+98
-84
lines changed

3 files changed

+98
-84
lines changed

compiler/rustc_middle/src/thir.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ macro_rules! thir_with_elements {
7373
}
7474
}
7575

76+
pub const UPVAR_ENV_PARAM: ParamId = ParamId::from_u32(0);
77+
7678
thir_with_elements! {
7779
arms: ArmId => Arm<'tcx> => "a{}",
7880
blocks: BlockId => Block => "b{}",
@@ -84,16 +86,16 @@ thir_with_elements! {
8486
/// Description of a type-checked function parameter.
8587
#[derive(Clone, Debug, HashStable)]
8688
pub struct Param<'tcx> {
87-
/// The pattern that appears in the parameter list.
88-
pub pat: Box<Pat<'tcx>>,
89+
/// The pattern that appears in the parameter list, or None for implicit parameters.
90+
pub pat: Option<Box<Pat<'tcx>>>,
8991
/// The possibly inferred type.
9092
pub ty: Ty<'tcx>,
9193
/// Span of the explicitly provided type, or None if inferred for closures.
9294
pub ty_span: Option<Span>,
9395
/// Whether this param is `self`, and how it is bound.
9496
pub self_kind: Option<hir::ImplicitSelfKind>,
9597
/// HirId for lints.
96-
pub hir_id: hir::HirId,
98+
pub hir_id: Option<hir::HirId>,
9799
}
98100

99101
#[derive(Copy, Clone, Debug, HashStable)]

compiler/rustc_mir_build/src/build/mod.rs

Lines changed: 35 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,19 @@ use rustc_data_structures::fx::FxHashMap;
77
use rustc_data_structures::sorted_map::SortedIndexMultiMap;
88
use rustc_errors::ErrorGuaranteed;
99
use rustc_hir as hir;
10+
use rustc_hir::def::DefKind;
1011
use rustc_hir::def_id::{DefId, LocalDefId};
11-
use rustc_hir::{GeneratorKind, ImplicitSelfKind, Node};
12+
use rustc_hir::{GeneratorKind, Node};
1213
use rustc_index::vec::{Idx, IndexVec};
1314
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
1415
use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
1516
use rustc_middle::middle::region;
1617
use rustc_middle::mir::interpret::ConstValue;
1718
use rustc_middle::mir::interpret::Scalar;
1819
use rustc_middle::mir::*;
19-
use rustc_middle::thir::{BindingMode, Expr, ExprId, LintLevel, LocalVarId, Param, PatKind, Thir};
20+
use rustc_middle::thir::{
21+
self, BindingMode, Expr, ExprId, LintLevel, LocalVarId, Param, ParamId, PatKind, Thir,
22+
};
2023
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable, TypeckResults};
2124
use rustc_span::symbol::sym;
2225
use rustc_span::Span;
@@ -97,26 +100,6 @@ fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_
97100
///////////////////////////////////////////////////////////////////////////
98101
// BuildMir -- walks a crate, looking for fn items and methods to build MIR from
99102

100-
fn liberated_closure_env_ty(
101-
tcx: TyCtxt<'_>,
102-
closure_expr_id: hir::HirId,
103-
body_id: hir::BodyId,
104-
) -> Ty<'_> {
105-
let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id);
106-
107-
let ty::Closure(closure_def_id, closure_substs) = *closure_ty.kind() else {
108-
bug!("closure expr does not have closure type: {:?}", closure_ty);
109-
};
110-
111-
let bound_vars =
112-
tcx.mk_bound_variable_kinds(std::iter::once(ty::BoundVariableKind::Region(ty::BrEnv)));
113-
let br =
114-
ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind: ty::BrEnv };
115-
let env_region = ty::ReLateBound(ty::INNERMOST, br);
116-
let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap();
117-
tcx.erase_late_bound_regions(ty::Binder::bind_with_vars(closure_env_ty, bound_vars))
118-
}
119-
120103
#[derive(Debug, PartialEq, Eq)]
121104
enum BlockFrame {
122105
/// Evaluation is currently within a statement.
@@ -446,13 +429,6 @@ macro_rules! unpack {
446429
///////////////////////////////////////////////////////////////////////////
447430
/// the main entry point for building MIR for a function
448431
449-
struct ArgInfo<'thir, 'tcx>(
450-
Ty<'tcx>,
451-
Option<Span>,
452-
Option<&'thir Param<'tcx>>,
453-
Option<ImplicitSelfKind>,
454-
);
455-
456432
fn construct_fn<'tcx>(
457433
tcx: TyCtxt<'tcx>,
458434
fn_def: ty::WithOptConstParam<LocalDefId>,
@@ -483,50 +459,28 @@ fn construct_fn<'tcx>(
483459
hir::Unsafety::Unsafe => Safety::FnUnsafe,
484460
};
485461

486-
let body = tcx.hir().body(body_id);
487-
let ty = tcx.type_of(fn_def.did);
488462
let mut abi = fn_sig.abi;
489-
let implicit_argument = match ty.kind() {
490-
ty::Closure(..) => {
491-
// HACK(eddyb) Avoid having RustCall on closures,
492-
// as it adds unnecessary (and wrong) auto-tupling.
493-
abi = Abi::Rust;
494-
vec![ArgInfo(liberated_closure_env_ty(tcx, fn_id, body_id), None, None, None)]
495-
}
496-
ty::Generator(..) => {
497-
let gen_ty = typeck_results.node_type(fn_id);
498-
499-
// The resume argument may be missing, in that case we need to provide it here.
500-
// It will always be `()` in this case.
501-
if body.params.is_empty() {
502-
vec![ArgInfo(gen_ty, None, None, None), ArgInfo(tcx.mk_unit(), None, None, None)]
503-
} else {
504-
vec![ArgInfo(gen_ty, None, None, None)]
505-
}
506-
}
507-
_ => vec![],
508-
};
509-
510-
let explicit_arguments =
511-
thir.params.iter().map(|arg| ArgInfo(arg.ty, arg.ty_span, Some(&arg), arg.self_kind));
463+
if let DefKind::Closure = tcx.def_kind(fn_def.did) {
464+
// HACK(eddyb) Avoid having RustCall on closures,
465+
// as it adds unnecessary (and wrong) auto-tupling.
466+
abi = Abi::Rust;
467+
}
512468

513-
let arguments = implicit_argument.into_iter().chain(explicit_arguments);
469+
let arguments = &thir.params;
514470

515471
let (yield_ty, return_ty) = if generator_kind.is_some() {
516-
let gen_ty = typeck_results.node_type(fn_id);
472+
let gen_ty = arguments[thir::UPVAR_ENV_PARAM].ty;
517473
let gen_sig = match gen_ty.kind() {
518474
ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
519475
_ => {
520-
span_bug!(span, "generator w/o generator type: {:?}", ty)
476+
span_bug!(span, "generator w/o generator type: {:?}", gen_ty)
521477
}
522478
};
523479
(Some(gen_sig.yield_ty), gen_sig.return_ty)
524480
} else {
525481
(None, fn_sig.output())
526482
};
527483

528-
let arguments: Vec<_> = arguments.collect();
529-
530484
let mut body = tcx.infer_ctxt().enter(|infcx| {
531485
let mut builder = Builder::new(
532486
thir,
@@ -542,9 +496,9 @@ fn construct_fn<'tcx>(
542496
);
543497

544498
let call_site_scope =
545-
region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
499+
region::Scope { id: body_id.hir_id.local_id, data: region::ScopeData::CallSite };
546500
let arg_scope =
547-
region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
501+
region::Scope { id: body_id.hir_id.local_id, data: region::ScopeData::Arguments };
548502
let source_info = builder.source_info(span);
549503
let call_site_s = (call_site_scope, source_info);
550504
unpack!(builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
@@ -560,7 +514,7 @@ fn construct_fn<'tcx>(
560514
builder.args_and_body(
561515
START_BLOCK,
562516
fn_def.did,
563-
&arguments,
517+
arguments,
564518
arg_scope,
565519
&thir[expr],
566520
)
@@ -819,18 +773,19 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
819773
&mut self,
820774
mut block: BasicBlock,
821775
fn_def_id: LocalDefId,
822-
arguments: &[ArgInfo<'_, 'tcx>],
776+
arguments: &IndexVec<ParamId, Param<'tcx>>,
823777
argument_scope: region::Scope,
824778
expr: &Expr<'tcx>,
825779
) -> BlockAnd<()> {
826780
// Allocate locals for the function arguments
827-
for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
781+
for param in arguments.iter() {
828782
let source_info =
829-
SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
830-
let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
783+
SourceInfo::outermost(param.pat.as_ref().map_or(self.fn_span, |pat| pat.span));
784+
let arg_local =
785+
self.local_decls.push(LocalDecl::with_source_info(param.ty, source_info));
831786

832787
// If this is a simple binding pattern, give debuginfo a nice name.
833-
if let Some(arg) = arg_opt && let Some(name) = arg.pat.simple_ident() {
788+
if let Some(ref pat) = param.pat && let Some(name) = pat.simple_ident() {
834789
self.var_debug_info.push(VarDebugInfo {
835790
name,
836791
source_info,
@@ -905,27 +860,28 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
905860

906861
let mut scope = None;
907862
// Bind the argument patterns
908-
for (index, arg_info) in arguments.iter().enumerate() {
863+
for (index, param) in arguments.iter().enumerate() {
909864
// Function arguments always get the first Local indices after the return place
910865
let local = Local::new(index + 1);
911866
let place = Place::from(local);
912-
let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
913867

914868
// Make sure we drop (parts of) the argument even when not matched on.
915869
self.schedule_drop(
916-
arg_opt.as_ref().map_or(expr.span, |arg| arg.pat.span),
870+
param.pat.as_ref().map_or(expr.span, |pat| pat.span),
917871
argument_scope,
918872
local,
919873
DropKind::Value,
920874
);
921875

922-
let Some(arg) = arg_opt else {
876+
let Some(ref pat) = param.pat else {
923877
continue;
924878
};
925879
let original_source_scope = self.source_scope;
926-
let span = arg.pat.span;
927-
self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
928-
match arg.pat.kind {
880+
let span = pat.span;
881+
if let Some(arg_hir_id) = param.hir_id {
882+
self.set_correct_source_scope_for_arg(arg_hir_id, original_source_scope, span);
883+
}
884+
match pat.kind {
929885
// Don't introduce extra copies for simple bindings
930886
PatKind::Binding {
931887
mutability,
@@ -936,16 +892,16 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
936892
} => {
937893
self.local_decls[local].mutability = mutability;
938894
self.local_decls[local].source_info.scope = self.source_scope;
939-
self.local_decls[local].local_info = if let Some(kind) = self_binding {
895+
self.local_decls[local].local_info = if let Some(kind) = param.self_kind {
940896
Some(Box::new(LocalInfo::User(ClearCrossCrate::Set(
941-
BindingForm::ImplicitSelf(*kind),
897+
BindingForm::ImplicitSelf(kind),
942898
))))
943899
} else {
944900
let binding_mode = ty::BindingMode::BindByValue(mutability);
945901
Some(Box::new(LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
946902
VarBindingForm {
947903
binding_mode,
948-
opt_ty_info,
904+
opt_ty_info: param.ty_span,
949905
opt_match_place: Some((None, span)),
950906
pat_span: span,
951907
},
@@ -957,12 +913,12 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
957913
scope = self.declare_bindings(
958914
scope,
959915
expr.span,
960-
&arg.pat,
916+
&pat,
961917
matches::ArmHasGuard(false),
962918
Some((Some(&place), span)),
963919
);
964920
let place_builder = PlaceBuilder::from(local);
965-
unpack!(block = self.place_into_pattern(block, &arg.pat, place_builder, false));
921+
unpack!(block = self.place_into_pattern(block, &pat, place_builder, false));
966922
}
967923
}
968924
self.source_scope = original_source_scope;

compiler/rustc_mir_build/src/thir/cx/mod.rs

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use crate::thir::util::UserAnnotatedTyHelpers;
88
use rustc_data_structures::steal::Steal;
99
use rustc_errors::ErrorGuaranteed;
1010
use rustc_hir as hir;
11+
use rustc_hir::def::DefKind;
1112
use rustc_hir::def_id::{DefId, LocalDefId};
1213
use rustc_hir::lang_items::LangItem;
1314
use rustc_hir::HirId;
@@ -31,8 +32,21 @@ pub(crate) fn thir_body<'tcx>(
3132

3233
let owner_id = hir.local_def_id_to_hir_id(owner_def.did);
3334
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);
3436
let explicit_params = cx.explicit_params(owner_id, fn_decl, body);
35-
cx.thir.params = explicit_params.collect();
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+
}
3650
}
3751

3852
Ok((tcx.alloc_steal_thir(cx.thir), expr))
@@ -94,6 +108,48 @@ impl<'tcx> Cx<'tcx> {
94108
pat_from_hir(self.tcx, self.param_env, self.typeck_results(), p)
95109
}
96110

111+
fn closure_env_param(&self, owner_def: LocalDefId, owner_id: HirId) -> Option<Param<'tcx>> {
112+
match self.tcx.def_kind(owner_def) {
113+
DefKind::Closure => {
114+
let closure_ty = self.typeck_results.node_type(owner_id);
115+
116+
let ty::Closure(closure_def_id, closure_substs) = *closure_ty.kind() else {
117+
bug!("closure expr does not have closure type: {:?}", closure_ty);
118+
};
119+
120+
let bound_vars = self.tcx.mk_bound_variable_kinds(std::iter::once(
121+
ty::BoundVariableKind::Region(ty::BrEnv),
122+
));
123+
let br = ty::BoundRegion {
124+
var: ty::BoundVar::from_usize(bound_vars.len() - 1),
125+
kind: ty::BrEnv,
126+
};
127+
let env_region = ty::ReLateBound(ty::INNERMOST, br);
128+
let closure_env_ty =
129+
self.tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap();
130+
let liberated_closure_env_ty = self.tcx.erase_late_bound_regions(
131+
ty::Binder::bind_with_vars(closure_env_ty, bound_vars),
132+
);
133+
let env_param = Param {
134+
ty: liberated_closure_env_ty,
135+
pat: None,
136+
ty_span: None,
137+
self_kind: None,
138+
hir_id: None,
139+
};
140+
141+
Some(env_param)
142+
}
143+
DefKind::Generator => {
144+
let gen_ty = self.typeck_results.node_type(owner_id);
145+
let gen_param =
146+
Param { ty: gen_ty, pat: None, ty_span: None, self_kind: None, hir_id: None };
147+
Some(gen_param)
148+
}
149+
_ => None,
150+
}
151+
}
152+
97153
fn explicit_params<'a>(
98154
&'a mut self,
99155
owner_id: HirId,
@@ -128,7 +184,7 @@ impl<'tcx> Cx<'tcx> {
128184
};
129185

130186
let pat = self.pattern_from_hir(param.pat);
131-
Param { pat, ty, ty_span, self_kind, hir_id: param.hir_id }
187+
Param { pat: Some(pat), ty, ty_span, self_kind, hir_id: Some(param.hir_id) }
132188
})
133189
}
134190
}

0 commit comments

Comments
 (0)