1use std::debug_assert_matches;
6
7use rustc_data_structures::fx::FxHashMap;
8use rustc_hir::PathSegment;
9use rustc_hir::def::DefKind;
10use rustc_hir::def_id::{DefId, LocalDefId};
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::diagnostics::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 create_self_position_kind(
75 tcx: TyCtxt<'_>,
76 delegation_id: LocalDefId,
77 sig_id: DefId,
78) -> SelfPositionKind {
79 match (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id)) {
80 (FnKind::AssocInherentImpl, FnKind::AssocTrait)
81 | (FnKind::AssocTraitImpl, FnKind::AssocTrait)
82 | (FnKind::AssocTrait, FnKind::AssocTrait)
83 | (FnKind::AssocTrait, FnKind::Free) => SelfPositionKind::Zero,
84
85 (FnKind::Free, FnKind::AssocTrait) => {
86 let propagate_self_ty = tcx.hir_delegation_info(delegation_id).propagate_self_ty;
87 SelfPositionKind::AfterLifetimes(propagate_self_ty)
88 }
89
90 _ => SelfPositionKind::None,
91 }
92}
93
94#[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)]
95enum FnKind {
96 Free,
97 AssocInherentImpl,
98 AssocTrait,
99 AssocTraitImpl,
100}
101
102fn fn_kind<'tcx>(tcx: TyCtxt<'tcx>, def_id: impl Into<DefId>) -> FnKind {
103 let def_id = def_id.into();
104
105 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);
106
107 let parent = tcx.parent(def_id);
108 match tcx.def_kind(parent) {
109 DefKind::Trait => FnKind::AssocTrait,
110 DefKind::Impl { of_trait: true } => FnKind::AssocTraitImpl,
111 DefKind::Impl { of_trait: false } => FnKind::AssocInherentImpl,
112 _ => FnKind::Free,
113 }
114}
115
116#[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)]
119enum InheritanceKind {
120 WithParent(bool),
130 Own,
134}
135
136fn create_mapping<'tcx>(
146 tcx: TyCtxt<'tcx>,
147 sig_id: DefId,
148 def_id: LocalDefId,
149) -> FxHashMap<u32, u32> {
150 let mut mapping: FxHashMap<u32, u32> = Default::default();
151
152 let self_pos_kind = create_self_position_kind(tcx, def_id, sig_id);
153 let is_self_at_zero = #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::Zero => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::Zero);
154
155 if is_self_at_zero {
157 mapping.insert(0, 0);
158 }
159
160 let mut args_index = 0;
161
162 args_index += is_self_at_zero as usize;
163 args_index += get_delegation_parent_args_count_without_self(tcx, def_id, sig_id);
164
165 let sig_generics = tcx.generics_of(sig_id);
166 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);
167
168 if process_sig_parent_generics {
169 for i in (sig_generics.has_self as usize)..sig_generics.parent_count {
170 let param = sig_generics.param_at(i, tcx);
171 if !param.kind.is_ty_or_const() {
172 mapping.insert(param.index, args_index as u32);
173 args_index += 1;
174 }
175 }
176 }
177
178 for param in &sig_generics.own_params {
179 if !param.kind.is_ty_or_const() {
180 mapping.insert(param.index, args_index as u32);
181 args_index += 1;
182 }
183 }
184
185 if #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::AfterLifetimes { .. } => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::AfterLifetimes { .. }) {
189 mapping.insert(0, args_index as u32);
190 args_index += 1;
191 }
192
193 if process_sig_parent_generics {
194 for i in (sig_generics.has_self as usize)..sig_generics.parent_count {
195 let param = sig_generics.param_at(i, tcx);
196 if param.kind.is_ty_or_const() {
197 mapping.insert(param.index, args_index as u32);
198 args_index += 1;
199 }
200 }
201 }
202
203 for param in &sig_generics.own_params {
204 if param.kind.is_ty_or_const() {
205 mapping.insert(param.index, args_index as u32);
206 args_index += 1;
207 }
208 }
209
210 mapping
211}
212
213fn get_delegation_parent_args_count_without_self<'tcx>(
214 tcx: TyCtxt<'tcx>,
215 delegation_id: LocalDefId,
216 sig_id: DefId,
217) -> usize {
218 let delegation_parent_args_count = tcx.generics_of(delegation_id).parent_count;
219
220 match (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id)) {
221 (FnKind::Free, FnKind::Free)
222 | (FnKind::Free, FnKind::AssocTrait)
223 | (FnKind::AssocTraitImpl, FnKind::AssocTrait) => 0,
224
225 (FnKind::AssocInherentImpl, FnKind::Free)
226 | (FnKind::AssocInherentImpl, FnKind::AssocTrait) => {
227 delegation_parent_args_count }
229
230 (FnKind::AssocTrait, FnKind::Free) | (FnKind::AssocTrait, FnKind::AssocTrait) => {
231 delegation_parent_args_count - 1 }
233
234 (FnKind::AssocTraitImpl, _)
237 | (_, FnKind::AssocTraitImpl)
238 | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
239 }
240}
241
242fn get_parent_and_inheritance_kind<'tcx>(
243 tcx: TyCtxt<'tcx>,
244 def_id: LocalDefId,
245 sig_id: DefId,
246) -> (Option<DefId>, InheritanceKind) {
247 match (fn_kind(tcx, def_id), fn_kind(tcx, sig_id)) {
248 (FnKind::Free, FnKind::Free) | (FnKind::Free, FnKind::AssocTrait) => {
249 (None, InheritanceKind::WithParent(true))
250 }
251
252 (FnKind::AssocTraitImpl, FnKind::AssocTrait) => {
253 (Some(tcx.parent(def_id.to_def_id())), InheritanceKind::Own)
254 }
255
256 (FnKind::AssocInherentImpl, FnKind::AssocTrait)
257 | (FnKind::AssocTrait, FnKind::AssocTrait)
258 | (FnKind::AssocInherentImpl, FnKind::Free)
259 | (FnKind::AssocTrait, FnKind::Free) => {
260 (Some(tcx.parent(def_id.to_def_id())), InheritanceKind::WithParent(false))
261 }
262
263 (FnKind::AssocTraitImpl, _)
266 | (_, FnKind::AssocTraitImpl)
267 | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
268 }
269}
270
271fn get_delegation_self_ty_or_err(tcx: TyCtxt<'_>, delegation_id: LocalDefId) -> Ty<'_> {
272 tcx.hir_delegation_info(delegation_id)
273 .self_ty_id
274 .map(|id| {
275 let ctx = ItemCtxt::new(tcx, delegation_id);
276 ctx.lower_ty(tcx.hir_node(id).expect_ty())
277 })
278 .unwrap_or_else(|| {
279 let err = DelegationSelfTypeNotSpecified { span: tcx.def_span(delegation_id) };
283 tcx.dcx().emit_err(err);
284
285 Ty::new_error_with_message(
286 tcx,
287 tcx.def_span(delegation_id),
288 "the self type must be specified",
289 )
290 })
291}
292
293fn get_delegation_self_ty<'tcx>(tcx: TyCtxt<'tcx>, delegation_id: LocalDefId) -> Option<Ty<'tcx>> {
294 let sig_id = tcx.hir_opt_delegation_sig_id(delegation_id).expect("Delegation must have sig_id");
295 let (caller_kind, callee_kind) = (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id));
296
297 match (caller_kind, callee_kind) {
298 (FnKind::Free, FnKind::AssocTrait)
299 | (FnKind::AssocInherentImpl, FnKind::Free)
300 | (FnKind::Free, FnKind::Free)
301 | (FnKind::AssocTrait, FnKind::Free)
302 | (FnKind::AssocTrait, FnKind::AssocTrait) => {
303 match create_self_position_kind(tcx, delegation_id, sig_id) {
304 SelfPositionKind::None => None,
305 SelfPositionKind::AfterLifetimes(propagate_self_ty) => {
306 if propagate_self_ty {
307 Some(get_delegation_self_ty_or_err(tcx, delegation_id))
308 } else {
309 let index = tcx.generics_of(delegation_id).own_counts().lifetimes;
311 Some(Ty::new_param(tcx, index as u32, kw::SelfUpper))
312 }
313 }
314 SelfPositionKind::Zero => Some(Ty::new_param(tcx, 0, kw::SelfUpper)),
315 }
316 }
317
318 (FnKind::AssocTraitImpl, FnKind::AssocTrait)
319 | (FnKind::AssocInherentImpl, FnKind::AssocTrait) => Some(
320 tcx.type_of(tcx.local_parent(delegation_id)).instantiate_identity().skip_norm_wip(),
321 ),
322
323 (FnKind::AssocTraitImpl, _)
326 | (_, FnKind::AssocTraitImpl)
327 | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
328 }
329}
330
331fn create_generic_args<'tcx>(
347 tcx: TyCtxt<'tcx>,
348 sig_id: DefId,
349 delegation_id: LocalDefId,
350 mut parent_args: &[ty::GenericArg<'tcx>],
351 child_args: &[ty::GenericArg<'tcx>],
352) -> Vec<ty::GenericArg<'tcx>> {
353 let (caller_kind, callee_kind) = (fn_kind(tcx, delegation_id), fn_kind(tcx, sig_id));
354
355 let delegation_args = ty::GenericArgs::identity_for_item(tcx, delegation_id);
356
357 let deleg_parent_args_without_self_count =
358 get_delegation_parent_args_count_without_self(tcx, delegation_id, sig_id);
359
360 let delegation_generics = tcx.generics_of(delegation_id);
361 let real_args_count = delegation_args.len() - delegation_generics.own_synthetic_params_count();
362 let synth_args = &delegation_args[real_args_count..];
363 let delegation_args = &delegation_args[..real_args_count];
364
365 let args = match (caller_kind, callee_kind) {
366 (FnKind::Free, FnKind::Free)
367 | (FnKind::Free, FnKind::AssocTrait)
368 | (FnKind::AssocInherentImpl, FnKind::Free)
369 | (FnKind::AssocTrait, FnKind::Free)
370 | (FnKind::AssocTrait, FnKind::AssocTrait) => delegation_args,
371
372 (FnKind::AssocTraitImpl, FnKind::AssocTrait) => {
373 let parent = tcx.local_parent(delegation_id);
377 parent_args =
378 tcx.impl_trait_header(parent).trait_ref.instantiate_identity().skip_norm_wip().args;
379
380 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");
381
382 tcx.mk_args(&delegation_args[delegation_generics.parent_count..])
383 }
384
385 (FnKind::AssocInherentImpl, FnKind::AssocTrait) => {
386 let self_ty =
387 tcx.type_of(tcx.local_parent(delegation_id)).instantiate_identity().skip_norm_wip();
388
389 tcx.mk_args_from_iter(
390 std::iter::once(ty::GenericArg::from(self_ty))
391 .chain(delegation_args.iter().copied()),
392 )
393 }
394
395 (FnKind::AssocTraitImpl, _)
398 | (_, FnKind::AssocTraitImpl)
399 | (_, FnKind::AssocInherentImpl) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
400 };
401
402 let mut new_args = ::alloc::vec::Vec::new()vec![];
403
404 let self_pos_kind = create_self_position_kind(tcx, delegation_id, sig_id);
405 let mut lifetimes_end_pos;
406
407 if !parent_args.is_empty() {
408 let parent_args_lifetimes_count =
409 parent_args.iter().filter(|a| a.as_region().is_some()).count();
410
411 match self_pos_kind {
412 SelfPositionKind::AfterLifetimes { .. } => {
413 new_args.extend(&parent_args[1..1 + parent_args_lifetimes_count]);
414
415 lifetimes_end_pos = parent_args_lifetimes_count;
416
417 new_args.push(parent_args[0]);
418
419 new_args.extend(&parent_args[1 + parent_args_lifetimes_count..]);
420 }
421 SelfPositionKind::Zero => {
422 lifetimes_end_pos = 1 + parent_args_lifetimes_count;
423 new_args.extend_from_slice(parent_args);
424
425 for i in 0..deleg_parent_args_without_self_count {
426 new_args.insert(1 + i, args[1 + i]);
427 }
428
429 lifetimes_end_pos += deleg_parent_args_without_self_count;
430 }
431 SelfPositionKind::None => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
433 };
434 } else {
435 let self_impact = #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::Zero => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::Zero) as usize;
436
437 lifetimes_end_pos = self_impact
438 + deleg_parent_args_without_self_count
439 + &args[self_impact + deleg_parent_args_without_self_count..]
440 .iter()
441 .filter(|a| a.as_region().is_some())
442 .count();
443
444 new_args.extend_from_slice(args);
445
446 if #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::AfterLifetimes(true) => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::AfterLifetimes(true)) {
449 new_args.insert(
450 lifetimes_end_pos,
451 ty::GenericArg::from(get_delegation_self_ty_or_err(tcx, delegation_id)),
452 );
453 }
454 }
455
456 if !child_args.is_empty() {
457 let child_lifetimes_count = child_args.iter().filter(|a| a.as_region().is_some()).count();
458
459 for i in 0..child_lifetimes_count {
460 new_args.insert(lifetimes_end_pos + i, child_args[i]);
461 }
462
463 new_args.extend_from_slice(&child_args[child_lifetimes_count..]);
464 } else if !parent_args.is_empty() {
465 let child_args = &delegation_args[delegation_generics.parent_count..];
466
467 let child_lifetimes_count =
468 child_args.iter().take_while(|a| a.as_region().is_some()).count();
469
470 for i in 0..child_lifetimes_count {
471 new_args.insert(lifetimes_end_pos + i, child_args[i]);
472 }
473
474 let skip_self = #[allow(non_exhaustive_omitted_patterns)] match self_pos_kind {
SelfPositionKind::AfterLifetimes(false) => true,
_ => false,
}matches!(self_pos_kind, SelfPositionKind::AfterLifetimes(false));
476 new_args.extend(&child_args[child_lifetimes_count + skip_self as usize..]);
477 }
478
479 new_args.extend(synth_args);
480
481 new_args
482}
483
484pub(crate) fn inherit_predicates_for_delegation_item<'tcx>(
485 tcx: TyCtxt<'tcx>,
486 def_id: LocalDefId,
487 sig_id: DefId,
488) -> ty::GenericPredicates<'tcx> {
489 struct PredicatesCollector<'tcx> {
490 tcx: TyCtxt<'tcx>,
491 preds: Vec<(ty::Clause<'tcx>, Span)>,
492 args: Vec<ty::GenericArg<'tcx>>,
493 folder: ParamIndexRemapper<'tcx>,
494 filter_self_preds: bool,
495 }
496
497 impl<'tcx> PredicatesCollector<'tcx> {
498 fn with_own_preds(
499 mut self,
500 f: impl Fn(DefId) -> ty::GenericPredicates<'tcx>,
501 def_id: DefId,
502 ) -> Self {
503 let preds = f(def_id);
504 let args = self.args.as_slice();
505
506 for pred in preds.predicates {
507 if self.filter_self_preds
510 && let Some(trait_pred) = pred.0.as_trait_clause()
511 && trait_pred.self_ty().skip_binder().is_param(0)
513 {
514 continue;
515 }
516
517 let new_pred = pred.0.fold_with(&mut self.folder);
518 self.preds.push((
519 EarlyBinder::bind(new_pred).instantiate(self.tcx, args).skip_norm_wip(),
520 pred.1,
521 ));
522 }
523
524 self
525 }
526
527 fn with_preds(
528 mut self,
529 f: impl Fn(DefId) -> ty::GenericPredicates<'tcx> + Copy,
530 def_id: DefId,
531 ) -> Self {
532 let preds = f(def_id);
533 if let Some(parent_def_id) = preds.parent {
534 self = self.with_own_preds(f, parent_def_id);
535 }
536
537 self.with_own_preds(f, def_id)
538 }
539 }
540
541 let (parent_args, child_args) = tcx.delegation_user_specified_args(def_id);
542 let (folder, args) = create_folder_and_args(tcx, def_id, sig_id, parent_args, child_args);
543 let self_pos_kind = create_self_position_kind(tcx, def_id, sig_id);
544 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));
545
546 let collector = PredicatesCollector { tcx, preds: ::alloc::vec::Vec::new()vec![], args, folder, filter_self_preds };
547 let (parent, inh_kind) = get_parent_and_inheritance_kind(tcx, def_id, sig_id);
548
549 let preds = match inh_kind {
553 InheritanceKind::WithParent(false) => {
554 collector.with_preds(|def_id| tcx.explicit_predicates_of(def_id), sig_id)
555 }
556 InheritanceKind::WithParent(true) => {
557 collector.with_preds(|def_id| tcx.predicates_of(def_id), sig_id)
558 }
559 InheritanceKind::Own => {
560 collector.with_own_preds(|def_id| tcx.predicates_of(def_id), sig_id)
561 }
562 }
563 .preds;
564
565 ty::GenericPredicates { parent, predicates: tcx.arena.alloc_from_iter(preds) }
566}
567
568fn create_folder_and_args<'tcx>(
569 tcx: TyCtxt<'tcx>,
570 def_id: LocalDefId,
571 sig_id: DefId,
572 parent_args: &'tcx [ty::GenericArg<'tcx>],
573 child_args: &'tcx [ty::GenericArg<'tcx>],
574) -> (ParamIndexRemapper<'tcx>, Vec<ty::GenericArg<'tcx>>) {
575 let args = create_generic_args(tcx, sig_id, def_id, parent_args, child_args);
576 let remap_table = create_mapping(tcx, sig_id, def_id);
577
578 (ParamIndexRemapper { tcx, remap_table }, args)
579}
580
581fn check_constraints<'tcx>(
582 tcx: TyCtxt<'tcx>,
583 def_id: LocalDefId,
584 sig_id: DefId,
585) -> Result<(), ErrorGuaranteed> {
586 let mut ret = Ok(());
587
588 let mut emit = |descr| {
589 ret = Err(tcx.dcx().emit_err(crate::diagnostics::UnsupportedDelegation {
590 span: tcx.def_span(def_id),
591 descr,
592 callee_span: tcx.def_span(sig_id),
593 }));
594 };
595
596 if tcx.fn_sig(sig_id).skip_binder().skip_binder().c_variadic() {
597 emit("delegation to C-variadic functions is not allowed");
599 }
600
601 ret
602}
603
604pub(crate) fn inherit_sig_for_delegation_item<'tcx>(
605 tcx: TyCtxt<'tcx>,
606 def_id: LocalDefId,
607) -> &'tcx [Ty<'tcx>] {
608 let sig_id = tcx.hir_opt_delegation_sig_id(def_id).expect("Delegation must have sig_id");
609 let caller_sig = tcx.fn_sig(sig_id);
610
611 if let Err(err) = check_constraints(tcx, def_id, sig_id) {
612 let sig_len = caller_sig.instantiate_identity().skip_binder().inputs().len() + 1;
613 let err_type = Ty::new_error(tcx, err);
614 return tcx.arena.alloc_from_iter((0..sig_len).map(|_| err_type));
615 }
616
617 let (parent_args, child_args) = tcx.delegation_user_specified_args(def_id);
618 let (mut folder, args) = create_folder_and_args(tcx, def_id, sig_id, parent_args, child_args);
619 let caller_sig = EarlyBinder::bind(caller_sig.skip_binder().fold_with(&mut folder));
620
621 let sig = caller_sig.instantiate(tcx, args.as_slice()).skip_binder();
622 let sig_iter = sig.inputs().iter().cloned().chain(std::iter::once(sig.output()));
623 tcx.arena.alloc_from_iter(sig_iter)
624}
625
626pub(crate) fn delegation_user_specified_args<'tcx>(
631 tcx: TyCtxt<'tcx>,
632 delegation_id: LocalDefId,
633) -> (&'tcx [ty::GenericArg<'tcx>], &'tcx [ty::GenericArg<'tcx>]) {
634 let info = tcx.hir_delegation_info(delegation_id);
635
636 let get_segment = |hir_id| -> Option<(&'tcx PathSegment<'tcx>, DefId)> {
637 let segment = tcx.hir_node(hir_id).expect_path_segment();
638 segment.res.opt_def_id().map(|def_id| (segment, def_id))
639 };
640
641 let ctx = ItemCtxt::new_for_delegation(tcx, delegation_id);
642 let lowerer = ctx.lowerer();
643
644 let parent_args = info.parent_args_segment_id.and_then(get_segment).map(|(segment, def_id)| {
645 let self_ty = get_delegation_self_ty(tcx, delegation_id);
646
647 lowerer
648 .lower_generic_args_of_path(segment.ident.span, def_id, &[], segment, self_ty)
649 .0
650 .as_slice()
651 });
652
653 let child_args = info
654 .child_args_segment_id
655 .and_then(get_segment)
656 .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))
657 .map(|(segment, def_id)| {
658 let parent_args = if let Some(parent_args) = parent_args {
659 parent_args
660 } else {
661 let parent = tcx.parent(def_id);
662 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(parent) {
DefKind::Trait => true,
_ => false,
}matches!(tcx.def_kind(parent), DefKind::Trait) {
663 ty::GenericArgs::identity_for_item(tcx, parent).as_slice()
664 } else {
665 &[]
666 }
667 };
668
669 let args = lowerer
670 .lower_generic_args_of_path(segment.ident.span, def_id, parent_args, segment, None)
671 .0;
672
673 let synth_params_count = tcx.generics_of(def_id).own_synthetic_params_count();
674 &args[parent_args.len()..args.len() - synth_params_count]
675 });
676
677 (parent_args.unwrap_or_default(), child_args.unwrap_or_default())
678}