1use std::assert_matches::debug_assert_matches;
10use std::borrow::Cow;
11use std::collections::hash_map::Entry;
12use std::mem::{replace, swap, take};
13use std::ops::ControlFlow;
14
15use rustc_ast::visit::{
16 AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,
17};
18use rustc_ast::*;
19use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
20use rustc_data_structures::unord::{UnordMap, UnordSet};
21use rustc_errors::codes::*;
22use rustc_errors::{
23 Applicability, Diag, DiagArgValue, ErrorGuaranteed, IntoDiagArg, MultiSpan, StashKey,
24 Suggestions, pluralize,
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::{
32 AssocTag, DELEGATION_INHERIT_ATTRS_START, DelegationFnSig, DelegationFnSigAttrs, Visibility,
33};
34use rustc_middle::{bug, span_bug};
35use rustc_session::config::{CrateType, ResolveDocLinks};
36use rustc_session::lint;
37use rustc_session::parse::feature_err;
38use rustc_span::source_map::{Spanned, respan};
39use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Symbol, SyntaxContext, kw, sym};
40use smallvec::{SmallVec, smallvec};
41use thin_vec::ThinVec;
42use tracing::{debug, instrument, trace};
43
44use crate::{
45 BindingError, BindingKey, Finalize, LexicalScopeBinding, Module, ModuleOrUniformRoot,
46 NameBinding, ParentScope, PathResult, ResolutionError, Resolver, Segment, TyCtxt, UseError,
47 Used, errors, path_names_to_string, rustdoc,
48};
49
50mod diagnostics;
51
52type Res = def::Res<NodeId>;
53
54use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
55
56#[derive(Copy, Clone, Debug)]
57struct BindingInfo {
58 span: Span,
59 annotation: BindingMode,
60}
61
62#[derive(Copy, Clone, PartialEq, Eq, Debug)]
63pub(crate) enum PatternSource {
64 Match,
65 Let,
66 For,
67 FnParam,
68}
69
70#[derive(Copy, Clone, Debug, PartialEq, Eq)]
71enum IsRepeatExpr {
72 No,
73 Yes,
74}
75
76struct IsNeverPattern;
77
78#[derive(Copy, Clone, Debug, PartialEq, Eq)]
81enum AnonConstKind {
82 EnumDiscriminant,
83 FieldDefaultValue,
84 InlineConst,
85 ConstArg(IsRepeatExpr),
86}
87
88impl PatternSource {
89 fn descr(self) -> &'static str {
90 match self {
91 PatternSource::Match => "match binding",
92 PatternSource::Let => "let binding",
93 PatternSource::For => "for binding",
94 PatternSource::FnParam => "function parameter",
95 }
96 }
97}
98
99impl IntoDiagArg for PatternSource {
100 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
101 DiagArgValue::Str(Cow::Borrowed(self.descr()))
102 }
103}
104
105#[derive(PartialEq)]
109enum PatBoundCtx {
110 Product,
112 Or,
114}
115
116type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;
128
129#[derive(Copy, Clone, Debug)]
131pub(crate) enum HasGenericParams {
132 Yes(Span),
133 No,
134}
135
136#[derive(Copy, Clone, Debug, Eq, PartialEq)]
138pub(crate) enum ConstantHasGenerics {
139 Yes,
140 No(NoConstantGenericsReason),
141}
142
143impl ConstantHasGenerics {
144 fn force_yes_if(self, b: bool) -> Self {
145 if b { Self::Yes } else { self }
146 }
147}
148
149#[derive(Copy, Clone, Debug, Eq, PartialEq)]
151pub(crate) enum NoConstantGenericsReason {
152 NonTrivialConstArg,
159 IsEnumDiscriminant,
168}
169
170#[derive(Copy, Clone, Debug, Eq, PartialEq)]
171pub(crate) enum ConstantItemKind {
172 Const,
173 Static,
174}
175
176impl ConstantItemKind {
177 pub(crate) fn as_str(&self) -> &'static str {
178 match self {
179 Self::Const => "const",
180 Self::Static => "static",
181 }
182 }
183}
184
185#[derive(Debug, Copy, Clone, PartialEq, Eq)]
186enum RecordPartialRes {
187 Yes,
188 No,
189}
190
191#[derive(Copy, Clone, Debug)]
194pub(crate) enum RibKind<'ra> {
195 Normal,
197
198 Block(Option<Module<'ra>>),
204
205 AssocItem,
210
211 FnOrCoroutine,
213
214 Item(HasGenericParams, DefKind),
216
217 ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
222
223 Module(Module<'ra>),
225
226 MacroDefinition(DefId),
228
229 ForwardGenericParamBan(ForwardGenericParamBanReason),
233
234 ConstParamTy,
237
238 InlineAsmSym,
241}
242
243#[derive(Copy, Clone, PartialEq, Eq, Debug)]
244pub(crate) enum ForwardGenericParamBanReason {
245 Default,
246 ConstParamTy,
247}
248
249impl RibKind<'_> {
250 pub(crate) fn contains_params(&self) -> bool {
253 match self {
254 RibKind::Normal
255 | RibKind::Block(..)
256 | RibKind::FnOrCoroutine
257 | RibKind::ConstantItem(..)
258 | RibKind::Module(_)
259 | RibKind::MacroDefinition(_)
260 | RibKind::InlineAsmSym => false,
261 RibKind::ConstParamTy
262 | RibKind::AssocItem
263 | RibKind::Item(..)
264 | RibKind::ForwardGenericParamBan(_) => true,
265 }
266 }
267
268 fn is_label_barrier(self) -> bool {
270 match self {
271 RibKind::Normal | RibKind::MacroDefinition(..) => false,
272 RibKind::FnOrCoroutine | RibKind::ConstantItem(..) => true,
273 kind => bug!("unexpected rib kind: {kind:?}"),
274 }
275 }
276}
277
278#[derive(Debug)]
291pub(crate) struct Rib<'ra, R = Res> {
292 pub bindings: FxIndexMap<Ident, R>,
293 pub patterns_with_skipped_bindings: UnordMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>,
294 pub kind: RibKind<'ra>,
295}
296
297impl<'ra, R> Rib<'ra, R> {
298 fn new(kind: RibKind<'ra>) -> Rib<'ra, R> {
299 Rib {
300 bindings: Default::default(),
301 patterns_with_skipped_bindings: Default::default(),
302 kind,
303 }
304 }
305}
306
307#[derive(Clone, Copy, Debug)]
308enum LifetimeUseSet {
309 One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
310 Many,
311}
312
313#[derive(Copy, Clone, Debug)]
314enum LifetimeRibKind {
315 Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
320
321 AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
338
339 Elided(LifetimeRes),
341
342 AnonymousReportError,
348
349 StaticIfNoLifetimeInScope { lint_id: NodeId, emit_lint: bool },
353
354 ElisionFailure,
356
357 ConstParamTy,
362
363 ConcreteAnonConst(NoConstantGenericsReason),
369
370 Item,
372}
373
374#[derive(Copy, Clone, Debug)]
375enum LifetimeBinderKind {
376 FnPtrType,
377 PolyTrait,
378 WhereBound,
379 Item,
382 ConstItem,
383 Function,
384 Closure,
385 ImplBlock,
386 ImplAssocType,
388}
389
390impl LifetimeBinderKind {
391 fn descr(self) -> &'static str {
392 use LifetimeBinderKind::*;
393 match self {
394 FnPtrType => "type",
395 PolyTrait => "bound",
396 WhereBound => "bound",
397 Item | ConstItem => "item",
398 ImplAssocType => "associated type",
399 ImplBlock => "impl block",
400 Function => "function",
401 Closure => "closure",
402 }
403 }
404}
405
406#[derive(Debug)]
407struct LifetimeRib {
408 kind: LifetimeRibKind,
409 bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
411}
412
413impl LifetimeRib {
414 fn new(kind: LifetimeRibKind) -> LifetimeRib {
415 LifetimeRib { bindings: Default::default(), kind }
416 }
417}
418
419#[derive(Copy, Clone, PartialEq, Eq, Debug)]
420pub(crate) enum AliasPossibility {
421 No,
422 Maybe,
423}
424
425#[derive(Copy, Clone, Debug)]
426pub(crate) enum PathSource<'a, 'ast, 'ra> {
427 Type,
429 Trait(AliasPossibility),
431 Expr(Option<&'ast Expr>),
433 Pat,
435 Struct(Option<&'a Expr>),
437 TupleStruct(Span, &'ra [Span]),
439 TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),
444 Delegation,
446 PreciseCapturingArg(Namespace),
448 ReturnTypeNotation,
450 DefineOpaques,
452 Macro,
454}
455
456impl PathSource<'_, '_, '_> {
457 fn namespace(self) -> Namespace {
458 match self {
459 PathSource::Type
460 | PathSource::Trait(_)
461 | PathSource::Struct(_)
462 | PathSource::DefineOpaques => TypeNS,
463 PathSource::Expr(..)
464 | PathSource::Pat
465 | PathSource::TupleStruct(..)
466 | PathSource::Delegation
467 | PathSource::ReturnTypeNotation => ValueNS,
468 PathSource::TraitItem(ns, _) => ns,
469 PathSource::PreciseCapturingArg(ns) => ns,
470 PathSource::Macro => MacroNS,
471 }
472 }
473
474 fn defer_to_typeck(self) -> bool {
475 match self {
476 PathSource::Type
477 | PathSource::Expr(..)
478 | PathSource::Pat
479 | PathSource::Struct(_)
480 | PathSource::TupleStruct(..)
481 | PathSource::ReturnTypeNotation => true,
482 PathSource::Trait(_)
483 | PathSource::TraitItem(..)
484 | PathSource::DefineOpaques
485 | PathSource::Delegation
486 | PathSource::PreciseCapturingArg(..)
487 | PathSource::Macro => false,
488 }
489 }
490
491 fn descr_expected(self) -> &'static str {
492 match &self {
493 PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
494 PathSource::Type => "type",
495 PathSource::Trait(_) => "trait",
496 PathSource::Pat => "unit struct, unit variant or constant",
497 PathSource::Struct(_) => "struct, variant or union type",
498 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
499 | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
500 PathSource::TraitItem(ns, _) => match ns {
501 TypeNS => "associated type",
502 ValueNS => "method or associated constant",
503 MacroNS => bug!("associated macro"),
504 },
505 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
506 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
509 ExprKind::Path(_, path)
511 if let [segment, _] = path.segments.as_slice()
512 && segment.ident.name == kw::PathRoot =>
513 {
514 "external crate"
515 }
516 ExprKind::Path(_, path)
517 if let Some(segment) = path.segments.last()
518 && let Some(c) = segment.ident.to_string().chars().next()
519 && c.is_uppercase() =>
520 {
521 "function, tuple struct or tuple variant"
522 }
523 _ => "function",
524 },
525 _ => "value",
526 },
527 PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
528 PathSource::PreciseCapturingArg(..) => "type or const parameter",
529 PathSource::Macro => "macro",
530 }
531 }
532
533 fn is_call(self) -> bool {
534 matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
535 }
536
537 pub(crate) fn is_expected(self, res: Res) -> bool {
538 match self {
539 PathSource::DefineOpaques => {
540 matches!(
541 res,
542 Res::Def(
543 DefKind::Struct
544 | DefKind::Union
545 | DefKind::Enum
546 | DefKind::TyAlias
547 | DefKind::AssocTy,
548 _
549 ) | Res::SelfTyAlias { .. }
550 )
551 }
552 PathSource::Type => matches!(
553 res,
554 Res::Def(
555 DefKind::Struct
556 | DefKind::Union
557 | DefKind::Enum
558 | DefKind::Trait
559 | DefKind::TraitAlias
560 | DefKind::TyAlias
561 | DefKind::AssocTy
562 | DefKind::TyParam
563 | DefKind::OpaqueTy
564 | DefKind::ForeignTy,
565 _,
566 ) | Res::PrimTy(..)
567 | Res::SelfTyParam { .. }
568 | Res::SelfTyAlias { .. }
569 ),
570 PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
571 PathSource::Trait(AliasPossibility::Maybe) => {
572 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
573 }
574 PathSource::Expr(..) => matches!(
575 res,
576 Res::Def(
577 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
578 | DefKind::Const
579 | DefKind::Static { .. }
580 | DefKind::Fn
581 | DefKind::AssocFn
582 | DefKind::AssocConst
583 | DefKind::ConstParam,
584 _,
585 ) | Res::Local(..)
586 | Res::SelfCtor(..)
587 ),
588 PathSource::Pat => {
589 res.expected_in_unit_struct_pat()
590 || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
591 }
592 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
593 PathSource::Struct(_) => matches!(
594 res,
595 Res::Def(
596 DefKind::Struct
597 | DefKind::Union
598 | DefKind::Variant
599 | DefKind::TyAlias
600 | DefKind::AssocTy,
601 _,
602 ) | Res::SelfTyParam { .. }
603 | Res::SelfTyAlias { .. }
604 ),
605 PathSource::TraitItem(ns, _) => match res {
606 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
607 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
608 _ => false,
609 },
610 PathSource::ReturnTypeNotation => match res {
611 Res::Def(DefKind::AssocFn, _) => true,
612 _ => false,
613 },
614 PathSource::Delegation => matches!(res, Res::Def(DefKind::Fn | DefKind::AssocFn, _)),
615 PathSource::PreciseCapturingArg(ValueNS) => {
616 matches!(res, Res::Def(DefKind::ConstParam, _))
617 }
618 PathSource::PreciseCapturingArg(TypeNS) => matches!(
620 res,
621 Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
622 ),
623 PathSource::PreciseCapturingArg(MacroNS) => false,
624 PathSource::Macro => matches!(res, Res::Def(DefKind::Macro(_), _)),
625 }
626 }
627
628 fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
629 match (self, has_unexpected_resolution) {
630 (PathSource::Trait(_), true) => E0404,
631 (PathSource::Trait(_), false) => E0405,
632 (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
633 (PathSource::Type | PathSource::DefineOpaques, false) => E0425,
634 (PathSource::Struct(_), true) => E0574,
635 (PathSource::Struct(_), false) => E0422,
636 (PathSource::Expr(..), true) | (PathSource::Delegation, true) => E0423,
637 (PathSource::Expr(..), false) | (PathSource::Delegation, false) => E0425,
638 (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
639 (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
640 (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
641 (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
642 (PathSource::PreciseCapturingArg(..), true) => E0799,
643 (PathSource::PreciseCapturingArg(..), false) => E0800,
644 (PathSource::Macro, _) => E0425,
645 }
646 }
647}
648
649#[derive(Clone, Copy)]
653enum MaybeExported<'a> {
654 Ok(NodeId),
655 Impl(Option<DefId>),
656 ImplItem(Result<DefId, &'a ast::Visibility>),
657 NestedUse(&'a ast::Visibility),
658}
659
660impl MaybeExported<'_> {
661 fn eval(self, r: &Resolver<'_, '_>) -> bool {
662 let def_id = match self {
663 MaybeExported::Ok(node_id) => Some(r.local_def_id(node_id)),
664 MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
665 trait_def_id.as_local()
666 }
667 MaybeExported::Impl(None) => return true,
668 MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
669 return vis.kind.is_pub();
670 }
671 };
672 def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
673 }
674}
675
676#[derive(Debug)]
678pub(crate) struct UnnecessaryQualification<'ra> {
679 pub binding: LexicalScopeBinding<'ra>,
680 pub node_id: NodeId,
681 pub path_span: Span,
682 pub removal_span: Span,
683}
684
685#[derive(Default, Debug)]
686pub(crate) struct DiagMetadata<'ast> {
687 current_trait_assoc_items: Option<&'ast [Box<AssocItem>]>,
689
690 pub(crate) current_self_type: Option<Ty>,
692
693 current_self_item: Option<NodeId>,
695
696 pub(crate) current_item: Option<&'ast Item>,
698
699 currently_processing_generic_args: bool,
702
703 current_function: Option<(FnKind<'ast>, Span)>,
705
706 unused_labels: FxIndexMap<NodeId, Span>,
709
710 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
712
713 current_pat: Option<&'ast Pat>,
714
715 in_if_condition: Option<&'ast Expr>,
717
718 in_assignment: Option<&'ast Expr>,
720 is_assign_rhs: bool,
721
722 in_non_gat_assoc_type: Option<bool>,
724
725 in_range: Option<(&'ast Expr, &'ast Expr)>,
727
728 current_trait_object: Option<&'ast [ast::GenericBound]>,
731
732 current_where_predicate: Option<&'ast WherePredicate>,
734
735 current_type_path: Option<&'ast Ty>,
736
737 current_impl_items: Option<&'ast [Box<AssocItem>]>,
739
740 current_impl_item: Option<&'ast AssocItem>,
742
743 currently_processing_impl_trait: Option<(TraitRef, Ty)>,
745
746 current_elision_failures: Vec<MissingLifetime>,
749}
750
751struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
752 r: &'a mut Resolver<'ra, 'tcx>,
753
754 parent_scope: ParentScope<'ra>,
756
757 ribs: PerNS<Vec<Rib<'ra>>>,
759
760 last_block_rib: Option<Rib<'ra>>,
762
763 label_ribs: Vec<Rib<'ra, NodeId>>,
765
766 lifetime_ribs: Vec<LifetimeRib>,
768
769 lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
775
776 current_trait_ref: Option<(Module<'ra>, TraitRef)>,
778
779 diag_metadata: Box<DiagMetadata<'ast>>,
781
782 in_func_body: bool,
788
789 lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
791}
792
793impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
795 fn visit_attribute(&mut self, _: &'ast Attribute) {
796 }
799 fn visit_item(&mut self, item: &'ast Item) {
800 let prev = replace(&mut self.diag_metadata.current_item, Some(item));
801 let old_ignore = replace(&mut self.in_func_body, false);
803 self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
804 self.in_func_body = old_ignore;
805 self.diag_metadata.current_item = prev;
806 }
807 fn visit_arm(&mut self, arm: &'ast Arm) {
808 self.resolve_arm(arm);
809 }
810 fn visit_block(&mut self, block: &'ast Block) {
811 let old_macro_rules = self.parent_scope.macro_rules;
812 self.resolve_block(block);
813 self.parent_scope.macro_rules = old_macro_rules;
814 }
815 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
816 bug!("encountered anon const without a manual call to `resolve_anon_const`: {constant:#?}");
817 }
818 fn visit_expr(&mut self, expr: &'ast Expr) {
819 self.resolve_expr(expr, None);
820 }
821 fn visit_pat(&mut self, p: &'ast Pat) {
822 let prev = self.diag_metadata.current_pat;
823 self.diag_metadata.current_pat = Some(p);
824
825 if let PatKind::Guard(subpat, _) = &p.kind {
826 self.visit_pat(subpat);
828 } else {
829 visit::walk_pat(self, p);
830 }
831
832 self.diag_metadata.current_pat = prev;
833 }
834 fn visit_local(&mut self, local: &'ast Local) {
835 let local_spans = match local.pat.kind {
836 PatKind::Wild => None,
838 _ => Some((
839 local.pat.span,
840 local.ty.as_ref().map(|ty| ty.span),
841 local.kind.init().map(|init| init.span),
842 )),
843 };
844 let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
845 self.resolve_local(local);
846 self.diag_metadata.current_let_binding = original;
847 }
848 fn visit_ty(&mut self, ty: &'ast Ty) {
849 let prev = self.diag_metadata.current_trait_object;
850 let prev_ty = self.diag_metadata.current_type_path;
851 match &ty.kind {
852 TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
853 let span = self.r.tcx.sess.source_map().start_point(ty.span);
857 self.resolve_elided_lifetime(ty.id, span);
858 visit::walk_ty(self, ty);
859 }
860 TyKind::Path(qself, path) => {
861 self.diag_metadata.current_type_path = Some(ty);
862
863 let source = if let Some(seg) = path.segments.last()
867 && let Some(args) = &seg.args
868 && matches!(**args, GenericArgs::ParenthesizedElided(..))
869 {
870 PathSource::ReturnTypeNotation
871 } else {
872 PathSource::Type
873 };
874
875 self.smart_resolve_path(ty.id, qself, path, source);
876
877 if qself.is_none()
879 && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
880 && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
881 partial_res.full_res()
882 {
883 let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
887 self.with_generic_param_rib(
888 &[],
889 RibKind::Normal,
890 ty.id,
891 LifetimeBinderKind::PolyTrait,
892 span,
893 |this| this.visit_path(path),
894 );
895 } else {
896 visit::walk_ty(self, ty)
897 }
898 }
899 TyKind::ImplicitSelf => {
900 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
901 let res = self
902 .resolve_ident_in_lexical_scope(
903 self_ty,
904 TypeNS,
905 Some(Finalize::new(ty.id, ty.span)),
906 None,
907 )
908 .map_or(Res::Err, |d| d.res());
909 self.r.record_partial_res(ty.id, PartialRes::new(res));
910 visit::walk_ty(self, ty)
911 }
912 TyKind::ImplTrait(..) => {
913 let candidates = self.lifetime_elision_candidates.take();
914 visit::walk_ty(self, ty);
915 self.lifetime_elision_candidates = candidates;
916 }
917 TyKind::TraitObject(bounds, ..) => {
918 self.diag_metadata.current_trait_object = Some(&bounds[..]);
919 visit::walk_ty(self, ty)
920 }
921 TyKind::FnPtr(fn_ptr) => {
922 let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());
923 self.with_generic_param_rib(
924 &fn_ptr.generic_params,
925 RibKind::Normal,
926 ty.id,
927 LifetimeBinderKind::FnPtrType,
928 span,
929 |this| {
930 this.visit_generic_params(&fn_ptr.generic_params, false);
931 this.resolve_fn_signature(
932 ty.id,
933 false,
934 fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
937 &fn_ptr.decl.output,
938 false,
939 )
940 },
941 )
942 }
943 TyKind::UnsafeBinder(unsafe_binder) => {
944 let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
945 self.with_generic_param_rib(
946 &unsafe_binder.generic_params,
947 RibKind::Normal,
948 ty.id,
949 LifetimeBinderKind::FnPtrType,
950 span,
951 |this| {
952 this.visit_generic_params(&unsafe_binder.generic_params, false);
953 this.with_lifetime_rib(
954 LifetimeRibKind::AnonymousReportError,
957 |this| this.visit_ty(&unsafe_binder.inner_ty),
958 );
959 },
960 )
961 }
962 TyKind::Array(element_ty, length) => {
963 self.visit_ty(element_ty);
964 self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
965 }
966 _ => visit::walk_ty(self, ty),
967 }
968 self.diag_metadata.current_trait_object = prev;
969 self.diag_metadata.current_type_path = prev_ty;
970 }
971
972 fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
973 match &t.kind {
974 TyPatKind::Range(start, end, _) => {
975 if let Some(start) = start {
976 self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
977 }
978 if let Some(end) = end {
979 self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
980 }
981 }
982 TyPatKind::Or(patterns) => {
983 for pat in patterns {
984 self.visit_ty_pat(pat)
985 }
986 }
987 TyPatKind::NotNull | TyPatKind::Err(_) => {}
988 }
989 }
990
991 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
992 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
993 self.with_generic_param_rib(
994 &tref.bound_generic_params,
995 RibKind::Normal,
996 tref.trait_ref.ref_id,
997 LifetimeBinderKind::PolyTrait,
998 span,
999 |this| {
1000 this.visit_generic_params(&tref.bound_generic_params, false);
1001 this.smart_resolve_path(
1002 tref.trait_ref.ref_id,
1003 &None,
1004 &tref.trait_ref.path,
1005 PathSource::Trait(AliasPossibility::Maybe),
1006 );
1007 this.visit_trait_ref(&tref.trait_ref);
1008 },
1009 );
1010 }
1011 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1012 self.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1013 let def_kind = self.r.local_def_kind(foreign_item.id);
1014 match foreign_item.kind {
1015 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
1016 self.with_generic_param_rib(
1017 &generics.params,
1018 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1019 foreign_item.id,
1020 LifetimeBinderKind::Item,
1021 generics.span,
1022 |this| visit::walk_item(this, foreign_item),
1023 );
1024 }
1025 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
1026 self.with_generic_param_rib(
1027 &generics.params,
1028 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1029 foreign_item.id,
1030 LifetimeBinderKind::Function,
1031 generics.span,
1032 |this| visit::walk_item(this, foreign_item),
1033 );
1034 }
1035 ForeignItemKind::Static(..) => {
1036 self.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1037 }
1038 ForeignItemKind::MacCall(..) => {
1039 panic!("unexpanded macro in resolve!")
1040 }
1041 }
1042 }
1043 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, _: &AttrVec, sp: Span, fn_id: NodeId) {
1044 let previous_value = self.diag_metadata.current_function;
1045 match fn_kind {
1046 FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1049 | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1050 self.visit_fn_header(&sig.header);
1051 self.visit_ident(ident);
1052 self.visit_generics(generics);
1053 self.resolve_fn_signature(
1054 fn_id,
1055 sig.decl.has_self(),
1056 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1057 &sig.decl.output,
1058 false,
1059 );
1060 return;
1061 }
1062 FnKind::Fn(..) => {
1063 self.diag_metadata.current_function = Some((fn_kind, sp));
1064 }
1065 FnKind::Closure(..) => {}
1067 };
1068 debug!("(resolving function) entering function");
1069
1070 if let FnKind::Fn(_, _, f) = fn_kind {
1071 for EiiImpl { node_id, eii_macro_path, .. } in &f.eii_impls {
1072 self.smart_resolve_path(*node_id, &None, &eii_macro_path, PathSource::Macro);
1073 }
1074 }
1075
1076 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1078 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1080 match fn_kind {
1081 FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1082 this.visit_generics(generics);
1083
1084 let declaration = &sig.decl;
1085 let coro_node_id = sig
1086 .header
1087 .coroutine_kind
1088 .map(|coroutine_kind| coroutine_kind.return_id());
1089
1090 this.resolve_fn_signature(
1091 fn_id,
1092 declaration.has_self(),
1093 declaration
1094 .inputs
1095 .iter()
1096 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1097 &declaration.output,
1098 coro_node_id.is_some(),
1099 );
1100
1101 if let Some(contract) = contract {
1102 this.visit_contract(contract);
1103 }
1104
1105 if let Some(body) = body {
1106 let previous_state = replace(&mut this.in_func_body, true);
1109 this.last_block_rib = None;
1111 this.with_lifetime_rib(
1113 LifetimeRibKind::Elided(LifetimeRes::Infer),
1114 |this| this.visit_block(body),
1115 );
1116
1117 debug!("(resolving function) leaving function");
1118 this.in_func_body = previous_state;
1119 }
1120 }
1121 FnKind::Closure(binder, _, declaration, body) => {
1122 this.visit_closure_binder(binder);
1123
1124 this.with_lifetime_rib(
1125 match binder {
1126 ClosureBinder::NotPresent => {
1128 LifetimeRibKind::AnonymousCreateParameter {
1129 binder: fn_id,
1130 report_in_path: false,
1131 }
1132 }
1133 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1134 },
1135 |this| this.resolve_params(&declaration.inputs),
1137 );
1138 this.with_lifetime_rib(
1139 match binder {
1140 ClosureBinder::NotPresent => {
1141 LifetimeRibKind::Elided(LifetimeRes::Infer)
1142 }
1143 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1144 },
1145 |this| visit::walk_fn_ret_ty(this, &declaration.output),
1146 );
1147
1148 let previous_state = replace(&mut this.in_func_body, true);
1151 this.with_lifetime_rib(
1153 LifetimeRibKind::Elided(LifetimeRes::Infer),
1154 |this| this.visit_expr(body),
1155 );
1156
1157 debug!("(resolving function) leaving function");
1158 this.in_func_body = previous_state;
1159 }
1160 }
1161 })
1162 });
1163 self.diag_metadata.current_function = previous_value;
1164 }
1165
1166 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1167 self.resolve_lifetime(lifetime, use_ctxt)
1168 }
1169
1170 fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1171 match arg {
1172 PreciseCapturingArg::Lifetime(_) => {}
1175
1176 PreciseCapturingArg::Arg(path, id) => {
1177 let mut check_ns = |ns| {
1184 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1185 };
1186 if !check_ns(TypeNS) && check_ns(ValueNS) {
1188 self.smart_resolve_path(
1189 *id,
1190 &None,
1191 path,
1192 PathSource::PreciseCapturingArg(ValueNS),
1193 );
1194 } else {
1195 self.smart_resolve_path(
1196 *id,
1197 &None,
1198 path,
1199 PathSource::PreciseCapturingArg(TypeNS),
1200 );
1201 }
1202 }
1203 }
1204
1205 visit::walk_precise_capturing_arg(self, arg)
1206 }
1207
1208 fn visit_generics(&mut self, generics: &'ast Generics) {
1209 self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1210 for p in &generics.where_clause.predicates {
1211 self.visit_where_predicate(p);
1212 }
1213 }
1214
1215 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1216 match b {
1217 ClosureBinder::NotPresent => {}
1218 ClosureBinder::For { generic_params, .. } => {
1219 self.visit_generic_params(
1220 generic_params,
1221 self.diag_metadata.current_self_item.is_some(),
1222 );
1223 }
1224 }
1225 }
1226
1227 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1228 debug!("visit_generic_arg({:?})", arg);
1229 let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1230 match arg {
1231 GenericArg::Type(ty) => {
1232 if let TyKind::Path(None, ref path) = ty.kind
1238 && path.is_potential_trivial_const_arg()
1241 {
1242 let mut check_ns = |ns| {
1243 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1244 .is_some()
1245 };
1246 if !check_ns(TypeNS) && check_ns(ValueNS) {
1247 self.resolve_anon_const_manual(
1248 true,
1249 AnonConstKind::ConstArg(IsRepeatExpr::No),
1250 |this| {
1251 this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1252 this.visit_path(path);
1253 },
1254 );
1255
1256 self.diag_metadata.currently_processing_generic_args = prev;
1257 return;
1258 }
1259 }
1260
1261 self.visit_ty(ty);
1262 }
1263 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1264 GenericArg::Const(ct) => {
1265 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1266 }
1267 }
1268 self.diag_metadata.currently_processing_generic_args = prev;
1269 }
1270
1271 fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1272 self.visit_ident(&constraint.ident);
1273 if let Some(ref gen_args) = constraint.gen_args {
1274 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1276 this.visit_generic_args(gen_args)
1277 });
1278 }
1279 match constraint.kind {
1280 AssocItemConstraintKind::Equality { ref term } => match term {
1281 Term::Ty(ty) => self.visit_ty(ty),
1282 Term::Const(c) => {
1283 self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1284 }
1285 },
1286 AssocItemConstraintKind::Bound { ref bounds } => {
1287 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1288 }
1289 }
1290 }
1291
1292 fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1293 let Some(ref args) = path_segment.args else {
1294 return;
1295 };
1296
1297 match &**args {
1298 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1299 GenericArgs::Parenthesized(p_args) => {
1300 for rib in self.lifetime_ribs.iter().rev() {
1302 match rib.kind {
1303 LifetimeRibKind::Generics {
1306 binder,
1307 kind: LifetimeBinderKind::PolyTrait,
1308 ..
1309 } => {
1310 self.resolve_fn_signature(
1311 binder,
1312 false,
1313 p_args.inputs.iter().map(|ty| (None, &**ty)),
1314 &p_args.output,
1315 false,
1316 );
1317 break;
1318 }
1319 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1322 visit::walk_generic_args(self, args);
1323 break;
1324 }
1325 LifetimeRibKind::AnonymousCreateParameter { .. }
1326 | LifetimeRibKind::AnonymousReportError
1327 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1328 | LifetimeRibKind::Elided(_)
1329 | LifetimeRibKind::ElisionFailure
1330 | LifetimeRibKind::ConcreteAnonConst(_)
1331 | LifetimeRibKind::ConstParamTy => {}
1332 }
1333 }
1334 }
1335 GenericArgs::ParenthesizedElided(_) => {}
1336 }
1337 }
1338
1339 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1340 debug!("visit_where_predicate {:?}", p);
1341 let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1342 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1343 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1344 bounded_ty,
1345 bounds,
1346 bound_generic_params,
1347 ..
1348 }) = &p.kind
1349 {
1350 let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1351 this.with_generic_param_rib(
1352 bound_generic_params,
1353 RibKind::Normal,
1354 bounded_ty.id,
1355 LifetimeBinderKind::WhereBound,
1356 span,
1357 |this| {
1358 this.visit_generic_params(bound_generic_params, false);
1359 this.visit_ty(bounded_ty);
1360 for bound in bounds {
1361 this.visit_param_bound(bound, BoundKind::Bound)
1362 }
1363 },
1364 );
1365 } else {
1366 visit::walk_where_predicate(this, p);
1367 }
1368 });
1369 self.diag_metadata.current_where_predicate = previous_value;
1370 }
1371
1372 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1373 for (op, _) in &asm.operands {
1374 match op {
1375 InlineAsmOperand::In { expr, .. }
1376 | InlineAsmOperand::Out { expr: Some(expr), .. }
1377 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1378 InlineAsmOperand::Out { expr: None, .. } => {}
1379 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1380 self.visit_expr(in_expr);
1381 if let Some(out_expr) = out_expr {
1382 self.visit_expr(out_expr);
1383 }
1384 }
1385 InlineAsmOperand::Const { anon_const, .. } => {
1386 self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1389 }
1390 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1391 InlineAsmOperand::Label { block } => self.visit_block(block),
1392 }
1393 }
1394 }
1395
1396 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1397 self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1399 this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1400 this.with_label_rib(RibKind::InlineAsmSym, |this| {
1401 this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1402 visit::walk_inline_asm_sym(this, sym);
1403 });
1404 })
1405 });
1406 }
1407
1408 fn visit_variant(&mut self, v: &'ast Variant) {
1409 self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1410 self.visit_id(v.id);
1411 walk_list!(self, visit_attribute, &v.attrs);
1412 self.visit_vis(&v.vis);
1413 self.visit_ident(&v.ident);
1414 self.visit_variant_data(&v.data);
1415 if let Some(discr) = &v.disr_expr {
1416 self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1417 }
1418 }
1419
1420 fn visit_field_def(&mut self, f: &'ast FieldDef) {
1421 self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1422 let FieldDef {
1423 attrs,
1424 id: _,
1425 span: _,
1426 vis,
1427 ident,
1428 ty,
1429 is_placeholder: _,
1430 default,
1431 safety: _,
1432 } = f;
1433 walk_list!(self, visit_attribute, attrs);
1434 try_visit!(self.visit_vis(vis));
1435 visit_opt!(self, visit_ident, ident);
1436 try_visit!(self.visit_ty(ty));
1437 if let Some(v) = &default {
1438 self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1439 }
1440 }
1441}
1442
1443impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1444 fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1445 let graph_root = resolver.graph_root;
1448 let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1449 let start_rib_kind = RibKind::Module(graph_root);
1450 LateResolutionVisitor {
1451 r: resolver,
1452 parent_scope,
1453 ribs: PerNS {
1454 value_ns: vec![Rib::new(start_rib_kind)],
1455 type_ns: vec![Rib::new(start_rib_kind)],
1456 macro_ns: vec![Rib::new(start_rib_kind)],
1457 },
1458 last_block_rib: None,
1459 label_ribs: Vec::new(),
1460 lifetime_ribs: Vec::new(),
1461 lifetime_elision_candidates: None,
1462 current_trait_ref: None,
1463 diag_metadata: Default::default(),
1464 in_func_body: false,
1466 lifetime_uses: Default::default(),
1467 }
1468 }
1469
1470 fn maybe_resolve_ident_in_lexical_scope(
1471 &mut self,
1472 ident: Ident,
1473 ns: Namespace,
1474 ) -> Option<LexicalScopeBinding<'ra>> {
1475 self.r.resolve_ident_in_lexical_scope(
1476 ident,
1477 ns,
1478 &self.parent_scope,
1479 None,
1480 &self.ribs[ns],
1481 None,
1482 Some(&self.diag_metadata),
1483 )
1484 }
1485
1486 fn resolve_ident_in_lexical_scope(
1487 &mut self,
1488 ident: Ident,
1489 ns: Namespace,
1490 finalize: Option<Finalize>,
1491 ignore_binding: Option<NameBinding<'ra>>,
1492 ) -> Option<LexicalScopeBinding<'ra>> {
1493 self.r.resolve_ident_in_lexical_scope(
1494 ident,
1495 ns,
1496 &self.parent_scope,
1497 finalize,
1498 &self.ribs[ns],
1499 ignore_binding,
1500 Some(&self.diag_metadata),
1501 )
1502 }
1503
1504 fn resolve_path(
1505 &mut self,
1506 path: &[Segment],
1507 opt_ns: Option<Namespace>, finalize: Option<Finalize>,
1509 source: PathSource<'_, 'ast, 'ra>,
1510 ) -> PathResult<'ra> {
1511 self.r.cm().resolve_path_with_ribs(
1512 path,
1513 opt_ns,
1514 &self.parent_scope,
1515 Some(source),
1516 finalize,
1517 Some(&self.ribs),
1518 None,
1519 None,
1520 Some(&self.diag_metadata),
1521 )
1522 }
1523
1524 fn with_rib<T>(
1544 &mut self,
1545 ns: Namespace,
1546 kind: RibKind<'ra>,
1547 work: impl FnOnce(&mut Self) -> T,
1548 ) -> T {
1549 self.ribs[ns].push(Rib::new(kind));
1550 let ret = work(self);
1551 self.ribs[ns].pop();
1552 ret
1553 }
1554
1555 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1556 let mut forward_ty_ban_rib =
1562 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1563 let mut forward_const_ban_rib =
1564 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1565 for param in params.iter() {
1566 match param.kind {
1567 GenericParamKind::Type { .. } => {
1568 forward_ty_ban_rib
1569 .bindings
1570 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1571 }
1572 GenericParamKind::Const { .. } => {
1573 forward_const_ban_rib
1574 .bindings
1575 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1576 }
1577 GenericParamKind::Lifetime => {}
1578 }
1579 }
1580
1581 if add_self_upper {
1591 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1593 }
1594
1595 let mut forward_ty_ban_rib_const_param_ty = Rib {
1598 bindings: forward_ty_ban_rib.bindings.clone(),
1599 patterns_with_skipped_bindings: Default::default(),
1600 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1601 };
1602 let mut forward_const_ban_rib_const_param_ty = Rib {
1603 bindings: forward_const_ban_rib.bindings.clone(),
1604 patterns_with_skipped_bindings: Default::default(),
1605 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1606 };
1607 if !self.r.tcx.features().generic_const_parameter_types() {
1610 forward_ty_ban_rib_const_param_ty.bindings.clear();
1611 forward_const_ban_rib_const_param_ty.bindings.clear();
1612 }
1613
1614 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1615 for param in params {
1616 match param.kind {
1617 GenericParamKind::Lifetime => {
1618 for bound in ¶m.bounds {
1619 this.visit_param_bound(bound, BoundKind::Bound);
1620 }
1621 }
1622 GenericParamKind::Type { ref default } => {
1623 for bound in ¶m.bounds {
1624 this.visit_param_bound(bound, BoundKind::Bound);
1625 }
1626
1627 if let Some(ty) = default {
1628 this.ribs[TypeNS].push(forward_ty_ban_rib);
1629 this.ribs[ValueNS].push(forward_const_ban_rib);
1630 this.visit_ty(ty);
1631 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1632 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1633 }
1634
1635 let i = &Ident::with_dummy_span(param.ident.name);
1637 forward_ty_ban_rib.bindings.swap_remove(i);
1638 forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1639 }
1640 GenericParamKind::Const { ref ty, span: _, ref default } => {
1641 assert!(param.bounds.is_empty());
1643
1644 this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1645 this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1646 if this.r.tcx.features().generic_const_parameter_types() {
1647 this.visit_ty(ty)
1648 } else {
1649 this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1650 this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1651 this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1652 this.visit_ty(ty)
1653 });
1654 this.ribs[TypeNS].pop().unwrap();
1655 this.ribs[ValueNS].pop().unwrap();
1656 }
1657 forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1658 forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1659
1660 if let Some(expr) = default {
1661 this.ribs[TypeNS].push(forward_ty_ban_rib);
1662 this.ribs[ValueNS].push(forward_const_ban_rib);
1663 this.resolve_anon_const(
1664 expr,
1665 AnonConstKind::ConstArg(IsRepeatExpr::No),
1666 );
1667 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1668 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1669 }
1670
1671 let i = &Ident::with_dummy_span(param.ident.name);
1673 forward_const_ban_rib.bindings.swap_remove(i);
1674 forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1675 }
1676 }
1677 }
1678 })
1679 }
1680
1681 #[instrument(level = "debug", skip(self, work))]
1682 fn with_lifetime_rib<T>(
1683 &mut self,
1684 kind: LifetimeRibKind,
1685 work: impl FnOnce(&mut Self) -> T,
1686 ) -> T {
1687 self.lifetime_ribs.push(LifetimeRib::new(kind));
1688 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1689 let ret = work(self);
1690 self.lifetime_elision_candidates = outer_elision_candidates;
1691 self.lifetime_ribs.pop();
1692 ret
1693 }
1694
1695 #[instrument(level = "debug", skip(self))]
1696 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1697 let ident = lifetime.ident;
1698
1699 if ident.name == kw::StaticLifetime {
1700 self.record_lifetime_res(
1701 lifetime.id,
1702 LifetimeRes::Static,
1703 LifetimeElisionCandidate::Named,
1704 );
1705 return;
1706 }
1707
1708 if ident.name == kw::UnderscoreLifetime {
1709 return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1710 }
1711
1712 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1713 while let Some(rib) = lifetime_rib_iter.next() {
1714 let normalized_ident = ident.normalize_to_macros_2_0();
1715 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1716 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1717
1718 if let LifetimeRes::Param { param, binder } = res {
1719 match self.lifetime_uses.entry(param) {
1720 Entry::Vacant(v) => {
1721 debug!("First use of {:?} at {:?}", res, ident.span);
1722 let use_set = self
1723 .lifetime_ribs
1724 .iter()
1725 .rev()
1726 .find_map(|rib| match rib.kind {
1727 LifetimeRibKind::Item
1730 | LifetimeRibKind::AnonymousReportError
1731 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1732 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1733 LifetimeRibKind::AnonymousCreateParameter {
1736 binder: anon_binder,
1737 ..
1738 } => Some(if binder == anon_binder {
1739 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1740 } else {
1741 LifetimeUseSet::Many
1742 }),
1743 LifetimeRibKind::Elided(r) => Some(if res == r {
1746 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1747 } else {
1748 LifetimeUseSet::Many
1749 }),
1750 LifetimeRibKind::Generics { .. }
1751 | LifetimeRibKind::ConstParamTy => None,
1752 LifetimeRibKind::ConcreteAnonConst(_) => {
1753 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1754 }
1755 })
1756 .unwrap_or(LifetimeUseSet::Many);
1757 debug!(?use_ctxt, ?use_set);
1758 v.insert(use_set);
1759 }
1760 Entry::Occupied(mut o) => {
1761 debug!("Many uses of {:?} at {:?}", res, ident.span);
1762 *o.get_mut() = LifetimeUseSet::Many;
1763 }
1764 }
1765 }
1766 return;
1767 }
1768
1769 match rib.kind {
1770 LifetimeRibKind::Item => break,
1771 LifetimeRibKind::ConstParamTy => {
1772 self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1773 self.record_lifetime_res(
1774 lifetime.id,
1775 LifetimeRes::Error,
1776 LifetimeElisionCandidate::Ignore,
1777 );
1778 return;
1779 }
1780 LifetimeRibKind::ConcreteAnonConst(cause) => {
1781 self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1782 self.record_lifetime_res(
1783 lifetime.id,
1784 LifetimeRes::Error,
1785 LifetimeElisionCandidate::Ignore,
1786 );
1787 return;
1788 }
1789 LifetimeRibKind::AnonymousCreateParameter { .. }
1790 | LifetimeRibKind::Elided(_)
1791 | LifetimeRibKind::Generics { .. }
1792 | LifetimeRibKind::ElisionFailure
1793 | LifetimeRibKind::AnonymousReportError
1794 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1795 }
1796 }
1797
1798 let normalized_ident = ident.normalize_to_macros_2_0();
1799 let outer_res = lifetime_rib_iter
1800 .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1801
1802 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1803 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1804 }
1805
1806 #[instrument(level = "debug", skip(self))]
1807 fn resolve_anonymous_lifetime(
1808 &mut self,
1809 lifetime: &Lifetime,
1810 id_for_lint: NodeId,
1811 elided: bool,
1812 ) {
1813 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1814
1815 let kind =
1816 if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1817 let missing_lifetime = MissingLifetime {
1818 id: lifetime.id,
1819 span: lifetime.ident.span,
1820 kind,
1821 count: 1,
1822 id_for_lint,
1823 };
1824 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1825 for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1826 debug!(?rib.kind);
1827 match rib.kind {
1828 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1829 let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1830 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1831 return;
1832 }
1833 LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1834 let mut lifetimes_in_scope = vec![];
1835 for rib in self.lifetime_ribs[..i].iter().rev() {
1836 lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1837 if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1839 && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1840 {
1841 lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1842 }
1843 if let LifetimeRibKind::Item = rib.kind {
1844 break;
1845 }
1846 }
1847 if lifetimes_in_scope.is_empty() {
1848 self.record_lifetime_res(
1849 lifetime.id,
1850 LifetimeRes::Static,
1851 elision_candidate,
1852 );
1853 return;
1854 } else if emit_lint {
1855 self.r.lint_buffer.buffer_lint(
1856 lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1857 node_id,
1858 lifetime.ident.span,
1859 lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1860 elided,
1861 span: lifetime.ident.span,
1862 lifetimes_in_scope: lifetimes_in_scope.into(),
1863 },
1864 );
1865 }
1866 }
1867 LifetimeRibKind::AnonymousReportError => {
1868 if elided {
1869 let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1870 if let LifetimeRibKind::Generics {
1871 span,
1872 kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1873 ..
1874 } = rib.kind
1875 {
1876 Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
1877 lo: span.shrink_to_lo(),
1878 hi: lifetime.ident.span.shrink_to_hi(),
1879 })
1880 } else {
1881 None
1882 }
1883 });
1884 if !self.in_func_body
1887 && let Some((module, _)) = &self.current_trait_ref
1888 && let Some(ty) = &self.diag_metadata.current_self_type
1889 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1890 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1891 {
1892 if def_id_matches_path(
1893 self.r.tcx,
1894 trait_id,
1895 &["core", "iter", "traits", "iterator", "Iterator"],
1896 ) {
1897 self.r.dcx().emit_err(errors::LendingIteratorReportError {
1898 lifetime: lifetime.ident.span,
1899 ty: ty.span,
1900 });
1901 } else {
1902 let decl = if !trait_id.is_local()
1903 && let Some(assoc) = self.diag_metadata.current_impl_item
1904 && let AssocItemKind::Type(_) = assoc.kind
1905 && let assocs = self.r.tcx.associated_items(trait_id)
1906 && let Some(ident) = assoc.kind.ident()
1907 && let Some(assoc) = assocs.find_by_ident_and_kind(
1908 self.r.tcx,
1909 ident,
1910 AssocTag::Type,
1911 trait_id,
1912 ) {
1913 let mut decl: MultiSpan =
1914 self.r.tcx.def_span(assoc.def_id).into();
1915 decl.push_span_label(
1916 self.r.tcx.def_span(trait_id),
1917 String::new(),
1918 );
1919 decl
1920 } else {
1921 DUMMY_SP.into()
1922 };
1923 let mut err = self.r.dcx().create_err(
1924 errors::AnonymousLifetimeNonGatReportError {
1925 lifetime: lifetime.ident.span,
1926 decl,
1927 },
1928 );
1929 self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
1930 err.emit();
1931 }
1932 } else {
1933 self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
1934 span: lifetime.ident.span,
1935 suggestion,
1936 });
1937 }
1938 } else {
1939 self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
1940 span: lifetime.ident.span,
1941 });
1942 };
1943 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1944 return;
1945 }
1946 LifetimeRibKind::Elided(res) => {
1947 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1948 return;
1949 }
1950 LifetimeRibKind::ElisionFailure => {
1951 self.diag_metadata.current_elision_failures.push(missing_lifetime);
1952 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1953 return;
1954 }
1955 LifetimeRibKind::Item => break,
1956 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1957 LifetimeRibKind::ConcreteAnonConst(_) => {
1958 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1960 }
1961 }
1962 }
1963 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1964 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1965 }
1966
1967 fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
1968 let Some((rib, span)) =
1969 self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
1970 LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
1971 Some((rib, span))
1972 }
1973 _ => None,
1974 })
1975 else {
1976 return;
1977 };
1978 if !rib.bindings.is_empty() {
1979 err.span_label(
1980 span,
1981 format!(
1982 "there {} named lifetime{} specified on the impl block you could use",
1983 if rib.bindings.len() == 1 { "is a" } else { "are" },
1984 pluralize!(rib.bindings.len()),
1985 ),
1986 );
1987 if rib.bindings.len() == 1 {
1988 err.span_suggestion_verbose(
1989 lifetime.shrink_to_hi(),
1990 "consider using the lifetime from the impl block",
1991 format!("{} ", rib.bindings.keys().next().unwrap()),
1992 Applicability::MaybeIncorrect,
1993 );
1994 }
1995 } else {
1996 struct AnonRefFinder;
1997 impl<'ast> Visitor<'ast> for AnonRefFinder {
1998 type Result = ControlFlow<Span>;
1999
2000 fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
2001 if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
2002 return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
2003 }
2004 visit::walk_ty(self, ty)
2005 }
2006
2007 fn visit_lifetime(
2008 &mut self,
2009 lt: &'ast ast::Lifetime,
2010 _cx: visit::LifetimeCtxt,
2011 ) -> Self::Result {
2012 if lt.ident.name == kw::UnderscoreLifetime {
2013 return ControlFlow::Break(lt.ident.span);
2014 }
2015 visit::walk_lifetime(self, lt)
2016 }
2017 }
2018
2019 if let Some(ty) = &self.diag_metadata.current_self_type
2020 && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2021 {
2022 err.multipart_suggestion_verbose(
2023 "add a lifetime to the impl block and use it in the self type and associated \
2024 type",
2025 vec![
2026 (span, "<'a>".to_string()),
2027 (sp, "'a ".to_string()),
2028 (lifetime.shrink_to_hi(), "'a ".to_string()),
2029 ],
2030 Applicability::MaybeIncorrect,
2031 );
2032 } else if let Some(item) = &self.diag_metadata.current_item
2033 && let ItemKind::Impl(impl_) = &item.kind
2034 && let Some(of_trait) = &impl_.of_trait
2035 && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2036 {
2037 err.multipart_suggestion_verbose(
2038 "add a lifetime to the impl block and use it in the trait and associated type",
2039 vec![
2040 (span, "<'a>".to_string()),
2041 (sp, "'a".to_string()),
2042 (lifetime.shrink_to_hi(), "'a ".to_string()),
2043 ],
2044 Applicability::MaybeIncorrect,
2045 );
2046 } else {
2047 err.span_label(
2048 span,
2049 "you could add a lifetime on the impl block, if the trait or the self type \
2050 could have one",
2051 );
2052 }
2053 }
2054 }
2055
2056 #[instrument(level = "debug", skip(self))]
2057 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2058 let id = self.r.next_node_id();
2059 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2060
2061 self.record_lifetime_res(
2062 anchor_id,
2063 LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2064 LifetimeElisionCandidate::Ignore,
2065 );
2066 self.resolve_anonymous_lifetime(<, anchor_id, true);
2067 }
2068
2069 #[instrument(level = "debug", skip(self))]
2070 fn create_fresh_lifetime(
2071 &mut self,
2072 ident: Ident,
2073 binder: NodeId,
2074 kind: MissingLifetimeKind,
2075 ) -> LifetimeRes {
2076 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2077 debug!(?ident.span);
2078
2079 let param = self.r.next_node_id();
2081 let res = LifetimeRes::Fresh { param, binder, kind };
2082 self.record_lifetime_param(param, res);
2083
2084 self.r
2086 .extra_lifetime_params_map
2087 .entry(binder)
2088 .or_insert_with(Vec::new)
2089 .push((ident, param, res));
2090 res
2091 }
2092
2093 #[instrument(level = "debug", skip(self))]
2094 fn resolve_elided_lifetimes_in_path(
2095 &mut self,
2096 partial_res: PartialRes,
2097 path: &[Segment],
2098 source: PathSource<'_, 'ast, 'ra>,
2099 path_span: Span,
2100 ) {
2101 let proj_start = path.len() - partial_res.unresolved_segments();
2102 for (i, segment) in path.iter().enumerate() {
2103 if segment.has_lifetime_args {
2104 continue;
2105 }
2106 let Some(segment_id) = segment.id else {
2107 continue;
2108 };
2109
2110 let type_def_id = match partial_res.base_res() {
2113 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2114 self.r.tcx.parent(def_id)
2115 }
2116 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2117 self.r.tcx.parent(def_id)
2118 }
2119 Res::Def(DefKind::Struct, def_id)
2120 | Res::Def(DefKind::Union, def_id)
2121 | Res::Def(DefKind::Enum, def_id)
2122 | Res::Def(DefKind::TyAlias, def_id)
2123 | Res::Def(DefKind::Trait, def_id)
2124 if i + 1 == proj_start =>
2125 {
2126 def_id
2127 }
2128 _ => continue,
2129 };
2130
2131 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2132 if expected_lifetimes == 0 {
2133 continue;
2134 }
2135
2136 let node_ids = self.r.next_node_ids(expected_lifetimes);
2137 self.record_lifetime_res(
2138 segment_id,
2139 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2140 LifetimeElisionCandidate::Ignore,
2141 );
2142
2143 let inferred = match source {
2144 PathSource::Trait(..)
2145 | PathSource::TraitItem(..)
2146 | PathSource::Type
2147 | PathSource::PreciseCapturingArg(..)
2148 | PathSource::ReturnTypeNotation
2149 | PathSource::Macro => false,
2150 PathSource::Expr(..)
2151 | PathSource::Pat
2152 | PathSource::Struct(_)
2153 | PathSource::TupleStruct(..)
2154 | PathSource::DefineOpaques
2155 | PathSource::Delegation => true,
2156 };
2157 if inferred {
2158 for id in node_ids {
2161 self.record_lifetime_res(
2162 id,
2163 LifetimeRes::Infer,
2164 LifetimeElisionCandidate::Named,
2165 );
2166 }
2167 continue;
2168 }
2169
2170 let elided_lifetime_span = if segment.has_generic_args {
2171 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2173 } else {
2174 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2178 };
2179 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2180
2181 let kind = if segment.has_generic_args {
2182 MissingLifetimeKind::Comma
2183 } else {
2184 MissingLifetimeKind::Brackets
2185 };
2186 let missing_lifetime = MissingLifetime {
2187 id: node_ids.start,
2188 id_for_lint: segment_id,
2189 span: elided_lifetime_span,
2190 kind,
2191 count: expected_lifetimes,
2192 };
2193 let mut should_lint = true;
2194 for rib in self.lifetime_ribs.iter().rev() {
2195 match rib.kind {
2196 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2203 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2204 let sess = self.r.tcx.sess;
2205 let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2206 sess.source_map(),
2207 expected_lifetimes,
2208 path_span,
2209 !segment.has_generic_args,
2210 elided_lifetime_span,
2211 );
2212 self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2213 span: path_span,
2214 subdiag,
2215 });
2216 should_lint = false;
2217
2218 for id in node_ids {
2219 self.record_lifetime_res(
2220 id,
2221 LifetimeRes::Error,
2222 LifetimeElisionCandidate::Named,
2223 );
2224 }
2225 break;
2226 }
2227 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2229 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2231 for id in node_ids {
2232 let res = self.create_fresh_lifetime(ident, binder, kind);
2233 self.record_lifetime_res(
2234 id,
2235 res,
2236 replace(&mut candidate, LifetimeElisionCandidate::Named),
2237 );
2238 }
2239 break;
2240 }
2241 LifetimeRibKind::Elided(res) => {
2242 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2243 for id in node_ids {
2244 self.record_lifetime_res(
2245 id,
2246 res,
2247 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2248 );
2249 }
2250 break;
2251 }
2252 LifetimeRibKind::ElisionFailure => {
2253 self.diag_metadata.current_elision_failures.push(missing_lifetime);
2254 for id in node_ids {
2255 self.record_lifetime_res(
2256 id,
2257 LifetimeRes::Error,
2258 LifetimeElisionCandidate::Ignore,
2259 );
2260 }
2261 break;
2262 }
2263 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2268 for id in node_ids {
2269 self.record_lifetime_res(
2270 id,
2271 LifetimeRes::Error,
2272 LifetimeElisionCandidate::Ignore,
2273 );
2274 }
2275 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2276 break;
2277 }
2278 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2279 LifetimeRibKind::ConcreteAnonConst(_) => {
2280 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2282 }
2283 }
2284 }
2285
2286 if should_lint {
2287 self.r.lint_buffer.buffer_lint(
2288 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2289 segment_id,
2290 elided_lifetime_span,
2291 lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2292 expected_lifetimes,
2293 path_span,
2294 !segment.has_generic_args,
2295 elided_lifetime_span,
2296 ),
2297 );
2298 }
2299 }
2300 }
2301
2302 #[instrument(level = "debug", skip(self))]
2303 fn record_lifetime_res(
2304 &mut self,
2305 id: NodeId,
2306 res: LifetimeRes,
2307 candidate: LifetimeElisionCandidate,
2308 ) {
2309 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2310 panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2311 }
2312
2313 match res {
2314 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2315 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2316 candidates.push((res, candidate));
2317 }
2318 }
2319 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2320 }
2321 }
2322
2323 #[instrument(level = "debug", skip(self))]
2324 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2325 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2326 panic!(
2327 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2328 )
2329 }
2330 }
2331
2332 #[instrument(level = "debug", skip(self, inputs))]
2334 fn resolve_fn_signature(
2335 &mut self,
2336 fn_id: NodeId,
2337 has_self: bool,
2338 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2339 output_ty: &'ast FnRetTy,
2340 report_elided_lifetimes_in_path: bool,
2341 ) {
2342 let rib = LifetimeRibKind::AnonymousCreateParameter {
2343 binder: fn_id,
2344 report_in_path: report_elided_lifetimes_in_path,
2345 };
2346 self.with_lifetime_rib(rib, |this| {
2347 let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2349 debug!(?elision_lifetime);
2350
2351 let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2352 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2353 this.r.lifetime_elision_allowed.insert(fn_id);
2354 LifetimeRibKind::Elided(*res)
2355 } else {
2356 LifetimeRibKind::ElisionFailure
2357 };
2358 this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2359 let elision_failures =
2360 replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2361 if !elision_failures.is_empty() {
2362 let Err(failure_info) = elision_lifetime else { bug!() };
2363 this.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2364 }
2365 });
2366 }
2367
2368 fn resolve_fn_params(
2372 &mut self,
2373 has_self: bool,
2374 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2375 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2376 enum Elision {
2377 None,
2379 Self_(LifetimeRes),
2381 Param(LifetimeRes),
2383 Err,
2385 }
2386
2387 let outer_candidates = self.lifetime_elision_candidates.take();
2389
2390 let mut elision_lifetime = Elision::None;
2392 let mut parameter_info = Vec::new();
2394 let mut all_candidates = Vec::new();
2395
2396 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2398 for (pat, _) in inputs.clone() {
2399 debug!("resolving bindings in pat = {pat:?}");
2400 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2401 if let Some(pat) = pat {
2402 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2403 }
2404 });
2405 }
2406 self.apply_pattern_bindings(bindings);
2407
2408 for (index, (pat, ty)) in inputs.enumerate() {
2409 debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2410 debug_assert_matches!(self.lifetime_elision_candidates, None);
2412 self.lifetime_elision_candidates = Some(Default::default());
2413 self.visit_ty(ty);
2414 let local_candidates = self.lifetime_elision_candidates.take();
2415
2416 if let Some(candidates) = local_candidates {
2417 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2418 let lifetime_count = distinct.len();
2419 if lifetime_count != 0 {
2420 parameter_info.push(ElisionFnParameter {
2421 index,
2422 ident: if let Some(pat) = pat
2423 && let PatKind::Ident(_, ident, _) = pat.kind
2424 {
2425 Some(ident)
2426 } else {
2427 None
2428 },
2429 lifetime_count,
2430 span: ty.span,
2431 });
2432 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2433 match candidate {
2434 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2435 None
2436 }
2437 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2438 }
2439 }));
2440 }
2441 if !distinct.is_empty() {
2442 match elision_lifetime {
2443 Elision::None => {
2445 if let Some(res) = distinct.get_only() {
2446 elision_lifetime = Elision::Param(*res)
2448 } else {
2449 elision_lifetime = Elision::Err;
2451 }
2452 }
2453 Elision::Param(_) => elision_lifetime = Elision::Err,
2455 Elision::Self_(_) | Elision::Err => {}
2457 }
2458 }
2459 }
2460
2461 if index == 0 && has_self {
2463 let self_lifetime = self.find_lifetime_for_self(ty);
2464 elision_lifetime = match self_lifetime {
2465 Set1::One(lifetime) => Elision::Self_(lifetime),
2467 Set1::Many => Elision::Err,
2472 Set1::Empty => Elision::None,
2475 }
2476 }
2477 debug!("(resolving function / closure) recorded parameter");
2478 }
2479
2480 debug_assert_matches!(self.lifetime_elision_candidates, None);
2482 self.lifetime_elision_candidates = outer_candidates;
2483
2484 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2485 return Ok(res);
2486 }
2487
2488 Err((all_candidates, parameter_info))
2490 }
2491
2492 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2494 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2498 r: &'a Resolver<'ra, 'tcx>,
2499 impl_self: Option<Res>,
2500 lifetime: Set1<LifetimeRes>,
2501 }
2502
2503 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2504 fn visit_ty(&mut self, ty: &'ra Ty) {
2505 trace!("FindReferenceVisitor considering ty={:?}", ty);
2506 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2507 let mut visitor =
2509 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2510 visitor.visit_ty(ty);
2511 trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2512 if visitor.self_found {
2513 let lt_id = if let Some(lt) = lt {
2514 lt.id
2515 } else {
2516 let res = self.r.lifetimes_res_map[&ty.id];
2517 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2518 start
2519 };
2520 let lt_res = self.r.lifetimes_res_map[<_id];
2521 trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2522 self.lifetime.insert(lt_res);
2523 }
2524 }
2525 visit::walk_ty(self, ty)
2526 }
2527
2528 fn visit_expr(&mut self, _: &'ra Expr) {}
2531 }
2532
2533 struct SelfVisitor<'a, 'ra, 'tcx> {
2536 r: &'a Resolver<'ra, 'tcx>,
2537 impl_self: Option<Res>,
2538 self_found: bool,
2539 }
2540
2541 impl SelfVisitor<'_, '_, '_> {
2542 fn is_self_ty(&self, ty: &Ty) -> bool {
2544 match ty.kind {
2545 TyKind::ImplicitSelf => true,
2546 TyKind::Path(None, _) => {
2547 let path_res = self.r.partial_res_map[&ty.id].full_res();
2548 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2549 return true;
2550 }
2551 self.impl_self.is_some() && path_res == self.impl_self
2552 }
2553 _ => false,
2554 }
2555 }
2556 }
2557
2558 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2559 fn visit_ty(&mut self, ty: &'ra Ty) {
2560 trace!("SelfVisitor considering ty={:?}", ty);
2561 if self.is_self_ty(ty) {
2562 trace!("SelfVisitor found Self");
2563 self.self_found = true;
2564 }
2565 visit::walk_ty(self, ty)
2566 }
2567
2568 fn visit_expr(&mut self, _: &'ra Expr) {}
2571 }
2572
2573 let impl_self = self
2574 .diag_metadata
2575 .current_self_type
2576 .as_ref()
2577 .and_then(|ty| {
2578 if let TyKind::Path(None, _) = ty.kind {
2579 self.r.partial_res_map.get(&ty.id)
2580 } else {
2581 None
2582 }
2583 })
2584 .and_then(|res| res.full_res())
2585 .filter(|res| {
2586 matches!(
2590 res,
2591 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2592 )
2593 });
2594 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2595 visitor.visit_ty(ty);
2596 trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2597 visitor.lifetime
2598 }
2599
2600 fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2603 let mut suggestion = None;
2604
2605 for i in (0..self.label_ribs.len()).rev() {
2606 let rib = &self.label_ribs[i];
2607
2608 if let RibKind::MacroDefinition(def) = rib.kind
2609 && def == self.r.macro_def(label.span.ctxt())
2612 {
2613 label.span.remove_mark();
2614 }
2615
2616 let ident = label.normalize_to_macro_rules();
2617 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2618 let definition_span = ident.span;
2619 return if self.is_label_valid_from_rib(i) {
2620 Ok((*id, definition_span))
2621 } else {
2622 Err(ResolutionError::UnreachableLabel {
2623 name: label.name,
2624 definition_span,
2625 suggestion,
2626 })
2627 };
2628 }
2629
2630 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2633 }
2634
2635 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2636 }
2637
2638 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2640 let ribs = &self.label_ribs[rib_index + 1..];
2641 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2642 }
2643
2644 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2645 debug!("resolve_adt");
2646 let kind = self.r.local_def_kind(item.id);
2647 self.with_current_self_item(item, |this| {
2648 this.with_generic_param_rib(
2649 &generics.params,
2650 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2651 item.id,
2652 LifetimeBinderKind::Item,
2653 generics.span,
2654 |this| {
2655 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2656 this.with_self_rib(
2657 Res::SelfTyAlias {
2658 alias_to: item_def_id,
2659 forbid_generic: false,
2660 is_trait_impl: false,
2661 },
2662 |this| {
2663 visit::walk_item(this, item);
2664 },
2665 );
2666 },
2667 );
2668 });
2669 }
2670
2671 fn future_proof_import(&mut self, use_tree: &UseTree) {
2672 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2673 let ident = segment.ident;
2674 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2675 return;
2676 }
2677
2678 let nss = match use_tree.kind {
2679 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2680 _ => &[TypeNS],
2681 };
2682 let report_error = |this: &Self, ns| {
2683 if this.should_report_errs() {
2684 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2685 this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2686 }
2687 };
2688
2689 for &ns in nss {
2690 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2691 Some(LexicalScopeBinding::Res(..)) => {
2692 report_error(self, ns);
2693 }
2694 Some(LexicalScopeBinding::Item(binding)) => {
2695 if let Some(LexicalScopeBinding::Res(..)) =
2696 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2697 {
2698 report_error(self, ns);
2699 }
2700 }
2701 None => {}
2702 }
2703 }
2704 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2705 for (use_tree, _) in items {
2706 self.future_proof_import(use_tree);
2707 }
2708 }
2709 }
2710
2711 fn resolve_item(&mut self, item: &'ast Item) {
2712 let mod_inner_docs =
2713 matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2714 if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2715 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2716 }
2717
2718 debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2719
2720 let def_kind = self.r.local_def_kind(item.id);
2721 match item.kind {
2722 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2723 self.with_generic_param_rib(
2724 &generics.params,
2725 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2726 item.id,
2727 LifetimeBinderKind::Item,
2728 generics.span,
2729 |this| visit::walk_item(this, item),
2730 );
2731 }
2732
2733 ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2734 self.with_generic_param_rib(
2735 &generics.params,
2736 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2737 item.id,
2738 LifetimeBinderKind::Function,
2739 generics.span,
2740 |this| visit::walk_item(this, item),
2741 );
2742 self.resolve_define_opaques(define_opaque);
2743 }
2744
2745 ItemKind::Enum(_, ref generics, _)
2746 | ItemKind::Struct(_, ref generics, _)
2747 | ItemKind::Union(_, ref generics, _) => {
2748 self.resolve_adt(item, generics);
2749 }
2750
2751 ItemKind::Impl(Impl {
2752 ref generics,
2753 ref of_trait,
2754 ref self_ty,
2755 items: ref impl_items,
2756 ..
2757 }) => {
2758 self.diag_metadata.current_impl_items = Some(impl_items);
2759 self.resolve_implementation(
2760 &item.attrs,
2761 generics,
2762 of_trait.as_deref(),
2763 self_ty,
2764 item.id,
2765 impl_items,
2766 );
2767 self.diag_metadata.current_impl_items = None;
2768 }
2769
2770 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2771 self.with_generic_param_rib(
2773 &generics.params,
2774 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2775 item.id,
2776 LifetimeBinderKind::Item,
2777 generics.span,
2778 |this| {
2779 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2780 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2781 this.visit_generics(generics);
2782 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2783 this.resolve_trait_items(items);
2784 });
2785 },
2786 );
2787 }
2788
2789 ItemKind::TraitAlias(box TraitAlias { ref generics, ref bounds, .. }) => {
2790 self.with_generic_param_rib(
2792 &generics.params,
2793 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2794 item.id,
2795 LifetimeBinderKind::Item,
2796 generics.span,
2797 |this| {
2798 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2799 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2800 this.visit_generics(generics);
2801 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2802 });
2803 },
2804 );
2805 }
2806
2807 ItemKind::Mod(..) => {
2808 let module = self.r.expect_module(self.r.local_def_id(item.id).to_def_id());
2809 let orig_module = replace(&mut self.parent_scope.module, module);
2810 self.with_rib(ValueNS, RibKind::Module(module), |this| {
2811 this.with_rib(TypeNS, RibKind::Module(module), |this| {
2812 if mod_inner_docs {
2813 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2814 }
2815 let old_macro_rules = this.parent_scope.macro_rules;
2816 visit::walk_item(this, item);
2817 if item.attrs.iter().all(|attr| {
2820 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2821 }) {
2822 this.parent_scope.macro_rules = old_macro_rules;
2823 }
2824 })
2825 });
2826 self.parent_scope.module = orig_module;
2827 }
2828
2829 ItemKind::Static(box ast::StaticItem {
2830 ident,
2831 ref ty,
2832 ref expr,
2833 ref define_opaque,
2834 ..
2835 }) => {
2836 self.with_static_rib(def_kind, |this| {
2837 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2838 this.visit_ty(ty);
2839 });
2840 if let Some(expr) = expr {
2841 this.resolve_static_body(expr, Some((ident, ConstantItemKind::Static)));
2844 }
2845 });
2846 self.resolve_define_opaques(define_opaque);
2847 }
2848
2849 ItemKind::Const(box ast::ConstItem {
2850 ident,
2851 ref generics,
2852 ref ty,
2853 ref rhs,
2854 ref define_opaque,
2855 ..
2856 }) => {
2857 self.with_generic_param_rib(
2858 &generics.params,
2859 RibKind::Item(
2860 if self.r.tcx.features().generic_const_items() {
2861 HasGenericParams::Yes(generics.span)
2862 } else {
2863 HasGenericParams::No
2864 },
2865 def_kind,
2866 ),
2867 item.id,
2868 LifetimeBinderKind::ConstItem,
2869 generics.span,
2870 |this| {
2871 this.visit_generics(generics);
2872
2873 this.with_lifetime_rib(
2874 LifetimeRibKind::Elided(LifetimeRes::Static),
2875 |this| this.visit_ty(ty),
2876 );
2877
2878 if let Some(rhs) = rhs {
2879 this.resolve_const_item_rhs(
2880 rhs,
2881 Some((ident, ConstantItemKind::Const)),
2882 );
2883 }
2884 },
2885 );
2886 self.resolve_define_opaques(define_opaque);
2887 }
2888
2889 ItemKind::Use(ref use_tree) => {
2890 let maybe_exported = match use_tree.kind {
2891 UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2892 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2893 };
2894 self.resolve_doc_links(&item.attrs, maybe_exported);
2895
2896 self.future_proof_import(use_tree);
2897 }
2898
2899 ItemKind::MacroDef(_, ref macro_def) => {
2900 if macro_def.macro_rules {
2903 let def_id = self.r.local_def_id(item.id);
2904 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2905 }
2906
2907 if let Some(EiiExternTarget { extern_item_path, impl_unsafe: _, span: _ }) =
2908 ¯o_def.eii_extern_target
2909 {
2910 self.smart_resolve_path(
2911 item.id,
2912 &None,
2913 extern_item_path,
2914 PathSource::Expr(None),
2915 );
2916 }
2917 }
2918
2919 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2920 visit::walk_item(self, item);
2921 }
2922
2923 ItemKind::Delegation(ref delegation) => {
2924 let span = delegation.path.segments.last().unwrap().ident.span;
2925 self.with_generic_param_rib(
2926 &[],
2927 RibKind::Item(HasGenericParams::Yes(span), def_kind),
2928 item.id,
2929 LifetimeBinderKind::Function,
2930 span,
2931 |this| this.resolve_delegation(delegation),
2932 );
2933 }
2934
2935 ItemKind::ExternCrate(..) => {}
2936
2937 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2938 panic!("unexpanded macro in resolve!")
2939 }
2940 }
2941 }
2942
2943 fn with_generic_param_rib<F>(
2944 &mut self,
2945 params: &[GenericParam],
2946 kind: RibKind<'ra>,
2947 binder: NodeId,
2948 generics_kind: LifetimeBinderKind,
2949 generics_span: Span,
2950 f: F,
2951 ) where
2952 F: FnOnce(&mut Self),
2953 {
2954 debug!("with_generic_param_rib");
2955 let lifetime_kind =
2956 LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
2957
2958 let mut function_type_rib = Rib::new(kind);
2959 let mut function_value_rib = Rib::new(kind);
2960 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2961
2962 if !params.is_empty() {
2964 let mut seen_bindings = FxHashMap::default();
2965 let mut seen_lifetimes = FxHashSet::default();
2967
2968 for ns in [ValueNS, TypeNS] {
2970 for parent_rib in self.ribs[ns].iter().rev() {
2971 if matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
2974 break;
2975 }
2976
2977 seen_bindings
2978 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2979 }
2980 }
2981
2982 for rib in self.lifetime_ribs.iter().rev() {
2984 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2985 if let LifetimeRibKind::Item = rib.kind {
2986 break;
2987 }
2988 }
2989
2990 for param in params {
2991 let ident = param.ident.normalize_to_macros_2_0();
2992 debug!("with_generic_param_rib: {}", param.id);
2993
2994 if let GenericParamKind::Lifetime = param.kind
2995 && let Some(&original) = seen_lifetimes.get(&ident)
2996 {
2997 diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
2998 self.record_lifetime_param(param.id, LifetimeRes::Error);
3000 continue;
3001 }
3002
3003 match seen_bindings.entry(ident) {
3004 Entry::Occupied(entry) => {
3005 let span = *entry.get();
3006 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3007 self.report_error(param.ident.span, err);
3008 let rib = match param.kind {
3009 GenericParamKind::Lifetime => {
3010 self.record_lifetime_param(param.id, LifetimeRes::Error);
3012 continue;
3013 }
3014 GenericParamKind::Type { .. } => &mut function_type_rib,
3015 GenericParamKind::Const { .. } => &mut function_value_rib,
3016 };
3017
3018 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3020 rib.bindings.insert(ident, Res::Err);
3021 continue;
3022 }
3023 Entry::Vacant(entry) => {
3024 entry.insert(param.ident.span);
3025 }
3026 }
3027
3028 if param.ident.name == kw::UnderscoreLifetime {
3029 let is_raw_underscore_lifetime = self
3032 .r
3033 .tcx
3034 .sess
3035 .psess
3036 .raw_identifier_spans
3037 .iter()
3038 .any(|span| span == param.span());
3039
3040 self.r
3041 .dcx()
3042 .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
3043 .emit_unless_delay(is_raw_underscore_lifetime);
3044 self.record_lifetime_param(param.id, LifetimeRes::Error);
3046 continue;
3047 }
3048
3049 if param.ident.name == kw::StaticLifetime {
3050 self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
3051 span: param.ident.span,
3052 lifetime: param.ident,
3053 });
3054 self.record_lifetime_param(param.id, LifetimeRes::Error);
3056 continue;
3057 }
3058
3059 let def_id = self.r.local_def_id(param.id);
3060
3061 let (rib, def_kind) = match param.kind {
3063 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3064 GenericParamKind::Const { .. } => {
3065 (&mut function_value_rib, DefKind::ConstParam)
3066 }
3067 GenericParamKind::Lifetime => {
3068 let res = LifetimeRes::Param { param: def_id, binder };
3069 self.record_lifetime_param(param.id, res);
3070 function_lifetime_rib.bindings.insert(ident, (param.id, res));
3071 continue;
3072 }
3073 };
3074
3075 let res = match kind {
3076 RibKind::Item(..) | RibKind::AssocItem => {
3077 Res::Def(def_kind, def_id.to_def_id())
3078 }
3079 RibKind::Normal => {
3080 if self.r.tcx.features().non_lifetime_binders()
3083 && matches!(param.kind, GenericParamKind::Type { .. })
3084 {
3085 Res::Def(def_kind, def_id.to_def_id())
3086 } else {
3087 Res::Err
3088 }
3089 }
3090 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
3091 };
3092 self.r.record_partial_res(param.id, PartialRes::new(res));
3093 rib.bindings.insert(ident, res);
3094 }
3095 }
3096
3097 self.lifetime_ribs.push(function_lifetime_rib);
3098 self.ribs[ValueNS].push(function_value_rib);
3099 self.ribs[TypeNS].push(function_type_rib);
3100
3101 f(self);
3102
3103 self.ribs[TypeNS].pop();
3104 self.ribs[ValueNS].pop();
3105 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3106
3107 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3109 for (_, res) in function_lifetime_rib.bindings.values() {
3110 candidates.retain(|(r, _)| r != res);
3111 }
3112 }
3113
3114 if let LifetimeBinderKind::FnPtrType
3115 | LifetimeBinderKind::WhereBound
3116 | LifetimeBinderKind::Function
3117 | LifetimeBinderKind::ImplBlock = generics_kind
3118 {
3119 self.maybe_report_lifetime_uses(generics_span, params)
3120 }
3121 }
3122
3123 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3124 self.label_ribs.push(Rib::new(kind));
3125 f(self);
3126 self.label_ribs.pop();
3127 }
3128
3129 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3130 let kind = RibKind::Item(HasGenericParams::No, def_kind);
3131 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3132 }
3133
3134 #[instrument(level = "debug", skip(self, f))]
3143 fn with_constant_rib(
3144 &mut self,
3145 is_repeat: IsRepeatExpr,
3146 may_use_generics: ConstantHasGenerics,
3147 item: Option<(Ident, ConstantItemKind)>,
3148 f: impl FnOnce(&mut Self),
3149 ) {
3150 let f = |this: &mut Self| {
3151 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3152 this.with_rib(
3153 TypeNS,
3154 RibKind::ConstantItem(
3155 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3156 item,
3157 ),
3158 |this| {
3159 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3160 },
3161 )
3162 })
3163 };
3164
3165 if let ConstantHasGenerics::No(cause) = may_use_generics {
3166 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3167 } else {
3168 f(self)
3169 }
3170 }
3171
3172 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3173 let previous_value =
3175 replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3176 let result = f(self);
3177 self.diag_metadata.current_self_type = previous_value;
3178 result
3179 }
3180
3181 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3182 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3183 let result = f(self);
3184 self.diag_metadata.current_self_item = previous_value;
3185 result
3186 }
3187
3188 fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3190 let trait_assoc_items =
3191 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3192
3193 let walk_assoc_item =
3194 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3195 this.with_generic_param_rib(
3196 &generics.params,
3197 RibKind::AssocItem,
3198 item.id,
3199 kind,
3200 generics.span,
3201 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3202 );
3203 };
3204
3205 for item in trait_items {
3206 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3207 match &item.kind {
3208 AssocItemKind::Const(box ast::ConstItem {
3209 generics,
3210 ty,
3211 rhs,
3212 define_opaque,
3213 ..
3214 }) => {
3215 self.with_generic_param_rib(
3216 &generics.params,
3217 RibKind::AssocItem,
3218 item.id,
3219 LifetimeBinderKind::ConstItem,
3220 generics.span,
3221 |this| {
3222 this.with_lifetime_rib(
3223 LifetimeRibKind::StaticIfNoLifetimeInScope {
3224 lint_id: item.id,
3225 emit_lint: false,
3226 },
3227 |this| {
3228 this.visit_generics(generics);
3229 this.visit_ty(ty);
3230
3231 if let Some(rhs) = rhs {
3234 this.resolve_const_item_rhs(rhs, None);
3240 }
3241 },
3242 )
3243 },
3244 );
3245
3246 self.resolve_define_opaques(define_opaque);
3247 }
3248 AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3249 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3250
3251 self.resolve_define_opaques(define_opaque);
3252 }
3253 AssocItemKind::Delegation(delegation) => {
3254 self.with_generic_param_rib(
3255 &[],
3256 RibKind::AssocItem,
3257 item.id,
3258 LifetimeBinderKind::Function,
3259 delegation.path.segments.last().unwrap().ident.span,
3260 |this| this.resolve_delegation(delegation),
3261 );
3262 }
3263 AssocItemKind::Type(box TyAlias { generics, .. }) => self
3264 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3265 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3266 }),
3267 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3268 panic!("unexpanded macro in resolve!")
3269 }
3270 };
3271 }
3272
3273 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3274 }
3275
3276 fn with_optional_trait_ref<T>(
3278 &mut self,
3279 opt_trait_ref: Option<&TraitRef>,
3280 self_type: &'ast Ty,
3281 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3282 ) -> T {
3283 let mut new_val = None;
3284 let mut new_id = None;
3285 if let Some(trait_ref) = opt_trait_ref {
3286 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3287 self.diag_metadata.currently_processing_impl_trait =
3288 Some((trait_ref.clone(), self_type.clone()));
3289 let res = self.smart_resolve_path_fragment(
3290 &None,
3291 &path,
3292 PathSource::Trait(AliasPossibility::No),
3293 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3294 RecordPartialRes::Yes,
3295 None,
3296 );
3297 self.diag_metadata.currently_processing_impl_trait = None;
3298 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3299 new_id = Some(def_id);
3300 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3301 }
3302 }
3303 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3304 let result = f(self, new_id);
3305 self.current_trait_ref = original_trait_ref;
3306 result
3307 }
3308
3309 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3310 let mut self_type_rib = Rib::new(RibKind::Normal);
3311
3312 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3314 self.ribs[ns].push(self_type_rib);
3315 f(self);
3316 self.ribs[ns].pop();
3317 }
3318
3319 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3320 self.with_self_rib_ns(TypeNS, self_res, f)
3321 }
3322
3323 fn resolve_implementation(
3324 &mut self,
3325 attrs: &[ast::Attribute],
3326 generics: &'ast Generics,
3327 of_trait: Option<&'ast ast::TraitImplHeader>,
3328 self_type: &'ast Ty,
3329 item_id: NodeId,
3330 impl_items: &'ast [Box<AssocItem>],
3331 ) {
3332 debug!("resolve_implementation");
3333 self.with_generic_param_rib(
3335 &generics.params,
3336 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3337 item_id,
3338 LifetimeBinderKind::ImplBlock,
3339 generics.span,
3340 |this| {
3341 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3343 this.with_lifetime_rib(
3344 LifetimeRibKind::AnonymousCreateParameter {
3345 binder: item_id,
3346 report_in_path: true
3347 },
3348 |this| {
3349 this.with_optional_trait_ref(
3351 of_trait.map(|t| &t.trait_ref),
3352 self_type,
3353 |this, trait_id| {
3354 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3355
3356 let item_def_id = this.r.local_def_id(item_id);
3357
3358 if let Some(trait_id) = trait_id {
3360 this.r
3361 .trait_impls
3362 .entry(trait_id)
3363 .or_default()
3364 .push(item_def_id);
3365 }
3366
3367 let item_def_id = item_def_id.to_def_id();
3368 let res = Res::SelfTyAlias {
3369 alias_to: item_def_id,
3370 forbid_generic: false,
3371 is_trait_impl: trait_id.is_some()
3372 };
3373 this.with_self_rib(res, |this| {
3374 if let Some(of_trait) = of_trait {
3375 visit::walk_trait_ref(this, &of_trait.trait_ref);
3377 }
3378 this.visit_ty(self_type);
3380 this.visit_generics(generics);
3382
3383 this.with_current_self_type(self_type, |this| {
3385 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3386 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3387 let mut seen_trait_items = Default::default();
3388 for item in impl_items {
3389 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3390 }
3391 });
3392 });
3393 });
3394 },
3395 )
3396 },
3397 );
3398 });
3399 },
3400 );
3401 }
3402
3403 fn resolve_impl_item(
3404 &mut self,
3405 item: &'ast AssocItem,
3406 seen_trait_items: &mut FxHashMap<DefId, Span>,
3407 trait_id: Option<DefId>,
3408 ) {
3409 use crate::ResolutionError::*;
3410 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3411 let prev = self.diag_metadata.current_impl_item.take();
3412 self.diag_metadata.current_impl_item = Some(&item);
3413 match &item.kind {
3414 AssocItemKind::Const(box ast::ConstItem {
3415 ident,
3416 generics,
3417 ty,
3418 rhs,
3419 define_opaque,
3420 ..
3421 }) => {
3422 debug!("resolve_implementation AssocItemKind::Const");
3423 self.with_generic_param_rib(
3424 &generics.params,
3425 RibKind::AssocItem,
3426 item.id,
3427 LifetimeBinderKind::ConstItem,
3428 generics.span,
3429 |this| {
3430 this.with_lifetime_rib(
3431 LifetimeRibKind::AnonymousCreateParameter {
3435 binder: item.id,
3436 report_in_path: true,
3437 },
3438 |this| {
3439 this.with_lifetime_rib(
3440 LifetimeRibKind::StaticIfNoLifetimeInScope {
3441 lint_id: item.id,
3442 emit_lint: true,
3444 },
3445 |this| {
3446 this.check_trait_item(
3449 item.id,
3450 *ident,
3451 &item.kind,
3452 ValueNS,
3453 item.span,
3454 seen_trait_items,
3455 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3456 );
3457
3458 this.visit_generics(generics);
3459 this.visit_ty(ty);
3460 if let Some(rhs) = rhs {
3461 this.resolve_const_item_rhs(rhs, None);
3467 }
3468 },
3469 )
3470 },
3471 );
3472 },
3473 );
3474 self.resolve_define_opaques(define_opaque);
3475 }
3476 AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3477 debug!("resolve_implementation AssocItemKind::Fn");
3478 self.with_generic_param_rib(
3480 &generics.params,
3481 RibKind::AssocItem,
3482 item.id,
3483 LifetimeBinderKind::Function,
3484 generics.span,
3485 |this| {
3486 this.check_trait_item(
3489 item.id,
3490 *ident,
3491 &item.kind,
3492 ValueNS,
3493 item.span,
3494 seen_trait_items,
3495 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3496 );
3497
3498 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3499 },
3500 );
3501
3502 self.resolve_define_opaques(define_opaque);
3503 }
3504 AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3505 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3506 debug!("resolve_implementation AssocItemKind::Type");
3507 self.with_generic_param_rib(
3509 &generics.params,
3510 RibKind::AssocItem,
3511 item.id,
3512 LifetimeBinderKind::ImplAssocType,
3513 generics.span,
3514 |this| {
3515 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3516 this.check_trait_item(
3519 item.id,
3520 *ident,
3521 &item.kind,
3522 TypeNS,
3523 item.span,
3524 seen_trait_items,
3525 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3526 );
3527
3528 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3529 });
3530 },
3531 );
3532 self.diag_metadata.in_non_gat_assoc_type = None;
3533 }
3534 AssocItemKind::Delegation(box delegation) => {
3535 debug!("resolve_implementation AssocItemKind::Delegation");
3536 self.with_generic_param_rib(
3537 &[],
3538 RibKind::AssocItem,
3539 item.id,
3540 LifetimeBinderKind::Function,
3541 delegation.path.segments.last().unwrap().ident.span,
3542 |this| {
3543 this.check_trait_item(
3544 item.id,
3545 delegation.ident,
3546 &item.kind,
3547 ValueNS,
3548 item.span,
3549 seen_trait_items,
3550 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3551 );
3552
3553 this.resolve_delegation(delegation)
3554 },
3555 );
3556 }
3557 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3558 panic!("unexpanded macro in resolve!")
3559 }
3560 }
3561 self.diag_metadata.current_impl_item = prev;
3562 }
3563
3564 fn check_trait_item<F>(
3565 &mut self,
3566 id: NodeId,
3567 mut ident: Ident,
3568 kind: &AssocItemKind,
3569 ns: Namespace,
3570 span: Span,
3571 seen_trait_items: &mut FxHashMap<DefId, Span>,
3572 err: F,
3573 ) where
3574 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3575 {
3576 let Some((module, _)) = self.current_trait_ref else {
3578 return;
3579 };
3580 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3581 let key = BindingKey::new(ident, ns);
3582 let mut binding = self.r.resolution(module, key).and_then(|r| r.best_binding());
3583 debug!(?binding);
3584 if binding.is_none() {
3585 let ns = match ns {
3588 ValueNS => TypeNS,
3589 TypeNS => ValueNS,
3590 _ => ns,
3591 };
3592 let key = BindingKey::new(ident, ns);
3593 binding = self.r.resolution(module, key).and_then(|r| r.best_binding());
3594 debug!(?binding);
3595 }
3596
3597 let feed_visibility = |this: &mut Self, def_id| {
3598 let vis = this.r.tcx.visibility(def_id);
3599 let vis = if vis.is_visible_locally() {
3600 vis.expect_local()
3601 } else {
3602 this.r.dcx().span_delayed_bug(
3603 span,
3604 "error should be emitted when an unexpected trait item is used",
3605 );
3606 Visibility::Public
3607 };
3608 this.r.feed_visibility(this.r.feed(id), vis);
3609 };
3610
3611 let Some(binding) = binding else {
3612 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3614 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3615 let path_names = path_names_to_string(path);
3616 self.report_error(span, err(ident, path_names, candidate));
3617 feed_visibility(self, module.def_id());
3618 return;
3619 };
3620
3621 let res = binding.res();
3622 let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3623 feed_visibility(self, id_in_trait);
3624
3625 match seen_trait_items.entry(id_in_trait) {
3626 Entry::Occupied(entry) => {
3627 self.report_error(
3628 span,
3629 ResolutionError::TraitImplDuplicate {
3630 name: ident,
3631 old_span: *entry.get(),
3632 trait_item_span: binding.span,
3633 },
3634 );
3635 return;
3636 }
3637 Entry::Vacant(entry) => {
3638 entry.insert(span);
3639 }
3640 };
3641
3642 match (def_kind, kind) {
3643 (DefKind::AssocTy, AssocItemKind::Type(..))
3644 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3645 | (DefKind::AssocConst, AssocItemKind::Const(..))
3646 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3647 self.r.record_partial_res(id, PartialRes::new(res));
3648 return;
3649 }
3650 _ => {}
3651 }
3652
3653 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3655 let (code, kind) = match kind {
3656 AssocItemKind::Const(..) => (E0323, "const"),
3657 AssocItemKind::Fn(..) => (E0324, "method"),
3658 AssocItemKind::Type(..) => (E0325, "type"),
3659 AssocItemKind::Delegation(..) => (E0324, "method"),
3660 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3661 span_bug!(span, "unexpanded macro")
3662 }
3663 };
3664 let trait_path = path_names_to_string(path);
3665 self.report_error(
3666 span,
3667 ResolutionError::TraitImplMismatch {
3668 name: ident,
3669 kind,
3670 code,
3671 trait_path,
3672 trait_item_span: binding.span,
3673 },
3674 );
3675 }
3676
3677 fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3678 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3679 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3680 this.visit_expr(expr)
3681 });
3682 })
3683 }
3684
3685 fn resolve_const_item_rhs(
3686 &mut self,
3687 rhs: &'ast ConstItemRhs,
3688 item: Option<(Ident, ConstantItemKind)>,
3689 ) {
3690 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| match rhs {
3691 ConstItemRhs::TypeConst(anon_const) => {
3692 this.resolve_anon_const(anon_const, AnonConstKind::ConstArg(IsRepeatExpr::No));
3693 }
3694 ConstItemRhs::Body(expr) => {
3695 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3696 this.visit_expr(expr)
3697 });
3698 }
3699 })
3700 }
3701
3702 fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3703 self.smart_resolve_path(
3704 delegation.id,
3705 &delegation.qself,
3706 &delegation.path,
3707 PathSource::Delegation,
3708 );
3709 if let Some(qself) = &delegation.qself {
3710 self.visit_ty(&qself.ty);
3711 }
3712 self.visit_path(&delegation.path);
3713 let Some(body) = &delegation.body else { return };
3714 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3715 let span = delegation.path.segments.last().unwrap().ident.span;
3716 let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3717 let res = Res::Local(delegation.id);
3718 this.innermost_rib_bindings(ValueNS).insert(ident, res);
3719
3720 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3722 this.visit_block(body);
3723 });
3724 });
3725 }
3726
3727 fn resolve_params(&mut self, params: &'ast [Param]) {
3728 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3729 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3730 for Param { pat, .. } in params {
3731 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3732 }
3733 this.apply_pattern_bindings(bindings);
3734 });
3735 for Param { ty, .. } in params {
3736 self.visit_ty(ty);
3737 }
3738 }
3739
3740 fn resolve_local(&mut self, local: &'ast Local) {
3741 debug!("resolving local ({:?})", local);
3742 visit_opt!(self, visit_ty, &local.ty);
3744
3745 if let Some((init, els)) = local.kind.init_else_opt() {
3747 self.visit_expr(init);
3748
3749 if let Some(els) = els {
3751 self.visit_block(els);
3752 }
3753 }
3754
3755 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3757 }
3758
3759 fn compute_and_check_binding_map(
3779 &mut self,
3780 pat: &Pat,
3781 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3782 let mut binding_map = FxIndexMap::default();
3783 let mut is_never_pat = false;
3784
3785 pat.walk(&mut |pat| {
3786 match pat.kind {
3787 PatKind::Ident(annotation, ident, ref sub_pat)
3788 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3789 {
3790 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3791 }
3792 PatKind::Or(ref ps) => {
3793 match self.compute_and_check_or_pat_binding_map(ps) {
3796 Ok(bm) => binding_map.extend(bm),
3797 Err(IsNeverPattern) => is_never_pat = true,
3798 }
3799 return false;
3800 }
3801 PatKind::Never => is_never_pat = true,
3802 _ => {}
3803 }
3804
3805 true
3806 });
3807
3808 if is_never_pat {
3809 for (_, binding) in binding_map {
3810 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3811 }
3812 Err(IsNeverPattern)
3813 } else {
3814 Ok(binding_map)
3815 }
3816 }
3817
3818 fn is_base_res_local(&self, nid: NodeId) -> bool {
3819 matches!(
3820 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3821 Some(Res::Local(..))
3822 )
3823 }
3824
3825 fn compute_and_check_or_pat_binding_map(
3845 &mut self,
3846 pats: &[Pat],
3847 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3848 let mut missing_vars = FxIndexMap::default();
3849 let mut inconsistent_vars = FxIndexMap::default();
3850
3851 let not_never_pats = pats
3853 .iter()
3854 .filter_map(|pat| {
3855 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3856 Some((binding_map, pat))
3857 })
3858 .collect::<Vec<_>>();
3859
3860 for &(ref map_outer, pat_outer) in not_never_pats.iter() {
3862 let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
3864
3865 for &(ref map, pat) in inners {
3866 for (&name, binding_inner) in map {
3867 match map_outer.get(&name) {
3868 None => {
3869 let binding_error =
3871 missing_vars.entry(name).or_insert_with(|| BindingError {
3872 name,
3873 origin: Default::default(),
3874 target: Default::default(),
3875 could_be_path: name.as_str().starts_with(char::is_uppercase),
3876 });
3877 binding_error.origin.push((binding_inner.span, pat.clone()));
3878 binding_error.target.push(pat_outer.clone());
3879 }
3880 Some(binding_outer) => {
3881 if binding_outer.annotation != binding_inner.annotation {
3882 inconsistent_vars
3884 .entry(name)
3885 .or_insert((binding_inner.span, binding_outer.span));
3886 }
3887 }
3888 }
3889 }
3890 }
3891 }
3892
3893 for (name, mut v) in missing_vars {
3895 if inconsistent_vars.contains_key(&name) {
3896 v.could_be_path = false;
3897 }
3898 self.report_error(
3899 v.origin.iter().next().unwrap().0,
3900 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3901 );
3902 }
3903
3904 for (name, v) in inconsistent_vars {
3906 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3907 }
3908
3909 if not_never_pats.is_empty() {
3911 Err(IsNeverPattern)
3913 } else {
3914 let mut binding_map = FxIndexMap::default();
3915 for (bm, _) in not_never_pats {
3916 binding_map.extend(bm);
3917 }
3918 Ok(binding_map)
3919 }
3920 }
3921
3922 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3924 let mut is_or_or_never = false;
3925 pat.walk(&mut |pat| match pat.kind {
3926 PatKind::Or(..) | PatKind::Never => {
3927 is_or_or_never = true;
3928 false
3929 }
3930 _ => true,
3931 });
3932 if is_or_or_never {
3933 let _ = self.compute_and_check_binding_map(pat);
3934 }
3935 }
3936
3937 fn resolve_arm(&mut self, arm: &'ast Arm) {
3938 self.with_rib(ValueNS, RibKind::Normal, |this| {
3939 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3940 visit_opt!(this, visit_expr, &arm.guard);
3941 visit_opt!(this, visit_expr, &arm.body);
3942 });
3943 }
3944
3945 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3947 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3948 self.resolve_pattern(pat, pat_src, &mut bindings);
3949 self.apply_pattern_bindings(bindings);
3950 }
3951
3952 fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3954 let rib_bindings = self.innermost_rib_bindings(ValueNS);
3955 let Some((_, pat_bindings)) = pat_bindings.pop() else {
3956 bug!("tried applying nonexistent bindings from pattern");
3957 };
3958
3959 if rib_bindings.is_empty() {
3960 *rib_bindings = pat_bindings;
3963 } else {
3964 rib_bindings.extend(pat_bindings);
3965 }
3966 }
3967
3968 fn resolve_pattern(
3971 &mut self,
3972 pat: &'ast Pat,
3973 pat_src: PatternSource,
3974 bindings: &mut PatternBindings,
3975 ) {
3976 self.visit_pat(pat);
3982 self.resolve_pattern_inner(pat, pat_src, bindings);
3983 self.check_consistent_bindings(pat);
3985 }
3986
3987 #[tracing::instrument(skip(self, bindings), level = "debug")]
4007 fn resolve_pattern_inner(
4008 &mut self,
4009 pat: &'ast Pat,
4010 pat_src: PatternSource,
4011 bindings: &mut PatternBindings,
4012 ) {
4013 pat.walk(&mut |pat| {
4015 match pat.kind {
4016 PatKind::Ident(bmode, ident, ref sub) => {
4017 let has_sub = sub.is_some();
4020 let res = self
4021 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
4022 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
4023 self.r.record_partial_res(pat.id, PartialRes::new(res));
4024 self.r.record_pat_span(pat.id, pat.span);
4025 }
4026 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
4027 self.smart_resolve_path(
4028 pat.id,
4029 qself,
4030 path,
4031 PathSource::TupleStruct(
4032 pat.span,
4033 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4034 ),
4035 );
4036 }
4037 PatKind::Path(ref qself, ref path) => {
4038 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4039 }
4040 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4041 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4042 self.record_patterns_with_skipped_bindings(pat, rest);
4043 }
4044 PatKind::Or(ref ps) => {
4045 bindings.push((PatBoundCtx::Or, Default::default()));
4049 for p in ps {
4050 bindings.push((PatBoundCtx::Product, Default::default()));
4054 self.resolve_pattern_inner(p, pat_src, bindings);
4055 let collected = bindings.pop().unwrap().1;
4058 bindings.last_mut().unwrap().1.extend(collected);
4059 }
4060 let collected = bindings.pop().unwrap().1;
4064 bindings.last_mut().unwrap().1.extend(collected);
4065
4066 return false;
4068 }
4069 PatKind::Guard(ref subpat, ref guard) => {
4070 bindings.push((PatBoundCtx::Product, Default::default()));
4072 let binding_ctx_stack_len = bindings.len();
4075 self.resolve_pattern_inner(subpat, pat_src, bindings);
4076 assert_eq!(bindings.len(), binding_ctx_stack_len);
4077 let subpat_bindings = bindings.pop().unwrap().1;
4080 self.with_rib(ValueNS, RibKind::Normal, |this| {
4081 *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4082 this.resolve_expr(guard, None);
4083 });
4084 bindings.last_mut().unwrap().1.extend(subpat_bindings);
4091 return false;
4093 }
4094 _ => {}
4095 }
4096 true
4097 });
4098 }
4099
4100 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4101 match rest {
4102 ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4103 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4105 && let Some(res) = partial_res.full_res()
4106 && let Some(def_id) = res.opt_def_id()
4107 {
4108 self.ribs[ValueNS]
4109 .last_mut()
4110 .unwrap()
4111 .patterns_with_skipped_bindings
4112 .entry(def_id)
4113 .or_default()
4114 .push((
4115 pat.span,
4116 match rest {
4117 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4118 _ => Ok(()),
4119 },
4120 ));
4121 }
4122 }
4123 ast::PatFieldsRest::None => {}
4124 }
4125 }
4126
4127 fn fresh_binding(
4128 &mut self,
4129 ident: Ident,
4130 pat_id: NodeId,
4131 pat_src: PatternSource,
4132 bindings: &mut PatternBindings,
4133 ) -> Res {
4134 let ident = ident.normalize_to_macro_rules();
4138
4139 let already_bound_and = bindings
4141 .iter()
4142 .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4143 if already_bound_and {
4144 use ResolutionError::*;
4146 let error = match pat_src {
4147 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4149 _ => IdentifierBoundMoreThanOnceInSamePattern,
4151 };
4152 self.report_error(ident.span, error(ident));
4153 }
4154
4155 let already_bound_or = bindings
4158 .iter()
4159 .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4160 let res = if let Some(&res) = already_bound_or {
4161 res
4164 } else {
4165 Res::Local(pat_id)
4167 };
4168
4169 bindings.last_mut().unwrap().1.insert(ident, res);
4171 res
4172 }
4173
4174 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4175 &mut self.ribs[ns].last_mut().unwrap().bindings
4176 }
4177
4178 fn try_resolve_as_non_binding(
4179 &mut self,
4180 pat_src: PatternSource,
4181 ann: BindingMode,
4182 ident: Ident,
4183 has_sub: bool,
4184 ) -> Option<Res> {
4185 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4189
4190 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4191 let (res, binding) = match ls_binding {
4192 LexicalScopeBinding::Item(binding)
4193 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4194 {
4195 self.r.record_use(ident, binding, Used::Other);
4200 return None;
4201 }
4202 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4203 LexicalScopeBinding::Res(res) => (res, None),
4204 };
4205
4206 match res {
4207 Res::SelfCtor(_) | Res::Def(
4209 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4210 _,
4211 ) if is_syntactic_ambiguity => {
4212 if let Some(binding) = binding {
4214 self.r.record_use(ident, binding, Used::Other);
4215 }
4216 Some(res)
4217 }
4218 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4219 let binding = binding.expect("no binding for a ctor or static");
4225 self.report_error(
4226 ident.span,
4227 ResolutionError::BindingShadowsSomethingUnacceptable {
4228 shadowing_binding: pat_src,
4229 name: ident.name,
4230 participle: if binding.is_import() { "imported" } else { "defined" },
4231 article: binding.res().article(),
4232 shadowed_binding: binding.res(),
4233 shadowed_binding_span: binding.span,
4234 },
4235 );
4236 None
4237 }
4238 Res::Def(DefKind::ConstParam, def_id) => {
4239 self.report_error(
4242 ident.span,
4243 ResolutionError::BindingShadowsSomethingUnacceptable {
4244 shadowing_binding: pat_src,
4245 name: ident.name,
4246 participle: "defined",
4247 article: res.article(),
4248 shadowed_binding: res,
4249 shadowed_binding_span: self.r.def_span(def_id),
4250 }
4251 );
4252 None
4253 }
4254 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4255 None
4257 }
4258 Res::SelfCtor(_) => {
4259 self.r.dcx().span_delayed_bug(
4262 ident.span,
4263 "unexpected `SelfCtor` in pattern, expected identifier"
4264 );
4265 None
4266 }
4267 _ => span_bug!(
4268 ident.span,
4269 "unexpected resolution for an identifier in pattern: {:?}",
4270 res,
4271 ),
4272 }
4273 }
4274
4275 fn smart_resolve_path(
4281 &mut self,
4282 id: NodeId,
4283 qself: &Option<Box<QSelf>>,
4284 path: &Path,
4285 source: PathSource<'_, 'ast, 'ra>,
4286 ) {
4287 self.smart_resolve_path_fragment(
4288 qself,
4289 &Segment::from_path(path),
4290 source,
4291 Finalize::new(id, path.span),
4292 RecordPartialRes::Yes,
4293 None,
4294 );
4295 }
4296
4297 #[instrument(level = "debug", skip(self))]
4298 fn smart_resolve_path_fragment(
4299 &mut self,
4300 qself: &Option<Box<QSelf>>,
4301 path: &[Segment],
4302 source: PathSource<'_, 'ast, 'ra>,
4303 finalize: Finalize,
4304 record_partial_res: RecordPartialRes,
4305 parent_qself: Option<&QSelf>,
4306 ) -> PartialRes {
4307 let ns = source.namespace();
4308
4309 let Finalize { node_id, path_span, .. } = finalize;
4310 let report_errors = |this: &mut Self, res: Option<Res>| {
4311 if this.should_report_errs() {
4312 let (err, candidates) = this.smart_resolve_report_errors(
4313 path,
4314 None,
4315 path_span,
4316 source,
4317 res,
4318 parent_qself,
4319 );
4320
4321 let def_id = this.parent_scope.module.nearest_parent_mod();
4322 let instead = res.is_some();
4323 let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4324 && path[0].ident.span.lo() == end.span.lo()
4325 && !matches!(start.kind, ExprKind::Lit(_))
4326 {
4327 let mut sugg = ".";
4328 let mut span = start.span.between(end.span);
4329 if span.lo() + BytePos(2) == span.hi() {
4330 span = span.with_lo(span.lo() + BytePos(1));
4333 sugg = "";
4334 }
4335 Some((
4336 span,
4337 "you might have meant to write `.` instead of `..`",
4338 sugg.to_string(),
4339 Applicability::MaybeIncorrect,
4340 ))
4341 } else if res.is_none()
4342 && let PathSource::Type
4343 | PathSource::Expr(_)
4344 | PathSource::PreciseCapturingArg(..) = source
4345 {
4346 this.suggest_adding_generic_parameter(path, source)
4347 } else {
4348 None
4349 };
4350
4351 let ue = UseError {
4352 err,
4353 candidates,
4354 def_id,
4355 instead,
4356 suggestion,
4357 path: path.into(),
4358 is_call: source.is_call(),
4359 };
4360
4361 this.r.use_injections.push(ue);
4362 }
4363
4364 PartialRes::new(Res::Err)
4365 };
4366
4367 let report_errors_for_call =
4373 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4374 let (following_seg, prefix_path) = match path.split_last() {
4378 Some((last, path)) if !path.is_empty() => (Some(last), path),
4379 _ => return Some(parent_err),
4380 };
4381
4382 let (mut err, candidates) = this.smart_resolve_report_errors(
4383 prefix_path,
4384 following_seg,
4385 path_span,
4386 PathSource::Type,
4387 None,
4388 parent_qself,
4389 );
4390
4391 let failed_to_resolve = match parent_err.node {
4406 ResolutionError::FailedToResolve { .. } => true,
4407 _ => false,
4408 };
4409 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4410
4411 err.messages = take(&mut parent_err.messages);
4413 err.code = take(&mut parent_err.code);
4414 swap(&mut err.span, &mut parent_err.span);
4415 if failed_to_resolve {
4416 err.children = take(&mut parent_err.children);
4417 } else {
4418 err.children.append(&mut parent_err.children);
4419 }
4420 err.sort_span = parent_err.sort_span;
4421 err.is_lint = parent_err.is_lint.clone();
4422
4423 match &mut err.suggestions {
4425 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4426 Suggestions::Enabled(parent_suggestions) => {
4427 typo_suggestions.append(parent_suggestions)
4429 }
4430 Suggestions::Sealed(_) | Suggestions::Disabled => {
4431 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4436 }
4437 },
4438 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4439 }
4440
4441 parent_err.cancel();
4442
4443 let def_id = this.parent_scope.module.nearest_parent_mod();
4444
4445 if this.should_report_errs() {
4446 if candidates.is_empty() {
4447 if path.len() == 2
4448 && let [segment] = prefix_path
4449 {
4450 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4456 } else {
4457 err.emit();
4462 }
4463 } else {
4464 this.r.use_injections.push(UseError {
4466 err,
4467 candidates,
4468 def_id,
4469 instead: false,
4470 suggestion: None,
4471 path: prefix_path.into(),
4472 is_call: source.is_call(),
4473 });
4474 }
4475 } else {
4476 err.cancel();
4477 }
4478
4479 None
4482 };
4483
4484 let partial_res = match self.resolve_qpath_anywhere(
4485 qself,
4486 path,
4487 ns,
4488 source.defer_to_typeck(),
4489 finalize,
4490 source,
4491 ) {
4492 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4493 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4495 && let [Segment { ident, .. }] = path
4496 && items.iter().any(|item| {
4497 if let AssocItemKind::Type(alias) = &item.kind
4498 && alias.ident == *ident
4499 {
4500 true
4501 } else {
4502 false
4503 }
4504 })
4505 {
4506 let mut diag = self.r.tcx.dcx().struct_allow("");
4507 diag.span_suggestion_verbose(
4508 path_span.shrink_to_lo(),
4509 "there is an associated type with the same name",
4510 "Self::",
4511 Applicability::MaybeIncorrect,
4512 );
4513 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4514 }
4515
4516 if source.is_expected(res) || res == Res::Err {
4517 partial_res
4518 } else {
4519 report_errors(self, Some(res))
4520 }
4521 }
4522
4523 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4524 if ns == ValueNS {
4528 let item_name = path.last().unwrap().ident;
4529 let traits = self.traits_in_scope(item_name, ns);
4530 self.r.trait_map.insert(node_id, traits);
4531 }
4532
4533 if PrimTy::from_name(path[0].ident.name).is_some() {
4534 let mut std_path = Vec::with_capacity(1 + path.len());
4535
4536 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4537 std_path.extend(path);
4538 if let PathResult::Module(_) | PathResult::NonModule(_) =
4539 self.resolve_path(&std_path, Some(ns), None, source)
4540 {
4541 let item_span =
4543 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4544
4545 self.r.confused_type_with_std_module.insert(item_span, path_span);
4546 self.r.confused_type_with_std_module.insert(path_span, path_span);
4547 }
4548 }
4549
4550 partial_res
4551 }
4552
4553 Err(err) => {
4554 if let Some(err) = report_errors_for_call(self, err) {
4555 self.report_error(err.span, err.node);
4556 }
4557
4558 PartialRes::new(Res::Err)
4559 }
4560
4561 _ => report_errors(self, None),
4562 };
4563
4564 if record_partial_res == RecordPartialRes::Yes {
4565 self.r.record_partial_res(node_id, partial_res);
4567 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4568 self.lint_unused_qualifications(path, ns, finalize);
4569 }
4570
4571 partial_res
4572 }
4573
4574 fn self_type_is_available(&mut self) -> bool {
4575 let binding = self
4576 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4577 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4578 }
4579
4580 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4581 let ident = Ident::new(kw::SelfLower, self_span);
4582 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4583 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4584 }
4585
4586 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4590 if self.should_report_errs() {
4591 self.r.report_error(span, resolution_error);
4592 }
4593 }
4594
4595 #[inline]
4596 fn should_report_errs(&self) -> bool {
4600 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4601 && !self.r.glob_error.is_some()
4602 }
4603
4604 fn resolve_qpath_anywhere(
4606 &mut self,
4607 qself: &Option<Box<QSelf>>,
4608 path: &[Segment],
4609 primary_ns: Namespace,
4610 defer_to_typeck: bool,
4611 finalize: Finalize,
4612 source: PathSource<'_, 'ast, 'ra>,
4613 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4614 let mut fin_res = None;
4615
4616 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4617 if i == 0 || ns != primary_ns {
4618 match self.resolve_qpath(qself, path, ns, finalize, source)? {
4619 Some(partial_res)
4620 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4621 {
4622 return Ok(Some(partial_res));
4623 }
4624 partial_res => {
4625 if fin_res.is_none() {
4626 fin_res = partial_res;
4627 }
4628 }
4629 }
4630 }
4631 }
4632
4633 assert!(primary_ns != MacroNS);
4634 if qself.is_none()
4635 && let PathResult::NonModule(res) =
4636 self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4637 {
4638 return Ok(Some(res));
4639 }
4640
4641 Ok(fin_res)
4642 }
4643
4644 fn resolve_qpath(
4646 &mut self,
4647 qself: &Option<Box<QSelf>>,
4648 path: &[Segment],
4649 ns: Namespace,
4650 finalize: Finalize,
4651 source: PathSource<'_, 'ast, 'ra>,
4652 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4653 debug!(
4654 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4655 qself, path, ns, finalize,
4656 );
4657
4658 if let Some(qself) = qself {
4659 if qself.position == 0 {
4660 return Ok(Some(PartialRes::with_unresolved_segments(
4664 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4665 path.len(),
4666 )));
4667 }
4668
4669 let num_privacy_errors = self.r.privacy_errors.len();
4670 let trait_res = self.smart_resolve_path_fragment(
4672 &None,
4673 &path[..qself.position],
4674 PathSource::Trait(AliasPossibility::No),
4675 Finalize::new(finalize.node_id, qself.path_span),
4676 RecordPartialRes::No,
4677 Some(&qself),
4678 );
4679
4680 if trait_res.expect_full_res() == Res::Err {
4681 return Ok(Some(trait_res));
4682 }
4683
4684 self.r.privacy_errors.truncate(num_privacy_errors);
4687
4688 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4696 let partial_res = self.smart_resolve_path_fragment(
4697 &None,
4698 &path[..=qself.position],
4699 PathSource::TraitItem(ns, &source),
4700 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4701 RecordPartialRes::No,
4702 Some(&qself),
4703 );
4704
4705 return Ok(Some(PartialRes::with_unresolved_segments(
4709 partial_res.base_res(),
4710 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4711 )));
4712 }
4713
4714 let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4715 PathResult::NonModule(path_res) => path_res,
4716 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4717 PartialRes::new(module.res().unwrap())
4718 }
4719 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4723 PartialRes::new(Res::Err)
4724 }
4725 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4738 if (ns == TypeNS || path.len() > 1)
4739 && PrimTy::from_name(path[0].ident.name).is_some() =>
4740 {
4741 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4742 let tcx = self.r.tcx();
4743
4744 let gate_err_sym_msg = match prim {
4745 PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4746 Some((sym::f16, "the type `f16` is unstable"))
4747 }
4748 PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4749 Some((sym::f128, "the type `f128` is unstable"))
4750 }
4751 _ => None,
4752 };
4753
4754 if let Some((sym, msg)) = gate_err_sym_msg {
4755 let span = path[0].ident.span;
4756 if !span.allows_unstable(sym) {
4757 feature_err(tcx.sess, sym, span, msg).emit();
4758 }
4759 };
4760
4761 if let Some(id) = path[0].id {
4763 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4764 }
4765
4766 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4767 }
4768 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4769 PartialRes::new(module.res().unwrap())
4770 }
4771 PathResult::Failed {
4772 is_error_from_last_segment: false,
4773 span,
4774 label,
4775 suggestion,
4776 module,
4777 segment_name,
4778 error_implied_by_parse_error: _,
4779 } => {
4780 return Err(respan(
4781 span,
4782 ResolutionError::FailedToResolve {
4783 segment: Some(segment_name),
4784 label,
4785 suggestion,
4786 module,
4787 },
4788 ));
4789 }
4790 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4791 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4792 };
4793
4794 Ok(Some(result))
4795 }
4796
4797 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4798 if let Some(label) = label {
4799 if label.ident.as_str().as_bytes()[1] != b'_' {
4800 self.diag_metadata.unused_labels.insert(id, label.ident.span);
4801 }
4802
4803 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4804 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4805 }
4806
4807 self.with_label_rib(RibKind::Normal, |this| {
4808 let ident = label.ident.normalize_to_macro_rules();
4809 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4810 f(this);
4811 });
4812 } else {
4813 f(self);
4814 }
4815 }
4816
4817 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4818 self.with_resolved_label(label, id, |this| this.visit_block(block));
4819 }
4820
4821 fn resolve_block(&mut self, block: &'ast Block) {
4822 debug!("(resolving block) entering block");
4823 let orig_module = self.parent_scope.module;
4825 let anonymous_module = self.r.block_map.get(&block.id).copied();
4826
4827 let mut num_macro_definition_ribs = 0;
4828 if let Some(anonymous_module) = anonymous_module {
4829 debug!("(resolving block) found anonymous module, moving down");
4830 self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4831 self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4832 self.parent_scope.module = anonymous_module;
4833 } else {
4834 self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
4835 }
4836
4837 for stmt in &block.stmts {
4839 if let StmtKind::Item(ref item) = stmt.kind
4840 && let ItemKind::MacroDef(..) = item.kind
4841 {
4842 num_macro_definition_ribs += 1;
4843 let res = self.r.local_def_id(item.id).to_def_id();
4844 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4845 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4846 }
4847
4848 self.visit_stmt(stmt);
4849 }
4850
4851 self.parent_scope.module = orig_module;
4853 for _ in 0..num_macro_definition_ribs {
4854 self.ribs[ValueNS].pop();
4855 self.label_ribs.pop();
4856 }
4857 self.last_block_rib = self.ribs[ValueNS].pop();
4858 if anonymous_module.is_some() {
4859 self.ribs[TypeNS].pop();
4860 }
4861 debug!("(resolving block) leaving block");
4862 }
4863
4864 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4865 debug!(
4866 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4867 constant, anon_const_kind
4868 );
4869
4870 let is_trivial_const_arg = if self.r.tcx.features().min_generic_const_args() {
4871 matches!(constant.mgca_disambiguation, MgcaDisambiguation::Direct)
4872 } else {
4873 constant.value.is_potential_trivial_const_arg()
4874 };
4875
4876 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4877 this.resolve_expr(&constant.value, None)
4878 })
4879 }
4880
4881 fn resolve_anon_const_manual(
4888 &mut self,
4889 is_trivial_const_arg: bool,
4890 anon_const_kind: AnonConstKind,
4891 resolve_expr: impl FnOnce(&mut Self),
4892 ) {
4893 let is_repeat_expr = match anon_const_kind {
4894 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4895 _ => IsRepeatExpr::No,
4896 };
4897
4898 let may_use_generics = match anon_const_kind {
4899 AnonConstKind::EnumDiscriminant => {
4900 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4901 }
4902 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4903 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4904 AnonConstKind::ConstArg(_) => {
4905 if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4906 ConstantHasGenerics::Yes
4907 } else {
4908 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4909 }
4910 }
4911 };
4912
4913 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4914 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4915 resolve_expr(this);
4916 });
4917 });
4918 }
4919
4920 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4921 self.resolve_expr(&f.expr, Some(e));
4922 self.visit_ident(&f.ident);
4923 walk_list!(self, visit_attribute, f.attrs.iter());
4924 }
4925
4926 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4927 self.record_candidate_traits_for_expr_if_necessary(expr);
4931
4932 match expr.kind {
4934 ExprKind::Path(ref qself, ref path) => {
4935 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4936 visit::walk_expr(self, expr);
4937 }
4938
4939 ExprKind::Struct(ref se) => {
4940 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
4941 if let Some(qself) = &se.qself {
4945 self.visit_ty(&qself.ty);
4946 }
4947 self.visit_path(&se.path);
4948 walk_list!(self, resolve_expr_field, &se.fields, expr);
4949 match &se.rest {
4950 StructRest::Base(expr) => self.visit_expr(expr),
4951 StructRest::Rest(_span) => {}
4952 StructRest::None => {}
4953 }
4954 }
4955
4956 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4957 match self.resolve_label(label.ident) {
4958 Ok((node_id, _)) => {
4959 self.r.label_res_map.insert(expr.id, node_id);
4961 self.diag_metadata.unused_labels.swap_remove(&node_id);
4962 }
4963 Err(error) => {
4964 self.report_error(label.ident.span, error);
4965 }
4966 }
4967
4968 visit::walk_expr(self, expr);
4970 }
4971
4972 ExprKind::Break(None, Some(ref e)) => {
4973 self.resolve_expr(e, Some(expr));
4976 }
4977
4978 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
4979 self.visit_expr(scrutinee);
4980 self.resolve_pattern_top(pat, PatternSource::Let);
4981 }
4982
4983 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
4984 self.visit_expr(scrutinee);
4985 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4987 self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
4988 for (_, bindings) in &mut bindings {
4993 for (_, binding) in bindings {
4994 *binding = Res::Err;
4995 }
4996 }
4997 self.apply_pattern_bindings(bindings);
4998 }
4999
5000 ExprKind::If(ref cond, ref then, ref opt_else) => {
5001 self.with_rib(ValueNS, RibKind::Normal, |this| {
5002 let old = this.diag_metadata.in_if_condition.replace(cond);
5003 this.visit_expr(cond);
5004 this.diag_metadata.in_if_condition = old;
5005 this.visit_block(then);
5006 });
5007 if let Some(expr) = opt_else {
5008 self.visit_expr(expr);
5009 }
5010 }
5011
5012 ExprKind::Loop(ref block, label, _) => {
5013 self.resolve_labeled_block(label, expr.id, block)
5014 }
5015
5016 ExprKind::While(ref cond, ref block, label) => {
5017 self.with_resolved_label(label, expr.id, |this| {
5018 this.with_rib(ValueNS, RibKind::Normal, |this| {
5019 let old = this.diag_metadata.in_if_condition.replace(cond);
5020 this.visit_expr(cond);
5021 this.diag_metadata.in_if_condition = old;
5022 this.visit_block(block);
5023 })
5024 });
5025 }
5026
5027 ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
5028 self.visit_expr(iter);
5029 self.with_rib(ValueNS, RibKind::Normal, |this| {
5030 this.resolve_pattern_top(pat, PatternSource::For);
5031 this.resolve_labeled_block(label, expr.id, body);
5032 });
5033 }
5034
5035 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5036
5037 ExprKind::Field(ref subexpression, _) => {
5039 self.resolve_expr(subexpression, Some(expr));
5040 }
5041 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
5042 self.resolve_expr(receiver, Some(expr));
5043 for arg in args {
5044 self.resolve_expr(arg, None);
5045 }
5046 self.visit_path_segment(seg);
5047 }
5048
5049 ExprKind::Call(ref callee, ref arguments) => {
5050 self.resolve_expr(callee, Some(expr));
5051 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5052 for (idx, argument) in arguments.iter().enumerate() {
5053 if const_args.contains(&idx) {
5056 let is_trivial_const_arg = argument.is_potential_trivial_const_arg();
5059 self.resolve_anon_const_manual(
5060 is_trivial_const_arg,
5061 AnonConstKind::ConstArg(IsRepeatExpr::No),
5062 |this| this.resolve_expr(argument, None),
5063 );
5064 } else {
5065 self.resolve_expr(argument, None);
5066 }
5067 }
5068 }
5069 ExprKind::Type(ref _type_expr, ref _ty) => {
5070 visit::walk_expr(self, expr);
5071 }
5072 ExprKind::Closure(box ast::Closure {
5074 binder: ClosureBinder::For { ref generic_params, span },
5075 ..
5076 }) => {
5077 self.with_generic_param_rib(
5078 generic_params,
5079 RibKind::Normal,
5080 expr.id,
5081 LifetimeBinderKind::Closure,
5082 span,
5083 |this| visit::walk_expr(this, expr),
5084 );
5085 }
5086 ExprKind::Closure(..) => visit::walk_expr(self, expr),
5087 ExprKind::Gen(..) => {
5088 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5089 }
5090 ExprKind::Repeat(ref elem, ref ct) => {
5091 self.visit_expr(elem);
5092 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5093 }
5094 ExprKind::ConstBlock(ref ct) => {
5095 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5096 }
5097 ExprKind::Index(ref elem, ref idx, _) => {
5098 self.resolve_expr(elem, Some(expr));
5099 self.visit_expr(idx);
5100 }
5101 ExprKind::Assign(ref lhs, ref rhs, _) => {
5102 if !self.diag_metadata.is_assign_rhs {
5103 self.diag_metadata.in_assignment = Some(expr);
5104 }
5105 self.visit_expr(lhs);
5106 self.diag_metadata.is_assign_rhs = true;
5107 self.diag_metadata.in_assignment = None;
5108 self.visit_expr(rhs);
5109 self.diag_metadata.is_assign_rhs = false;
5110 }
5111 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5112 self.diag_metadata.in_range = Some((start, end));
5113 self.resolve_expr(start, Some(expr));
5114 self.resolve_expr(end, Some(expr));
5115 self.diag_metadata.in_range = None;
5116 }
5117 _ => {
5118 visit::walk_expr(self, expr);
5119 }
5120 }
5121 }
5122
5123 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5124 match expr.kind {
5125 ExprKind::Field(_, ident) => {
5126 let traits = self.traits_in_scope(ident, ValueNS);
5131 self.r.trait_map.insert(expr.id, traits);
5132 }
5133 ExprKind::MethodCall(ref call) => {
5134 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
5135 let traits = self.traits_in_scope(call.seg.ident, ValueNS);
5136 self.r.trait_map.insert(expr.id, traits);
5137 }
5138 _ => {
5139 }
5141 }
5142 }
5143
5144 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
5145 self.r.traits_in_scope(
5146 self.current_trait_ref.as_ref().map(|(module, _)| *module),
5147 &self.parent_scope,
5148 ident.span.ctxt(),
5149 Some((ident.name, ns)),
5150 )
5151 }
5152
5153 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5154 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5158 let res = *doc_link_resolutions
5159 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5160 .or_default()
5161 .entry((Symbol::intern(path_str), ns))
5162 .or_insert_with_key(|(path, ns)| {
5163 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5164 if let Some(res) = res
5165 && let Some(def_id) = res.opt_def_id()
5166 && self.is_invalid_proc_macro_item_for_doc(def_id)
5167 {
5168 return None;
5171 }
5172 res
5173 });
5174 self.r.doc_link_resolutions = doc_link_resolutions;
5175 res
5176 }
5177
5178 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5179 if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5180 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5181 {
5182 return false;
5183 }
5184 let Some(local_did) = did.as_local() else { return true };
5185 !self.r.proc_macros.contains(&local_did)
5186 }
5187
5188 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5189 match self.r.tcx.sess.opts.resolve_doc_links {
5190 ResolveDocLinks::None => return,
5191 ResolveDocLinks::ExportedMetadata
5192 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5193 || !maybe_exported.eval(self.r) =>
5194 {
5195 return;
5196 }
5197 ResolveDocLinks::Exported
5198 if !maybe_exported.eval(self.r)
5199 && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5200 {
5201 return;
5202 }
5203 ResolveDocLinks::ExportedMetadata
5204 | ResolveDocLinks::Exported
5205 | ResolveDocLinks::All => {}
5206 }
5207
5208 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5209 return;
5210 }
5211
5212 let mut need_traits_in_scope = false;
5213 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5214 let mut any_resolved = false;
5216 let mut need_assoc = false;
5217 for ns in [TypeNS, ValueNS, MacroNS] {
5218 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5219 any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5222 } else if ns != MacroNS {
5223 need_assoc = true;
5224 }
5225 }
5226
5227 if need_assoc || !any_resolved {
5229 let mut path = &path_str[..];
5230 while let Some(idx) = path.rfind("::") {
5231 path = &path[..idx];
5232 need_traits_in_scope = true;
5233 for ns in [TypeNS, ValueNS, MacroNS] {
5234 self.resolve_and_cache_rustdoc_path(path, ns);
5235 }
5236 }
5237 }
5238 }
5239
5240 if need_traits_in_scope {
5241 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5243 doc_link_traits_in_scope
5244 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5245 .or_insert_with(|| {
5246 self.r
5247 .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5248 .into_iter()
5249 .filter_map(|tr| {
5250 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5251 return None;
5254 }
5255 Some(tr.def_id)
5256 })
5257 .collect()
5258 });
5259 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5260 }
5261 }
5262
5263 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5264 if let Some(seg) = path.first()
5266 && seg.ident.name == kw::PathRoot
5267 {
5268 return;
5269 }
5270
5271 if finalize.path_span.from_expansion()
5272 || path.iter().any(|seg| seg.ident.span.from_expansion())
5273 {
5274 return;
5275 }
5276
5277 let end_pos =
5278 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5279 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5280 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5289 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5290 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5291 (res == binding.res()).then_some((seg, binding))
5292 });
5293
5294 if let Some((seg, binding)) = unqualified {
5295 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5296 binding,
5297 node_id: finalize.node_id,
5298 path_span: finalize.path_span,
5299 removal_span: path[0].ident.span.until(seg.ident.span),
5300 });
5301 }
5302 }
5303
5304 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5305 if let Some(define_opaque) = define_opaque {
5306 for (id, path) in define_opaque {
5307 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5308 }
5309 }
5310 }
5311}
5312
5313struct ItemInfoCollector<'a, 'ra, 'tcx> {
5316 r: &'a mut Resolver<'ra, 'tcx>,
5317}
5318
5319impl ItemInfoCollector<'_, '_, '_> {
5320 fn collect_fn_info(
5321 &mut self,
5322 header: FnHeader,
5323 decl: &FnDecl,
5324 id: NodeId,
5325 attrs: &[Attribute],
5326 ) {
5327 static NAMES_TO_FLAGS: &[(Symbol, DelegationFnSigAttrs)] = &[
5328 (sym::target_feature, DelegationFnSigAttrs::TARGET_FEATURE),
5329 (sym::must_use, DelegationFnSigAttrs::MUST_USE),
5330 ];
5331
5332 let mut to_inherit_attrs = AttrVec::new();
5333 let mut attrs_flags = DelegationFnSigAttrs::empty();
5334
5335 'attrs_loop: for attr in attrs {
5336 for &(name, flag) in NAMES_TO_FLAGS {
5337 if attr.has_name(name) {
5338 attrs_flags.set(flag, true);
5339
5340 if flag.bits() >= DELEGATION_INHERIT_ATTRS_START.bits() {
5341 to_inherit_attrs.push(attr.clone());
5342 }
5343
5344 continue 'attrs_loop;
5345 }
5346 }
5347 }
5348
5349 let sig = DelegationFnSig {
5350 header,
5351 param_count: decl.inputs.len(),
5352 has_self: decl.has_self(),
5353 c_variadic: decl.c_variadic(),
5354 attrs_flags,
5355 to_inherit_attrs,
5356 };
5357
5358 self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5359 }
5360}
5361
5362impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5363 fn visit_item(&mut self, item: &'ast Item) {
5364 match &item.kind {
5365 ItemKind::TyAlias(box TyAlias { generics, .. })
5366 | ItemKind::Const(box ConstItem { generics, .. })
5367 | ItemKind::Fn(box Fn { generics, .. })
5368 | ItemKind::Enum(_, generics, _)
5369 | ItemKind::Struct(_, generics, _)
5370 | ItemKind::Union(_, generics, _)
5371 | ItemKind::Impl(Impl { generics, .. })
5372 | ItemKind::Trait(box Trait { generics, .. })
5373 | ItemKind::TraitAlias(box TraitAlias { generics, .. }) => {
5374 if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5375 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5376 }
5377
5378 let def_id = self.r.local_def_id(item.id);
5379 let count = generics
5380 .params
5381 .iter()
5382 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5383 .count();
5384 self.r.item_generics_num_lifetimes.insert(def_id, count);
5385 }
5386
5387 ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5388 for foreign_item in items {
5389 if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5390 let new_header =
5391 FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5392 self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5393 }
5394 }
5395 }
5396
5397 ItemKind::Mod(..)
5398 | ItemKind::Static(..)
5399 | ItemKind::Use(..)
5400 | ItemKind::ExternCrate(..)
5401 | ItemKind::MacroDef(..)
5402 | ItemKind::GlobalAsm(..)
5403 | ItemKind::MacCall(..)
5404 | ItemKind::DelegationMac(..) => {}
5405 ItemKind::Delegation(..) => {
5406 }
5411 }
5412 visit::walk_item(self, item)
5413 }
5414
5415 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5416 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5417 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5418 }
5419 visit::walk_assoc_item(self, item, ctxt);
5420 }
5421}
5422
5423impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5424 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5425 visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5426 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5427 late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5428 visit::walk_crate(&mut late_resolution_visitor, krate);
5429 for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5430 self.lint_buffer.buffer_lint(
5431 lint::builtin::UNUSED_LABELS,
5432 *id,
5433 *span,
5434 errors::UnusedLabel,
5435 );
5436 }
5437 }
5438}
5439
5440fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5442 let mut path = expected_path.iter().rev();
5443 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5444 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5445 return false;
5446 }
5447 def_id = parent;
5448 }
5449 true
5450}