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