1use std::iter;
40use std::ops::ControlFlow;
41
42use ast::visit::Visitor;
43use hir::def::{DefKind, Res};
44use hir::{BodyId, HirId};
45use rustc_abi::ExternAbi;
46use rustc_ast as ast;
47use rustc_ast::node_id::NodeMap;
48use rustc_ast::*;
49use rustc_data_structures::fx::FxHashSet;
50use rustc_hir::attrs::{AttributeKind, InlineAttr};
51use rustc_hir::{self as hir, FnDeclFlags};
52use rustc_middle::span_bug;
53use rustc_middle::ty::{Asyncness, PerOwnerResolverData};
54use rustc_span::def_id::{DefId, LocalDefId};
55use rustc_span::symbol::kw;
56use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, sym};
57
58use crate::delegation::generics::{
59 GenericsGenerationResult, GenericsGenerationResults, GenericsPosition,
60};
61use crate::diagnostics::{
62 CycleInDelegationSignatureResolution, DelegationAttemptedBlockWithDefsDeletion,
63 DelegationBlockSpecifiedWhenNoParams, UnresolvedDelegationCallee,
64};
65use crate::{
66 AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
67};
68
69mod generics;
70
71pub(crate) struct DelegationResults<'hir> {
72 pub body_id: hir::BodyId,
73 pub sig: hir::FnSig<'hir>,
74 pub ident: Ident,
75 pub generics: &'hir hir::Generics<'hir>,
76}
77
78struct AttrAdditionInfo {
79 pub equals: fn(&hir::Attribute) -> bool,
80 pub kind: AttrAdditionKind,
81}
82
83enum AttrAdditionKind {
84 Default { factory: fn(Span) -> hir::Attribute },
85 Inherit { factory: fn(Span, &hir::Attribute) -> hir::Attribute },
86}
87
88#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ParamInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "ParamInfo",
"param_count", &self.param_count, "c_variadic", &self.c_variadic,
"splatted", &&self.splatted)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for ParamInfo {
#[inline]
fn clone(&self) -> ParamInfo {
let _: ::core::clone::AssertParamIsClone<usize>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Option<u8>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ParamInfo { }Copy, #[automatically_derived]
impl ::core::cmp::Eq for ParamInfo {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<bool>;
let _: ::core::cmp::AssertParamIsEq<Option<u8>>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ParamInfo {
#[inline]
fn eq(&self, other: &ParamInfo) -> bool {
self.c_variadic == other.c_variadic &&
self.param_count == other.param_count &&
self.splatted == other.splatted
}
}PartialEq)]
90struct ParamInfo {
91 pub param_count: usize,
93
94 pub c_variadic: bool,
96
97 pub splatted: Option<u8>,
99}
100
101const PARENT_ID: hir::ItemLocalId = hir::ItemLocalId::ZERO;
102
103static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
104 AttrAdditionInfo {
105 equals: |a| #[allow(non_exhaustive_omitted_patterns)] match a {
hir::Attribute::Parsed(AttributeKind::MustUse { .. }) => true,
_ => false,
}matches!(a, hir::Attribute::Parsed(AttributeKind::MustUse { .. })),
106 kind: AttrAdditionKind::Inherit {
107 factory: |span, original_attr| {
108 let reason = match original_attr {
109 hir::Attribute::Parsed(AttributeKind::MustUse { reason, .. }) => *reason,
110 _ => None,
111 };
112
113 hir::Attribute::Parsed(AttributeKind::MustUse { span, reason })
114 },
115 },
116 },
117 AttrAdditionInfo {
118 equals: |a| #[allow(non_exhaustive_omitted_patterns)] match a {
hir::Attribute::Parsed(AttributeKind::Inline(..)) => true,
_ => false,
}matches!(a, hir::Attribute::Parsed(AttributeKind::Inline(..))),
119 kind: AttrAdditionKind::Default {
120 factory: |span| hir::Attribute::Parsed(AttributeKind::Inline(InlineAttr::Hint, span)),
121 },
122 },
123];
124
125impl<'hir> LoweringContext<'_, 'hir> {
126 fn is_method(&self, def_id: DefId, span: Span) -> bool {
127 match self.tcx.def_kind(def_id) {
128 DefKind::Fn => false,
129 DefKind::AssocFn => self.tcx.associated_item(def_id).is_method(),
130 _ => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpected DefKind for delegation item"))span_bug!(span, "unexpected DefKind for delegation item"),
131 }
132 }
133
134 fn check_for_cycles(&self, mut def_id: DefId, span: Span) -> Result<(), ErrorGuaranteed> {
135 let mut visited: FxHashSet<DefId> = Default::default();
136
137 loop {
138 visited.insert(def_id);
139
140 if let Some(local_id) = def_id.as_local()
144 && let Some(info) = self.tcx.resolutions(()).delegation_infos.get(&local_id)
145 && let Ok(id) = info.resolution_id
146 {
147 def_id = id;
148 if visited.contains(&def_id) {
149 return Err(match visited.len() {
150 1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
151 _ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
152 });
153 }
154 } else {
155 return Ok(());
156 }
157 }
158 }
159
160 pub(crate) fn lower_delegation(
161 &mut self,
162 delegation: &Delegation,
163 item_id: NodeId,
164 ) -> DelegationResults<'hir> {
165 let span = self.lower_span(delegation.last_segment_span());
166
167 let Some(info) = self.tcx.resolutions(()).delegation_infos.get(&self.owner.def_id) else {
168 self.dcx().span_delayed_bug(
169 span,
170 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("delegation resolution record was not found for {0:?}",
self.owner.def_id))
})format!("delegation resolution record was not found for {:?}", self.owner.def_id),
171 );
172
173 return self.generate_delegation_error(span, delegation);
174 };
175
176 let sig_id = info.resolution_id.and_then(|id| self.check_for_cycles(id, span).map(|_| id));
177
178 let Ok(sig_id) = sig_id else {
181 self.dcx().span_delayed_bug(
182 span,
183 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("LoweringContext: the delegation {0:?} is unresolved",
item_id))
})format!("LoweringContext: the delegation {:?} is unresolved", item_id),
184 );
185
186 return self.generate_delegation_error(span, delegation);
187 };
188
189 self.add_attrs_if_needed(span, sig_id);
190
191 let is_method = self.is_method(sig_id, span);
192
193 let param_info = self.param_info(sig_id);
194
195 if !self.check_block_soundness(delegation, sig_id, is_method, param_info.param_count) {
196 return self.generate_delegation_error(span, delegation);
197 }
198
199 let mut generics = self.uplift_delegation_generics(delegation, sig_id);
200
201 let (body_id, call_expr_id, unused_target_expr) = self.lower_delegation_body(
202 delegation,
203 sig_id,
204 param_info.param_count,
205 &mut generics,
206 span,
207 );
208
209 let decl = self.lower_delegation_decl(
210 delegation.source,
211 sig_id,
212 param_info,
213 span,
214 &generics,
215 delegation.id,
216 call_expr_id,
217 unused_target_expr,
218 );
219
220 let sig = self.lower_delegation_sig(sig_id, decl, span);
221 let ident = self.lower_ident(delegation.ident);
222
223 let generics = self.arena.alloc(hir::Generics {
224 has_where_clause_predicates: false,
225 params: self.arena.alloc_from_iter(generics.all_params()),
226 predicates: self.arena.alloc_from_iter(generics.all_predicates()),
227 span,
228 where_clause_span: span,
229 });
230
231 DelegationResults { body_id, sig, ident, generics }
232 }
233
234 fn check_block_soundness(
235 &self,
236 delegation: &Delegation,
237 sig_id: DefId,
238 is_method: bool,
239 param_count: usize,
240 ) -> bool {
241 let Some(block) = delegation.body.as_ref() else { return true };
242 let should_generate_block = self.should_generate_block(delegation, sig_id, is_method);
243
244 if param_count == 0 && should_generate_block {
247 self.dcx().emit_err(DelegationBlockSpecifiedWhenNoParams { span: block.span });
248 return false;
249 }
250
251 struct DefinitionsFinder<'a> {
252 all_owners: &'a NodeMap<PerOwnerResolverData<'a>>,
253 nested_def_ids: &'a NodeMap<LocalDefId>,
255 }
256
257 impl<'a> ast::visit::Visitor<'a> for DefinitionsFinder<'a> {
258 type Result = ControlFlow<()>;
259
260 fn visit_id(&mut self, id: NodeId) -> Self::Result {
261 match self.all_owners.contains_key(&id) || self.nested_def_ids.contains_key(&id) {
276 true => ControlFlow::Break(()),
277 false => ControlFlow::Continue(()),
278 }
279 }
280 }
281
282 let mut collector = DefinitionsFinder {
283 all_owners: &self.resolver.owners,
284 nested_def_ids: &self.owner.node_id_to_def_id,
285 };
286
287 let contains_defs = collector.visit_block(block).is_break();
288
289 if !should_generate_block && contains_defs {
292 self.dcx().emit_err(DelegationAttemptedBlockWithDefsDeletion { span: block.span });
293 return false;
294 }
295
296 true
297 }
298
299 fn should_generate_block(
300 &self,
301 delegation: &Delegation,
302 sig_id: DefId,
303 is_method: bool,
304 ) -> bool {
305 is_method
306 || #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(sig_id) {
DefKind::Fn => true,
_ => false,
}matches!(self.tcx.def_kind(sig_id), DefKind::Fn)
307 || #[allow(non_exhaustive_omitted_patterns)] match delegation.source {
DelegationSource::Single => true,
_ => false,
}matches!(delegation.source, DelegationSource::Single)
308 }
309
310 fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
311 let new_attrs =
312 self.create_new_attrs(ATTRS_ADDITIONS, span, sig_id, self.attrs.get(&PARENT_ID));
313
314 if new_attrs.is_empty() {
315 return;
316 }
317
318 let new_arena_allocated_attrs = match self.attrs.get(&PARENT_ID) {
319 Some(existing_attrs) => self.arena.alloc_from_iter(
320 existing_attrs.iter().map(|a| a.clone()).chain(new_attrs.into_iter()),
321 ),
322 None => self.arena.alloc_from_iter(new_attrs.into_iter()),
323 };
324
325 self.attrs.insert(PARENT_ID, new_arena_allocated_attrs);
326 }
327
328 fn create_new_attrs(
329 &self,
330 candidate_additions: &[AttrAdditionInfo],
331 span: Span,
332 sig_id: DefId,
333 existing_attrs: Option<&&[hir::Attribute]>,
334 ) -> Vec<hir::Attribute> {
335 candidate_additions
336 .iter()
337 .filter_map(|addition_info| {
338 if let Some(existing_attrs) = existing_attrs
339 && existing_attrs
340 .iter()
341 .any(|existing_attr| (addition_info.equals)(existing_attr))
342 {
343 return None;
344 }
345
346 match addition_info.kind {
347 AttrAdditionKind::Default { factory } => Some(factory(span)),
348 AttrAdditionKind::Inherit { factory, .. } =>
349 {
350 #[allow(deprecated)]
351 self.tcx
352 .get_all_attrs(sig_id)
353 .iter()
354 .find_map(|a| (addition_info.equals)(a).then(|| factory(span, a)))
355 }
356 }
357 })
358 .collect::<Vec<_>>()
359 }
360
361 fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
362 self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
363 }
364
365 fn param_info(&self, def_id: DefId) -> ParamInfo {
367 let sig = self.tcx.fn_sig(def_id).skip_binder().skip_binder();
368
369 ParamInfo {
370 param_count: sig.inputs().len() + usize::from(sig.c_variadic()),
371 c_variadic: sig.c_variadic(),
372 splatted: sig.splatted(),
373 }
374 }
375
376 fn lower_delegation_decl(
377 &mut self,
378 source: DelegationSource,
379 sig_id: DefId,
380 param_info: ParamInfo,
381 span: Span,
382 generics: &GenericsGenerationResults<'hir>,
383 call_path_node_id: NodeId,
384 call_expr_id: HirId,
385 unused_target_expr: bool,
386 ) -> &'hir hir::FnDecl<'hir> {
387 let ParamInfo { param_count, c_variadic, splatted } = param_info;
388
389 let decl_param_count = param_count - c_variadic as usize;
392 let inputs = self.arena.alloc_from_iter((0..decl_param_count).map(|arg| hir::Ty {
393 hir_id: self.next_id(),
394 kind: hir::TyKind::InferDelegation(hir::InferDelegation::Sig(
395 sig_id,
396 hir::InferDelegationSig::Input(arg),
397 )),
398 span,
399 }));
400
401 let output = self.arena.alloc(hir::Ty {
402 hir_id: self.next_id(),
403 kind: hir::TyKind::InferDelegation(hir::InferDelegation::Sig(
404 sig_id,
405 hir::InferDelegationSig::Output(self.arena.alloc(hir::DelegationInfo {
406 call_expr_id,
407 call_path_res: self.get_resolution_id(call_path_node_id),
408 child_seg_id: generics.child.args_segment_id,
409 child_seg_id_for_sig: generics.child.segment_id_for_sig(),
410 parent_seg_id_for_sig: generics.parent.segment_id_for_sig(),
411 self_ty_propagation_kind: generics.self_ty_propagation_kind,
412 group_id: {
413 let id = match source {
414 DelegationSource::Single => None,
415 DelegationSource::List(expn_id) => Some(expn_id),
416 DelegationSource::Glob => {
417 Some(self.tcx.expn_that_defined(self.owner.def_id).expect_local())
418 }
419 };
420
421 id.map(|id| (id, unused_target_expr))
422 },
423 })),
424 )),
425 span,
426 });
427
428 self.arena.alloc(hir::FnDecl {
429 inputs,
430 output: hir::FnRetTy::Return(output),
431 fn_decl_kind: FnDeclFlags::default()
432 .set_lifetime_elision_allowed(true)
433 .set_c_variadic(c_variadic)
434 .set_splatted(splatted, inputs.len())
435 .unwrap(),
436 })
437 }
438
439 fn lower_delegation_sig(
440 &mut self,
441 sig_id: DefId,
442 decl: &'hir hir::FnDecl<'hir>,
443 span: Span,
444 ) -> hir::FnSig<'hir> {
445 let sig = self.tcx.fn_sig(sig_id).skip_binder().skip_binder();
446 let asyncness = match self.tcx.asyncness(sig_id) {
447 Asyncness::Yes => hir::IsAsync::Async(span),
448 Asyncness::No => hir::IsAsync::NotAsync,
449 };
450
451 let header = hir::FnHeader {
452 safety: if self.tcx.codegen_fn_attrs(sig_id).safe_target_features {
453 hir::HeaderSafety::SafeTargetFeatures
454 } else {
455 hir::HeaderSafety::Normal(sig.safety())
456 },
457 constness: self.tcx.constness(sig_id),
458 asyncness,
459 abi: sig.abi(),
460 };
461
462 hir::FnSig { decl, header, span }
463 }
464
465 fn generate_param(
466 &mut self,
467 is_method: bool,
468 idx: usize,
469 span: Span,
470 ) -> (hir::Param<'hir>, NodeId) {
471 let pat_node_id = self.next_node_id();
472 let pat_id = self.lower_node_id(pat_node_id);
473 let name = if is_method && idx == 0 {
475 kw::SelfLower
476 } else {
477 Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", idx))
})format!("arg{idx}"))
478 };
479 let ident = Ident::with_dummy_span(name);
480 let pat = self.arena.alloc(hir::Pat {
481 hir_id: pat_id,
482 kind: hir::PatKind::Binding(hir::BindingMode::NONE, pat_id, ident, None),
483 span,
484 default_binding_modes: false,
485 });
486
487 (hir::Param { hir_id: self.next_id(), pat, ty_span: span, span }, pat_node_id)
488 }
489
490 fn generate_arg(
491 &mut self,
492 is_method: bool,
493 idx: usize,
494 param_id: HirId,
495 span: Span,
496 ) -> hir::Expr<'hir> {
497 let name = if is_method && idx == 0 {
499 kw::SelfLower
500 } else {
501 Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", idx))
})format!("arg{idx}"))
502 };
503
504 let segments = self.arena.alloc_from_iter(iter::once(hir::PathSegment {
505 ident: Ident::with_dummy_span(name),
506 hir_id: self.next_id(),
507 res: Res::Local(param_id),
508 args: None,
509 infer_args: false,
510 delegation_child_segment: false,
511 }));
512
513 let path = self.arena.alloc(hir::Path { span, res: Res::Local(param_id), segments });
514 self.mk_expr(hir::ExprKind::Path(hir::QPath::Resolved(None, path)), span)
515 }
516
517 fn lower_delegation_body(
518 &mut self,
519 delegation: &Delegation,
520 sig_id: DefId,
521 param_count: usize,
522 generics: &mut GenericsGenerationResults<'hir>,
523 span: Span,
524 ) -> (BodyId, HirId, bool) {
525 let block = delegation.body.as_deref();
526 let mut call_expr_id = HirId::INVALID;
527 let mut unused_target_expr = false;
528
529 let block_id = self.lower_body(|this| {
530 let mut parameters: Vec<hir::Param<'_>> = Vec::with_capacity(param_count);
531 let mut args: Vec<hir::Expr<'_>> = Vec::with_capacity(param_count);
532 let mut stmts: &[hir::Stmt<'hir>] = &[];
533
534 let is_method = this.is_method(sig_id, span);
535 let should_generate_block = this.should_generate_block(delegation, sig_id, is_method);
536
537 unused_target_expr = block.is_some() && (param_count == 0 || !should_generate_block);
541
542 for idx in 0..param_count {
543 let (param, pat_node_id) = this.generate_param(is_method, idx, span);
544 parameters.push(param);
545
546 let generate_arg =
547 |this: &mut Self| this.generate_arg(is_method, idx, param.pat.hir_id, span);
548
549 let arg = if let Some(block) = block
550 && idx == 0
551 && should_generate_block
552 {
553 let mut self_resolver = SelfResolver {
554 ctxt: this,
555 path_id: delegation.id,
556 self_param_id: pat_node_id,
557 };
558 self_resolver.visit_block(block);
559 this.ident_and_label_to_local_id.insert(pat_node_id, param.pat.hir_id.local_id);
561
562 let block = this.lower_block_noalloc(HirId::INVALID, block, false);
566
567 stmts = block.stmts;
568
569 if let Some(&expr) = block.expr { expr } else { generate_arg(this) }
575 } else {
576 generate_arg(this)
577 };
578
579 args.push(arg);
580 }
581
582 let (final_expr, hir_id) =
583 this.finalize_body_lowering(delegation, stmts, args, generics, span);
584
585 call_expr_id = hir_id;
586
587 (this.arena.alloc_from_iter(parameters), final_expr)
588 });
589
590 if true {
{
match (&call_expr_id, &HirId::INVALID) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_ne!(call_expr_id, HirId::INVALID);
591
592 (block_id, call_expr_id, unused_target_expr)
593 }
594
595 fn finalize_body_lowering(
596 &mut self,
597 delegation: &Delegation,
598 stmts: &'hir [hir::Stmt<'hir>],
599 args: Vec<hir::Expr<'hir>>,
600 generics: &mut GenericsGenerationResults<'hir>,
601 span: Span,
602 ) -> (hir::Expr<'hir>, HirId) {
603 let path = self.lower_qpath(
604 delegation.id,
605 &delegation.qself,
606 &delegation.path,
607 ParamMode::Optional,
608 AllowReturnTypeNotation::No,
609 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
610 None,
611 );
612
613 let new_path = match path {
614 hir::QPath::Resolved(ty, path) => {
615 let mut new_path = path.clone();
616 let len = new_path.segments.len();
617
618 new_path.segments = self.arena.alloc_from_iter(
619 new_path.segments.iter().enumerate().map(|(idx, segment)| {
620 if idx + 2 == len {
621 self.process_segment(span, segment, &mut generics.parent)
622 } else if idx + 1 == len {
623 self.process_segment(span, segment, &mut generics.child)
624 } else {
625 segment.clone()
626 }
627 }),
628 );
629
630 let ty = match generics.self_ty_propagation_kind {
633 Some(hir::DelegationSelfTyPropagationKind::SelfParam) => {
634 let self_param = generics.parent.generics.find_self_param();
635 let path = self.create_generic_arg_path(self_param);
636 let kind = hir::TyKind::Path(path);
637
638 let ty = match ty {
639 Some(ty) => hir::Ty { kind, ..ty.clone() },
640 None => hir::Ty { kind, hir_id: self.next_id(), span },
641 };
642
643 Some(&*self.arena.alloc(ty))
644 }
645 _ => ty,
646 };
647
648 hir::QPath::Resolved(ty, self.arena.alloc(new_path))
649 }
650 hir::QPath::TypeRelative(..) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("until inherent methods are supported")));
}unreachable!("until inherent methods are supported"),
651 };
652
653 if let Some(hir::DelegationSelfTyPropagationKind::SelfTy(id)) =
654 generics.self_ty_propagation_kind.as_mut()
655 {
656 *id = match new_path {
657 hir::QPath::Resolved(ty, _) => {
658 ty.expect("must contain self type as `SelfTy` propagation kind is specified")
659 }
660 hir::QPath::TypeRelative(ty, _) => ty,
661 }
662 .hir_id;
663 }
664
665 let callee_path = self.arena.alloc(self.mk_expr(hir::ExprKind::Path(new_path), span));
666 let args = self.arena.alloc_from_iter(args);
667 let call = self.mk_expr(hir::ExprKind::Call(callee_path, args), span);
668
669 let expr = if let Some((parent, of_trait)) = self.should_wrap_return_value(delegation) {
670 let res = Res::SelfTyAlias { alias_to: parent.to_def_id(), is_trait_impl: of_trait };
671 let ident = Ident::new(kw::SelfUpper, span);
672 let path = self.create_resolved_path(res, ident, span);
673
674 let initializer = hir::ExprKind::Struct(
676 self.arena.alloc(path),
677 self.arena.alloc_slice(&[hir::ExprField {
678 hir_id: self.next_id(),
679 is_shorthand: false,
680 ident: Ident::new(sym::integer(0), span),
681 expr: self.arena.alloc(call),
682 span,
683 }]),
684 hir::StructTailExpr::None,
685 );
686
687 self.arena.alloc(self.mk_expr(initializer, span))
688 } else {
689 self.arena.alloc(call)
690 };
691
692 let block = self.arena.alloc(hir::Block {
693 stmts,
694 expr: Some(expr),
695 hir_id: self.next_id(),
696 rules: hir::BlockCheckMode::DefaultBlock,
697 span,
698 targeted_by_break: false,
699 });
700
701 (self.mk_expr(hir::ExprKind::Block(block, None), span), call.hir_id)
702 }
703
704 fn should_wrap_return_value(&self, delegation: &Delegation) -> Option<(LocalDefId, bool)> {
705 if delegation.body.is_none() {
707 return None;
708 }
709
710 let tcx = self.tcx;
711 let parent = tcx.local_parent(self.owner.def_id);
712 let parent_kind = tcx.def_kind(parent);
713
714 if !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(parent) {
DefKind::Impl { .. } => true,
_ => false,
}matches!(tcx.def_kind(parent), DefKind::Impl { .. }) {
725 return None;
726 }
727
728 let is_trait_impl = parent_kind == DefKind::Impl { of_trait: true };
729
730 Some((parent, is_trait_impl)).filter(|_| {
732 self.get_resolution_id(delegation.id).is_some_and(|id| {
733 tcx.def_kind(id) == DefKind::AssocFn
734 && tcx.def_kind(tcx.parent(id)) == DefKind::Trait
738 && tcx.fn_sig(id).skip_binder().output().skip_binder().is_param(0)
739 })
740 })
741 }
742
743 fn process_segment(
744 &mut self,
745 span: Span,
746 segment: &hir::PathSegment<'hir>,
747 result: &mut GenericsGenerationResult<'hir>,
748 ) -> hir::PathSegment<'hir> {
749 let infer_indices = result.generics.infer_indices();
750 result.generics.into_hir_generics(self, span);
751
752 let mut segment = segment.clone();
753 let mut args_iter = result.generics.create_args_iterator();
754
755 let new_args = segment
756 .args
757 .filter(|args| !args.is_empty())
758 .map(|args| {
759 self.arena.alloc_from_iter(args.args.iter().enumerate().map(|(idx, arg)| {
760 if infer_indices.contains(&idx) {
761 args_iter.next(self, |_| arg.hir_id()).expect("arg must exist for infer")
762 } else {
763 *arg
764 }
765 }))
766 })
767 .unwrap_or_else(|| self.arena.alloc_from_iter(args_iter.consume_all(self)));
768
769 segment.args = (!new_args.is_empty()).then(|| {
771 &*self.arena.alloc(hir::GenericArgs {
772 args: new_args,
773 constraints: &[],
774 parenthesized: hir::GenericArgsParentheses::No,
775 span_ext: segment.args.map_or(span, |args| args.span_ext),
776 })
777 });
778
779 result.args_segment_id = segment.hir_id;
780 result.use_for_sig_inheritance = !result.generics.is_trait_impl();
781
782 segment.delegation_child_segment = result.generics.pos() == GenericsPosition::Child;
783
784 segment
785 }
786
787 fn generate_delegation_error(
788 &mut self,
789 span: Span,
790 delegation: &Delegation,
791 ) -> DelegationResults<'hir> {
792 let decl = self.arena.alloc(hir::FnDecl::dummy(span));
793
794 let header = self.generate_header_error();
795 let sig = hir::FnSig { decl, header, span };
796
797 let ident = self.lower_ident(delegation.ident);
798
799 let body_id = self.lower_body(|this| {
800 let path = this.lower_qpath(
801 delegation.id,
802 &delegation.qself,
803 &delegation.path,
804 ParamMode::Optional,
805 AllowReturnTypeNotation::No,
806 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
807 None,
808 );
809
810 let callee_path = this.arena.alloc(this.mk_expr(hir::ExprKind::Path(path), span));
811 let args = if let Some(block) = delegation.body.as_ref() {
812 this.arena.alloc_slice(&[this.lower_block_expr(block)])
813 } else {
814 &mut []
815 };
816
817 let call = this.arena.alloc(this.mk_expr(hir::ExprKind::Call(callee_path, args), span));
818
819 let block = this.arena.alloc(hir::Block {
820 stmts: &[],
821 expr: Some(call),
822 hir_id: this.next_id(),
823 rules: hir::BlockCheckMode::DefaultBlock,
824 span,
825 targeted_by_break: false,
826 });
827
828 (&[], this.mk_expr(hir::ExprKind::Block(block, None), span))
829 });
830
831 let generics = hir::Generics::empty();
832 DelegationResults { ident, generics, body_id, sig }
833 }
834
835 fn generate_header_error(&self) -> hir::FnHeader {
836 hir::FnHeader {
837 safety: hir::Safety::Safe.into(),
838 constness: hir::Constness::NotConst,
839 asyncness: hir::IsAsync::NotAsync,
840 abi: ExternAbi::Rust,
841 }
842 }
843
844 #[inline]
845 fn mk_expr(&mut self, kind: hir::ExprKind<'hir>, span: Span) -> hir::Expr<'hir> {
846 hir::Expr { hir_id: self.next_id(), kind, span }
847 }
848}
849
850struct SelfResolver<'a, 'b, 'hir> {
851 ctxt: &'a mut LoweringContext<'b, 'hir>,
852 path_id: NodeId,
853 self_param_id: NodeId,
854}
855
856impl SelfResolver<'_, '_, '_> {
857 fn try_replace_id(&mut self, id: NodeId) {
858 if let Some(res) = self.ctxt.get_partial_res(id)
859 && let Some(Res::Local(sig_id)) = res.full_res()
860 && sig_id == self.path_id
861 {
862 self.ctxt.partial_res_overrides.insert(id, self.self_param_id);
863 }
864 }
865}
866
867impl<'ast> Visitor<'ast> for SelfResolver<'_, '_, '_> {
868 fn visit_id(&mut self, id: NodeId) {
869 self.try_replace_id(id);
870 }
871}