1use std::iter;
40
41use ast::visit::Visitor;
42use hir::def::{DefKind, Res};
43use hir::{BodyId, HirId};
44use rustc_abi::ExternAbi;
45use rustc_ast as ast;
46use rustc_ast::*;
47use rustc_data_structures::fx::FxHashSet;
48use rustc_errors::ErrorGuaranteed;
49use rustc_hir::attrs::{AttributeKind, InlineAttr};
50use rustc_hir::def_id::DefId;
51use rustc_hir::{self as hir, FnDeclFlags};
52use rustc_middle::span_bug;
53use rustc_middle::ty::Asyncness;
54use rustc_span::symbol::kw;
55use rustc_span::{Ident, Span, Symbol};
56use smallvec::SmallVec;
57
58use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
59use crate::errors::{CycleInDelegationSignatureResolution, UnresolvedDelegationCallee};
60use crate::{
61 AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
62 ResolverAstLoweringExt,
63};
64
65mod generics;
66
67pub(crate) struct DelegationResults<'hir> {
68 pub body_id: hir::BodyId,
69 pub sig: hir::FnSig<'hir>,
70 pub ident: Ident,
71 pub generics: &'hir hir::Generics<'hir>,
72}
73
74struct AttrAdditionInfo {
75 pub equals: fn(&hir::Attribute) -> bool,
76 pub kind: AttrAdditionKind,
77}
78
79enum AttrAdditionKind {
80 Default { factory: fn(Span) -> hir::Attribute },
81 Inherit { factory: fn(Span, &hir::Attribute) -> hir::Attribute },
82}
83
84const PARENT_ID: hir::ItemLocalId = hir::ItemLocalId::ZERO;
85
86static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
87 AttrAdditionInfo {
88 equals: |a| #[allow(non_exhaustive_omitted_patterns)] match a {
hir::Attribute::Parsed(AttributeKind::MustUse { .. }) => true,
_ => false,
}matches!(a, hir::Attribute::Parsed(AttributeKind::MustUse { .. })),
89 kind: AttrAdditionKind::Inherit {
90 factory: |span, original_attr| {
91 let reason = match original_attr {
92 hir::Attribute::Parsed(AttributeKind::MustUse { reason, .. }) => *reason,
93 _ => None,
94 };
95
96 hir::Attribute::Parsed(AttributeKind::MustUse { span, reason })
97 },
98 },
99 },
100 AttrAdditionInfo {
101 equals: |a| #[allow(non_exhaustive_omitted_patterns)] match a {
hir::Attribute::Parsed(AttributeKind::Inline(..)) => true,
_ => false,
}matches!(a, hir::Attribute::Parsed(AttributeKind::Inline(..))),
102 kind: AttrAdditionKind::Default {
103 factory: |span| hir::Attribute::Parsed(AttributeKind::Inline(InlineAttr::Hint, span)),
104 },
105 },
106];
107
108impl<'hir> LoweringContext<'_, 'hir> {
109 fn is_method(&self, def_id: DefId, span: Span) -> bool {
110 match self.tcx.def_kind(def_id) {
111 DefKind::Fn => false,
112 DefKind::AssocFn => self.tcx.associated_item(def_id).is_method(),
113 _ => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpected DefKind for delegation item"))span_bug!(span, "unexpected DefKind for delegation item"),
114 }
115 }
116
117 pub(crate) fn lower_delegation(
118 &mut self,
119 delegation: &Delegation,
120 item_id: NodeId,
121 ) -> DelegationResults<'hir> {
122 let span = self.lower_span(delegation.path.segments.last().unwrap().ident.span);
123
124 let sig_id = if let Some(delegation_info) = self.resolver.delegation_info(self.owner.def_id)
126 {
127 self.get_sig_id(delegation_info.resolution_node, span)
128 } else {
129 self.dcx().span_delayed_bug(
130 span,
131 ::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),
132 );
133
134 return self.generate_delegation_error(span, delegation);
135 };
136
137 match sig_id {
138 Ok(sig_id) => {
139 self.add_attrs_if_needed(span, sig_id);
140
141 let is_method = self.is_method(sig_id, span);
142
143 let (param_count, c_variadic) = self.param_count(sig_id);
144
145 let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);
146
147 let (body_id, call_expr_id) = self.lower_delegation_body(
148 delegation,
149 is_method,
150 param_count,
151 &mut generics,
152 span,
153 );
154
155 let decl = self.lower_delegation_decl(
156 sig_id,
157 param_count,
158 c_variadic,
159 span,
160 &generics,
161 delegation.id,
162 call_expr_id,
163 );
164
165 let sig = self.lower_delegation_sig(sig_id, decl, span);
166 let ident = self.lower_ident(delegation.ident);
167
168 let generics = self.arena.alloc(hir::Generics {
169 has_where_clause_predicates: false,
170 params: self.arena.alloc_from_iter(generics.all_params()),
171 predicates: self.arena.alloc_from_iter(generics.all_predicates()),
172 span,
173 where_clause_span: span,
174 });
175
176 DelegationResults { body_id, sig, ident, generics }
177 }
178 Err(_) => self.generate_delegation_error(span, delegation),
179 }
180 }
181
182 fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
183 let new_attrs =
184 self.create_new_attrs(ATTRS_ADDITIONS, span, sig_id, self.attrs.get(&PARENT_ID));
185
186 if new_attrs.is_empty() {
187 return;
188 }
189
190 let new_arena_allocated_attrs = match self.attrs.get(&PARENT_ID) {
191 Some(existing_attrs) => self.arena.alloc_from_iter(
192 existing_attrs.iter().map(|a| a.clone()).chain(new_attrs.into_iter()),
193 ),
194 None => self.arena.alloc_from_iter(new_attrs.into_iter()),
195 };
196
197 self.attrs.insert(PARENT_ID, new_arena_allocated_attrs);
198 }
199
200 fn create_new_attrs(
201 &self,
202 candidate_additions: &[AttrAdditionInfo],
203 span: Span,
204 sig_id: DefId,
205 existing_attrs: Option<&&[hir::Attribute]>,
206 ) -> Vec<hir::Attribute> {
207 candidate_additions
208 .iter()
209 .filter_map(|addition_info| {
210 if let Some(existing_attrs) = existing_attrs
211 && existing_attrs
212 .iter()
213 .any(|existing_attr| (addition_info.equals)(existing_attr))
214 {
215 return None;
216 }
217
218 match addition_info.kind {
219 AttrAdditionKind::Default { factory } => Some(factory(span)),
220 AttrAdditionKind::Inherit { factory, .. } =>
221 {
222 #[allow(deprecated)]
223 self.tcx
224 .get_all_attrs(sig_id)
225 .iter()
226 .find_map(|a| (addition_info.equals)(a).then(|| factory(span, a)))
227 }
228 }
229 })
230 .collect::<Vec<_>>()
231 }
232
233 fn get_sig_id(&self, mut node_id: NodeId, span: Span) -> Result<DefId, ErrorGuaranteed> {
234 let mut visited: FxHashSet<NodeId> = Default::default();
235 let mut path: SmallVec<[DefId; 1]> = Default::default();
236
237 loop {
238 visited.insert(node_id);
239
240 let Some(def_id) = self.get_resolution_id(node_id) else {
241 return Err(self.tcx.dcx().span_delayed_bug(
242 span,
243 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("LoweringContext: couldn\'t resolve node {0:?} in delegation item",
node_id))
})format!(
244 "LoweringContext: couldn't resolve node {:?} in delegation item",
245 node_id
246 ),
247 ));
248 };
249
250 path.push(def_id);
251
252 if let Some(local_id) = def_id.as_local()
256 && let Some(delegation_info) = self.resolver.delegation_info(local_id)
257 {
258 node_id = delegation_info.resolution_node;
259 if visited.contains(&node_id) {
260 return Err(match visited.len() {
263 1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
264 _ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
265 });
266 }
267 } else {
268 return Ok(path[0]);
269 }
270 }
271 }
272
273 fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
274 self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
275 }
276
277 fn param_count(&self, def_id: DefId) -> (usize, bool ) {
279 let sig = self.tcx.fn_sig(def_id).skip_binder().skip_binder();
280 (sig.inputs().len() + usize::from(sig.c_variadic()), sig.c_variadic())
281 }
282
283 fn lower_delegation_decl(
284 &mut self,
285 sig_id: DefId,
286 param_count: usize,
287 c_variadic: bool,
288 span: Span,
289 generics: &GenericsGenerationResults<'hir>,
290 call_path_node_id: NodeId,
291 call_expr_id: HirId,
292 ) -> &'hir hir::FnDecl<'hir> {
293 let decl_param_count = param_count - c_variadic as usize;
296 let inputs = self.arena.alloc_from_iter((0..decl_param_count).map(|arg| hir::Ty {
297 hir_id: self.next_id(),
298 kind: hir::TyKind::InferDelegation(hir::InferDelegation::Sig(
299 sig_id,
300 hir::InferDelegationSig::Input(arg),
301 )),
302 span,
303 }));
304
305 let output = self.arena.alloc(hir::Ty {
306 hir_id: self.next_id(),
307 kind: hir::TyKind::InferDelegation(hir::InferDelegation::Sig(
308 sig_id,
309 hir::InferDelegationSig::Output(self.arena.alloc(hir::DelegationInfo {
310 call_expr_id,
311 call_path_res: self.get_resolution_id(call_path_node_id),
312 child_args_segment_id: generics.child.args_segment_id,
313 parent_args_segment_id: generics.parent.args_segment_id,
314 self_ty_id: generics.self_ty_id,
315 propagate_self_ty: generics.propagate_self_ty,
316 })),
317 )),
318 span,
319 });
320
321 self.arena.alloc(hir::FnDecl {
322 inputs,
323 output: hir::FnRetTy::Return(output),
324 fn_decl_kind: FnDeclFlags::default()
325 .set_lifetime_elision_allowed(true)
326 .set_c_variadic(c_variadic),
327 })
328 }
329
330 fn lower_delegation_sig(
331 &mut self,
332 sig_id: DefId,
333 decl: &'hir hir::FnDecl<'hir>,
334 span: Span,
335 ) -> hir::FnSig<'hir> {
336 let sig = self.tcx.fn_sig(sig_id).skip_binder().skip_binder();
337 let asyncness = match self.tcx.asyncness(sig_id) {
338 Asyncness::Yes => hir::IsAsync::Async(span),
339 Asyncness::No => hir::IsAsync::NotAsync,
340 };
341
342 let header = hir::FnHeader {
343 safety: if self.tcx.codegen_fn_attrs(sig_id).safe_target_features {
344 hir::HeaderSafety::SafeTargetFeatures
345 } else {
346 hir::HeaderSafety::Normal(sig.safety())
347 },
348 constness: self.tcx.constness(sig_id),
349 asyncness,
350 abi: sig.abi(),
351 };
352
353 hir::FnSig { decl, header, span }
354 }
355
356 fn generate_param(
357 &mut self,
358 is_method: bool,
359 idx: usize,
360 span: Span,
361 ) -> (hir::Param<'hir>, NodeId) {
362 let pat_node_id = self.next_node_id();
363 let pat_id = self.lower_node_id(pat_node_id);
364 let name = if is_method && idx == 0 {
366 kw::SelfLower
367 } else {
368 Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", idx))
})format!("arg{idx}"))
369 };
370 let ident = Ident::with_dummy_span(name);
371 let pat = self.arena.alloc(hir::Pat {
372 hir_id: pat_id,
373 kind: hir::PatKind::Binding(hir::BindingMode::NONE, pat_id, ident, None),
374 span,
375 default_binding_modes: false,
376 });
377
378 (hir::Param { hir_id: self.next_id(), pat, ty_span: span, span }, pat_node_id)
379 }
380
381 fn generate_arg(
382 &mut self,
383 is_method: bool,
384 idx: usize,
385 param_id: HirId,
386 span: Span,
387 ) -> hir::Expr<'hir> {
388 let name = if is_method && idx == 0 {
390 kw::SelfLower
391 } else {
392 Symbol::intern(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", idx))
})format!("arg{idx}"))
393 };
394
395 let segments = self.arena.alloc_from_iter(iter::once(hir::PathSegment {
396 ident: Ident::with_dummy_span(name),
397 hir_id: self.next_id(),
398 res: Res::Local(param_id),
399 args: None,
400 infer_args: false,
401 }));
402
403 let path = self.arena.alloc(hir::Path { span, res: Res::Local(param_id), segments });
404 self.mk_expr(hir::ExprKind::Path(hir::QPath::Resolved(None, path)), span)
405 }
406
407 fn lower_delegation_body(
408 &mut self,
409 delegation: &Delegation,
410 is_method: bool,
411 param_count: usize,
412 generics: &mut GenericsGenerationResults<'hir>,
413 span: Span,
414 ) -> (BodyId, HirId) {
415 let block = delegation.body.as_deref();
416 let mut call_expr_id = HirId::INVALID;
417
418 let block_id = self.lower_body(|this| {
419 let mut parameters: Vec<hir::Param<'_>> = Vec::with_capacity(param_count);
420 let mut args: Vec<hir::Expr<'_>> = Vec::with_capacity(param_count);
421
422 for idx in 0..param_count {
423 let (param, pat_node_id) = this.generate_param(is_method, idx, span);
424 parameters.push(param);
425
426 let arg = if let Some(block) = block
427 && idx == 0
428 {
429 let mut self_resolver = SelfResolver {
430 ctxt: this,
431 path_id: delegation.id,
432 self_param_id: pat_node_id,
433 };
434 self_resolver.visit_block(block);
435 this.ident_and_label_to_local_id.insert(pat_node_id, param.pat.hir_id.local_id);
437 this.lower_target_expr(&block)
438 } else {
439 this.generate_arg(is_method, idx, param.pat.hir_id, span)
440 };
441 args.push(arg);
442 }
443
444 if param_count == 0
450 && let Some(block) = block
451 {
452 args.push(this.lower_target_expr(&block));
453 }
454
455 let (final_expr, hir_id) =
456 this.finalize_body_lowering(delegation, args, generics, span);
457
458 call_expr_id = hir_id;
459
460 (this.arena.alloc_from_iter(parameters), final_expr)
461 });
462
463 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);
464
465 (block_id, call_expr_id)
466 }
467
468 fn lower_target_expr(&mut self, block: &Block) -> hir::Expr<'hir> {
471 if let [stmt] = block.stmts.as_slice()
472 && let StmtKind::Expr(expr) = &stmt.kind
473 {
474 return self.lower_expr_mut(expr);
475 }
476
477 let block = self.lower_block(block, false);
478 self.mk_expr(hir::ExprKind::Block(block, None), block.span)
479 }
480
481 fn finalize_body_lowering(
482 &mut self,
483 delegation: &Delegation,
484 args: Vec<hir::Expr<'hir>>,
485 generics: &mut GenericsGenerationResults<'hir>,
486 span: Span,
487 ) -> (hir::Expr<'hir>, HirId) {
488 let path = self.lower_qpath(
489 delegation.id,
490 &delegation.qself,
491 &delegation.path,
492 ParamMode::Optional,
493 AllowReturnTypeNotation::No,
494 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
495 None,
496 );
497
498 let new_path = match path {
499 hir::QPath::Resolved(ty, path) => {
500 let mut new_path = path.clone();
501 let len = new_path.segments.len();
502
503 new_path.segments = self.arena.alloc_from_iter(
504 new_path.segments.iter().enumerate().map(|(idx, segment)| {
505 if idx + 2 == len {
506 self.process_segment(span, segment, &mut generics.parent)
507 } else if idx + 1 == len {
508 self.process_segment(span, segment, &mut generics.child)
509 } else {
510 segment.clone()
511 }
512 }),
513 );
514
515 hir::QPath::Resolved(ty, self.arena.alloc(new_path))
516 }
517 hir::QPath::TypeRelative(ty, segment) => {
518 let segment = self.process_segment(span, segment, &mut generics.child);
519
520 hir::QPath::TypeRelative(ty, self.arena.alloc(segment))
521 }
522 };
523
524 generics.self_ty_id = match new_path {
525 hir::QPath::Resolved(ty, _) => ty,
526 hir::QPath::TypeRelative(ty, _) => Some(ty),
527 }
528 .map(|ty| ty.hir_id);
529
530 let callee_path = self.arena.alloc(self.mk_expr(hir::ExprKind::Path(new_path), span));
531 let args = self.arena.alloc_from_iter(args);
532 let call = self.arena.alloc(self.mk_expr(hir::ExprKind::Call(callee_path, args), span));
533
534 let block = self.arena.alloc(hir::Block {
535 stmts: &[],
536 expr: Some(call),
537 hir_id: self.next_id(),
538 rules: hir::BlockCheckMode::DefaultBlock,
539 span,
540 targeted_by_break: false,
541 });
542
543 (self.mk_expr(hir::ExprKind::Block(block, None), span), call.hir_id)
544 }
545
546 fn process_segment(
547 &mut self,
548 span: Span,
549 segment: &hir::PathSegment<'hir>,
550 result: &mut GenericsGenerationResult<'hir>,
551 ) -> hir::PathSegment<'hir> {
552 let details = result.generics.args_propagation_details();
553
554 let generics = result.generics.into_hir_generics(self, span);
557 let segment = if details.should_propagate {
558 let args = generics.into_generic_args(self, span);
559
560 let args = if args.is_empty() { None } else { Some(args) };
562
563 hir::PathSegment { args, ..segment.clone() }
564 } else {
565 segment.clone()
566 };
567
568 if details.use_args_in_sig_inheritance {
569 result.args_segment_id = Some(segment.hir_id);
570 }
571
572 segment
573 }
574
575 fn generate_delegation_error(
576 &mut self,
577 span: Span,
578 delegation: &Delegation,
579 ) -> DelegationResults<'hir> {
580 let decl = self.arena.alloc(hir::FnDecl::dummy(span));
581
582 let header = self.generate_header_error();
583 let sig = hir::FnSig { decl, header, span };
584
585 let ident = self.lower_ident(delegation.ident);
586
587 let body_id = self.lower_body(|this| {
588 let path = this.lower_qpath(
589 delegation.id,
590 &delegation.qself,
591 &delegation.path,
592 ParamMode::Optional,
593 AllowReturnTypeNotation::No,
594 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
595 None,
596 );
597
598 let callee_path = this.arena.alloc(this.mk_expr(hir::ExprKind::Path(path), span));
599 let args = if let Some(block) = delegation.body.as_ref() {
600 this.arena.alloc_slice(&[this.lower_target_expr(block)])
601 } else {
602 &mut []
603 };
604
605 let call = this.arena.alloc(this.mk_expr(hir::ExprKind::Call(callee_path, args), span));
606
607 let block = this.arena.alloc(hir::Block {
608 stmts: &[],
609 expr: Some(call),
610 hir_id: this.next_id(),
611 rules: hir::BlockCheckMode::DefaultBlock,
612 span,
613 targeted_by_break: false,
614 });
615
616 (&[], this.mk_expr(hir::ExprKind::Block(block, None), span))
617 });
618
619 let generics = hir::Generics::empty();
620 DelegationResults { ident, generics, body_id, sig }
621 }
622
623 fn generate_header_error(&self) -> hir::FnHeader {
624 hir::FnHeader {
625 safety: hir::Safety::Safe.into(),
626 constness: hir::Constness::NotConst,
627 asyncness: hir::IsAsync::NotAsync,
628 abi: ExternAbi::Rust,
629 }
630 }
631
632 #[inline]
633 fn mk_expr(&mut self, kind: hir::ExprKind<'hir>, span: Span) -> hir::Expr<'hir> {
634 hir::Expr { hir_id: self.next_id(), kind, span }
635 }
636}
637
638struct SelfResolver<'a, 'b, 'hir> {
639 ctxt: &'a mut LoweringContext<'b, 'hir>,
640 path_id: NodeId,
641 self_param_id: NodeId,
642}
643
644impl SelfResolver<'_, '_, '_> {
645 fn try_replace_id(&mut self, id: NodeId) {
646 if let Some(res) = self.ctxt.get_partial_res(id)
647 && let Some(Res::Local(sig_id)) = res.full_res()
648 && sig_id == self.path_id
649 {
650 self.ctxt.partial_res_overrides.insert(id, self.self_param_id);
651 }
652 }
653}
654
655impl<'ast> Visitor<'ast> for SelfResolver<'_, '_, '_> {
656 fn visit_id(&mut self, id: NodeId) {
657 self.try_replace_id(id);
658 }
659}