Skip to main content

rustc_ast_lowering/
delegation.rs

1//! This module implements expansion of delegation items with early resolved paths.
2//! It includes a delegation to a free functions:
3//!
4//! ```ignore (illustrative)
5//! reuse module::name { target_expr_template }
6//! ```
7//!
8//! And delegation to a trait methods:
9//!
10//! ```ignore (illustrative)
11//! reuse <Type as Trait>::name { target_expr_template }
12//! ```
13//!
14//! After expansion for both cases we get:
15//!
16//! ```ignore (illustrative)
17//! fn name(
18//!     arg0: InferDelegation(sig_id, Input(0)),
19//!     arg1: InferDelegation(sig_id, Input(1)),
20//!     ...,
21//!     argN: InferDelegation(sig_id, Input(N)),
22//! ) -> InferDelegation(sig_id, Output) {
23//!     callee_path(target_expr_template(arg0), arg1, ..., argN)
24//! }
25//! ```
26//!
27//! Where `callee_path` is a path in delegation item e.g. `<Type as Trait>::name`.
28//! `sig_id` is a id of item from which the signature is inherited. It may be a delegation
29//! item id (`item_id`) in case of impl trait or path resolution id (`path_id`) otherwise.
30//!
31//! Since we do not have a proper way to obtain function type information by path resolution
32//! in AST, we mark each function parameter type as `InferDelegation` and inherit it during
33//! HIR ty lowering.
34//!
35//! Similarly generics, predicates and header are set to the "default" values.
36//! In case of discrepancy with callee function the `UnsupportedDelegation` error will
37//! also be emitted during HIR ty lowering.
38
39use 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, GenericArgsMode, ImplTraitContext, ImplTraitPosition, LoweringContext,
62    ParamMode, 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        // Delegation can be unresolved in illegal places such as function bodies in extern blocks (see #151356)
125        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 = self.lower_delegation_body(
148                    delegation,
149                    is_method,
150                    param_count,
151                    &mut generics,
152                    span,
153                );
154
155                let decl =
156                    self.lower_delegation_decl(sig_id, param_count, c_variadic, span, &generics);
157
158                let sig = self.lower_delegation_sig(sig_id, decl, span);
159                let ident = self.lower_ident(delegation.ident);
160
161                let generics = self.arena.alloc(hir::Generics {
162                    has_where_clause_predicates: false,
163                    params: self.arena.alloc_from_iter(generics.all_params(span, self)),
164                    predicates: self.arena.alloc_from_iter(generics.all_predicates(span, self)),
165                    span,
166                    where_clause_span: span,
167                });
168
169                DelegationResults { body_id, sig, ident, generics }
170            }
171            Err(_) => self.generate_delegation_error(span, delegation),
172        }
173    }
174
175    fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
176        let new_attrs =
177            self.create_new_attrs(ATTRS_ADDITIONS, span, sig_id, self.attrs.get(&PARENT_ID));
178
179        if new_attrs.is_empty() {
180            return;
181        }
182
183        let new_arena_allocated_attrs = match self.attrs.get(&PARENT_ID) {
184            Some(existing_attrs) => self.arena.alloc_from_iter(
185                existing_attrs.iter().map(|a| a.clone()).chain(new_attrs.into_iter()),
186            ),
187            None => self.arena.alloc_from_iter(new_attrs.into_iter()),
188        };
189
190        self.attrs.insert(PARENT_ID, new_arena_allocated_attrs);
191    }
192
193    fn create_new_attrs(
194        &self,
195        candidate_additions: &[AttrAdditionInfo],
196        span: Span,
197        sig_id: DefId,
198        existing_attrs: Option<&&[hir::Attribute]>,
199    ) -> Vec<hir::Attribute> {
200        candidate_additions
201            .iter()
202            .filter_map(|addition_info| {
203                if let Some(existing_attrs) = existing_attrs
204                    && existing_attrs
205                        .iter()
206                        .any(|existing_attr| (addition_info.equals)(existing_attr))
207                {
208                    return None;
209                }
210
211                match addition_info.kind {
212                    AttrAdditionKind::Default { factory } => Some(factory(span)),
213                    AttrAdditionKind::Inherit { factory, .. } =>
214                    {
215                        #[allow(deprecated)]
216                        self.tcx
217                            .get_all_attrs(sig_id)
218                            .iter()
219                            .find_map(|a| (addition_info.equals)(a).then(|| factory(span, a)))
220                    }
221                }
222            })
223            .collect::<Vec<_>>()
224    }
225
226    fn get_sig_id(&self, mut node_id: NodeId, span: Span) -> Result<DefId, ErrorGuaranteed> {
227        let mut visited: FxHashSet<NodeId> = Default::default();
228        let mut path: SmallVec<[DefId; 1]> = Default::default();
229
230        loop {
231            visited.insert(node_id);
232
233            let Some(def_id) = self.get_resolution_id(node_id) else {
234                return Err(self.tcx.dcx().span_delayed_bug(
235                    span,
236                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("LoweringContext: couldn\'t resolve node {0:?} in delegation item",
                node_id))
    })format!(
237                        "LoweringContext: couldn't resolve node {:?} in delegation item",
238                        node_id
239                    ),
240                ));
241            };
242
243            path.push(def_id);
244
245            // If def_id is in local crate and it corresponds to another delegation
246            // it means that we refer to another delegation as a callee, so in order to obtain
247            // a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
248            if let Some(local_id) = def_id.as_local()
249                && let Some(delegation_info) = self.resolver.delegation_info(local_id)
250            {
251                node_id = delegation_info.resolution_node;
252                if visited.contains(&node_id) {
253                    // We encountered a cycle in the resolution, or delegation callee refers to non-existent
254                    // entity, in this case emit an error.
255                    return Err(match visited.len() {
256                        1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
257                        _ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
258                    });
259                }
260            } else {
261                return Ok(path[0]);
262            }
263        }
264    }
265
266    fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
267        self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
268    }
269
270    // Function parameter count, including C variadic `...` if present.
271    fn param_count(&self, def_id: DefId) -> (usize, bool /*c_variadic*/) {
272        let sig = self.tcx.fn_sig(def_id).skip_binder().skip_binder();
273        (sig.inputs().len() + usize::from(sig.c_variadic()), sig.c_variadic())
274    }
275
276    fn lower_delegation_decl(
277        &mut self,
278        sig_id: DefId,
279        param_count: usize,
280        c_variadic: bool,
281        span: Span,
282        generics: &GenericsGenerationResults<'hir>,
283    ) -> &'hir hir::FnDecl<'hir> {
284        // The last parameter in C variadic functions is skipped in the signature,
285        // like during regular lowering.
286        let decl_param_count = param_count - c_variadic as usize;
287        let inputs = self.arena.alloc_from_iter((0..decl_param_count).map(|arg| hir::Ty {
288            hir_id: self.next_id(),
289            kind: hir::TyKind::InferDelegation(hir::InferDelegation::Sig(
290                sig_id,
291                hir::InferDelegationSig::Input(arg),
292            )),
293            span,
294        }));
295
296        let output = self.arena.alloc(hir::Ty {
297            hir_id: self.next_id(),
298            kind: hir::TyKind::InferDelegation(hir::InferDelegation::Sig(
299                sig_id,
300                hir::InferDelegationSig::Output(self.arena.alloc(hir::DelegationGenerics {
301                    child_args_segment_id: generics.child.args_segment_id,
302                    parent_args_segment_id: generics.parent.args_segment_id,
303                    self_ty_id: generics.self_ty_id,
304                    propagate_self_ty: generics.propagate_self_ty,
305                })),
306            )),
307            span,
308        });
309
310        self.arena.alloc(hir::FnDecl {
311            inputs,
312            output: hir::FnRetTy::Return(output),
313            fn_decl_kind: FnDeclFlags::default()
314                .set_lifetime_elision_allowed(true)
315                .set_c_variadic(c_variadic),
316        })
317    }
318
319    fn lower_delegation_sig(
320        &mut self,
321        sig_id: DefId,
322        decl: &'hir hir::FnDecl<'hir>,
323        span: Span,
324    ) -> hir::FnSig<'hir> {
325        let sig = self.tcx.fn_sig(sig_id).skip_binder().skip_binder();
326        let asyncness = match self.tcx.asyncness(sig_id) {
327            Asyncness::Yes => hir::IsAsync::Async(span),
328            Asyncness::No => hir::IsAsync::NotAsync,
329        };
330
331        let header = hir::FnHeader {
332            safety: if self.tcx.codegen_fn_attrs(sig_id).safe_target_features {
333                hir::HeaderSafety::SafeTargetFeatures
334            } else {
335                hir::HeaderSafety::Normal(sig.safety())
336            },
337            constness: self.tcx.constness(sig_id),
338            asyncness,
339            abi: sig.abi(),
340        };
341
342        hir::FnSig { decl, header, span }
343    }
344
345    fn generate_param(
346        &mut self,
347        is_method: bool,
348        idx: usize,
349        span: Span,
350    ) -> (hir::Param<'hir>, NodeId) {
351        let pat_node_id = self.next_node_id();
352        let pat_id = self.lower_node_id(pat_node_id);
353        // FIXME(cjgillot) AssocItem currently relies on self parameter being exactly named `self`.
354        let name = if is_method && idx == 0 {
355            kw::SelfLower
356        } else {
357            Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", idx))
    })format!("arg{idx}"))
