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