1use std::assert_matches::debug_assert_matches;
10use std::borrow::Cow;
11use std::collections::BTreeSet;
12use std::collections::hash_map::Entry;
13use std::mem::{replace, swap, take};
14
15use rustc_ast::ptr::P;
16use rustc_ast::visit::{
17 AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,
18};
19use rustc_ast::*;
20use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
21use rustc_data_structures::unord::{UnordMap, UnordSet};
22use rustc_errors::codes::*;
23use rustc_errors::{
24 Applicability, DiagArgValue, ErrorGuaranteed, IntoDiagArg, StashKey, Suggestions,
25};
26use rustc_hir::def::Namespace::{self, *};
27use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS};
28use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId};
29use rustc_hir::{MissingLifetimeKind, PrimTy, TraitCandidate};
30use rustc_middle::middle::resolve_bound_vars::Set1;
31use rustc_middle::ty::DelegationFnSig;
32use rustc_middle::{bug, span_bug};
33use rustc_session::config::{CrateType, ResolveDocLinks};
34use rustc_session::lint::{self, BuiltinLintDiag};
35use rustc_session::parse::feature_err;
36use rustc_span::source_map::{Spanned, respan};
37use rustc_span::{BytePos, Ident, Span, Symbol, SyntaxContext, kw, sym};
38use smallvec::{SmallVec, smallvec};
39use thin_vec::ThinVec;
40use tracing::{debug, instrument, trace};
41
42use crate::{
43 BindingError, BindingKey, Finalize, LexicalScopeBinding, Module, ModuleOrUniformRoot,
44 NameBinding, ParentScope, PathResult, ResolutionError, Resolver, Segment, TyCtxt, UseError,
45 Used, errors, path_names_to_string, rustdoc,
46};
47
48mod diagnostics;
49
50type Res = def::Res<NodeId>;
51
52use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
53
54#[derive(Copy, Clone, Debug)]
55struct BindingInfo {
56 span: Span,
57 annotation: BindingMode,
58}
59
60#[derive(Copy, Clone, PartialEq, Eq, Debug)]
61pub(crate) enum PatternSource {
62 Match,
63 Let,
64 For,
65 FnParam,
66}
67
68#[derive(Copy, Clone, Debug, PartialEq, Eq)]
69enum IsRepeatExpr {
70 No,
71 Yes,
72}
73
74struct IsNeverPattern;
75
76#[derive(Copy, Clone, Debug, PartialEq, Eq)]
79enum AnonConstKind {
80 EnumDiscriminant,
81 FieldDefaultValue,
82 InlineConst,
83 ConstArg(IsRepeatExpr),
84}
85
86impl PatternSource {
87 fn descr(self) -> &'static str {
88 match self {
89 PatternSource::Match => "match binding",
90 PatternSource::Let => "let binding",
91 PatternSource::For => "for binding",
92 PatternSource::FnParam => "function parameter",
93 }
94 }
95}
96
97impl IntoDiagArg for PatternSource {
98 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
99 DiagArgValue::Str(Cow::Borrowed(self.descr()))
100 }
101}
102
103#[derive(PartialEq)]
107enum PatBoundCtx {
108 Product,
110 Or,
112}
113
114type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;
126
127#[derive(Copy, Clone, Debug)]
129pub(crate) enum HasGenericParams {
130 Yes(Span),
131 No,
132}
133
134#[derive(Copy, Clone, Debug, Eq, PartialEq)]
136pub(crate) enum ConstantHasGenerics {
137 Yes,
138 No(NoConstantGenericsReason),
139}
140
141impl ConstantHasGenerics {
142 fn force_yes_if(self, b: bool) -> Self {
143 if b { Self::Yes } else { self }
144 }
145}
146
147#[derive(Copy, Clone, Debug, Eq, PartialEq)]
149pub(crate) enum NoConstantGenericsReason {
150 NonTrivialConstArg,
157 IsEnumDiscriminant,
166}
167
168#[derive(Copy, Clone, Debug, Eq, PartialEq)]
169pub(crate) enum ConstantItemKind {
170 Const,
171 Static,
172}
173
174impl ConstantItemKind {
175 pub(crate) fn as_str(&self) -> &'static str {
176 match self {
177 Self::Const => "const",
178 Self::Static => "static",
179 }
180 }
181}
182
183#[derive(Debug, Copy, Clone, PartialEq, Eq)]
184enum RecordPartialRes {
185 Yes,
186 No,
187}
188
189#[derive(Copy, Clone, Debug)]
192pub(crate) enum RibKind<'ra> {
193 Normal,
195
196 AssocItem,
201
202 FnOrCoroutine,
204
205 Item(HasGenericParams, DefKind),
207
208 ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
213
214 Module(Module<'ra>),
216
217 MacroDefinition(DefId),
219
220 ForwardGenericParamBan(ForwardGenericParamBanReason),
224
225 ConstParamTy,
228
229 InlineAsmSym,
232}
233
234#[derive(Copy, Clone, PartialEq, Eq, Debug)]
235pub(crate) enum ForwardGenericParamBanReason {
236 Default,
237 ConstParamTy,
238}
239
240impl RibKind<'_> {
241 pub(crate) fn contains_params(&self) -> bool {
244 match self {
245 RibKind::Normal
246 | RibKind::FnOrCoroutine
247 | RibKind::ConstantItem(..)
248 | RibKind::Module(_)
249 | RibKind::MacroDefinition(_)
250 | RibKind::InlineAsmSym => false,
251 RibKind::ConstParamTy
252 | RibKind::AssocItem
253 | RibKind::Item(..)
254 | RibKind::ForwardGenericParamBan(_) => true,
255 }
256 }
257
258 fn is_label_barrier(self) -> bool {
260 match self {
261 RibKind::Normal | RibKind::MacroDefinition(..) => false,
262
263 RibKind::AssocItem
264 | RibKind::FnOrCoroutine
265 | RibKind::Item(..)
266 | RibKind::ConstantItem(..)
267 | RibKind::Module(..)
268 | RibKind::ForwardGenericParamBan(_)
269 | RibKind::ConstParamTy
270 | RibKind::InlineAsmSym => true,
271 }
272 }
273}
274
275#[derive(Debug)]
288pub(crate) struct Rib<'ra, R = Res> {
289 pub bindings: FxIndexMap<Ident, R>,
290 pub patterns_with_skipped_bindings: UnordMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>,
291 pub kind: RibKind<'ra>,
292}
293
294impl<'ra, R> Rib<'ra, R> {
295 fn new(kind: RibKind<'ra>) -> Rib<'ra, R> {
296 Rib {
297 bindings: Default::default(),
298 patterns_with_skipped_bindings: Default::default(),
299 kind,
300 }
301 }
302}
303
304#[derive(Clone, Copy, Debug)]
305enum LifetimeUseSet {
306 One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
307 Many,
308}
309
310#[derive(Copy, Clone, Debug)]
311enum LifetimeRibKind {
312 Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
317
318 AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
335
336 Elided(LifetimeRes),
338
339 AnonymousReportError,
345
346 StaticIfNoLifetimeInScope { lint_id: NodeId, emit_lint: bool },
350
351 ElisionFailure,
353
354 ConstParamTy,
359
360 ConcreteAnonConst(NoConstantGenericsReason),
366
367 Item,
369}
370
371#[derive(Copy, Clone, Debug)]
372enum LifetimeBinderKind {
373 BareFnType,
374 PolyTrait,
375 WhereBound,
376 Item,
377 ConstItem,
378 Function,
379 Closure,
380 ImplBlock,
381}
382
383impl LifetimeBinderKind {
384 fn descr(self) -> &'static str {
385 use LifetimeBinderKind::*;
386 match self {
387 BareFnType => "type",
388 PolyTrait => "bound",
389 WhereBound => "bound",
390 Item | ConstItem => "item",
391 ImplBlock => "impl block",
392 Function => "function",
393 Closure => "closure",
394 }
395 }
396}
397
398#[derive(Debug)]
399struct LifetimeRib {
400 kind: LifetimeRibKind,
401 bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
403}
404
405impl LifetimeRib {
406 fn new(kind: LifetimeRibKind) -> LifetimeRib {
407 LifetimeRib { bindings: Default::default(), kind }
408 }
409}
410
411#[derive(Copy, Clone, PartialEq, Eq, Debug)]
412pub(crate) enum AliasPossibility {
413 No,
414 Maybe,
415}
416
417#[derive(Copy, Clone, Debug)]
418pub(crate) enum PathSource<'a, 'c> {
419 Type,
421 Trait(AliasPossibility),
423 Expr(Option<&'a Expr>),
425 Pat,
427 Struct,
429 TupleStruct(Span, &'a [Span]),
431 TraitItem(Namespace, &'c PathSource<'a, 'c>),
436 Delegation,
438 PreciseCapturingArg(Namespace),
440 ReturnTypeNotation,
442 DefineOpaques,
444}
445
446impl<'a> PathSource<'a, '_> {
447 fn namespace(self) -> Namespace {
448 match self {
449 PathSource::Type
450 | PathSource::Trait(_)
451 | PathSource::Struct
452 | PathSource::DefineOpaques => TypeNS,
453 PathSource::Expr(..)
454 | PathSource::Pat
455 | PathSource::TupleStruct(..)
456 | PathSource::Delegation
457 | PathSource::ReturnTypeNotation => ValueNS,
458 PathSource::TraitItem(ns, _) => ns,
459 PathSource::PreciseCapturingArg(ns) => ns,
460 }
461 }
462
463 fn defer_to_typeck(self) -> bool {
464 match self {
465 PathSource::Type
466 | PathSource::Expr(..)
467 | PathSource::Pat
468 | PathSource::Struct
469 | PathSource::TupleStruct(..)
470 | PathSource::ReturnTypeNotation => true,
471 PathSource::Trait(_)
472 | PathSource::TraitItem(..)
473 | PathSource::DefineOpaques
474 | PathSource::Delegation
475 | PathSource::PreciseCapturingArg(..) => false,
476 }
477 }
478
479 fn descr_expected(self) -> &'static str {
480 match &self {
481 PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
482 PathSource::Type => "type",
483 PathSource::Trait(_) => "trait",
484 PathSource::Pat => "unit struct, unit variant or constant",
485 PathSource::Struct => "struct, variant or union type",
486 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
487 | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
488 PathSource::TraitItem(ns, _) => match ns {
489 TypeNS => "associated type",
490 ValueNS => "method or associated constant",
491 MacroNS => bug!("associated macro"),
492 },
493 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
494 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
497 ExprKind::Path(_, path)
499 if let [segment, _] = path.segments.as_slice()
500 && segment.ident.name == kw::PathRoot =>
501 {
502 "external crate"
503 }
504 ExprKind::Path(_, path)
505 if let Some(segment) = path.segments.last()
506 && let Some(c) = segment.ident.to_string().chars().next()
507 && c.is_uppercase() =>
508 {
509 "function, tuple struct or tuple variant"
510 }
511 _ => "function",
512 },
513 _ => "value",
514 },
515 PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
516 PathSource::PreciseCapturingArg(..) => "type or const parameter",
517 }
518 }
519
520 fn is_call(self) -> bool {
521 matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
522 }
523
524 pub(crate) fn is_expected(self, res: Res) -> bool {
525 match self {
526 PathSource::DefineOpaques => {
527 matches!(
528 res,
529 Res::Def(
530 DefKind::Struct
531 | DefKind::Union
532 | DefKind::Enum
533 | DefKind::TyAlias
534 | DefKind::AssocTy,
535 _
536 ) | Res::SelfTyAlias { .. }
537 )
538 }
539 PathSource::Type => matches!(
540 res,
541 Res::Def(
542 DefKind::Struct
543 | DefKind::Union
544 | DefKind::Enum
545 | DefKind::Trait
546 | DefKind::TraitAlias
547 | DefKind::TyAlias
548 | DefKind::AssocTy
549 | DefKind::TyParam
550 | DefKind::OpaqueTy
551 | DefKind::ForeignTy,
552 _,
553 ) | Res::PrimTy(..)
554 | Res::SelfTyParam { .. }
555 | Res::SelfTyAlias { .. }
556 ),
557 PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
558 PathSource::Trait(AliasPossibility::Maybe) => {
559 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
560 }
561 PathSource::Expr(..) => matches!(
562 res,
563 Res::Def(
564 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
565 | DefKind::Const
566 | DefKind::Static { .. }
567 | DefKind::Fn
568 | DefKind::AssocFn
569 | DefKind::AssocConst
570 | DefKind::ConstParam,
571 _,
572 ) | Res::Local(..)
573 | Res::SelfCtor(..)
574 ),
575 PathSource::Pat => {
576 res.expected_in_unit_struct_pat()
577 || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
578 }
579 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
580 PathSource::Struct => matches!(
581 res,
582 Res::Def(
583 DefKind::Struct
584 | DefKind::Union
585 | DefKind::Variant
586 | DefKind::TyAlias
587 | DefKind::AssocTy,
588 _,
589 ) | Res::SelfTyParam { .. }
590 | Res::SelfTyAlias { .. }
591 ),
592 PathSource::TraitItem(ns, _) => match res {
593 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
594 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
595 _ => false,
596 },
597 PathSource::ReturnTypeNotation => match res {
598 Res::Def(DefKind::AssocFn, _) => true,
599 _ => false,
600 },
601 PathSource::Delegation => matches!(res, Res::Def(DefKind::Fn | DefKind::AssocFn, _)),
602 PathSource::PreciseCapturingArg(ValueNS) => {
603 matches!(res, Res::Def(DefKind::ConstParam, _))
604 }
605 PathSource::PreciseCapturingArg(TypeNS) => matches!(
607 res,
608 Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
609 ),
610 PathSource::PreciseCapturingArg(MacroNS) => false,
611 }
612 }
613
614 fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
615 match (self, has_unexpected_resolution) {
616 (PathSource::Trait(_), true) => E0404,
617 (PathSource::Trait(_), false) => E0405,
618 (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
619 (PathSource::Type | PathSource::DefineOpaques, false) => E0412,
620 (PathSource::Struct, true) => E0574,
621 (PathSource::Struct, false) => E0422,
622 (PathSource::Expr(..), true) | (PathSource::Delegation, true) => E0423,
623 (PathSource::Expr(..), false) | (PathSource::Delegation, false) => E0425,
624 (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
625 (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
626 (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
627 (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
628 (PathSource::PreciseCapturingArg(..), true) => E0799,
629 (PathSource::PreciseCapturingArg(..), false) => E0800,
630 }
631 }
632}
633
634#[derive(Clone, Copy)]
638enum MaybeExported<'a> {
639 Ok(NodeId),
640 Impl(Option<DefId>),
641 ImplItem(Result<DefId, &'a Visibility>),
642 NestedUse(&'a Visibility),
643}
644
645impl MaybeExported<'_> {
646 fn eval(self, r: &Resolver<'_, '_>) -> bool {
647 let def_id = match self {
648 MaybeExported::Ok(node_id) => Some(r.local_def_id(node_id)),
649 MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
650 trait_def_id.as_local()
651 }
652 MaybeExported::Impl(None) => return true,
653 MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
654 return vis.kind.is_pub();
655 }
656 };
657 def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
658 }
659}
660
661#[derive(Debug)]
663pub(crate) struct UnnecessaryQualification<'ra> {
664 pub binding: LexicalScopeBinding<'ra>,
665 pub node_id: NodeId,
666 pub path_span: Span,
667 pub removal_span: Span,
668}
669
670#[derive(Default, Debug)]
671struct DiagMetadata<'ast> {
672 current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
674
675 current_self_type: Option<Ty>,
677
678 current_self_item: Option<NodeId>,
680
681 current_item: Option<&'ast Item>,
683
684 currently_processing_generic_args: bool,
687
688 current_function: Option<(FnKind<'ast>, Span)>,
690
691 unused_labels: FxIndexMap<NodeId, Span>,
694
695 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
697
698 current_pat: Option<&'ast Pat>,
699
700 in_if_condition: Option<&'ast Expr>,
702
703 in_assignment: Option<&'ast Expr>,
705 is_assign_rhs: bool,
706
707 in_non_gat_assoc_type: Option<bool>,
709
710 in_range: Option<(&'ast Expr, &'ast Expr)>,
712
713 current_trait_object: Option<&'ast [ast::GenericBound]>,
716
717 current_where_predicate: Option<&'ast WherePredicate>,
719
720 current_type_path: Option<&'ast Ty>,
721
722 current_impl_items: Option<&'ast [P<AssocItem>]>,
724
725 currently_processing_impl_trait: Option<(TraitRef, Ty)>,
727
728 current_elision_failures: Vec<MissingLifetime>,
731}
732
733struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
734 r: &'a mut Resolver<'ra, 'tcx>,
735
736 parent_scope: ParentScope<'ra>,
738
739 ribs: PerNS<Vec<Rib<'ra>>>,
741
742 last_block_rib: Option<Rib<'ra>>,
744
745 label_ribs: Vec<Rib<'ra, NodeId>>,
747
748 lifetime_ribs: Vec<LifetimeRib>,
750
751 lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
757
758 current_trait_ref: Option<(Module<'ra>, TraitRef)>,
760
761 diag_metadata: Box<DiagMetadata<'ast>>,
763
764 in_func_body: bool,
770
771 lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
773}
774
775impl<'ra: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
777 fn visit_attribute(&mut self, _: &'ast Attribute) {
778 }
781 fn visit_item(&mut self, item: &'ast Item) {
782 let prev = replace(&mut self.diag_metadata.current_item, Some(item));
783 let old_ignore = replace(&mut self.in_func_body, false);
785 self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
786 self.in_func_body = old_ignore;
787 self.diag_metadata.current_item = prev;
788 }
789 fn visit_arm(&mut self, arm: &'ast Arm) {
790 self.resolve_arm(arm);
791 }
792 fn visit_block(&mut self, block: &'ast Block) {
793 let old_macro_rules = self.parent_scope.macro_rules;
794 self.resolve_block(block);
795 self.parent_scope.macro_rules = old_macro_rules;
796 }
797 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
798 bug!("encountered anon const without a manual call to `resolve_anon_const`: {constant:#?}");
799 }
800 fn visit_expr(&mut self, expr: &'ast Expr) {
801 self.resolve_expr(expr, None);
802 }
803 fn visit_pat(&mut self, p: &'ast Pat) {
804 let prev = self.diag_metadata.current_pat;
805 self.diag_metadata.current_pat = Some(p);
806
807 if let PatKind::Guard(subpat, _) = &p.kind {
808 self.visit_pat(subpat);
810 } else {
811 visit::walk_pat(self, p);
812 }
813
814 self.diag_metadata.current_pat = prev;
815 }
816 fn visit_local(&mut self, local: &'ast Local) {
817 let local_spans = match local.pat.kind {
818 PatKind::Wild => None,
820 _ => Some((
821 local.pat.span,
822 local.ty.as_ref().map(|ty| ty.span),
823 local.kind.init().map(|init| init.span),
824 )),
825 };
826 let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
827 self.resolve_local(local);
828 self.diag_metadata.current_let_binding = original;
829 }
830 fn visit_ty(&mut self, ty: &'ast Ty) {
831 let prev = self.diag_metadata.current_trait_object;
832 let prev_ty = self.diag_metadata.current_type_path;
833 match &ty.kind {
834 TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
835 let span = self.r.tcx.sess.source_map().start_point(ty.span);
839 self.resolve_elided_lifetime(ty.id, span);
840 visit::walk_ty(self, ty);
841 }
842 TyKind::Path(qself, path) => {
843 self.diag_metadata.current_type_path = Some(ty);
844
845 let source = if let Some(seg) = path.segments.last()
849 && let Some(args) = &seg.args
850 && matches!(**args, GenericArgs::ParenthesizedElided(..))
851 {
852 PathSource::ReturnTypeNotation
853 } else {
854 PathSource::Type
855 };
856
857 self.smart_resolve_path(ty.id, qself, path, source);
858
859 if qself.is_none()
861 && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
862 && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
863 partial_res.full_res()
864 {
865 let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
869 self.with_generic_param_rib(
870 &[],
871 RibKind::Normal,
872 LifetimeRibKind::Generics {
873 binder: ty.id,
874 kind: LifetimeBinderKind::PolyTrait,
875 span,
876 },
877 |this| this.visit_path(path),
878 );
879 } else {
880 visit::walk_ty(self, ty)
881 }
882 }
883 TyKind::ImplicitSelf => {
884 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
885 let res = self
886 .resolve_ident_in_lexical_scope(
887 self_ty,
888 TypeNS,
889 Some(Finalize::new(ty.id, ty.span)),
890 None,
891 )
892 .map_or(Res::Err, |d| d.res());
893 self.r.record_partial_res(ty.id, PartialRes::new(res));
894 visit::walk_ty(self, ty)
895 }
896 TyKind::ImplTrait(..) => {
897 let candidates = self.lifetime_elision_candidates.take();
898 visit::walk_ty(self, ty);
899 self.lifetime_elision_candidates = candidates;
900 }
901 TyKind::TraitObject(bounds, ..) => {
902 self.diag_metadata.current_trait_object = Some(&bounds[..]);
903 visit::walk_ty(self, ty)
904 }
905 TyKind::BareFn(bare_fn) => {
906 let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo());
907 self.with_generic_param_rib(
908 &bare_fn.generic_params,
909 RibKind::Normal,
910 LifetimeRibKind::Generics {
911 binder: ty.id,
912 kind: LifetimeBinderKind::BareFnType,
913 span,
914 },
915 |this| {
916 this.visit_generic_params(&bare_fn.generic_params, false);
917 this.with_lifetime_rib(
918 LifetimeRibKind::AnonymousCreateParameter {
919 binder: ty.id,
920 report_in_path: false,
921 },
922 |this| {
923 this.resolve_fn_signature(
924 ty.id,
925 false,
926 bare_fn
929 .decl
930 .inputs
931 .iter()
932 .map(|Param { ty, .. }| (None, &**ty)),
933 &bare_fn.decl.output,
934 )
935 },
936 );
937 },
938 )
939 }
940 TyKind::UnsafeBinder(unsafe_binder) => {
941 let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
942 self.with_generic_param_rib(
943 &unsafe_binder.generic_params,
944 RibKind::Normal,
945 LifetimeRibKind::Generics {
946 binder: ty.id,
947 kind: LifetimeBinderKind::BareFnType,
948 span,
949 },
950 |this| {
951 this.visit_generic_params(&unsafe_binder.generic_params, false);
952 this.with_lifetime_rib(
953 LifetimeRibKind::AnonymousReportError,
956 |this| this.visit_ty(&unsafe_binder.inner_ty),
957 );
958 },
959 )
960 }
961 TyKind::Array(element_ty, length) => {
962 self.visit_ty(element_ty);
963 self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
964 }
965 TyKind::Typeof(ct) => {
966 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
967 }
968 _ => visit::walk_ty(self, ty),
969 }
970 self.diag_metadata.current_trait_object = prev;
971 self.diag_metadata.current_type_path = prev_ty;
972 }
973
974 fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
975 match &t.kind {
976 TyPatKind::Range(start, end, _) => {
977 if let Some(start) = start {
978 self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
979 }
980 if let Some(end) = end {
981 self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
982 }
983 }
984 TyPatKind::Or(patterns) => {
985 for pat in patterns {
986 self.visit_ty_pat(pat)
987 }
988 }
989 TyPatKind::Err(_) => {}
990 }
991 }
992
993 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
994 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
995 self.with_generic_param_rib(
996 &tref.bound_generic_params,
997 RibKind::Normal,
998 LifetimeRibKind::Generics {
999 binder: tref.trait_ref.ref_id,
1000 kind: LifetimeBinderKind::PolyTrait,
1001 span,
1002 },
1003 |this| {
1004 this.visit_generic_params(&tref.bound_generic_params, false);
1005 this.smart_resolve_path(
1006 tref.trait_ref.ref_id,
1007 &None,
1008 &tref.trait_ref.path,
1009 PathSource::Trait(AliasPossibility::Maybe),
1010 );
1011 this.visit_trait_ref(&tref.trait_ref);
1012 },
1013 );
1014 }
1015 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1016 self.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1017 let def_kind = self.r.local_def_kind(foreign_item.id);
1018 match foreign_item.kind {
1019 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
1020 self.with_generic_param_rib(
1021 &generics.params,
1022 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1023 LifetimeRibKind::Generics {
1024 binder: foreign_item.id,
1025 kind: LifetimeBinderKind::Item,
1026 span: generics.span,
1027 },
1028 |this| visit::walk_item(this, foreign_item),
1029 );
1030 }
1031 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
1032 self.with_generic_param_rib(
1033 &generics.params,
1034 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1035 LifetimeRibKind::Generics {
1036 binder: foreign_item.id,
1037 kind: LifetimeBinderKind::Function,
1038 span: generics.span,
1039 },
1040 |this| visit::walk_item(this, foreign_item),
1041 );
1042 }
1043 ForeignItemKind::Static(..) => {
1044 self.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1045 }
1046 ForeignItemKind::MacCall(..) => {
1047 panic!("unexpanded macro in resolve!")
1048 }
1049 }
1050 }
1051 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
1052 let previous_value = self.diag_metadata.current_function;
1053 match fn_kind {
1054 FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1057 | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1058 self.visit_fn_header(&sig.header);
1059 self.visit_ident(ident);
1060 self.visit_generics(generics);
1061 self.with_lifetime_rib(
1062 LifetimeRibKind::AnonymousCreateParameter {
1063 binder: fn_id,
1064 report_in_path: false,
1065 },
1066 |this| {
1067 this.resolve_fn_signature(
1068 fn_id,
1069 sig.decl.has_self(),
1070 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1071 &sig.decl.output,
1072 );
1073 },
1074 );
1075 return;
1076 }
1077 FnKind::Fn(..) => {
1078 self.diag_metadata.current_function = Some((fn_kind, sp));
1079 }
1080 FnKind::Closure(..) => {}
1082 };
1083 debug!("(resolving function) entering function");
1084
1085 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1087 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1089 match fn_kind {
1090 FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1091 this.visit_generics(generics);
1092
1093 let declaration = &sig.decl;
1094 let coro_node_id = sig
1095 .header
1096 .coroutine_kind
1097 .map(|coroutine_kind| coroutine_kind.return_id());
1098
1099 this.with_lifetime_rib(
1100 LifetimeRibKind::AnonymousCreateParameter {
1101 binder: fn_id,
1102 report_in_path: coro_node_id.is_some(),
1103 },
1104 |this| {
1105 this.resolve_fn_signature(
1106 fn_id,
1107 declaration.has_self(),
1108 declaration
1109 .inputs
1110 .iter()
1111 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1112 &declaration.output,
1113 );
1114 },
1115 );
1116
1117 if let Some(contract) = contract {
1118 this.visit_contract(contract);
1119 }
1120
1121 if let Some(body) = body {
1122 let previous_state = replace(&mut this.in_func_body, true);
1125 this.last_block_rib = None;
1127 this.with_lifetime_rib(
1129 LifetimeRibKind::Elided(LifetimeRes::Infer),
1130 |this| this.visit_block(body),
1131 );
1132
1133 debug!("(resolving function) leaving function");
1134 this.in_func_body = previous_state;
1135 }
1136 }
1137 FnKind::Closure(binder, _, declaration, body) => {
1138 this.visit_closure_binder(binder);
1139
1140 this.with_lifetime_rib(
1141 match binder {
1142 ClosureBinder::NotPresent => {
1144 LifetimeRibKind::AnonymousCreateParameter {
1145 binder: fn_id,
1146 report_in_path: false,
1147 }
1148 }
1149 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1150 },
1151 |this| this.resolve_params(&declaration.inputs),
1153 );
1154 this.with_lifetime_rib(
1155 match binder {
1156 ClosureBinder::NotPresent => {
1157 LifetimeRibKind::Elided(LifetimeRes::Infer)
1158 }
1159 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1160 },
1161 |this| visit::walk_fn_ret_ty(this, &declaration.output),
1162 );
1163
1164 let previous_state = replace(&mut this.in_func_body, true);
1167 this.with_lifetime_rib(
1169 LifetimeRibKind::Elided(LifetimeRes::Infer),
1170 |this| this.visit_expr(body),
1171 );
1172
1173 debug!("(resolving function) leaving function");
1174 this.in_func_body = previous_state;
1175 }
1176 }
1177 })
1178 });
1179 self.diag_metadata.current_function = previous_value;
1180 }
1181
1182 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1183 self.resolve_lifetime(lifetime, use_ctxt)
1184 }
1185
1186 fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1187 match arg {
1188 PreciseCapturingArg::Lifetime(_) => {}
1191
1192 PreciseCapturingArg::Arg(path, id) => {
1193 let mut check_ns = |ns| {
1200 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1201 };
1202 if !check_ns(TypeNS) && check_ns(ValueNS) {
1204 self.smart_resolve_path(
1205 *id,
1206 &None,
1207 path,
1208 PathSource::PreciseCapturingArg(ValueNS),
1209 );
1210 } else {
1211 self.smart_resolve_path(
1212 *id,
1213 &None,
1214 path,
1215 PathSource::PreciseCapturingArg(TypeNS),
1216 );
1217 }
1218 }
1219 }
1220
1221 visit::walk_precise_capturing_arg(self, arg)
1222 }
1223
1224 fn visit_generics(&mut self, generics: &'ast Generics) {
1225 self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1226 for p in &generics.where_clause.predicates {
1227 self.visit_where_predicate(p);
1228 }
1229 }
1230
1231 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1232 match b {
1233 ClosureBinder::NotPresent => {}
1234 ClosureBinder::For { generic_params, .. } => {
1235 self.visit_generic_params(
1236 generic_params,
1237 self.diag_metadata.current_self_item.is_some(),
1238 );
1239 }
1240 }
1241 }
1242
1243 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1244 debug!("visit_generic_arg({:?})", arg);
1245 let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1246 match arg {
1247 GenericArg::Type(ty) => {
1248 if let TyKind::Path(None, ref path) = ty.kind
1254 && path.is_potential_trivial_const_arg(false)
1257 {
1258 let mut check_ns = |ns| {
1259 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1260 .is_some()
1261 };
1262 if !check_ns(TypeNS) && check_ns(ValueNS) {
1263 self.resolve_anon_const_manual(
1264 true,
1265 AnonConstKind::ConstArg(IsRepeatExpr::No),
1266 |this| {
1267 this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1268 this.visit_path(path);
1269 },
1270 );
1271
1272 self.diag_metadata.currently_processing_generic_args = prev;
1273 return;
1274 }
1275 }
1276
1277 self.visit_ty(ty);
1278 }
1279 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1280 GenericArg::Const(ct) => {
1281 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1282 }
1283 }
1284 self.diag_metadata.currently_processing_generic_args = prev;
1285 }
1286
1287 fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1288 self.visit_ident(&constraint.ident);
1289 if let Some(ref gen_args) = constraint.gen_args {
1290 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1292 this.visit_generic_args(gen_args)
1293 });
1294 }
1295 match constraint.kind {
1296 AssocItemConstraintKind::Equality { ref term } => match term {
1297 Term::Ty(ty) => self.visit_ty(ty),
1298 Term::Const(c) => {
1299 self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1300 }
1301 },
1302 AssocItemConstraintKind::Bound { ref bounds } => {
1303 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1304 }
1305 }
1306 }
1307
1308 fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1309 let Some(ref args) = path_segment.args else {
1310 return;
1311 };
1312
1313 match &**args {
1314 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1315 GenericArgs::Parenthesized(p_args) => {
1316 for rib in self.lifetime_ribs.iter().rev() {
1318 match rib.kind {
1319 LifetimeRibKind::Generics {
1322 binder,
1323 kind: LifetimeBinderKind::PolyTrait,
1324 ..
1325 } => {
1326 self.with_lifetime_rib(
1327 LifetimeRibKind::AnonymousCreateParameter {
1328 binder,
1329 report_in_path: false,
1330 },
1331 |this| {
1332 this.resolve_fn_signature(
1333 binder,
1334 false,
1335 p_args.inputs.iter().map(|ty| (None, &**ty)),
1336 &p_args.output,
1337 )
1338 },
1339 );
1340 break;
1341 }
1342 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1345 visit::walk_generic_args(self, args);
1346 break;
1347 }
1348 LifetimeRibKind::AnonymousCreateParameter { .. }
1349 | LifetimeRibKind::AnonymousReportError
1350 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1351 | LifetimeRibKind::Elided(_)
1352 | LifetimeRibKind::ElisionFailure
1353 | LifetimeRibKind::ConcreteAnonConst(_)
1354 | LifetimeRibKind::ConstParamTy => {}
1355 }
1356 }
1357 }
1358 GenericArgs::ParenthesizedElided(_) => {}
1359 }
1360 }
1361
1362 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1363 debug!("visit_where_predicate {:?}", p);
1364 let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1365 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1366 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1367 bounded_ty,
1368 bounds,
1369 bound_generic_params,
1370 ..
1371 }) = &p.kind
1372 {
1373 let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1374 this.with_generic_param_rib(
1375 bound_generic_params,
1376 RibKind::Normal,
1377 LifetimeRibKind::Generics {
1378 binder: bounded_ty.id,
1379 kind: LifetimeBinderKind::WhereBound,
1380 span,
1381 },
1382 |this| {
1383 this.visit_generic_params(bound_generic_params, false);
1384 this.visit_ty(bounded_ty);
1385 for bound in bounds {
1386 this.visit_param_bound(bound, BoundKind::Bound)
1387 }
1388 },
1389 );
1390 } else {
1391 visit::walk_where_predicate(this, p);
1392 }
1393 });
1394 self.diag_metadata.current_where_predicate = previous_value;
1395 }
1396
1397 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1398 for (op, _) in &asm.operands {
1399 match op {
1400 InlineAsmOperand::In { expr, .. }
1401 | InlineAsmOperand::Out { expr: Some(expr), .. }
1402 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1403 InlineAsmOperand::Out { expr: None, .. } => {}
1404 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1405 self.visit_expr(in_expr);
1406 if let Some(out_expr) = out_expr {
1407 self.visit_expr(out_expr);
1408 }
1409 }
1410 InlineAsmOperand::Const { anon_const, .. } => {
1411 self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1414 }
1415 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1416 InlineAsmOperand::Label { block } => self.visit_block(block),
1417 }
1418 }
1419 }
1420
1421 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1422 self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1424 this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1425 this.with_label_rib(RibKind::InlineAsmSym, |this| {
1426 this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1427 visit::walk_inline_asm_sym(this, sym);
1428 });
1429 })
1430 });
1431 }
1432
1433 fn visit_variant(&mut self, v: &'ast Variant) {
1434 self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1435 visit::walk_variant(self, v)
1436 }
1437
1438 fn visit_variant_discr(&mut self, discr: &'ast AnonConst) {
1439 self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1440 }
1441
1442 fn visit_field_def(&mut self, f: &'ast FieldDef) {
1443 self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1444 let FieldDef {
1445 attrs,
1446 id: _,
1447 span: _,
1448 vis,
1449 ident,
1450 ty,
1451 is_placeholder: _,
1452 default,
1453 safety: _,
1454 } = f;
1455 walk_list!(self, visit_attribute, attrs);
1456 try_visit!(self.visit_vis(vis));
1457 visit_opt!(self, visit_ident, ident);
1458 try_visit!(self.visit_ty(ty));
1459 if let Some(v) = &default {
1460 self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1461 }
1462 }
1463}
1464
1465impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1466 fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1467 let graph_root = resolver.graph_root;
1470 let parent_scope = ParentScope::module(graph_root, resolver);
1471 let start_rib_kind = RibKind::Module(graph_root);
1472 LateResolutionVisitor {
1473 r: resolver,
1474 parent_scope,
1475 ribs: PerNS {
1476 value_ns: vec![Rib::new(start_rib_kind)],
1477 type_ns: vec![Rib::new(start_rib_kind)],
1478 macro_ns: vec![Rib::new(start_rib_kind)],
1479 },
1480 last_block_rib: None,
1481 label_ribs: Vec::new(),
1482 lifetime_ribs: Vec::new(),
1483 lifetime_elision_candidates: None,
1484 current_trait_ref: None,
1485 diag_metadata: Default::default(),
1486 in_func_body: false,
1488 lifetime_uses: Default::default(),
1489 }
1490 }
1491
1492 fn maybe_resolve_ident_in_lexical_scope(
1493 &mut self,
1494 ident: Ident,
1495 ns: Namespace,
1496 ) -> Option<LexicalScopeBinding<'ra>> {
1497 self.r.resolve_ident_in_lexical_scope(
1498 ident,
1499 ns,
1500 &self.parent_scope,
1501 None,
1502 &self.ribs[ns],
1503 None,
1504 )
1505 }
1506
1507 fn resolve_ident_in_lexical_scope(
1508 &mut self,
1509 ident: Ident,
1510 ns: Namespace,
1511 finalize: Option<Finalize>,
1512 ignore_binding: Option<NameBinding<'ra>>,
1513 ) -> Option<LexicalScopeBinding<'ra>> {
1514 self.r.resolve_ident_in_lexical_scope(
1515 ident,
1516 ns,
1517 &self.parent_scope,
1518 finalize,
1519 &self.ribs[ns],
1520 ignore_binding,
1521 )
1522 }
1523
1524 fn resolve_path(
1525 &mut self,
1526 path: &[Segment],
1527 opt_ns: Option<Namespace>, finalize: Option<Finalize>,
1529 ) -> PathResult<'ra> {
1530 self.r.resolve_path_with_ribs(
1531 path,
1532 opt_ns,
1533 &self.parent_scope,
1534 finalize,
1535 Some(&self.ribs),
1536 None,
1537 None,
1538 )
1539 }
1540
1541 fn with_rib<T>(
1561 &mut self,
1562 ns: Namespace,
1563 kind: RibKind<'ra>,
1564 work: impl FnOnce(&mut Self) -> T,
1565 ) -> T {
1566 self.ribs[ns].push(Rib::new(kind));
1567 let ret = work(self);
1568 self.ribs[ns].pop();
1569 ret
1570 }
1571
1572 fn with_mod_rib<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1573 let module = self.r.expect_module(self.r.local_def_id(id).to_def_id());
1574 let orig_module = replace(&mut self.parent_scope.module, module);
1576 self.with_rib(ValueNS, RibKind::Module(module), |this| {
1577 this.with_rib(TypeNS, RibKind::Module(module), |this| {
1578 let ret = f(this);
1579 this.parent_scope.module = orig_module;
1580 ret
1581 })
1582 })
1583 }
1584
1585 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1586 let mut forward_ty_ban_rib =
1592 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1593 let mut forward_const_ban_rib =
1594 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1595 for param in params.iter() {
1596 match param.kind {
1597 GenericParamKind::Type { .. } => {
1598 forward_ty_ban_rib
1599 .bindings
1600 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1601 }
1602 GenericParamKind::Const { .. } => {
1603 forward_const_ban_rib
1604 .bindings
1605 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1606 }
1607 GenericParamKind::Lifetime => {}
1608 }
1609 }
1610
1611 if add_self_upper {
1621 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1623 }
1624
1625 let mut forward_ty_ban_rib_const_param_ty = Rib {
1628 bindings: forward_ty_ban_rib.bindings.clone(),
1629 patterns_with_skipped_bindings: Default::default(),
1630 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1631 };
1632 let mut forward_const_ban_rib_const_param_ty = Rib {
1633 bindings: forward_const_ban_rib.bindings.clone(),
1634 patterns_with_skipped_bindings: Default::default(),
1635 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1636 };
1637 if !self.r.tcx.features().generic_const_parameter_types() {
1640 forward_ty_ban_rib_const_param_ty.bindings.clear();
1641 forward_const_ban_rib_const_param_ty.bindings.clear();
1642 }
1643
1644 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1645 for param in params {
1646 match param.kind {
1647 GenericParamKind::Lifetime => {
1648 for bound in ¶m.bounds {
1649 this.visit_param_bound(bound, BoundKind::Bound);
1650 }
1651 }
1652 GenericParamKind::Type { ref default } => {
1653 for bound in ¶m.bounds {
1654 this.visit_param_bound(bound, BoundKind::Bound);
1655 }
1656
1657 if let Some(ty) = default {
1658 this.ribs[TypeNS].push(forward_ty_ban_rib);
1659 this.ribs[ValueNS].push(forward_const_ban_rib);
1660 this.visit_ty(ty);
1661 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1662 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1663 }
1664
1665 let i = &Ident::with_dummy_span(param.ident.name);
1667 forward_ty_ban_rib.bindings.swap_remove(i);
1668 forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1669 }
1670 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1671 assert!(param.bounds.is_empty());
1673
1674 this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1675 this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1676 if this.r.tcx.features().generic_const_parameter_types() {
1677 this.visit_ty(ty)
1678 } else {
1679 this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1680 this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1681 this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1682 this.visit_ty(ty)
1683 });
1684 this.ribs[TypeNS].pop().unwrap();
1685 this.ribs[ValueNS].pop().unwrap();
1686 }
1687 forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1688 forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1689
1690 if let Some(expr) = default {
1691 this.ribs[TypeNS].push(forward_ty_ban_rib);
1692 this.ribs[ValueNS].push(forward_const_ban_rib);
1693 this.resolve_anon_const(
1694 expr,
1695 AnonConstKind::ConstArg(IsRepeatExpr::No),
1696 );
1697 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1698 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1699 }
1700
1701 let i = &Ident::with_dummy_span(param.ident.name);
1703 forward_const_ban_rib.bindings.swap_remove(i);
1704 forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1705 }
1706 }
1707 }
1708 })
1709 }
1710
1711 #[instrument(level = "debug", skip(self, work))]
1712 fn with_lifetime_rib<T>(
1713 &mut self,
1714 kind: LifetimeRibKind,
1715 work: impl FnOnce(&mut Self) -> T,
1716 ) -> T {
1717 self.lifetime_ribs.push(LifetimeRib::new(kind));
1718 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1719 let ret = work(self);
1720 self.lifetime_elision_candidates = outer_elision_candidates;
1721 self.lifetime_ribs.pop();
1722 ret
1723 }
1724
1725 #[instrument(level = "debug", skip(self))]
1726 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1727 let ident = lifetime.ident;
1728
1729 if ident.name == kw::StaticLifetime {
1730 self.record_lifetime_res(
1731 lifetime.id,
1732 LifetimeRes::Static,
1733 LifetimeElisionCandidate::Named,
1734 );
1735 return;
1736 }
1737
1738 if ident.name == kw::UnderscoreLifetime {
1739 return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1740 }
1741
1742 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1743 while let Some(rib) = lifetime_rib_iter.next() {
1744 let normalized_ident = ident.normalize_to_macros_2_0();
1745 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1746 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1747
1748 if let LifetimeRes::Param { param, binder } = res {
1749 match self.lifetime_uses.entry(param) {
1750 Entry::Vacant(v) => {
1751 debug!("First use of {:?} at {:?}", res, ident.span);
1752 let use_set = self
1753 .lifetime_ribs
1754 .iter()
1755 .rev()
1756 .find_map(|rib| match rib.kind {
1757 LifetimeRibKind::Item
1760 | LifetimeRibKind::AnonymousReportError
1761 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1762 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1763 LifetimeRibKind::AnonymousCreateParameter {
1766 binder: anon_binder,
1767 ..
1768 } => Some(if binder == anon_binder {
1769 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1770 } else {
1771 LifetimeUseSet::Many
1772 }),
1773 LifetimeRibKind::Elided(r) => Some(if res == r {
1776 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1777 } else {
1778 LifetimeUseSet::Many
1779 }),
1780 LifetimeRibKind::Generics { .. }
1781 | LifetimeRibKind::ConstParamTy => None,
1782 LifetimeRibKind::ConcreteAnonConst(_) => {
1783 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1784 }
1785 })
1786 .unwrap_or(LifetimeUseSet::Many);
1787 debug!(?use_ctxt, ?use_set);
1788 v.insert(use_set);
1789 }
1790 Entry::Occupied(mut o) => {
1791 debug!("Many uses of {:?} at {:?}", res, ident.span);
1792 *o.get_mut() = LifetimeUseSet::Many;
1793 }
1794 }
1795 }
1796 return;
1797 }
1798
1799 match rib.kind {
1800 LifetimeRibKind::Item => break,
1801 LifetimeRibKind::ConstParamTy => {
1802 self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1803 self.record_lifetime_res(
1804 lifetime.id,
1805 LifetimeRes::Error,
1806 LifetimeElisionCandidate::Ignore,
1807 );
1808 return;
1809 }
1810 LifetimeRibKind::ConcreteAnonConst(cause) => {
1811 self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1812 self.record_lifetime_res(
1813 lifetime.id,
1814 LifetimeRes::Error,
1815 LifetimeElisionCandidate::Ignore,
1816 );
1817 return;
1818 }
1819 LifetimeRibKind::AnonymousCreateParameter { .. }
1820 | LifetimeRibKind::Elided(_)
1821 | LifetimeRibKind::Generics { .. }
1822 | LifetimeRibKind::ElisionFailure
1823 | LifetimeRibKind::AnonymousReportError
1824 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1825 }
1826 }
1827
1828 let normalized_ident = ident.normalize_to_macros_2_0();
1829 let outer_res = lifetime_rib_iter
1830 .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1831
1832 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1833 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1834 }
1835
1836 #[instrument(level = "debug", skip(self))]
1837 fn resolve_anonymous_lifetime(
1838 &mut self,
1839 lifetime: &Lifetime,
1840 id_for_lint: NodeId,
1841 elided: bool,
1842 ) {
1843 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1844
1845 let kind =
1846 if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1847 let missing_lifetime = MissingLifetime {
1848 id: lifetime.id,
1849 span: lifetime.ident.span,
1850 kind,
1851 count: 1,
1852 id_for_lint,
1853 };
1854 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1855 for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1856 debug!(?rib.kind);
1857 match rib.kind {
1858 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1859 let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1860 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1861 return;
1862 }
1863 LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1864 let mut lifetimes_in_scope = vec![];
1865 for rib in self.lifetime_ribs[..i].iter().rev() {
1866 lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1867 if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1869 && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1870 {
1871 lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1872 }
1873 if let LifetimeRibKind::Item = rib.kind {
1874 break;
1875 }
1876 }
1877 if lifetimes_in_scope.is_empty() {
1878 self.record_lifetime_res(
1879 lifetime.id,
1880 LifetimeRes::Static,
1881 elision_candidate,
1882 );
1883 return;
1884 } else if emit_lint {
1885 self.r.lint_buffer.buffer_lint(
1886 lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1887 node_id,
1888 lifetime.ident.span,
1889 lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1890 elided,
1891 span: lifetime.ident.span,
1892 lifetimes_in_scope: lifetimes_in_scope.into(),
1893 },
1894 );
1895 }
1896 }
1897 LifetimeRibKind::AnonymousReportError => {
1898 if elided {
1899 let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1900 if let LifetimeRibKind::Generics {
1901 span,
1902 kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1903 ..
1904 } = rib.kind
1905 {
1906 Some(errors::ElidedAnonymousLivetimeReportErrorSuggestion {
1907 lo: span.shrink_to_lo(),
1908 hi: lifetime.ident.span.shrink_to_hi(),
1909 })
1910 } else {
1911 None
1912 }
1913 });
1914 if !self.in_func_body
1917 && let Some((module, _)) = &self.current_trait_ref
1918 && let Some(ty) = &self.diag_metadata.current_self_type
1919 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1920 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1921 {
1922 if def_id_matches_path(
1923 self.r.tcx,
1924 trait_id,
1925 &["core", "iter", "traits", "iterator", "Iterator"],
1926 ) {
1927 self.r.dcx().emit_err(errors::LendingIteratorReportError {
1928 lifetime: lifetime.ident.span,
1929 ty: ty.span,
1930 });
1931 } else {
1932 self.r.dcx().emit_err(errors::AnonymousLivetimeNonGatReportError {
1933 lifetime: lifetime.ident.span,
1934 });
1935 }
1936 } else {
1937 self.r.dcx().emit_err(errors::ElidedAnonymousLivetimeReportError {
1938 span: lifetime.ident.span,
1939 suggestion,
1940 });
1941 }
1942 } else {
1943 self.r.dcx().emit_err(errors::ExplicitAnonymousLivetimeReportError {
1944 span: lifetime.ident.span,
1945 });
1946 };
1947 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1948 return;
1949 }
1950 LifetimeRibKind::Elided(res) => {
1951 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1952 return;
1953 }
1954 LifetimeRibKind::ElisionFailure => {
1955 self.diag_metadata.current_elision_failures.push(missing_lifetime);
1956 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1957 return;
1958 }
1959 LifetimeRibKind::Item => break,
1960 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1961 LifetimeRibKind::ConcreteAnonConst(_) => {
1962 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1964 }
1965 }
1966 }
1967 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1968 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1969 }
1970
1971 #[instrument(level = "debug", skip(self))]
1972 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1973 let id = self.r.next_node_id();
1974 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1975
1976 self.record_lifetime_res(
1977 anchor_id,
1978 LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
1979 LifetimeElisionCandidate::Ignore,
1980 );
1981 self.resolve_anonymous_lifetime(<, anchor_id, true);
1982 }
1983
1984 #[instrument(level = "debug", skip(self))]
1985 fn create_fresh_lifetime(
1986 &mut self,
1987 ident: Ident,
1988 binder: NodeId,
1989 kind: MissingLifetimeKind,
1990 ) -> LifetimeRes {
1991 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1992 debug!(?ident.span);
1993
1994 let param = self.r.next_node_id();
1996 let res = LifetimeRes::Fresh { param, binder, kind };
1997 self.record_lifetime_param(param, res);
1998
1999 self.r
2001 .extra_lifetime_params_map
2002 .entry(binder)
2003 .or_insert_with(Vec::new)
2004 .push((ident, param, res));
2005 res
2006 }
2007
2008 #[instrument(level = "debug", skip(self))]
2009 fn resolve_elided_lifetimes_in_path(
2010 &mut self,
2011 partial_res: PartialRes,
2012 path: &[Segment],
2013 source: PathSource<'_, '_>,
2014 path_span: Span,
2015 ) {
2016 let proj_start = path.len() - partial_res.unresolved_segments();
2017 for (i, segment) in path.iter().enumerate() {
2018 if segment.has_lifetime_args {
2019 continue;
2020 }
2021 let Some(segment_id) = segment.id else {
2022 continue;
2023 };
2024
2025 let type_def_id = match partial_res.base_res() {
2028 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2029 self.r.tcx.parent(def_id)
2030 }
2031 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2032 self.r.tcx.parent(def_id)
2033 }
2034 Res::Def(DefKind::Struct, def_id)
2035 | Res::Def(DefKind::Union, def_id)
2036 | Res::Def(DefKind::Enum, def_id)
2037 | Res::Def(DefKind::TyAlias, def_id)
2038 | Res::Def(DefKind::Trait, def_id)
2039 if i + 1 == proj_start =>
2040 {
2041 def_id
2042 }
2043 _ => continue,
2044 };
2045
2046 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2047 if expected_lifetimes == 0 {
2048 continue;
2049 }
2050
2051 let node_ids = self.r.next_node_ids(expected_lifetimes);
2052 self.record_lifetime_res(
2053 segment_id,
2054 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2055 LifetimeElisionCandidate::Ignore,
2056 );
2057
2058 let inferred = match source {
2059 PathSource::Trait(..)
2060 | PathSource::TraitItem(..)
2061 | PathSource::Type
2062 | PathSource::PreciseCapturingArg(..)
2063 | PathSource::ReturnTypeNotation => false,
2064 PathSource::Expr(..)
2065 | PathSource::Pat
2066 | PathSource::Struct
2067 | PathSource::TupleStruct(..)
2068 | PathSource::DefineOpaques
2069 | PathSource::Delegation => true,
2070 };
2071 if inferred {
2072 for id in node_ids {
2075 self.record_lifetime_res(
2076 id,
2077 LifetimeRes::Infer,
2078 LifetimeElisionCandidate::Named,
2079 );
2080 }
2081 continue;
2082 }
2083
2084 let elided_lifetime_span = if segment.has_generic_args {
2085 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2087 } else {
2088 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2092 };
2093 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2094
2095 let kind = if segment.has_generic_args {
2096 MissingLifetimeKind::Comma
2097 } else {
2098 MissingLifetimeKind::Brackets
2099 };
2100 let missing_lifetime = MissingLifetime {
2101 id: node_ids.start,
2102 id_for_lint: segment_id,
2103 span: elided_lifetime_span,
2104 kind,
2105 count: expected_lifetimes,
2106 };
2107 let mut should_lint = true;
2108 for rib in self.lifetime_ribs.iter().rev() {
2109 match rib.kind {
2110 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2117 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2118 let sess = self.r.tcx.sess;
2119 let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2120 sess.source_map(),
2121 expected_lifetimes,
2122 path_span,
2123 !segment.has_generic_args,
2124 elided_lifetime_span,
2125 );
2126 self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2127 span: path_span,
2128 subdiag,
2129 });
2130 should_lint = false;
2131
2132 for id in node_ids {
2133 self.record_lifetime_res(
2134 id,
2135 LifetimeRes::Error,
2136 LifetimeElisionCandidate::Named,
2137 );
2138 }
2139 break;
2140 }
2141 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2143 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2145 for id in node_ids {
2146 let res = self.create_fresh_lifetime(ident, binder, kind);
2147 self.record_lifetime_res(
2148 id,
2149 res,
2150 replace(&mut candidate, LifetimeElisionCandidate::Named),
2151 );
2152 }
2153 break;
2154 }
2155 LifetimeRibKind::Elided(res) => {
2156 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2157 for id in node_ids {
2158 self.record_lifetime_res(
2159 id,
2160 res,
2161 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2162 );
2163 }
2164 break;
2165 }
2166 LifetimeRibKind::ElisionFailure => {
2167 self.diag_metadata.current_elision_failures.push(missing_lifetime);
2168 for id in node_ids {
2169 self.record_lifetime_res(
2170 id,
2171 LifetimeRes::Error,
2172 LifetimeElisionCandidate::Ignore,
2173 );
2174 }
2175 break;
2176 }
2177 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2182 for id in node_ids {
2183 self.record_lifetime_res(
2184 id,
2185 LifetimeRes::Error,
2186 LifetimeElisionCandidate::Ignore,
2187 );
2188 }
2189 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2190 break;
2191 }
2192 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2193 LifetimeRibKind::ConcreteAnonConst(_) => {
2194 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2196 }
2197 }
2198 }
2199
2200 if should_lint {
2201 self.r.lint_buffer.buffer_lint(
2202 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2203 segment_id,
2204 elided_lifetime_span,
2205 lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2206 expected_lifetimes,
2207 path_span,
2208 !segment.has_generic_args,
2209 elided_lifetime_span,
2210 ),
2211 );
2212 }
2213 }
2214 }
2215
2216 #[instrument(level = "debug", skip(self))]
2217 fn record_lifetime_res(
2218 &mut self,
2219 id: NodeId,
2220 res: LifetimeRes,
2221 candidate: LifetimeElisionCandidate,
2222 ) {
2223 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2224 panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2225 }
2226
2227 match res {
2228 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2229 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2230 candidates.push((res, candidate));
2231 }
2232 }
2233 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2234 }
2235 }
2236
2237 #[instrument(level = "debug", skip(self))]
2238 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2239 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2240 panic!(
2241 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2242 )
2243 }
2244 }
2245
2246 #[instrument(level = "debug", skip(self, inputs))]
2248 fn resolve_fn_signature(
2249 &mut self,
2250 fn_id: NodeId,
2251 has_self: bool,
2252 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2253 output_ty: &'ast FnRetTy,
2254 ) {
2255 let elision_lifetime = self.resolve_fn_params(has_self, inputs);
2257 debug!(?elision_lifetime);
2258
2259 let outer_failures = take(&mut self.diag_metadata.current_elision_failures);
2260 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2261 self.r.lifetime_elision_allowed.insert(fn_id);
2262 LifetimeRibKind::Elided(*res)
2263 } else {
2264 LifetimeRibKind::ElisionFailure
2265 };
2266 self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2267 let elision_failures =
2268 replace(&mut self.diag_metadata.current_elision_failures, outer_failures);
2269 if !elision_failures.is_empty() {
2270 let Err(failure_info) = elision_lifetime else { bug!() };
2271 self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2272 }
2273 }
2274
2275 fn resolve_fn_params(
2279 &mut self,
2280 has_self: bool,
2281 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2282 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2283 enum Elision {
2284 None,
2286 Self_(LifetimeRes),
2288 Param(LifetimeRes),
2290 Err,
2292 }
2293
2294 let outer_candidates = self.lifetime_elision_candidates.take();
2296
2297 let mut elision_lifetime = Elision::None;
2299 let mut parameter_info = Vec::new();
2301 let mut all_candidates = Vec::new();
2302
2303 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2305 for (pat, _) in inputs.clone() {
2306 debug!("resolving bindings in pat = {pat:?}");
2307 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2308 if let Some(pat) = pat {
2309 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2310 }
2311 });
2312 }
2313 self.apply_pattern_bindings(bindings);
2314
2315 for (index, (pat, ty)) in inputs.enumerate() {
2316 debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2317 debug_assert_matches!(self.lifetime_elision_candidates, None);
2319 self.lifetime_elision_candidates = Some(Default::default());
2320 self.visit_ty(ty);
2321 let local_candidates = self.lifetime_elision_candidates.take();
2322
2323 if let Some(candidates) = local_candidates {
2324 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2325 let lifetime_count = distinct.len();
2326 if lifetime_count != 0 {
2327 parameter_info.push(ElisionFnParameter {
2328 index,
2329 ident: if let Some(pat) = pat
2330 && let PatKind::Ident(_, ident, _) = pat.kind
2331 {
2332 Some(ident)
2333 } else {
2334 None
2335 },
2336 lifetime_count,
2337 span: ty.span,
2338 });
2339 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2340 match candidate {
2341 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2342 None
2343 }
2344 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2345 }
2346 }));
2347 }
2348 if !distinct.is_empty() {
2349 match elision_lifetime {
2350 Elision::None => {
2352 if let Some(res) = distinct.get_only() {
2353 elision_lifetime = Elision::Param(*res)
2355 } else {
2356 elision_lifetime = Elision::Err;
2358 }
2359 }
2360 Elision::Param(_) => elision_lifetime = Elision::Err,
2362 Elision::Self_(_) | Elision::Err => {}
2364 }
2365 }
2366 }
2367
2368 if index == 0 && has_self {
2370 let self_lifetime = self.find_lifetime_for_self(ty);
2371 elision_lifetime = match self_lifetime {
2372 Set1::One(lifetime) => Elision::Self_(lifetime),
2374 Set1::Many => Elision::Err,
2379 Set1::Empty => Elision::None,
2382 }
2383 }
2384 debug!("(resolving function / closure) recorded parameter");
2385 }
2386
2387 debug_assert_matches!(self.lifetime_elision_candidates, None);
2389 self.lifetime_elision_candidates = outer_candidates;
2390
2391 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2392 return Ok(res);
2393 }
2394
2395 Err((all_candidates, parameter_info))
2397 }
2398
2399 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2401 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2405 r: &'a Resolver<'ra, 'tcx>,
2406 impl_self: Option<Res>,
2407 lifetime: Set1<LifetimeRes>,
2408 }
2409
2410 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2411 fn visit_ty(&mut self, ty: &'ra Ty) {
2412 trace!("FindReferenceVisitor considering ty={:?}", ty);
2413 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2414 let mut visitor =
2416 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2417 visitor.visit_ty(ty);
2418 trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2419 if visitor.self_found {
2420 let lt_id = if let Some(lt) = lt {
2421 lt.id
2422 } else {
2423 let res = self.r.lifetimes_res_map[&ty.id];
2424 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2425 start
2426 };
2427 let lt_res = self.r.lifetimes_res_map[<_id];
2428 trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2429 self.lifetime.insert(lt_res);
2430 }
2431 }
2432 visit::walk_ty(self, ty)
2433 }
2434
2435 fn visit_expr(&mut self, _: &'ra Expr) {}
2438 }
2439
2440 struct SelfVisitor<'a, 'ra, 'tcx> {
2443 r: &'a Resolver<'ra, 'tcx>,
2444 impl_self: Option<Res>,
2445 self_found: bool,
2446 }
2447
2448 impl SelfVisitor<'_, '_, '_> {
2449 fn is_self_ty(&self, ty: &Ty) -> bool {
2451 match ty.kind {
2452 TyKind::ImplicitSelf => true,
2453 TyKind::Path(None, _) => {
2454 let path_res = self.r.partial_res_map[&ty.id].full_res();
2455 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2456 return true;
2457 }
2458 self.impl_self.is_some() && path_res == self.impl_self
2459 }
2460 _ => false,
2461 }
2462 }
2463 }
2464
2465 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2466 fn visit_ty(&mut self, ty: &'ra Ty) {
2467 trace!("SelfVisitor considering ty={:?}", ty);
2468 if self.is_self_ty(ty) {
2469 trace!("SelfVisitor found Self");
2470 self.self_found = true;
2471 }
2472 visit::walk_ty(self, ty)
2473 }
2474
2475 fn visit_expr(&mut self, _: &'ra Expr) {}
2478 }
2479
2480 let impl_self = self
2481 .diag_metadata
2482 .current_self_type
2483 .as_ref()
2484 .and_then(|ty| {
2485 if let TyKind::Path(None, _) = ty.kind {
2486 self.r.partial_res_map.get(&ty.id)
2487 } else {
2488 None
2489 }
2490 })
2491 .and_then(|res| res.full_res())
2492 .filter(|res| {
2493 matches!(
2497 res,
2498 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2499 )
2500 });
2501 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2502 visitor.visit_ty(ty);
2503 trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2504 visitor.lifetime
2505 }
2506
2507 fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2510 let mut suggestion = None;
2511
2512 for i in (0..self.label_ribs.len()).rev() {
2513 let rib = &self.label_ribs[i];
2514
2515 if let RibKind::MacroDefinition(def) = rib.kind
2516 && def == self.r.macro_def(label.span.ctxt())
2519 {
2520 label.span.remove_mark();
2521 }
2522
2523 let ident = label.normalize_to_macro_rules();
2524 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2525 let definition_span = ident.span;
2526 return if self.is_label_valid_from_rib(i) {
2527 Ok((*id, definition_span))
2528 } else {
2529 Err(ResolutionError::UnreachableLabel {
2530 name: label.name,
2531 definition_span,
2532 suggestion,
2533 })
2534 };
2535 }
2536
2537 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2540 }
2541
2542 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2543 }
2544
2545 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2547 let ribs = &self.label_ribs[rib_index + 1..];
2548 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2549 }
2550
2551 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2552 debug!("resolve_adt");
2553 let kind = self.r.local_def_kind(item.id);
2554 self.with_current_self_item(item, |this| {
2555 this.with_generic_param_rib(
2556 &generics.params,
2557 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2558 LifetimeRibKind::Generics {
2559 binder: item.id,
2560 kind: LifetimeBinderKind::Item,
2561 span: generics.span,
2562 },
2563 |this| {
2564 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2565 this.with_self_rib(
2566 Res::SelfTyAlias {
2567 alias_to: item_def_id,
2568 forbid_generic: false,
2569 is_trait_impl: false,
2570 },
2571 |this| {
2572 visit::walk_item(this, item);
2573 },
2574 );
2575 },
2576 );
2577 });
2578 }
2579
2580 fn future_proof_import(&mut self, use_tree: &UseTree) {
2581 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2582 let ident = segment.ident;
2583 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2584 return;
2585 }
2586
2587 let nss = match use_tree.kind {
2588 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2589 _ => &[TypeNS],
2590 };
2591 let report_error = |this: &Self, ns| {
2592 if this.should_report_errs() {
2593 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2594 this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2595 }
2596 };
2597
2598 for &ns in nss {
2599 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2600 Some(LexicalScopeBinding::Res(..)) => {
2601 report_error(self, ns);
2602 }
2603 Some(LexicalScopeBinding::Item(binding)) => {
2604 if let Some(LexicalScopeBinding::Res(..)) =
2605 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2606 {
2607 report_error(self, ns);
2608 }
2609 }
2610 None => {}
2611 }
2612 }
2613 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2614 for (use_tree, _) in items {
2615 self.future_proof_import(use_tree);
2616 }
2617 }
2618 }
2619
2620 fn resolve_item(&mut self, item: &'ast Item) {
2621 let mod_inner_docs =
2622 matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2623 if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2624 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2625 }
2626
2627 debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2628
2629 let def_kind = self.r.local_def_kind(item.id);
2630 match item.kind {
2631 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2632 self.with_generic_param_rib(
2633 &generics.params,
2634 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2635 LifetimeRibKind::Generics {
2636 binder: item.id,
2637 kind: LifetimeBinderKind::Item,
2638 span: generics.span,
2639 },
2640 |this| visit::walk_item(this, item),
2641 );
2642 }
2643
2644 ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2645 self.with_generic_param_rib(
2646 &generics.params,
2647 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2648 LifetimeRibKind::Generics {
2649 binder: item.id,
2650 kind: LifetimeBinderKind::Function,
2651 span: generics.span,
2652 },
2653 |this| visit::walk_item(this, item),
2654 );
2655 self.resolve_define_opaques(define_opaque);
2656 }
2657
2658 ItemKind::Enum(_, ref generics, _)
2659 | ItemKind::Struct(_, ref generics, _)
2660 | ItemKind::Union(_, ref generics, _) => {
2661 self.resolve_adt(item, generics);
2662 }
2663
2664 ItemKind::Impl(box Impl {
2665 ref generics,
2666 ref of_trait,
2667 ref self_ty,
2668 items: ref impl_items,
2669 ..
2670 }) => {
2671 self.diag_metadata.current_impl_items = Some(impl_items);
2672 self.resolve_implementation(
2673 &item.attrs,
2674 generics,
2675 of_trait,
2676 self_ty,
2677 item.id,
2678 impl_items,
2679 );
2680 self.diag_metadata.current_impl_items = None;
2681 }
2682
2683 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2684 self.with_generic_param_rib(
2686 &generics.params,
2687 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2688 LifetimeRibKind::Generics {
2689 binder: item.id,
2690 kind: LifetimeBinderKind::Item,
2691 span: generics.span,
2692 },
2693 |this| {
2694 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2695 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2696 this.visit_generics(generics);
2697 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2698 this.resolve_trait_items(items);
2699 });
2700 },
2701 );
2702 }
2703
2704 ItemKind::TraitAlias(_, ref generics, ref bounds) => {
2705 self.with_generic_param_rib(
2707 &generics.params,
2708 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2709 LifetimeRibKind::Generics {
2710 binder: item.id,
2711 kind: LifetimeBinderKind::Item,
2712 span: generics.span,
2713 },
2714 |this| {
2715 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2716 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2717 this.visit_generics(generics);
2718 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2719 });
2720 },
2721 );
2722 }
2723
2724 ItemKind::Mod(..) => {
2725 self.with_mod_rib(item.id, |this| {
2726 if mod_inner_docs {
2727 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2728 }
2729 let old_macro_rules = this.parent_scope.macro_rules;
2730 visit::walk_item(this, item);
2731 if item.attrs.iter().all(|attr| {
2734 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2735 }) {
2736 this.parent_scope.macro_rules = old_macro_rules;
2737 }
2738 });
2739 }
2740
2741 ItemKind::Static(box ast::StaticItem {
2742 ident,
2743 ref ty,
2744 ref expr,
2745 ref define_opaque,
2746 ..
2747 }) => {
2748 self.with_static_rib(def_kind, |this| {
2749 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2750 this.visit_ty(ty);
2751 });
2752 if let Some(expr) = expr {
2753 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Static)));
2756 }
2757 });
2758 self.resolve_define_opaques(define_opaque);
2759 }
2760
2761 ItemKind::Const(box ast::ConstItem {
2762 ident,
2763 ref generics,
2764 ref ty,
2765 ref expr,
2766 ref define_opaque,
2767 ..
2768 }) => {
2769 self.with_generic_param_rib(
2770 &generics.params,
2771 RibKind::Item(
2772 if self.r.tcx.features().generic_const_items() {
2773 HasGenericParams::Yes(generics.span)
2774 } else {
2775 HasGenericParams::No
2776 },
2777 def_kind,
2778 ),
2779 LifetimeRibKind::Generics {
2780 binder: item.id,
2781 kind: LifetimeBinderKind::ConstItem,
2782 span: generics.span,
2783 },
2784 |this| {
2785 this.visit_generics(generics);
2786
2787 this.with_lifetime_rib(
2788 LifetimeRibKind::Elided(LifetimeRes::Static),
2789 |this| this.visit_ty(ty),
2790 );
2791
2792 if let Some(expr) = expr {
2793 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Const)));
2794 }
2795 },
2796 );
2797 self.resolve_define_opaques(define_opaque);
2798 }
2799
2800 ItemKind::Use(ref use_tree) => {
2801 let maybe_exported = match use_tree.kind {
2802 UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2803 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2804 };
2805 self.resolve_doc_links(&item.attrs, maybe_exported);
2806
2807 self.future_proof_import(use_tree);
2808 }
2809
2810 ItemKind::MacroDef(_, ref macro_def) => {
2811 if macro_def.macro_rules {
2814 let def_id = self.r.local_def_id(item.id);
2815 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2816 }
2817 }
2818
2819 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2820 visit::walk_item(self, item);
2821 }
2822
2823 ItemKind::Delegation(ref delegation) => {
2824 let span = delegation.path.segments.last().unwrap().ident.span;
2825 self.with_generic_param_rib(
2826 &[],
2827 RibKind::Item(HasGenericParams::Yes(span), def_kind),
2828 LifetimeRibKind::Generics {
2829 binder: item.id,
2830 kind: LifetimeBinderKind::Function,
2831 span,
2832 },
2833 |this| this.resolve_delegation(delegation),
2834 );
2835 }
2836
2837 ItemKind::ExternCrate(..) => {}
2838
2839 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2840 panic!("unexpanded macro in resolve!")
2841 }
2842 }
2843 }
2844
2845 fn with_generic_param_rib<'c, F>(
2846 &'c mut self,
2847 params: &'c [GenericParam],
2848 kind: RibKind<'ra>,
2849 lifetime_kind: LifetimeRibKind,
2850 f: F,
2851 ) where
2852 F: FnOnce(&mut Self),
2853 {
2854 debug!("with_generic_param_rib");
2855 let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. } =
2856 lifetime_kind
2857 else {
2858 panic!()
2859 };
2860
2861 let mut function_type_rib = Rib::new(kind);
2862 let mut function_value_rib = Rib::new(kind);
2863 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2864
2865 if !params.is_empty() {
2867 let mut seen_bindings = FxHashMap::default();
2868 let mut seen_lifetimes = FxHashSet::default();
2870
2871 for ns in [ValueNS, TypeNS] {
2873 for parent_rib in self.ribs[ns].iter().rev() {
2874 if matches!(parent_rib.kind, RibKind::Module(..)) {
2877 break;
2878 }
2879
2880 seen_bindings
2881 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2882 }
2883 }
2884
2885 for rib in self.lifetime_ribs.iter().rev() {
2887 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2888 if let LifetimeRibKind::Item = rib.kind {
2889 break;
2890 }
2891 }
2892
2893 for param in params {
2894 let ident = param.ident.normalize_to_macros_2_0();
2895 debug!("with_generic_param_rib: {}", param.id);
2896
2897 if let GenericParamKind::Lifetime = param.kind
2898 && let Some(&original) = seen_lifetimes.get(&ident)
2899 {
2900 diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
2901 self.record_lifetime_param(param.id, LifetimeRes::Error);
2903 continue;
2904 }
2905
2906 match seen_bindings.entry(ident) {
2907 Entry::Occupied(entry) => {
2908 let span = *entry.get();
2909 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
2910 self.report_error(param.ident.span, err);
2911 let rib = match param.kind {
2912 GenericParamKind::Lifetime => {
2913 self.record_lifetime_param(param.id, LifetimeRes::Error);
2915 continue;
2916 }
2917 GenericParamKind::Type { .. } => &mut function_type_rib,
2918 GenericParamKind::Const { .. } => &mut function_value_rib,
2919 };
2920
2921 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
2923 rib.bindings.insert(ident, Res::Err);
2924 continue;
2925 }
2926 Entry::Vacant(entry) => {
2927 entry.insert(param.ident.span);
2928 }
2929 }
2930
2931 if param.ident.name == kw::UnderscoreLifetime {
2932 self.r
2933 .dcx()
2934 .emit_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span });
2935 self.record_lifetime_param(param.id, LifetimeRes::Error);
2937 continue;
2938 }
2939
2940 if param.ident.name == kw::StaticLifetime {
2941 self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
2942 span: param.ident.span,
2943 lifetime: param.ident,
2944 });
2945 self.record_lifetime_param(param.id, LifetimeRes::Error);
2947 continue;
2948 }
2949
2950 let def_id = self.r.local_def_id(param.id);
2951
2952 let (rib, def_kind) = match param.kind {
2954 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2955 GenericParamKind::Const { .. } => {
2956 (&mut function_value_rib, DefKind::ConstParam)
2957 }
2958 GenericParamKind::Lifetime => {
2959 let res = LifetimeRes::Param { param: def_id, binder };
2960 self.record_lifetime_param(param.id, res);
2961 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2962 continue;
2963 }
2964 };
2965
2966 let res = match kind {
2967 RibKind::Item(..) | RibKind::AssocItem => {
2968 Res::Def(def_kind, def_id.to_def_id())
2969 }
2970 RibKind::Normal => {
2971 if self.r.tcx.features().non_lifetime_binders()
2974 && matches!(param.kind, GenericParamKind::Type { .. })
2975 {
2976 Res::Def(def_kind, def_id.to_def_id())
2977 } else {
2978 Res::Err
2979 }
2980 }
2981 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2982 };
2983 self.r.record_partial_res(param.id, PartialRes::new(res));
2984 rib.bindings.insert(ident, res);
2985 }
2986 }
2987
2988 self.lifetime_ribs.push(function_lifetime_rib);
2989 self.ribs[ValueNS].push(function_value_rib);
2990 self.ribs[TypeNS].push(function_type_rib);
2991
2992 f(self);
2993
2994 self.ribs[TypeNS].pop();
2995 self.ribs[ValueNS].pop();
2996 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2997
2998 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3000 for (_, res) in function_lifetime_rib.bindings.values() {
3001 candidates.retain(|(r, _)| r != res);
3002 }
3003 }
3004
3005 if let LifetimeBinderKind::BareFnType
3006 | LifetimeBinderKind::WhereBound
3007 | LifetimeBinderKind::Function
3008 | LifetimeBinderKind::ImplBlock = generics_kind
3009 {
3010 self.maybe_report_lifetime_uses(generics_span, params)
3011 }
3012 }
3013
3014 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3015 self.label_ribs.push(Rib::new(kind));
3016 f(self);
3017 self.label_ribs.pop();
3018 }
3019
3020 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3021 let kind = RibKind::Item(HasGenericParams::No, def_kind);
3022 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3023 }
3024
3025 #[instrument(level = "debug", skip(self, f))]
3034 fn with_constant_rib(
3035 &mut self,
3036 is_repeat: IsRepeatExpr,
3037 may_use_generics: ConstantHasGenerics,
3038 item: Option<(Ident, ConstantItemKind)>,
3039 f: impl FnOnce(&mut Self),
3040 ) {
3041 let f = |this: &mut Self| {
3042 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3043 this.with_rib(
3044 TypeNS,
3045 RibKind::ConstantItem(
3046 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3047 item,
3048 ),
3049 |this| {
3050 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3051 },
3052 )
3053 })
3054 };
3055
3056 if let ConstantHasGenerics::No(cause) = may_use_generics {
3057 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3058 } else {
3059 f(self)
3060 }
3061 }
3062
3063 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3064 let previous_value =
3066 replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3067 let result = f(self);
3068 self.diag_metadata.current_self_type = previous_value;
3069 result
3070 }
3071
3072 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3073 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3074 let result = f(self);
3075 self.diag_metadata.current_self_item = previous_value;
3076 result
3077 }
3078
3079 fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
3081 let trait_assoc_items =
3082 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3083
3084 let walk_assoc_item =
3085 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3086 this.with_generic_param_rib(
3087 &generics.params,
3088 RibKind::AssocItem,
3089 LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind },
3090 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3091 );
3092 };
3093
3094 for item in trait_items {
3095 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3096 match &item.kind {
3097 AssocItemKind::Const(box ast::ConstItem {
3098 generics,
3099 ty,
3100 expr,
3101 define_opaque,
3102 ..
3103 }) => {
3104 self.with_generic_param_rib(
3105 &generics.params,
3106 RibKind::AssocItem,
3107 LifetimeRibKind::Generics {
3108 binder: item.id,
3109 span: generics.span,
3110 kind: LifetimeBinderKind::ConstItem,
3111 },
3112 |this| {
3113 this.with_lifetime_rib(
3114 LifetimeRibKind::StaticIfNoLifetimeInScope {
3115 lint_id: item.id,
3116 emit_lint: false,
3117 },
3118 |this| {
3119 this.visit_generics(generics);
3120 this.visit_ty(ty);
3121
3122 if let Some(expr) = expr {
3125 this.resolve_const_body(expr, None);
3131 }
3132 },
3133 )
3134 },
3135 );
3136
3137 self.resolve_define_opaques(define_opaque);
3138 }
3139 AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3140 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3141
3142 self.resolve_define_opaques(define_opaque);
3143 }
3144 AssocItemKind::Delegation(delegation) => {
3145 self.with_generic_param_rib(
3146 &[],
3147 RibKind::AssocItem,
3148 LifetimeRibKind::Generics {
3149 binder: item.id,
3150 kind: LifetimeBinderKind::Function,
3151 span: delegation.path.segments.last().unwrap().ident.span,
3152 },
3153 |this| this.resolve_delegation(delegation),
3154 );
3155 }
3156 AssocItemKind::Type(box TyAlias { generics, .. }) => self
3157 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3158 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3159 }),
3160 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3161 panic!("unexpanded macro in resolve!")
3162 }
3163 };
3164 }
3165
3166 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3167 }
3168
3169 fn with_optional_trait_ref<T>(
3171 &mut self,
3172 opt_trait_ref: Option<&TraitRef>,
3173 self_type: &'ast Ty,
3174 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3175 ) -> T {
3176 let mut new_val = None;
3177 let mut new_id = None;
3178 if let Some(trait_ref) = opt_trait_ref {
3179 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3180 self.diag_metadata.currently_processing_impl_trait =
3181 Some((trait_ref.clone(), self_type.clone()));
3182 let res = self.smart_resolve_path_fragment(
3183 &None,
3184 &path,
3185 PathSource::Trait(AliasPossibility::No),
3186 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3187 RecordPartialRes::Yes,
3188 None,
3189 );
3190 self.diag_metadata.currently_processing_impl_trait = None;
3191 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3192 new_id = Some(def_id);
3193 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3194 }
3195 }
3196 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3197 let result = f(self, new_id);
3198 self.current_trait_ref = original_trait_ref;
3199 result
3200 }
3201
3202 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3203 let mut self_type_rib = Rib::new(RibKind::Normal);
3204
3205 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3207 self.ribs[ns].push(self_type_rib);
3208 f(self);
3209 self.ribs[ns].pop();
3210 }
3211
3212 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3213 self.with_self_rib_ns(TypeNS, self_res, f)
3214 }
3215
3216 fn resolve_implementation(
3217 &mut self,
3218 attrs: &[ast::Attribute],
3219 generics: &'ast Generics,
3220 opt_trait_reference: &'ast Option<TraitRef>,
3221 self_type: &'ast Ty,
3222 item_id: NodeId,
3223 impl_items: &'ast [P<AssocItem>],
3224 ) {
3225 debug!("resolve_implementation");
3226 self.with_generic_param_rib(
3228 &generics.params,
3229 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3230 LifetimeRibKind::Generics {
3231 span: generics.span,
3232 binder: item_id,
3233 kind: LifetimeBinderKind::ImplBlock,
3234 },
3235 |this| {
3236 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3238 this.with_lifetime_rib(
3239 LifetimeRibKind::AnonymousCreateParameter {
3240 binder: item_id,
3241 report_in_path: true
3242 },
3243 |this| {
3244 this.with_optional_trait_ref(
3246 opt_trait_reference.as_ref(),
3247 self_type,
3248 |this, trait_id| {
3249 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3250
3251 let item_def_id = this.r.local_def_id(item_id);
3252
3253 if let Some(trait_id) = trait_id {
3255 this.r
3256 .trait_impls
3257 .entry(trait_id)
3258 .or_default()
3259 .push(item_def_id);
3260 }
3261
3262 let item_def_id = item_def_id.to_def_id();
3263 let res = Res::SelfTyAlias {
3264 alias_to: item_def_id,
3265 forbid_generic: false,
3266 is_trait_impl: trait_id.is_some()
3267 };
3268 this.with_self_rib(res, |this| {
3269 if let Some(trait_ref) = opt_trait_reference.as_ref() {
3270 visit::walk_trait_ref(this, trait_ref);
3272 }
3273 this.visit_ty(self_type);
3275 this.visit_generics(generics);
3277
3278 this.with_current_self_type(self_type, |this| {
3280 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3281 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3282 let mut seen_trait_items = Default::default();
3283 for item in impl_items {
3284 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3285 }
3286 });
3287 });
3288 });
3289 },
3290 )
3291 },
3292 );
3293 });
3294 },
3295 );
3296 }
3297
3298 fn resolve_impl_item(
3299 &mut self,
3300 item: &'ast AssocItem,
3301 seen_trait_items: &mut FxHashMap<DefId, Span>,
3302 trait_id: Option<DefId>,
3303 ) {
3304 use crate::ResolutionError::*;
3305 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3306 match &item.kind {
3307 AssocItemKind::Const(box ast::ConstItem {
3308 ident,
3309 generics,
3310 ty,
3311 expr,
3312 define_opaque,
3313 ..
3314 }) => {
3315 debug!("resolve_implementation AssocItemKind::Const");
3316 self.with_generic_param_rib(
3317 &generics.params,
3318 RibKind::AssocItem,
3319 LifetimeRibKind::Generics {
3320 binder: item.id,
3321 span: generics.span,
3322 kind: LifetimeBinderKind::ConstItem,
3323 },
3324 |this| {
3325 this.with_lifetime_rib(
3326 LifetimeRibKind::AnonymousCreateParameter {
3329 binder: item.id,
3330 report_in_path: true,
3331 },
3332 |this| {
3333 this.with_lifetime_rib(
3334 LifetimeRibKind::StaticIfNoLifetimeInScope {
3335 lint_id: item.id,
3336 emit_lint: true,
3338 },
3339 |this| {
3340 this.check_trait_item(
3343 item.id,
3344 *ident,
3345 &item.kind,
3346 ValueNS,
3347 item.span,
3348 seen_trait_items,
3349 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3350 );
3351
3352 this.visit_generics(generics);
3353 this.visit_ty(ty);
3354 if let Some(expr) = expr {
3355 this.resolve_const_body(expr, None);
3361 }
3362 },
3363 )
3364 },
3365 );
3366 },
3367 );
3368 self.resolve_define_opaques(define_opaque);
3369 }
3370 AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3371 debug!("resolve_implementation AssocItemKind::Fn");
3372 self.with_generic_param_rib(
3374 &generics.params,
3375 RibKind::AssocItem,
3376 LifetimeRibKind::Generics {
3377 binder: item.id,
3378 span: generics.span,
3379 kind: LifetimeBinderKind::Function,
3380 },
3381 |this| {
3382 this.check_trait_item(
3385 item.id,
3386 *ident,
3387 &item.kind,
3388 ValueNS,
3389 item.span,
3390 seen_trait_items,
3391 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3392 );
3393
3394 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3395 },
3396 );
3397
3398 self.resolve_define_opaques(define_opaque);
3399 }
3400 AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3401 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3402 debug!("resolve_implementation AssocItemKind::Type");
3403 self.with_generic_param_rib(
3405 &generics.params,
3406 RibKind::AssocItem,
3407 LifetimeRibKind::Generics {
3408 binder: item.id,
3409 span: generics.span,
3410 kind: LifetimeBinderKind::Item,
3411 },
3412 |this| {
3413 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3414 this.check_trait_item(
3417 item.id,
3418 *ident,
3419 &item.kind,
3420 TypeNS,
3421 item.span,
3422 seen_trait_items,
3423 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3424 );
3425
3426 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3427 });
3428 },
3429 );
3430 self.diag_metadata.in_non_gat_assoc_type = None;
3431 }
3432 AssocItemKind::Delegation(box delegation) => {
3433 debug!("resolve_implementation AssocItemKind::Delegation");
3434 self.with_generic_param_rib(
3435 &[],
3436 RibKind::AssocItem,
3437 LifetimeRibKind::Generics {
3438 binder: item.id,
3439 kind: LifetimeBinderKind::Function,
3440 span: delegation.path.segments.last().unwrap().ident.span,
3441 },
3442 |this| {
3443 this.check_trait_item(
3444 item.id,
3445 delegation.ident,
3446 &item.kind,
3447 ValueNS,
3448 item.span,
3449 seen_trait_items,
3450 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3451 );
3452
3453 this.resolve_delegation(delegation)
3454 },
3455 );
3456 }
3457 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3458 panic!("unexpanded macro in resolve!")
3459 }
3460 }
3461 }
3462
3463 fn check_trait_item<F>(
3464 &mut self,
3465 id: NodeId,
3466 mut ident: Ident,
3467 kind: &AssocItemKind,
3468 ns: Namespace,
3469 span: Span,
3470 seen_trait_items: &mut FxHashMap<DefId, Span>,
3471 err: F,
3472 ) where
3473 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3474 {
3475 let Some((module, _)) = self.current_trait_ref else {
3477 return;
3478 };
3479 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3480 let key = BindingKey::new(ident, ns);
3481 let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
3482 debug!(?binding);
3483 if binding.is_none() {
3484 let ns = match ns {
3487 ValueNS => TypeNS,
3488 TypeNS => ValueNS,
3489 _ => ns,
3490 };
3491 let key = BindingKey::new(ident, ns);
3492 binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
3493 debug!(?binding);
3494 }
3495
3496 let feed_visibility = |this: &mut Self, def_id| {
3497 let vis = this.r.tcx.visibility(def_id);
3498 let vis = if vis.is_visible_locally() {
3499 vis.expect_local()
3500 } else {
3501 this.r.dcx().span_delayed_bug(
3502 span,
3503 "error should be emitted when an unexpected trait item is used",
3504 );
3505 rustc_middle::ty::Visibility::Public
3506 };
3507 this.r.feed_visibility(this.r.feed(id), vis);
3508 };
3509
3510 let Some(binding) = binding else {
3511 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3513 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3514 let path_names = path_names_to_string(path);
3515 self.report_error(span, err(ident, path_names, candidate));
3516 feed_visibility(self, module.def_id());
3517 return;
3518 };
3519
3520 let res = binding.res();
3521 let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3522 feed_visibility(self, id_in_trait);
3523
3524 match seen_trait_items.entry(id_in_trait) {
3525 Entry::Occupied(entry) => {
3526 self.report_error(
3527 span,
3528 ResolutionError::TraitImplDuplicate {
3529 name: ident,
3530 old_span: *entry.get(),
3531 trait_item_span: binding.span,
3532 },
3533 );
3534 return;
3535 }
3536 Entry::Vacant(entry) => {
3537 entry.insert(span);
3538 }
3539 };
3540
3541 match (def_kind, kind) {
3542 (DefKind::AssocTy, AssocItemKind::Type(..))
3543 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3544 | (DefKind::AssocConst, AssocItemKind::Const(..))
3545 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3546 self.r.record_partial_res(id, PartialRes::new(res));
3547 return;
3548 }
3549 _ => {}
3550 }
3551
3552 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3554 let (code, kind) = match kind {
3555 AssocItemKind::Const(..) => (E0323, "const"),
3556 AssocItemKind::Fn(..) => (E0324, "method"),
3557 AssocItemKind::Type(..) => (E0325, "type"),
3558 AssocItemKind::Delegation(..) => (E0324, "method"),
3559 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3560 span_bug!(span, "unexpanded macro")
3561 }
3562 };
3563 let trait_path = path_names_to_string(path);
3564 self.report_error(
3565 span,
3566 ResolutionError::TraitImplMismatch {
3567 name: ident,
3568 kind,
3569 code,
3570 trait_path,
3571 trait_item_span: binding.span,
3572 },
3573 );
3574 }
3575
3576 fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3577 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3578 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3579 this.visit_expr(expr)
3580 });
3581 })
3582 }
3583
3584 fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3585 self.smart_resolve_path(
3586 delegation.id,
3587 &delegation.qself,
3588 &delegation.path,
3589 PathSource::Delegation,
3590 );
3591 if let Some(qself) = &delegation.qself {
3592 self.visit_ty(&qself.ty);
3593 }
3594 self.visit_path(&delegation.path);
3595 let Some(body) = &delegation.body else { return };
3596 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3597 let span = delegation.path.segments.last().unwrap().ident.span;
3598 let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3599 let res = Res::Local(delegation.id);
3600 this.innermost_rib_bindings(ValueNS).insert(ident, res);
3601 this.visit_block(body);
3602 });
3603 }
3604
3605 fn resolve_params(&mut self, params: &'ast [Param]) {
3606 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3607 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3608 for Param { pat, .. } in params {
3609 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3610 }
3611 this.apply_pattern_bindings(bindings);
3612 });
3613 for Param { ty, .. } in params {
3614 self.visit_ty(ty);
3615 }
3616 }
3617
3618 fn resolve_local(&mut self, local: &'ast Local) {
3619 debug!("resolving local ({:?})", local);
3620 visit_opt!(self, visit_ty, &local.ty);
3622
3623 if let Some((init, els)) = local.kind.init_else_opt() {
3625 self.visit_expr(init);
3626
3627 if let Some(els) = els {
3629 self.visit_block(els);
3630 }
3631 }
3632
3633 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3635 }
3636
3637 fn compute_and_check_binding_map(
3657 &mut self,
3658 pat: &Pat,
3659 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3660 let mut binding_map = FxIndexMap::default();
3661 let mut is_never_pat = false;
3662
3663 pat.walk(&mut |pat| {
3664 match pat.kind {
3665 PatKind::Ident(annotation, ident, ref sub_pat)
3666 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3667 {
3668 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3669 }
3670 PatKind::Or(ref ps) => {
3671 match self.compute_and_check_or_pat_binding_map(ps) {
3674 Ok(bm) => binding_map.extend(bm),
3675 Err(IsNeverPattern) => is_never_pat = true,
3676 }
3677 return false;
3678 }
3679 PatKind::Never => is_never_pat = true,
3680 _ => {}
3681 }
3682
3683 true
3684 });
3685
3686 if is_never_pat {
3687 for (_, binding) in binding_map {
3688 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3689 }
3690 Err(IsNeverPattern)
3691 } else {
3692 Ok(binding_map)
3693 }
3694 }
3695
3696 fn is_base_res_local(&self, nid: NodeId) -> bool {
3697 matches!(
3698 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3699 Some(Res::Local(..))
3700 )
3701 }
3702
3703 fn compute_and_check_or_pat_binding_map(
3723 &mut self,
3724 pats: &[P<Pat>],
3725 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3726 let mut missing_vars = FxIndexMap::default();
3727 let mut inconsistent_vars = FxIndexMap::default();
3728
3729 let not_never_pats = pats
3731 .iter()
3732 .filter_map(|pat| {
3733 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3734 Some((binding_map, pat))
3735 })
3736 .collect::<Vec<_>>();
3737
3738 for (map_outer, pat_outer) in not_never_pats.iter() {
3740 let inners = not_never_pats
3742 .iter()
3743 .filter(|(_, pat)| pat.id != pat_outer.id)
3744 .flat_map(|(map, _)| map);
3745
3746 for (&name, binding_inner) in inners {
3747 match map_outer.get(&name) {
3748 None => {
3749 let binding_error =
3751 missing_vars.entry(name).or_insert_with(|| BindingError {
3752 name,
3753 origin: BTreeSet::new(),
3754 target: BTreeSet::new(),
3755 could_be_path: name.as_str().starts_with(char::is_uppercase),
3756 });
3757 binding_error.origin.insert(binding_inner.span);
3758 binding_error.target.insert(pat_outer.span);
3759 }
3760 Some(binding_outer) => {
3761 if binding_outer.annotation != binding_inner.annotation {
3762 inconsistent_vars
3764 .entry(name)
3765 .or_insert((binding_inner.span, binding_outer.span));
3766 }
3767 }
3768 }
3769 }
3770 }
3771
3772 for (name, mut v) in missing_vars {
3774 if inconsistent_vars.contains_key(&name) {
3775 v.could_be_path = false;
3776 }
3777 self.report_error(
3778 *v.origin.iter().next().unwrap(),
3779 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3780 );
3781 }
3782
3783 for (name, v) in inconsistent_vars {
3785 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3786 }
3787
3788 if not_never_pats.is_empty() {
3790 Err(IsNeverPattern)
3792 } else {
3793 let mut binding_map = FxIndexMap::default();
3794 for (bm, _) in not_never_pats {
3795 binding_map.extend(bm);
3796 }
3797 Ok(binding_map)
3798 }
3799 }
3800
3801 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3803 let mut is_or_or_never = false;
3804 pat.walk(&mut |pat| match pat.kind {
3805 PatKind::Or(..) | PatKind::Never => {
3806 is_or_or_never = true;
3807 false
3808 }
3809 _ => true,
3810 });
3811 if is_or_or_never {
3812 let _ = self.compute_and_check_binding_map(pat);
3813 }
3814 }
3815
3816 fn resolve_arm(&mut self, arm: &'ast Arm) {
3817 self.with_rib(ValueNS, RibKind::Normal, |this| {
3818 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3819 visit_opt!(this, visit_expr, &arm.guard);
3820 visit_opt!(this, visit_expr, &arm.body);
3821 });
3822 }
3823
3824 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3826 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3827 self.resolve_pattern(pat, pat_src, &mut bindings);
3828 self.apply_pattern_bindings(bindings);
3829 }
3830
3831 fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3833 let rib_bindings = self.innermost_rib_bindings(ValueNS);
3834 let Some((_, pat_bindings)) = pat_bindings.pop() else {
3835 bug!("tried applying nonexistent bindings from pattern");
3836 };
3837
3838 if rib_bindings.is_empty() {
3839 *rib_bindings = pat_bindings;
3842 } else {
3843 rib_bindings.extend(pat_bindings);
3844 }
3845 }
3846
3847 fn resolve_pattern(
3850 &mut self,
3851 pat: &'ast Pat,
3852 pat_src: PatternSource,
3853 bindings: &mut PatternBindings,
3854 ) {
3855 self.visit_pat(pat);
3861 self.resolve_pattern_inner(pat, pat_src, bindings);
3862 self.check_consistent_bindings(pat);
3864 }
3865
3866 #[tracing::instrument(skip(self, bindings), level = "debug")]
3886 fn resolve_pattern_inner(
3887 &mut self,
3888 pat: &'ast Pat,
3889 pat_src: PatternSource,
3890 bindings: &mut PatternBindings,
3891 ) {
3892 pat.walk(&mut |pat| {
3894 match pat.kind {
3895 PatKind::Ident(bmode, ident, ref sub) => {
3896 let has_sub = sub.is_some();
3899 let res = self
3900 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3901 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3902 self.r.record_partial_res(pat.id, PartialRes::new(res));
3903 self.r.record_pat_span(pat.id, pat.span);
3904 }
3905 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3906 self.smart_resolve_path(
3907 pat.id,
3908 qself,
3909 path,
3910 PathSource::TupleStruct(
3911 pat.span,
3912 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3913 ),
3914 );
3915 }
3916 PatKind::Path(ref qself, ref path) => {
3917 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3918 }
3919 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3920 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3921 self.record_patterns_with_skipped_bindings(pat, rest);
3922 }
3923 PatKind::Or(ref ps) => {
3924 bindings.push((PatBoundCtx::Or, Default::default()));
3928 for p in ps {
3929 bindings.push((PatBoundCtx::Product, Default::default()));
3933 self.resolve_pattern_inner(p, pat_src, bindings);
3934 let collected = bindings.pop().unwrap().1;
3937 bindings.last_mut().unwrap().1.extend(collected);
3938 }
3939 let collected = bindings.pop().unwrap().1;
3943 bindings.last_mut().unwrap().1.extend(collected);
3944
3945 return false;
3947 }
3948 PatKind::Guard(ref subpat, ref guard) => {
3949 bindings.push((PatBoundCtx::Product, Default::default()));
3951 let binding_ctx_stack_len = bindings.len();
3954 self.resolve_pattern_inner(subpat, pat_src, bindings);
3955 assert_eq!(bindings.len(), binding_ctx_stack_len);
3956 let subpat_bindings = bindings.pop().unwrap().1;
3959 self.with_rib(ValueNS, RibKind::Normal, |this| {
3960 *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
3961 this.resolve_expr(guard, None);
3962 });
3963 bindings.last_mut().unwrap().1.extend(subpat_bindings);
3970 return false;
3972 }
3973 _ => {}
3974 }
3975 true
3976 });
3977 }
3978
3979 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
3980 match rest {
3981 ast::PatFieldsRest::Rest | ast::PatFieldsRest::Recovered(_) => {
3982 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
3984 && let Some(res) = partial_res.full_res()
3985 && let Some(def_id) = res.opt_def_id()
3986 {
3987 self.ribs[ValueNS]
3988 .last_mut()
3989 .unwrap()
3990 .patterns_with_skipped_bindings
3991 .entry(def_id)
3992 .or_default()
3993 .push((
3994 pat.span,
3995 match rest {
3996 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
3997 _ => Ok(()),
3998 },
3999 ));
4000 }
4001 }
4002 ast::PatFieldsRest::None => {}
4003 }
4004 }
4005
4006 fn fresh_binding(
4007 &mut self,
4008 ident: Ident,
4009 pat_id: NodeId,
4010 pat_src: PatternSource,
4011 bindings: &mut PatternBindings,
4012 ) -> Res {
4013 let ident = ident.normalize_to_macro_rules();
4017
4018 let already_bound_and = bindings
4020 .iter()
4021 .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4022 if already_bound_and {
4023 use ResolutionError::*;
4025 let error = match pat_src {
4026 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4028 _ => IdentifierBoundMoreThanOnceInSamePattern,
4030 };
4031 self.report_error(ident.span, error(ident));
4032 }
4033
4034 let already_bound_or = bindings
4037 .iter()
4038 .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4039 let res = if let Some(&res) = already_bound_or {
4040 res
4043 } else {
4044 Res::Local(pat_id)
4046 };
4047
4048 bindings.last_mut().unwrap().1.insert(ident, res);
4050 res
4051 }
4052
4053 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4054 &mut self.ribs[ns].last_mut().unwrap().bindings
4055 }
4056
4057 fn try_resolve_as_non_binding(
4058 &mut self,
4059 pat_src: PatternSource,
4060 ann: BindingMode,
4061 ident: Ident,
4062 has_sub: bool,
4063 ) -> Option<Res> {
4064 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4068
4069 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4070 let (res, binding) = match ls_binding {
4071 LexicalScopeBinding::Item(binding)
4072 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4073 {
4074 self.r.record_use(ident, binding, Used::Other);
4079 return None;
4080 }
4081 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4082 LexicalScopeBinding::Res(res) => (res, None),
4083 };
4084
4085 match res {
4086 Res::SelfCtor(_) | Res::Def(
4088 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4089 _,
4090 ) if is_syntactic_ambiguity => {
4091 if let Some(binding) = binding {
4093 self.r.record_use(ident, binding, Used::Other);
4094 }
4095 Some(res)
4096 }
4097 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4098 let binding = binding.expect("no binding for a ctor or static");
4104 self.report_error(
4105 ident.span,
4106 ResolutionError::BindingShadowsSomethingUnacceptable {
4107 shadowing_binding: pat_src,
4108 name: ident.name,
4109 participle: if binding.is_import() { "imported" } else { "defined" },
4110 article: binding.res().article(),
4111 shadowed_binding: binding.res(),
4112 shadowed_binding_span: binding.span,
4113 },
4114 );
4115 None
4116 }
4117 Res::Def(DefKind::ConstParam, def_id) => {
4118 self.report_error(
4121 ident.span,
4122 ResolutionError::BindingShadowsSomethingUnacceptable {
4123 shadowing_binding: pat_src,
4124 name: ident.name,
4125 participle: "defined",
4126 article: res.article(),
4127 shadowed_binding: res,
4128 shadowed_binding_span: self.r.def_span(def_id),
4129 }
4130 );
4131 None
4132 }
4133 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4134 None
4136 }
4137 Res::SelfCtor(_) => {
4138 self.r.dcx().span_delayed_bug(
4141 ident.span,
4142 "unexpected `SelfCtor` in pattern, expected identifier"
4143 );
4144 None
4145 }
4146 _ => span_bug!(
4147 ident.span,
4148 "unexpected resolution for an identifier in pattern: {:?}",
4149 res,
4150 ),
4151 }
4152 }
4153
4154 fn smart_resolve_path(
4160 &mut self,
4161 id: NodeId,
4162 qself: &Option<P<QSelf>>,
4163 path: &Path,
4164 source: PathSource<'ast, '_>,
4165 ) {
4166 self.smart_resolve_path_fragment(
4167 qself,
4168 &Segment::from_path(path),
4169 source,
4170 Finalize::new(id, path.span),
4171 RecordPartialRes::Yes,
4172 None,
4173 );
4174 }
4175
4176 #[instrument(level = "debug", skip(self))]
4177 fn smart_resolve_path_fragment(
4178 &mut self,
4179 qself: &Option<P<QSelf>>,
4180 path: &[Segment],
4181 source: PathSource<'ast, '_>,
4182 finalize: Finalize,
4183 record_partial_res: RecordPartialRes,
4184 parent_qself: Option<&QSelf>,
4185 ) -> PartialRes {
4186 let ns = source.namespace();
4187
4188 let Finalize { node_id, path_span, .. } = finalize;
4189 let report_errors = |this: &mut Self, res: Option<Res>| {
4190 if this.should_report_errs() {
4191 let (err, candidates) = this.smart_resolve_report_errors(
4192 path,
4193 None,
4194 path_span,
4195 source,
4196 res,
4197 parent_qself,
4198 );
4199
4200 let def_id = this.parent_scope.module.nearest_parent_mod();
4201 let instead = res.is_some();
4202 let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4203 && path[0].ident.span.lo() == end.span.lo()
4204 && !matches!(start.kind, ExprKind::Lit(_))
4205 {
4206 let mut sugg = ".";
4207 let mut span = start.span.between(end.span);
4208 if span.lo() + BytePos(2) == span.hi() {
4209 span = span.with_lo(span.lo() + BytePos(1));
4212 sugg = "";
4213 }
4214 Some((
4215 span,
4216 "you might have meant to write `.` instead of `..`",
4217 sugg.to_string(),
4218 Applicability::MaybeIncorrect,
4219 ))
4220 } else if res.is_none()
4221 && let PathSource::Type
4222 | PathSource::Expr(_)
4223 | PathSource::PreciseCapturingArg(..) = source
4224 {
4225 this.suggest_adding_generic_parameter(path, source)
4226 } else {
4227 None
4228 };
4229
4230 let ue = UseError {
4231 err,
4232 candidates,
4233 def_id,
4234 instead,
4235 suggestion,
4236 path: path.into(),
4237 is_call: source.is_call(),
4238 };
4239
4240 this.r.use_injections.push(ue);
4241 }
4242
4243 PartialRes::new(Res::Err)
4244 };
4245
4246 let report_errors_for_call =
4252 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4253 let (following_seg, prefix_path) = match path.split_last() {
4257 Some((last, path)) if !path.is_empty() => (Some(last), path),
4258 _ => return Some(parent_err),
4259 };
4260
4261 let (mut err, candidates) = this.smart_resolve_report_errors(
4262 prefix_path,
4263 following_seg,
4264 path_span,
4265 PathSource::Type,
4266 None,
4267 parent_qself,
4268 );
4269
4270 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4285
4286 err.messages = take(&mut parent_err.messages);
4288 err.code = take(&mut parent_err.code);
4289 swap(&mut err.span, &mut parent_err.span);
4290 err.children = take(&mut parent_err.children);
4291 err.sort_span = parent_err.sort_span;
4292 err.is_lint = parent_err.is_lint.clone();
4293
4294 match &mut err.suggestions {
4296 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4297 Suggestions::Enabled(parent_suggestions) => {
4298 typo_suggestions.append(parent_suggestions)
4300 }
4301 Suggestions::Sealed(_) | Suggestions::Disabled => {
4302 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4307 }
4308 },
4309 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4310 }
4311
4312 parent_err.cancel();
4313
4314 let def_id = this.parent_scope.module.nearest_parent_mod();
4315
4316 if this.should_report_errs() {
4317 if candidates.is_empty() {
4318 if path.len() == 2
4319 && let [segment] = prefix_path
4320 {
4321 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4327 } else {
4328 err.emit();
4333 }
4334 } else {
4335 this.r.use_injections.push(UseError {
4337 err,
4338 candidates,
4339 def_id,
4340 instead: false,
4341 suggestion: None,
4342 path: prefix_path.into(),
4343 is_call: source.is_call(),
4344 });
4345 }
4346 } else {
4347 err.cancel();
4348 }
4349
4350 None
4353 };
4354
4355 let partial_res = match self.resolve_qpath_anywhere(
4356 qself,
4357 path,
4358 ns,
4359 path_span,
4360 source.defer_to_typeck(),
4361 finalize,
4362 source,
4363 ) {
4364 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4365 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4367 && let [Segment { ident, .. }] = path
4368 && items.iter().any(|item| {
4369 if let AssocItemKind::Type(alias) = &item.kind
4370 && alias.ident == *ident
4371 {
4372 true
4373 } else {
4374 false
4375 }
4376 })
4377 {
4378 let mut diag = self.r.tcx.dcx().struct_allow("");
4379 diag.span_suggestion_verbose(
4380 path_span.shrink_to_lo(),
4381 "there is an associated type with the same name",
4382 "Self::",
4383 Applicability::MaybeIncorrect,
4384 );
4385 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4386 }
4387
4388 if source.is_expected(res) || res == Res::Err {
4389 partial_res
4390 } else {
4391 report_errors(self, Some(res))
4392 }
4393 }
4394
4395 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4396 if ns == ValueNS {
4400 let item_name = path.last().unwrap().ident;
4401 let traits = self.traits_in_scope(item_name, ns);
4402 self.r.trait_map.insert(node_id, traits);
4403 }
4404
4405 if PrimTy::from_name(path[0].ident.name).is_some() {
4406 let mut std_path = Vec::with_capacity(1 + path.len());
4407
4408 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4409 std_path.extend(path);
4410 if let PathResult::Module(_) | PathResult::NonModule(_) =
4411 self.resolve_path(&std_path, Some(ns), None)
4412 {
4413 let item_span =
4415 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4416
4417 self.r.confused_type_with_std_module.insert(item_span, path_span);
4418 self.r.confused_type_with_std_module.insert(path_span, path_span);
4419 }
4420 }
4421
4422 partial_res
4423 }
4424
4425 Err(err) => {
4426 if let Some(err) = report_errors_for_call(self, err) {
4427 self.report_error(err.span, err.node);
4428 }
4429
4430 PartialRes::new(Res::Err)
4431 }
4432
4433 _ => report_errors(self, None),
4434 };
4435
4436 if record_partial_res == RecordPartialRes::Yes {
4437 self.r.record_partial_res(node_id, partial_res);
4439 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4440 self.lint_unused_qualifications(path, ns, finalize);
4441 }
4442
4443 partial_res
4444 }
4445
4446 fn self_type_is_available(&mut self) -> bool {
4447 let binding = self
4448 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4449 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4450 }
4451
4452 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4453 let ident = Ident::new(kw::SelfLower, self_span);
4454 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4455 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4456 }
4457
4458 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4462 if self.should_report_errs() {
4463 self.r.report_error(span, resolution_error);
4464 }
4465 }
4466
4467 #[inline]
4468 fn should_report_errs(&self) -> bool {
4472 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4473 && !self.r.glob_error.is_some()
4474 }
4475
4476 fn resolve_qpath_anywhere(
4478 &mut self,
4479 qself: &Option<P<QSelf>>,
4480 path: &[Segment],
4481 primary_ns: Namespace,
4482 span: Span,
4483 defer_to_typeck: bool,
4484 finalize: Finalize,
4485 source: PathSource<'ast, '_>,
4486 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4487 let mut fin_res = None;
4488
4489 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4490 if i == 0 || ns != primary_ns {
4491 match self.resolve_qpath(qself, path, ns, finalize, source)? {
4492 Some(partial_res)
4493 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4494 {
4495 return Ok(Some(partial_res));
4496 }
4497 partial_res => {
4498 if fin_res.is_none() {
4499 fin_res = partial_res;
4500 }
4501 }
4502 }
4503 }
4504 }
4505
4506 assert!(primary_ns != MacroNS);
4507
4508 if qself.is_none() {
4509 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
4510 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
4511 if let Ok((_, res)) =
4512 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false, None, None)
4513 {
4514 return Ok(Some(PartialRes::new(res)));
4515 }
4516 }
4517
4518 Ok(fin_res)
4519 }
4520
4521 fn resolve_qpath(
4523 &mut self,
4524 qself: &Option<P<QSelf>>,
4525 path: &[Segment],
4526 ns: Namespace,
4527 finalize: Finalize,
4528 source: PathSource<'ast, '_>,
4529 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4530 debug!(
4531 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4532 qself, path, ns, finalize,
4533 );
4534
4535 if let Some(qself) = qself {
4536 if qself.position == 0 {
4537 return Ok(Some(PartialRes::with_unresolved_segments(
4541 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4542 path.len(),
4543 )));
4544 }
4545
4546 let num_privacy_errors = self.r.privacy_errors.len();
4547 let trait_res = self.smart_resolve_path_fragment(
4549 &None,
4550 &path[..qself.position],
4551 PathSource::Trait(AliasPossibility::No),
4552 Finalize::new(finalize.node_id, qself.path_span),
4553 RecordPartialRes::No,
4554 Some(&qself),
4555 );
4556
4557 if trait_res.expect_full_res() == Res::Err {
4558 return Ok(Some(trait_res));
4559 }
4560
4561 self.r.privacy_errors.truncate(num_privacy_errors);
4564
4565 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4573 let partial_res = self.smart_resolve_path_fragment(
4574 &None,
4575 &path[..=qself.position],
4576 PathSource::TraitItem(ns, &source),
4577 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4578 RecordPartialRes::No,
4579 Some(&qself),
4580 );
4581
4582 return Ok(Some(PartialRes::with_unresolved_segments(
4586 partial_res.base_res(),
4587 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4588 )));
4589 }
4590
4591 let result = match self.resolve_path(path, Some(ns), Some(finalize)) {
4592 PathResult::NonModule(path_res) => path_res,
4593 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4594 PartialRes::new(module.res().unwrap())
4595 }
4596 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4600 PartialRes::new(Res::Err)
4601 }
4602 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4615 if (ns == TypeNS || path.len() > 1)
4616 && PrimTy::from_name(path[0].ident.name).is_some() =>
4617 {
4618 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4619 let tcx = self.r.tcx();
4620
4621 let gate_err_sym_msg = match prim {
4622 PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4623 Some((sym::f16, "the type `f16` is unstable"))
4624 }
4625 PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4626 Some((sym::f128, "the type `f128` is unstable"))
4627 }
4628 _ => None,
4629 };
4630
4631 if let Some((sym, msg)) = gate_err_sym_msg {
4632 let span = path[0].ident.span;
4633 if !span.allows_unstable(sym) {
4634 feature_err(tcx.sess, sym, span, msg).emit();
4635 }
4636 };
4637
4638 if let Some(id) = path[0].id {
4640 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4641 }
4642
4643 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4644 }
4645 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4646 PartialRes::new(module.res().unwrap())
4647 }
4648 PathResult::Failed {
4649 is_error_from_last_segment: false,
4650 span,
4651 label,
4652 suggestion,
4653 module,
4654 segment_name,
4655 error_implied_by_parse_error: _,
4656 } => {
4657 return Err(respan(
4658 span,
4659 ResolutionError::FailedToResolve {
4660 segment: Some(segment_name),
4661 label,
4662 suggestion,
4663 module,
4664 },
4665 ));
4666 }
4667 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4668 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4669 };
4670
4671 Ok(Some(result))
4672 }
4673
4674 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4675 if let Some(label) = label {
4676 if label.ident.as_str().as_bytes()[1] != b'_' {
4677 self.diag_metadata.unused_labels.insert(id, label.ident.span);
4678 }
4679
4680 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4681 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4682 }
4683
4684 self.with_label_rib(RibKind::Normal, |this| {
4685 let ident = label.ident.normalize_to_macro_rules();
4686 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4687 f(this);
4688 });
4689 } else {
4690 f(self);
4691 }
4692 }
4693
4694 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4695 self.with_resolved_label(label, id, |this| this.visit_block(block));
4696 }
4697
4698 fn resolve_block(&mut self, block: &'ast Block) {
4699 debug!("(resolving block) entering block");
4700 let orig_module = self.parent_scope.module;
4702 let anonymous_module = self.r.block_map.get(&block.id).cloned(); let mut num_macro_definition_ribs = 0;
4705 if let Some(anonymous_module) = anonymous_module {
4706 debug!("(resolving block) found anonymous module, moving down");
4707 self.ribs[ValueNS].push(Rib::new(RibKind::Module(anonymous_module)));
4708 self.ribs[TypeNS].push(Rib::new(RibKind::Module(anonymous_module)));
4709 self.parent_scope.module = anonymous_module;
4710 } else {
4711 self.ribs[ValueNS].push(Rib::new(RibKind::Normal));
4712 }
4713
4714 for stmt in &block.stmts {
4716 if let StmtKind::Item(ref item) = stmt.kind
4717 && let ItemKind::MacroDef(..) = item.kind
4718 {
4719 num_macro_definition_ribs += 1;
4720 let res = self.r.local_def_id(item.id).to_def_id();
4721 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4722 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4723 }
4724
4725 self.visit_stmt(stmt);
4726 }
4727
4728 self.parent_scope.module = orig_module;
4730 for _ in 0..num_macro_definition_ribs {
4731 self.ribs[ValueNS].pop();
4732 self.label_ribs.pop();
4733 }
4734 self.last_block_rib = self.ribs[ValueNS].pop();
4735 if anonymous_module.is_some() {
4736 self.ribs[TypeNS].pop();
4737 }
4738 debug!("(resolving block) leaving block");
4739 }
4740
4741 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4742 debug!(
4743 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4744 constant, anon_const_kind
4745 );
4746
4747 let is_trivial_const_arg = constant
4748 .value
4749 .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4750 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4751 this.resolve_expr(&constant.value, None)
4752 })
4753 }
4754
4755 fn resolve_anon_const_manual(
4762 &mut self,
4763 is_trivial_const_arg: bool,
4764 anon_const_kind: AnonConstKind,
4765 resolve_expr: impl FnOnce(&mut Self),
4766 ) {
4767 let is_repeat_expr = match anon_const_kind {
4768 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4769 _ => IsRepeatExpr::No,
4770 };
4771
4772 let may_use_generics = match anon_const_kind {
4773 AnonConstKind::EnumDiscriminant => {
4774 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4775 }
4776 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4777 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4778 AnonConstKind::ConstArg(_) => {
4779 if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4780 ConstantHasGenerics::Yes
4781 } else {
4782 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4783 }
4784 }
4785 };
4786
4787 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4788 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4789 resolve_expr(this);
4790 });
4791 });
4792 }
4793
4794 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4795 self.resolve_expr(&f.expr, Some(e));
4796 self.visit_ident(&f.ident);
4797 walk_list!(self, visit_attribute, f.attrs.iter());
4798 }
4799
4800 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4801 self.record_candidate_traits_for_expr_if_necessary(expr);
4805
4806 match expr.kind {
4808 ExprKind::Path(ref qself, ref path) => {
4809 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4810 visit::walk_expr(self, expr);
4811 }
4812
4813 ExprKind::Struct(ref se) => {
4814 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct);
4815 if let Some(qself) = &se.qself {
4819 self.visit_ty(&qself.ty);
4820 }
4821 self.visit_path(&se.path);
4822 walk_list!(self, resolve_expr_field, &se.fields, expr);
4823 match &se.rest {
4824 StructRest::Base(expr) => self.visit_expr(expr),
4825 StructRest::Rest(_span) => {}
4826 StructRest::None => {}
4827 }
4828 }
4829
4830 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4831 match self.resolve_label(label.ident) {
4832 Ok((node_id, _)) => {
4833 self.r.label_res_map.insert(expr.id, node_id);
4835 self.diag_metadata.unused_labels.swap_remove(&node_id);
4836 }
4837 Err(error) => {
4838 self.report_error(label.ident.span, error);
4839 }
4840 }
4841
4842 visit::walk_expr(self, expr);
4844 }
4845
4846 ExprKind::Break(None, Some(ref e)) => {
4847 self.resolve_expr(e, Some(expr));
4850 }
4851
4852 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
4853 self.visit_expr(scrutinee);
4854 self.resolve_pattern_top(pat, PatternSource::Let);
4855 }
4856
4857 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
4858 self.visit_expr(scrutinee);
4859 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4861 self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
4862 for (_, bindings) in &mut bindings {
4867 for (_, binding) in bindings {
4868 *binding = Res::Err;
4869 }
4870 }
4871 self.apply_pattern_bindings(bindings);
4872 }
4873
4874 ExprKind::If(ref cond, ref then, ref opt_else) => {
4875 self.with_rib(ValueNS, RibKind::Normal, |this| {
4876 let old = this.diag_metadata.in_if_condition.replace(cond);
4877 this.visit_expr(cond);
4878 this.diag_metadata.in_if_condition = old;
4879 this.visit_block(then);
4880 });
4881 if let Some(expr) = opt_else {
4882 self.visit_expr(expr);
4883 }
4884 }
4885
4886 ExprKind::Loop(ref block, label, _) => {
4887 self.resolve_labeled_block(label, expr.id, block)
4888 }
4889
4890 ExprKind::While(ref cond, ref block, label) => {
4891 self.with_resolved_label(label, expr.id, |this| {
4892 this.with_rib(ValueNS, RibKind::Normal, |this| {
4893 let old = this.diag_metadata.in_if_condition.replace(cond);
4894 this.visit_expr(cond);
4895 this.diag_metadata.in_if_condition = old;
4896 this.visit_block(block);
4897 })
4898 });
4899 }
4900
4901 ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4902 self.visit_expr(iter);
4903 self.with_rib(ValueNS, RibKind::Normal, |this| {
4904 this.resolve_pattern_top(pat, PatternSource::For);
4905 this.resolve_labeled_block(label, expr.id, body);
4906 });
4907 }
4908
4909 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4910
4911 ExprKind::Field(ref subexpression, _) => {
4913 self.resolve_expr(subexpression, Some(expr));
4914 }
4915 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
4916 self.resolve_expr(receiver, Some(expr));
4917 for arg in args {
4918 self.resolve_expr(arg, None);
4919 }
4920 self.visit_path_segment(seg);
4921 }
4922
4923 ExprKind::Call(ref callee, ref arguments) => {
4924 self.resolve_expr(callee, Some(expr));
4925 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
4926 for (idx, argument) in arguments.iter().enumerate() {
4927 if const_args.contains(&idx) {
4930 let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
4931 self.r.tcx.features().min_generic_const_args(),
4932 );
4933 self.resolve_anon_const_manual(
4934 is_trivial_const_arg,
4935 AnonConstKind::ConstArg(IsRepeatExpr::No),
4936 |this| this.resolve_expr(argument, None),
4937 );
4938 } else {
4939 self.resolve_expr(argument, None);
4940 }
4941 }
4942 }
4943 ExprKind::Type(ref _type_expr, ref _ty) => {
4944 visit::walk_expr(self, expr);
4945 }
4946 ExprKind::Closure(box ast::Closure {
4948 binder: ClosureBinder::For { ref generic_params, span },
4949 ..
4950 }) => {
4951 self.with_generic_param_rib(
4952 generic_params,
4953 RibKind::Normal,
4954 LifetimeRibKind::Generics {
4955 binder: expr.id,
4956 kind: LifetimeBinderKind::Closure,
4957 span,
4958 },
4959 |this| visit::walk_expr(this, expr),
4960 );
4961 }
4962 ExprKind::Closure(..) => visit::walk_expr(self, expr),
4963 ExprKind::Gen(..) => {
4964 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
4965 }
4966 ExprKind::Repeat(ref elem, ref ct) => {
4967 self.visit_expr(elem);
4968 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
4969 }
4970 ExprKind::ConstBlock(ref ct) => {
4971 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
4972 }
4973 ExprKind::Index(ref elem, ref idx, _) => {
4974 self.resolve_expr(elem, Some(expr));
4975 self.visit_expr(idx);
4976 }
4977 ExprKind::Assign(ref lhs, ref rhs, _) => {
4978 if !self.diag_metadata.is_assign_rhs {
4979 self.diag_metadata.in_assignment = Some(expr);
4980 }
4981 self.visit_expr(lhs);
4982 self.diag_metadata.is_assign_rhs = true;
4983 self.diag_metadata.in_assignment = None;
4984 self.visit_expr(rhs);
4985 self.diag_metadata.is_assign_rhs = false;
4986 }
4987 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
4988 self.diag_metadata.in_range = Some((start, end));
4989 self.resolve_expr(start, Some(expr));
4990 self.resolve_expr(end, Some(expr));
4991 self.diag_metadata.in_range = None;
4992 }
4993 _ => {
4994 visit::walk_expr(self, expr);
4995 }
4996 }
4997 }
4998
4999 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5000 match expr.kind {
5001 ExprKind::Field(_, ident) => {
5002 let traits = self.traits_in_scope(ident, ValueNS);
5007 self.r.trait_map.insert(expr.id, traits);
5008 }
5009 ExprKind::MethodCall(ref call) => {
5010 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
5011 let traits = self.traits_in_scope(call.seg.ident, ValueNS);
5012 self.r.trait_map.insert(expr.id, traits);
5013 }
5014 _ => {
5015 }
5017 }
5018 }
5019
5020 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
5021 self.r.traits_in_scope(
5022 self.current_trait_ref.as_ref().map(|(module, _)| *module),
5023 &self.parent_scope,
5024 ident.span.ctxt(),
5025 Some((ident.name, ns)),
5026 )
5027 }
5028
5029 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5030 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5034 let res = *doc_link_resolutions
5035 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5036 .or_default()
5037 .entry((Symbol::intern(path_str), ns))
5038 .or_insert_with_key(|(path, ns)| {
5039 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5040 if let Some(res) = res
5041 && let Some(def_id) = res.opt_def_id()
5042 && self.is_invalid_proc_macro_item_for_doc(def_id)
5043 {
5044 return None;
5047 }
5048 res
5049 });
5050 self.r.doc_link_resolutions = doc_link_resolutions;
5051 res
5052 }
5053
5054 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5055 if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5056 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5057 {
5058 return false;
5059 }
5060 let Some(local_did) = did.as_local() else { return true };
5061 !self.r.proc_macros.contains(&local_did)
5062 }
5063
5064 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5065 match self.r.tcx.sess.opts.resolve_doc_links {
5066 ResolveDocLinks::None => return,
5067 ResolveDocLinks::ExportedMetadata
5068 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5069 || !maybe_exported.eval(self.r) =>
5070 {
5071 return;
5072 }
5073 ResolveDocLinks::Exported
5074 if !maybe_exported.eval(self.r)
5075 && !rustdoc::has_primitive_or_keyword_docs(attrs) =>
5076 {
5077 return;
5078 }
5079 ResolveDocLinks::ExportedMetadata
5080 | ResolveDocLinks::Exported
5081 | ResolveDocLinks::All => {}
5082 }
5083
5084 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5085 return;
5086 }
5087
5088 let mut need_traits_in_scope = false;
5089 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5090 let mut any_resolved = false;
5092 let mut need_assoc = false;
5093 for ns in [TypeNS, ValueNS, MacroNS] {
5094 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5095 any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5098 } else if ns != MacroNS {
5099 need_assoc = true;
5100 }
5101 }
5102
5103 if need_assoc || !any_resolved {
5105 let mut path = &path_str[..];
5106 while let Some(idx) = path.rfind("::") {
5107 path = &path[..idx];
5108 need_traits_in_scope = true;
5109 for ns in [TypeNS, ValueNS, MacroNS] {
5110 self.resolve_and_cache_rustdoc_path(path, ns);
5111 }
5112 }
5113 }
5114 }
5115
5116 if need_traits_in_scope {
5117 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5119 doc_link_traits_in_scope
5120 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5121 .or_insert_with(|| {
5122 self.r
5123 .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5124 .into_iter()
5125 .filter_map(|tr| {
5126 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5127 return None;
5130 }
5131 Some(tr.def_id)
5132 })
5133 .collect()
5134 });
5135 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5136 }
5137 }
5138
5139 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5140 if let Some(seg) = path.first()
5142 && seg.ident.name == kw::PathRoot
5143 {
5144 return;
5145 }
5146
5147 if finalize.path_span.from_expansion()
5148 || path.iter().any(|seg| seg.ident.span.from_expansion())
5149 {
5150 return;
5151 }
5152
5153 let end_pos =
5154 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5155 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5156 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5165 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5166 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5167 (res == binding.res()).then_some((seg, binding))
5168 });
5169
5170 if let Some((seg, binding)) = unqualified {
5171 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5172 binding,
5173 node_id: finalize.node_id,
5174 path_span: finalize.path_span,
5175 removal_span: path[0].ident.span.until(seg.ident.span),
5176 });
5177 }
5178 }
5179
5180 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5181 if let Some(define_opaque) = define_opaque {
5182 for (id, path) in define_opaque {
5183 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5184 }
5185 }
5186 }
5187}
5188
5189struct ItemInfoCollector<'a, 'ra, 'tcx> {
5192 r: &'a mut Resolver<'ra, 'tcx>,
5193}
5194
5195impl ItemInfoCollector<'_, '_, '_> {
5196 fn collect_fn_info(
5197 &mut self,
5198 header: FnHeader,
5199 decl: &FnDecl,
5200 id: NodeId,
5201 attrs: &[Attribute],
5202 ) {
5203 let sig = DelegationFnSig {
5204 header,
5205 param_count: decl.inputs.len(),
5206 has_self: decl.has_self(),
5207 c_variadic: decl.c_variadic(),
5208 target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5209 };
5210 self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5211 }
5212}
5213
5214impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5215 fn visit_item(&mut self, item: &'ast Item) {
5216 match &item.kind {
5217 ItemKind::TyAlias(box TyAlias { generics, .. })
5218 | ItemKind::Const(box ConstItem { generics, .. })
5219 | ItemKind::Fn(box Fn { generics, .. })
5220 | ItemKind::Enum(_, generics, _)
5221 | ItemKind::Struct(_, generics, _)
5222 | ItemKind::Union(_, generics, _)
5223 | ItemKind::Impl(box Impl { generics, .. })
5224 | ItemKind::Trait(box Trait { generics, .. })
5225 | ItemKind::TraitAlias(_, generics, _) => {
5226 if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5227 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5228 }
5229
5230 let def_id = self.r.local_def_id(item.id);
5231 let count = generics
5232 .params
5233 .iter()
5234 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5235 .count();
5236 self.r.item_generics_num_lifetimes.insert(def_id, count);
5237 }
5238
5239 ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5240 for foreign_item in items {
5241 if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5242 let new_header =
5243 FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5244 self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5245 }
5246 }
5247 }
5248
5249 ItemKind::Mod(..)
5250 | ItemKind::Static(..)
5251 | ItemKind::Use(..)
5252 | ItemKind::ExternCrate(..)
5253 | ItemKind::MacroDef(..)
5254 | ItemKind::GlobalAsm(..)
5255 | ItemKind::MacCall(..)
5256 | ItemKind::DelegationMac(..) => {}
5257 ItemKind::Delegation(..) => {
5258 }
5263 }
5264 visit::walk_item(self, item)
5265 }
5266
5267 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5268 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5269 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5270 }
5271 visit::walk_assoc_item(self, item, ctxt);
5272 }
5273}
5274
5275impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5276 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5277 visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5278 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5279 late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5280 visit::walk_crate(&mut late_resolution_visitor, krate);
5281 for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5282 self.lint_buffer.buffer_lint(
5283 lint::builtin::UNUSED_LABELS,
5284 *id,
5285 *span,
5286 BuiltinLintDiag::UnusedLabel,
5287 );
5288 }
5289 }
5290}
5291
5292fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5294 let mut path = expected_path.iter().rev();
5295 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5296 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5297 return false;
5298 }
5299 def_id = parent;
5300 }
5301 true
5302}