358        };
359        let ident = Ident::with_dummy_span(name);
360        let pat = self.arena.alloc(hir::Pat {
361            hir_id: pat_id,
362            kind: hir::PatKind::Binding(hir::BindingMode::NONE, pat_id, ident, None),
363            span,
364            default_binding_modes: false,
365        });
366
367        (hir::Param { hir_id: self.next_id(), pat, ty_span: span, span }, pat_node_id)
368    }
369
370    fn generate_arg(
371        &mut self,
372        is_method: bool,
373        idx: usize,
374        param_id: HirId,
375        span: Span,
376    ) -> hir::Expr<'hir> {
377        // FIXME(cjgillot) AssocItem currently relies on self parameter being exactly named `self`.
378        let name = if is_method && idx == 0 {
379            kw::SelfLower
380        } else {
381            Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("arg{0}", idx))
    })format!("arg{idx}"))
382        };
383
384        let segments = self.arena.alloc_from_iter(iter::once(hir::PathSegment {
385            ident: Ident::with_dummy_span(name),
386            hir_id: self.next_id(),
387            res: Res::Local(param_id),
388            args: None,
389            infer_args: false,
390        }));
391
392        let path = self.arena.alloc(hir::Path { span, res: Res::Local(param_id), segments });
393        self.mk_expr(hir::ExprKind::Path(hir::QPath::Resolved(None, path)), span)
394    }
395
396    fn lower_delegation_body(
397        &mut self,
398        delegation: &Delegation,
399        is_method: bool,
400        param_count: usize,
401        generics: &mut GenericsGenerationResults<'hir>,
402        span: Span,
403    ) -> BodyId {
404        let block = delegation.body.as_deref();
405
406        self.lower_body(|this| {
407            let mut parameters: Vec<hir::Param<'_>> = Vec::with_capacity(param_count);
408            let mut args: Vec<hir::Expr<'_>> = Vec::with_capacity(param_count);
409
410            for idx in 0..param_count {
411                let (param, pat_node_id) = this.generate_param(is_method, idx, span);
412                parameters.push(param);
413
414                let arg = if let Some(block) = block
415                    && idx == 0
416                {
417                    let mut self_resolver = SelfResolver {
418                        ctxt: this,
419                        path_id: delegation.id,
420                        self_param_id: pat_node_id,
421                    };
422                    self_resolver.visit_block(block);
423                    // Target expr needs to lower `self` path.
424                    this.ident_and_label_to_local_id.insert(pat_node_id, param.pat.hir_id.local_id);
425                    this.lower_target_expr(&block)
426                } else {
427                    this.generate_arg(is_method, idx, param.pat.hir_id, span)
428                };
429                args.push(arg);
430            }
431
432            // If we have no params in signature function but user still wrote some code in
433            // delegation body, then add this code as first arg, eventually an error will be shown,
434            // also nested delegations may need to access information about this code (#154332),
435            // so it is better to leave this code as opposed to bodies of extern functions,
436            // which are completely erased from existence.
437            if param_count == 0
438                && let Some(block) = block
439            {
440                args.push(this.lower_target_expr(&block));
441            }
442
443            let final_expr = this.finalize_body_lowering(delegation, args, generics, span);
444
445            (this.arena.alloc_from_iter(parameters), final_expr)
446        })
447    }
448
449    // FIXME(fn_delegation): Alternatives for target expression lowering:
450    // https://github.com/rust-lang/rfcs/pull/3530#issuecomment-2197170600.
451    fn lower_target_expr(&mut self, block: &Block) -> hir::Expr<'hir> {
452        if let [stmt] = block.stmts.as_slice()
453            && let StmtKind::Expr(expr) = &stmt.kind
454        {
455            return self.lower_expr_mut(expr);
456        }
457
458        let block = self.lower_block(block, false);
459        self.mk_expr(hir::ExprKind::Block(block, None), block.span)
460    }
461
462    // Generates expression for the resulting body. If possible, `MethodCall` is used
463    // to allow autoref/autoderef for target expression. For example in:
464    //
465    // trait Trait : Sized {
466    //     fn by_value(self) -> i32 { 1 }
467    //     fn by_mut_ref(&mut self) -> i32 { 2 }
468    //     fn by_ref(&self) -> i32 { 3 }
469    // }
470    //
471    // struct NewType(SomeType);
472    // impl Trait for NewType {
473    //     reuse Trait::* { self.0 }
474    // }
475    //
476    // `self.0` will automatically coerce.
477    fn finalize_body_lowering(
478        &mut self,
479        delegation: &Delegation,
480        args: Vec<hir::Expr<'hir>>,
481        generics: &mut GenericsGenerationResults<'hir>,
482        span: Span,
483    ) -> hir::Expr<'hir> {
484        let args = self.arena.alloc_from_iter(args);
485
486        let has_generic_args =
487            delegation.path.segments.iter().rev().skip(1).any(|segment| segment.args.is_some());
488
489        let call = if self
490            .get_resolution_id(delegation.id)
491            .map(|def_id| self.is_method(def_id, span))
492            .unwrap_or_default()
493            && delegation.qself.is_none()
494            && !has_generic_args
495            && !args.is_empty()
496        {
497            let ast_segment = delegation.path.segments.last().unwrap();
498            let segment = self.lower_path_segment(
499                delegation.path.span,
500                ast_segment,
501                ParamMode::Optional,
502                GenericArgsMode::Err,
503                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
504                None,
505            );
506
507            // FIXME(fn_delegation): proper support for parent generics propagation
508            // in method call scenario.
509            let segment = self.process_segment(span, &segment, &mut generics.child);
510            let segment = self.arena.alloc(segment);
511
512            self.arena.alloc(hir::Expr {
513                hir_id: self.next_id(),
514                kind: hir::ExprKind::MethodCall(segment, &args[0], &args[1..], span),
515                span,
516            })
517        } else {
518            let path = self.lower_qpath(
519                delegation.id,
520                &delegation.qself,
521                &delegation.path,
522                ParamMode::Optional,
523                AllowReturnTypeNotation::No,
524                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
525                None,
526            );
527
528            let new_path = match path {
529                hir::QPath::Resolved(ty, path) => {
530                    let mut new_path = path.clone();
531                    let len = new_path.segments.len();
532
533                    new_path.segments = self.arena.alloc_from_iter(
534                        new_path.segments.iter().enumerate().map(|(idx, segment)| {
535                            if idx + 2 == len {
536                                self.process_segment(span, segment, &mut generics.parent)
537                            } else if idx + 1 == len {
538                                self.process_segment(span, segment, &mut generics.child)
539                            } else {
540                                segment.clone()
541                            }
542                        }),
543                    );
544
545                    hir::QPath::Resolved(ty, self.arena.alloc(new_path))
546                }
547                hir::QPath::TypeRelative(ty, segment) => {
548                    let segment = self.process_segment(span, segment, &mut generics.child);
549
550                    hir::QPath::TypeRelative(ty, self.arena.alloc(segment))
551                }
552            };
553
554            generics.self_ty_id = match new_path {
555                hir::QPath::Resolved(ty, _) => ty,
556                hir::QPath::TypeRelative(ty, _) => Some(ty),
557            }
558            .map(|ty| ty.hir_id);
559
560            let callee_path = self.arena.alloc(self.mk_expr(hir::ExprKind::Path(new_path), span));
561            self.arena.alloc(self.mk_expr(hir::ExprKind::Call(callee_path, args), span))
562        };
563
564        let block = self.arena.alloc(hir::Block {
565            stmts: &[],
566            expr: Some(call),
567            hir_id: self.next_id(),
568            rules: hir::BlockCheckMode::DefaultBlock,
569            span,
570            targeted_by_break: false,
571        });
572
573        self.mk_expr(hir::ExprKind::Block(block, None), span)
574    }
575
576    fn process_segment(
577        &mut self,
578        span: Span,
579        segment: &hir::PathSegment<'hir>,
580        result: &mut GenericsGenerationResult<'hir>,
581    ) -> hir::PathSegment<'hir> {
582        let details = result.generics.args_propagation_details();
583
584        let segment = if details.should_propagate {
585            let generics = result.generics.into_hir_generics(self, span);
586            let args = generics.into_generic_args(self, span);
587
588            // Needed for better error messages (`trait-impl-wrong-args-count.rs` test).
589            let args = if args.is_empty() { None } else { Some(args) };
590
591            hir::PathSegment { args, ..segment.clone() }
592        } else {
593            segment.clone()
594        };
595
596        if details.use_args_in_sig_inheritance {
597            result.args_segment_id = Some(segment.hir_id);
598        }
599
600        segment
601    }
602
603    fn generate_delegation_error(
604        &mut self,
605        span: Span,
606        delegation: &Delegation,
607    ) -> DelegationResults<'hir> {
608        let decl = self.arena.alloc(hir::FnDecl::dummy(span));
609
610        let header = self.generate_header_error();
611        let sig = hir::FnSig { decl, header, span };
612
613        let ident = self.lower_ident(delegation.ident);
614
615        let body_id = self.lower_body(|this| {
616            let path = this.lower_qpath(
617                delegation.id,
618                &delegation.qself,
619                &delegation.path,
620                ParamMode::Optional,
621                AllowReturnTypeNotation::No,
622                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
623                None,
624            );
625
626            let callee_path = this.arena.alloc(this.mk_expr(hir::ExprKind::Path(path), span));
627            let args = if let Some(block) = delegation.body.as_ref() {
628                this.arena.alloc_slice(&[this.lower_target_expr(block)])
629            } else {
630                &mut []
631            };
632
633            let call = this.arena.alloc(this.mk_expr(hir::ExprKind::Call(callee_path, args), span));
634
635            let block = this.arena.alloc(hir::Block {
636                stmts: &[],
637                expr: Some(call),
638                hir_id: this.next_id(),
639                rules: hir::BlockCheckMode::DefaultBlock,
640                span,
641                targeted_by_break: false,
642            });
643
644            (&[], this.mk_expr(hir::ExprKind::Block(block, None), span))
645        });
646
647        let generics = hir::Generics::empty();
648        DelegationResults { ident, generics, body_id, sig }
649    }
650
651    fn generate_header_error(&self) -> hir::FnHeader {
652        hir::FnHeader {
653            safety: hir::Safety::Safe.into(),
654            constness: hir::Constness::NotConst,
655            asyncness: hir::IsAsync::NotAsync,
656            abi: ExternAbi::Rust,
657        }
658    }
659
660    #[inline]
661    fn mk_expr(&mut self, kind: hir::ExprKind<'hir>, span: Span) -> hir::Expr<'hir> {
662        hir::Expr { hir_id: self.next_id(), kind, span }
663    }
664}
665
666struct SelfResolver<'a, 'b, 'hir> {
667    ctxt: &'a mut LoweringContext<'b, 'hir>,
668    path_id: NodeId,
669    self_param_id: NodeId,
670}
671
672impl SelfResolver<'_, '_, '_> {
673    fn try_replace_id(&mut self, id: NodeId) {
674        if let Some(res) = self.ctxt.get_partial_res(id)
675            && let Some(Res::Local(sig_id)) = res.full_res()
676            && sig_id == self.path_id
677        {
678            self.ctxt.partial_res_overrides.insert(id, self.self_param_id);
679        }
680    }
681}
682
683impl<'ast> Visitor<'ast> for SelfResolver<'_, '_, '_> {
684    fn visit_id(&mut self, id: NodeId) {
685        self.try_replace_id(id);
686    }
687}