1use std::debug_assert_matches;
6
7use rustc_data_structures::fx::FxHashMap;
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::{DefId, LocalDefId};
10use rustc_hir::{DelegationGenerics, HirId, PathSegment};
11use rustc_middle::ty::{
12 self, EarlyBinder, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt,
13};
14use rustc_span::{ErrorGuaranteed, Span, kw};
15
16use crate::collect::ItemCtxt;
17use crate::errors::DelegationSelfTypeNotSpecified;
18use crate::hir_ty_lowering::HirTyLowerer;
19
20type RemapTable = FxHashMap<u32, u32>;
21
22struct ParamIndexRemapper<'tcx> {
23 tcx: TyCtxt<'tcx>,
24 remap_table: RemapTable,
25}
26
27impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ParamIndexRemapper<'tcx> {
28 fn cx(&self) -> TyCtxt<'tcx> {
29 self.tcx
30 }
31
32 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
33 if !ty.has_param() {
34 return ty;
35 }
36
37 if let ty::Param(param) = ty.kind()
38 && let Some(index) = self.remap_table.get(¶m.index)
39 {
40 return Ty::new_param(self.tcx, *index, param.name);
41 }
42 ty.super_fold_with(self)
43 }
44
45 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
46 if let ty::ReEarlyParam(param) = r.kind()
47 && let Some(index) = self.remap_table.get(¶m.index).copied()
48 {
49 return ty::Region::new_early_param(
50 self.tcx,
51 ty::EarlyParamRegion { index, name: param.name },
52 );
53 }
54 r
55 }
56
57 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
58 if let ty::ConstKind::Param(param) = ct.kind()
59 && let Some(idx) = self.remap_table.get(¶m.index)
60 {
61 let param = ty::ParamConst::new(*idx, param.name);
62 return ty::Const::new_param(self.tcx, param);
63 }
64 ct.super_fold_with(self)
65 }
66}
67
68enum SelfPositionKind {
69 AfterLifetimes(bool ),
70 Zero,
71 None,
72}
73
74fn get_delegation_generics(tcx: TyCtxt<'_>, delegation_id: LocalDefId) -> &DelegationGenerics {
75 tcx.hir_node(tcx.local_def_id_to_hir_id(delegation_id))
76 .fn_sig()
77 .expect("processing delegation")
78 .decl
79 .opt_delegation_generics()
80 .expect("processing delegation")
81}
82
83fn create_self_position_kind(
84 tcx: TyCtxt<'_>,
85 delegation_id: LocalDefId,
86 sig_id: DefId,
87) -> SelfPositionKind {
88 match (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id)) {
89 (FnKind::AssocInherentImpl, FnKind::AssocTrait)
90 | (FnKind::AssocTraitImpl, FnKind::AssocTrait)
91 | (FnKind::AssocTrait, FnKind::AssocTrait)
92 | (FnKind::AssocTrait, FnKind::Free) => SelfPositionKind::Zero,
93
94 (FnKind::Free, FnKind::AssocTrait) => {
95 let propagate_self_ty = get_delegation_generics(tcx, delegation_id).propagate_self_ty;
96 SelfPositionKind::AfterLifetimes(propagate_self_ty)
97 }
98
99 _ => SelfPositionKind::None,
100 }
101}
102
103#[derive(#[automatically_derived]
impl ::core::clone::Clone for FnKind {
#[inline]
fn clone(&self) -> FnKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for FnKind { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for FnKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
FnKind::Free => "Free",
FnKind::AssocInherentImpl => "AssocInherentImpl",
FnKind::AssocTrait => "AssocTrait",
FnKind::AssocTraitImpl => "AssocTraitImpl",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for FnKind {
#[inline]
fn eq(&self, other: &FnKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
104enum FnKind {
105 Free,
106 AssocInherentImpl,
107 AssocTrait,
108 AssocTraitImpl,
109}
110
111fn fn_kind<'tcx>(tcx: TyCtxt<'tcx>, def_id: impl Into<DefId>) -> FnKind {
112 let def_id = def_id.into();
113
114 if true {
{
match tcx.def_kind(def_id) {
DefKind::Fn | DefKind::AssocFn => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::Fn | DefKind::AssocFn",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn);
115
116 let parent = tcx.parent(def_id);
117 match tcx.def_kind(parent) {
118 DefKind::Trait => FnKind::AssocTrait,
119 DefKind::Impl { of_trait: true } => FnKind::AssocTraitImpl,
120 DefKind::Impl { of_trait: false } => FnKind::AssocInherentImpl,
121 _ => FnKind::Free,
122 }
123}
124
125#[derive(#[automatically_derived]
impl ::core::clone::Clone for InheritanceKind {
#[inline]
fn clone(&self) -> InheritanceKind {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for InheritanceKind { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for InheritanceKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
InheritanceKind::WithParent(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"WithParent", &__self_0),
InheritanceKind::Own =>
::core::fmt::Formatter::write_str(f, "Own"),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for InheritanceKind {
#[inline]
fn eq(&self, other: &InheritanceKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(InheritanceKind::WithParent(__self_0),
InheritanceKind::WithParent(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq)]
128enum InheritanceKind {
129 WithParent(bool),
139 Own,
143}
144
145fn create_mapping<'tcx>(
155 tcx: TyCtxt<'tcx>,
156 sig_id: DefId,
157 def_id: LocalDefId,
158) -> FxHashMap<u32, u32> {
159 let mut mapping: FxHashMap<u32, u32> = Default::default();
160
161 let self_pos_kind = create_self_position_kind(tcx, def_id, sig_id);
162 let is_self_at_zero = #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::Zero => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::Zero);
163
164 if is_self_at_zero {
166 mapping.insert(0, 0);
167 }
168
169 let mut args_index = 0;
170
171 args_index += is_self_at_zero as usize;
172 args_index += get_delegation_parent_args_count_without_self(tcx, def_id, sig_id);
173
174 let sig_generics = tcx.generics_of(sig_id);
175 let process_sig_parent_generics = #[allow(non_exhaustive_omitted_patterns)] match fn_kind(tcx, sig_id) {
FnKind::AssocTrait => true,
_ => false,
}matches!(fn_kind(tcx, sig_id), FnKind::AssocTrait);
176
177 if process_sig_parent_generics {
178 for i in (sig_generics.has_self as usize)..sig_generics.parent_count {
179 let param = sig_generics.param_at(i, tcx);
180 if !param.kind.is_ty_or_const() {
181 mapping.insert(param.index, args_index as u32);
182 args_index += 1;
183 }
184 }
185 }
186
187 for param in &sig_generics.own_params {
188 if !param.kind.is_ty_or_const() {
189 mapping.insert(param.index, args_index as u32);
190 args_index += 1;
191 }
192 }
193
194 if #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::AfterLifetimes { .. } => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::AfterLifetimes { .. }) {
198 mapping.insert(0, args_index as u32);
199 args_index += 1;
200 }
201
202 if process_sig_parent_generics {
203 for i in (sig_generics.has_self as usize)..sig_generics.parent_count {
204 let param = sig_generics.param_at(i, tcx);
205 if param.kind.is_ty_or_const() {
206 mapping.insert(param.index, args_index as u32);
207 args_index += 1;
208 }
209 }
210 }
211
212 for param in &sig_generics.own_params {
213 if param.kind.is_ty_or_const() {
214 mapping.insert(param.index, args_index as u32);
215 args_index += 1;
216 }
217 }
218
219 mapping
220}
221
222fn get_delegation_parent_args_count_without_self<'tcx>(
223 tcx: TyCtxt<'tcx>,
224 delegation_id: LocalDefId,
225 sig_id: DefId,
226) -> usize {
227 let delegation_parent_args_count = tcx.generics_of(delegation_id).parent_count;
228
229 match (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id)) {
230 (FnKind::Free, FnKind::Free)
231 | (FnKind::Free, FnKind::AssocTrait)
232 | (FnKind::AssocTraitImpl, FnKind::AssocTrait) => 0,
233
234 (FnKind::AssocInherentImpl, FnKind::Free)
235 | (FnKind::AssocInherentImpl, FnKind::AssocTrait) => {
236 delegation_parent_args_count }
238
239 (FnKind::AssocTrait, FnKind::Free) | (FnKind::AssocTrait, FnKind::AssocTrait) => {
240 delegation_parent_args_count - 1 }
242
243 (FnKind::AssocTraitImpl, _)
246 | (_, FnKind::AssocTraitImpl)
247 | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
248 }
249}
250
251fn get_parent_and_inheritance_kind<'tcx>(
252 tcx: TyCtxt<'tcx>,
253 def_id: LocalDefId,
254 sig_id: DefId,
255) -> (Option<DefId>, InheritanceKind) {
256 match (fn_kind(tcx, def_id), fn_kind(tcx, sig_id)) {
257 (FnKind::Free, FnKind::Free) | (FnKind::Free, FnKind::AssocTrait) => {
258 (None, InheritanceKind::WithParent(true))
259 }
260
261 (FnKind::AssocTraitImpl, FnKind::AssocTrait) => {
262 (Some(tcx.parent(def_id.to_def_id())), InheritanceKind::Own)
263 }
264
265 (FnKind::AssocInherentImpl, FnKind::AssocTrait)
266 | (FnKind::AssocTrait, FnKind::AssocTrait)
267 | (FnKind::AssocInherentImpl, FnKind::Free)
268 | (FnKind::AssocTrait, FnKind::Free) => {
269 (Some(tcx.parent(def_id.to_def_id())), InheritanceKind::WithParent(false))
270 }
271
272 (FnKind::AssocTraitImpl, _)
275 | (_, FnKind::AssocTraitImpl)
276 | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
277 }
278}
279
280fn get_delegation_self_ty_or_err(tcx: TyCtxt<'_>, delegation_id: LocalDefId) -> Ty<'_> {
281 get_delegation_generics(tcx, delegation_id)
282 .self_ty_id
283 .map(|id| {
284 let ctx = ItemCtxt::new(tcx, delegation_id);
285 ctx.lower_ty(tcx.hir_node(id).expect_ty())
286 })
287 .unwrap_or_else(|| {
288 let err = DelegationSelfTypeNotSpecified { span: tcx.def_span(delegation_id) };
292 tcx.dcx().emit_err(err);
293
294 Ty::new_error_with_message(
295 tcx,
296 tcx.def_span(delegation_id),
297 "the self type must be specified",
298 )
299 })
300}
301
302fn get_delegation_self_ty<'tcx>(tcx: TyCtxt<'tcx>, delegation_id: LocalDefId) -> Option<Ty<'tcx>> {
303 let sig_id = tcx.hir_opt_delegation_sig_id(delegation_id).expect("Delegation must have sig_id");
304 let (caller_kind, callee_kind) = (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id));
305
306 match (caller_kind, callee_kind) {
307 (FnKind::Free, FnKind::AssocTrait)
308 | (FnKind::AssocInherentImpl, FnKind::Free)
309 | (FnKind::Free, FnKind::Free)
310 | (FnKind::AssocTrait, FnKind::Free)
311 | (FnKind::AssocTrait, FnKind::AssocTrait) => {
312 match create_self_position_kind(tcx, delegation_id, sig_id) {
313 SelfPositionKind::None => None,
314 SelfPositionKind::AfterLifetimes(propagate_self_ty) => {
315 if propagate_self_ty {
316 Some(get_delegation_self_ty_or_err(tcx, delegation_id))
317 } else {
318 let index = tcx.generics_of(delegation_id).own_counts().lifetimes;
320 Some(Ty::new_param(tcx, index as u32, kw::SelfUpper))
321 }
322 }
323 SelfPositionKind::Zero => Some(Ty::new_param(tcx, 0, kw::SelfUpper)),
324 }
325 }
326
327 (FnKind::AssocTraitImpl, FnKind::AssocTrait)
328 | (FnKind::AssocInherentImpl, FnKind::AssocTrait) => Some(
329 tcx.type_of(tcx.local_parent(delegation_id)).instantiate_identity().skip_norm_wip(),
330 ),
331
332 (FnKind::AssocTraitImpl, _)
335 | (_, FnKind::AssocTraitImpl)
336 | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
337 }
338}
339
340fn create_generic_args<'tcx>(
356 tcx: TyCtxt<'tcx>,
357 sig_id: DefId,
358 delegation_id: LocalDefId,
359 mut parent_args: &[ty::GenericArg<'tcx>],
360 child_args: &[ty::GenericArg<'tcx>],
361) -> Vec<ty::GenericArg<'tcx>> {
362 let (caller_kind, callee_kind) = (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id));
363
364 let delegation_args = ty::GenericArgs::identity_for_item(tcx, delegation_id);
365
366 let deleg_parent_args_without_self_count =
367 get_delegation_parent_args_count_without_self(tcx, delegation_id, sig_id);
368
369 let delegation_generics = tcx.generics_of(delegation_id);
370 let real_args_count = delegation_args.len() - delegation_generics.own_synthetic_params_count();
371 let synth_args = &delegation_args[real_args_count..];
372 let delegation_args = &delegation_args[..real_args_count];
373
374 let args = match (caller_kind, callee_kind) {
375 (FnKind::Free, FnKind::Free)
376 | (FnKind::Free, FnKind::AssocTrait)
377 | (FnKind::AssocInherentImpl, FnKind::Free)
378 | (FnKind::AssocTrait, FnKind::Free)
379 | (FnKind::AssocTrait, FnKind::AssocTrait) => delegation_args,
380
381 (FnKind::AssocTraitImpl, FnKind::AssocTrait) => {
382 let parent = tcx.local_parent(delegation_id);
386 parent_args =
387 tcx.impl_trait_header(parent).trait_ref.instantiate_identity().skip_norm_wip().args;
388
389 if !child_args.is_empty() {
{
::core::panicking::panic_fmt(format_args!("Child args can not be used in trait impl case"));
}
};assert!(child_args.is_empty(), "Child args can not be used in trait impl case");
390
391 tcx.mk_args(&delegation_args[delegation_generics.parent_count..])
392 }
393
394 (FnKind::AssocInherentImpl, FnKind::AssocTrait) => {
395 let self_ty =
396 tcx.type_of(tcx.local_parent(delegation_id)).instantiate_identity().skip_norm_wip();
397
398 tcx.mk_args_from_iter(
399 std::iter::once(ty::GenericArg::from(self_ty))
400 .chain(delegation_args.iter().copied()),
401 )
402 }
403
404 (FnKind::AssocTraitImpl, _)
407 | (_, FnKind::AssocTraitImpl)
408 | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
409 };
410
411 let mut new_args = ::alloc::vec::Vec::new()vec![];
412
413 let self_pos_kind = create_self_position_kind(tcx, delegation_id, sig_id);
414 let mut lifetimes_end_pos;
415
416 if !parent_args.is_empty() {
417 let parent_args_lifetimes_count =
418 parent_args.iter().filter(|a| a.as_region().is_some()).count();
419
420 match self_pos_kind {
421 SelfPositionKind::AfterLifetimes { .. } => {
422 new_args.extend(&parent_args[1..1 + parent_args_lifetimes_count]);
423
424 lifetimes_end_pos = parent_args_lifetimes_count;
425
426 new_args.push(parent_args[0]);
427
428 new_args.extend(&parent_args[1 + parent_args_lifetimes_count..]);
429 }
430 SelfPositionKind::Zero => {
431 lifetimes_end_pos = 1 + parent_args_lifetimes_count;
432 new_args.extend_from_slice(parent_args);
433
434 for i in 0..deleg_parent_args_without_self_count {
435 new_args.insert(1 + i, args[1 + i]);
436 }
437
438 lifetimes_end_pos += deleg_parent_args_without_self_count;
439 }
440 SelfPositionKind::None => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
442 };
443 } else {
444 let self_impact = #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::Zero => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::Zero) as usize;
445
446 lifetimes_end_pos = self_impact
447 + deleg_parent_args_without_self_count
448 + &args[self_impact + deleg_parent_args_without_self_count..]
449 .iter()
450 .filter(|a| a.as_region().is_some())
451 .count();
452
453 new_args.extend_from_slice(args);
454
455 if #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::AfterLifetimes(true) => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::AfterLifetimes(true)) {
458 new_args.insert(
459 lifetimes_end_pos,
460 ty::GenericArg::from(get_delegation_self_ty_or_err(tcx, delegation_id)),
461 );
462 }
463 }
464
465 if !child_args.is_empty() {
466 let child_lifetimes_count = child_args.iter().filter(|a| a.as_region().is_some()).count();
467
468 for i in 0..child_lifetimes_count {
469 new_args.insert(lifetimes_end_pos + i, child_args[i]);
470 }
471
472 new_args.extend_from_slice(&child_args[child_lifetimes_count..]);
473 } else if !parent_args.is_empty() {
474 let child_args = &delegation_args[delegation_generics.parent_count..];
475
476 let child_lifetimes_count =
477 child_args.iter().take_while(|a| a.as_region().is_some()).count();
478
479 for i in 0..child_lifetimes_count {
480 new_args.insert(lifetimes_end_pos + i, child_args[i]);
481 }
482
483 let skip_self = #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::AfterLifetimes(false) => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::AfterLifetimes(false));
485 new_args.extend(&child_args[child_lifetimes_count + skip_self as usize..]);
486 }
487
488 new_args.extend(synth_args);
489
490 new_args
491}
492
493pub(crate) fn inherit_predicates_for_delegation_item<'tcx>(
494 tcx: TyCtxt<'tcx>,
495 def_id: LocalDefId,
496 sig_id: DefId,
497) -> ty::GenericPredicates<'tcx> {
498 struct PredicatesCollector<'tcx> {
499 tcx: TyCtxt<'tcx>,
500 preds: Vec<(ty::Clause<'tcx>, Span)>,
501 args: Vec<ty::GenericArg<'tcx>>,
502 folder: ParamIndexRemapper<'tcx>,
503 filter_self_preds: bool,
504 }
505
506 impl<'tcx> PredicatesCollector<'tcx> {
507 fn with_own_preds(
508 mut self,
509 f: impl Fn(DefId) -> ty::GenericPredicates<'tcx>,
510 def_id: DefId,
511 ) -> Self {
512 let preds = f(def_id);
513 let args = self.args.as_slice();
514
515 for pred in preds.predicates {
516 if self.filter_self_preds
519 && let Some(trait_pred) = pred.0.as_trait_clause()
520 && trait_pred.self_ty().skip_binder().is_param(0)
522 {
523 continue;
524 }
525
526 let new_pred = pred.0.fold_with(&mut self.folder);
527 self.preds.push((
528 EarlyBinder::bind(new_pred).instantiate(self.tcx, args).skip_norm_wip(),
529 pred.1,
530 ));
531 }
532
533 self
534 }
535
536 fn with_preds(
537 mut self,
538 f: impl Fn(DefId) -> ty::GenericPredicates<'tcx> + Copy,
539 def_id: DefId,
540 ) -> Self {
541 let preds = f(def_id);
542 if let Some(parent_def_id) = preds.parent {
543 self = self.with_own_preds(f, parent_def_id);
544 }
545
546 self.with_own_preds(f, def_id)
547 }
548 }
549
550 let (parent_args, child_args) = get_delegation_user_specified_args(tcx, def_id);
551 let (folder, args) = create_folder_and_args(tcx, def_id, sig_id, parent_args, child_args);
552 let self_pos_kind = create_self_position_kind(tcx, def_id, sig_id);
553 let filter_self_preds = #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::AfterLifetimes(true) => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::AfterLifetimes(true));
554
555 let collector = PredicatesCollector { tcx, preds: ::alloc::vec::Vec::new()vec![], args, folder, filter_self_preds };
556 let (parent, inh_kind) = get_parent_and_inheritance_kind(tcx, def_id, sig_id);
557
558 let preds = match inh_kind {
562 InheritanceKind::WithParent(false) => {
563 collector.with_preds(|def_id| tcx.explicit_predicates_of(def_id), sig_id)
564 }
565 InheritanceKind::WithParent(true) => {
566 collector.with_preds(|def_id| tcx.predicates_of(def_id), sig_id)
567 }
568 InheritanceKind::Own => {
569 collector.with_own_preds(|def_id| tcx.predicates_of(def_id), sig_id)
570 }
571 }
572 .preds;
573
574 ty::GenericPredicates { parent, predicates: tcx.arena.alloc_from_iter(preds) }
575}
576
577fn create_folder_and_args<'tcx>(
578 tcx: TyCtxt<'tcx>,
579 def_id: LocalDefId,
580 sig_id: DefId,
581 parent_args: &'tcx [ty::GenericArg<'tcx>],
582 child_args: &'tcx [ty::GenericArg<'tcx>],
583) -> (ParamIndexRemapper<'tcx>, Vec<ty::GenericArg<'tcx>>) {
584 let args = create_generic_args(tcx, sig_id, def_id, parent_args, child_args);
585 let remap_table = create_mapping(tcx, sig_id, def_id);
586
587 (ParamIndexRemapper { tcx, remap_table }, args)
588}
589
590fn check_constraints<'tcx>(
591 tcx: TyCtxt<'tcx>,
592 def_id: LocalDefId,
593 sig_id: DefId,
594) -> Result<(), ErrorGuaranteed> {
595 let mut ret = Ok(());
596
597 let mut emit = |descr| {
598 ret = Err(tcx.dcx().emit_err(crate::errors::UnsupportedDelegation {
599 span: tcx.def_span(def_id),
600 descr,
601 callee_span: tcx.def_span(sig_id),
602 }));
603 };
604
605 if tcx.fn_sig(sig_id).skip_binder().skip_binder().c_variadic() {
606 emit("delegation to C-variadic functions is not allowed");
608 }
609
610 ret
611}
612
613pub(crate) fn inherit_sig_for_delegation_item<'tcx>(
614 tcx: TyCtxt<'tcx>,
615 def_id: LocalDefId,
616) -> &'tcx [Ty<'tcx>] {
617 let sig_id = tcx.hir_opt_delegation_sig_id(def_id).expect("Delegation must have sig_id");
618 let caller_sig = tcx.fn_sig(sig_id);
619
620 if let Err(err) = check_constraints(tcx, def_id, sig_id) {
621 let sig_len = caller_sig.instantiate_identity().skip_binder().inputs().len() + 1;
622 let err_type = Ty::new_error(tcx, err);
623 return tcx.arena.alloc_from_iter((0..sig_len).map(|_| err_type));
624 }
625
626 let (parent_args, child_args) = get_delegation_user_specified_args(tcx, def_id);
627 let (mut folder, args) = create_folder_and_args(tcx, def_id, sig_id, parent_args, child_args);
628 let caller_sig = EarlyBinder::bind(caller_sig.skip_binder().fold_with(&mut folder));
629
630 let sig = caller_sig.instantiate(tcx, args.as_slice()).skip_binder();
631 let sig_iter = sig.inputs().iter().cloned().chain(std::iter::once(sig.output()));
632 tcx.arena.alloc_from_iter(sig_iter)
633}
634
635fn get_delegation_user_specified_args<'tcx>(
640 tcx: TyCtxt<'tcx>,
641 delegation_id: LocalDefId,
642) -> (&'tcx [ty::GenericArg<'tcx>], &'tcx [ty::GenericArg<'tcx>]) {
643 let info = get_delegation_generics(tcx, delegation_id);
644
645 let get_segment = |hir_id: HirId| -> Option<(&'tcx PathSegment<'tcx>, DefId)> {
646 let segment = tcx.hir_node(hir_id).expect_path_segment();
647 segment.res.opt_def_id().map(|def_id| (segment, def_id))
648 };
649
650 let ctx = ItemCtxt::new(tcx, delegation_id);
651 let lowerer = ctx.lowerer();
652
653 let parent_args = info.parent_args_segment_id.and_then(get_segment).map(|(segment, def_id)| {
654 let self_ty = get_delegation_self_ty(tcx, delegation_id);
655
656 lowerer
657 .lower_generic_args_of_path(segment.ident.span, def_id, &[], segment, self_ty)
658 .0
659 .as_slice()
660 });
661
662 let child_args = info
663 .child_args_segment_id
664 .and_then(get_segment)
665 .filter(|(_, def_id)| #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(*def_id) {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(tcx.def_kind(*def_id), DefKind::Fn | DefKind::AssocFn))
666 .map(|(segment, def_id)| {
667 let parent_args = if let Some(parent_args) = parent_args {
668 parent_args
669 } else {
670 let parent = tcx.parent(def_id);
671 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(parent) {
DefKind::Trait => true,
_ => false,
}matches!(tcx.def_kind(parent), DefKind::Trait) {
672 ty::GenericArgs::identity_for_item(tcx, parent).as_slice()
673 } else {
674 &[]
675 }
676 };
677
678 let args = lowerer
679 .lower_generic_args_of_path(segment.ident.span, def_id, parent_args, segment, None)
680 .0;
681
682 let synth_params_count = tcx.generics_of(def_id).own_synthetic_params_count();
683 &args[parent_args.len()..args.len() - synth_params_count]
684 });
685
686 (parent_args.unwrap_or_default(), child_args.unwrap_or_default())
687}