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 TyKind::Typeof(ct) => {
958 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
959 }
960 _ => visit::walk_ty(self, ty),
961 }
962 self.diag_metadata.current_trait_object = prev;
963 self.diag_metadata.current_type_path = prev_ty;
964 }
965
966 fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
967 match &t.kind {
968 TyPatKind::Range(start, end, _) => {
969 if let Some(start) = start {
970 self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
971 }
972 if let Some(end) = end {
973 self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
974 }
975 }
976 TyPatKind::Or(patterns) => {
977 for pat in patterns {
978 self.visit_ty_pat(pat)
979 }
980 }
981 TyPatKind::NotNull | TyPatKind::Err(_) => {}
982 }
983 }
984
985 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
986 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
987 self.with_generic_param_rib(
988 &tref.bound_generic_params,
989 RibKind::Normal,
990 tref.trait_ref.ref_id,
991 LifetimeBinderKind::PolyTrait,
992 span,
993 |this| {
994 this.visit_generic_params(&tref.bound_generic_params, false);
995 this.smart_resolve_path(
996 tref.trait_ref.ref_id,
997 &None,
998 &tref.trait_ref.path,
999 PathSource::Trait(AliasPossibility::Maybe),
1000 );
1001 this.visit_trait_ref(&tref.trait_ref);
1002 },
1003 );
1004 }
1005 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1006 self.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1007 let def_kind = self.r.local_def_kind(foreign_item.id);
1008 match foreign_item.kind {
1009 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
1010 self.with_generic_param_rib(
1011 &generics.params,
1012 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1013 foreign_item.id,
1014 LifetimeBinderKind::Item,
1015 generics.span,
1016 |this| visit::walk_item(this, foreign_item),
1017 );
1018 }
1019 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
1020 self.with_generic_param_rib(
1021 &generics.params,
1022 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1023 foreign_item.id,
1024 LifetimeBinderKind::Function,
1025 generics.span,
1026 |this| visit::walk_item(this, foreign_item),
1027 );
1028 }
1029 ForeignItemKind::Static(..) => {
1030 self.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1031 }
1032 ForeignItemKind::MacCall(..) => {
1033 panic!("unexpanded macro in resolve!")
1034 }
1035 }
1036 }
1037 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
1038 let previous_value = self.diag_metadata.current_function;
1039 match fn_kind {
1040 FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1043 | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1044 self.visit_fn_header(&sig.header);
1045 self.visit_ident(ident);
1046 self.visit_generics(generics);
1047 self.resolve_fn_signature(
1048 fn_id,
1049 sig.decl.has_self(),
1050 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1051 &sig.decl.output,
1052 false,
1053 );
1054 return;
1055 }
1056 FnKind::Fn(..) => {
1057 self.diag_metadata.current_function = Some((fn_kind, sp));
1058 }
1059 FnKind::Closure(..) => {}
1061 };
1062 debug!("(resolving function) entering function");
1063
1064 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1066 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1068 match fn_kind {
1069 FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1070 this.visit_generics(generics);
1071
1072 let declaration = &sig.decl;
1073 let coro_node_id = sig
1074 .header
1075 .coroutine_kind
1076 .map(|coroutine_kind| coroutine_kind.return_id());
1077
1078 this.resolve_fn_signature(
1079 fn_id,
1080 declaration.has_self(),
1081 declaration
1082 .inputs
1083 .iter()
1084 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1085 &declaration.output,
1086 coro_node_id.is_some(),
1087 );
1088
1089 if let Some(contract) = contract {
1090 this.visit_contract(contract);
1091 }
1092
1093 if let Some(body) = body {
1094 let previous_state = replace(&mut this.in_func_body, true);
1097 this.last_block_rib = None;
1099 this.with_lifetime_rib(
1101 LifetimeRibKind::Elided(LifetimeRes::Infer),
1102 |this| this.visit_block(body),
1103 );
1104
1105 debug!("(resolving function) leaving function");
1106 this.in_func_body = previous_state;
1107 }
1108 }
1109 FnKind::Closure(binder, _, declaration, body) => {
1110 this.visit_closure_binder(binder);
1111
1112 this.with_lifetime_rib(
1113 match binder {
1114 ClosureBinder::NotPresent => {
1116 LifetimeRibKind::AnonymousCreateParameter {
1117 binder: fn_id,
1118 report_in_path: false,
1119 }
1120 }
1121 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1122 },
1123 |this| this.resolve_params(&declaration.inputs),
1125 );
1126 this.with_lifetime_rib(
1127 match binder {
1128 ClosureBinder::NotPresent => {
1129 LifetimeRibKind::Elided(LifetimeRes::Infer)
1130 }
1131 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1132 },
1133 |this| visit::walk_fn_ret_ty(this, &declaration.output),
1134 );
1135
1136 let previous_state = replace(&mut this.in_func_body, true);
1139 this.with_lifetime_rib(
1141 LifetimeRibKind::Elided(LifetimeRes::Infer),
1142 |this| this.visit_expr(body),
1143 );
1144
1145 debug!("(resolving function) leaving function");
1146 this.in_func_body = previous_state;
1147 }
1148 }
1149 })
1150 });
1151 self.diag_metadata.current_function = previous_value;
1152 }
1153
1154 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1155 self.resolve_lifetime(lifetime, use_ctxt)
1156 }
1157
1158 fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1159 match arg {
1160 PreciseCapturingArg::Lifetime(_) => {}
1163
1164 PreciseCapturingArg::Arg(path, id) => {
1165 let mut check_ns = |ns| {
1172 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1173 };
1174 if !check_ns(TypeNS) && check_ns(ValueNS) {
1176 self.smart_resolve_path(
1177 *id,
1178 &None,
1179 path,
1180 PathSource::PreciseCapturingArg(ValueNS),
1181 );
1182 } else {
1183 self.smart_resolve_path(
1184 *id,
1185 &None,
1186 path,
1187 PathSource::PreciseCapturingArg(TypeNS),
1188 );
1189 }
1190 }
1191 }
1192
1193 visit::walk_precise_capturing_arg(self, arg)
1194 }
1195
1196 fn visit_generics(&mut self, generics: &'ast Generics) {
1197 self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1198 for p in &generics.where_clause.predicates {
1199 self.visit_where_predicate(p);
1200 }
1201 }
1202
1203 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1204 match b {
1205 ClosureBinder::NotPresent => {}
1206 ClosureBinder::For { generic_params, .. } => {
1207 self.visit_generic_params(
1208 generic_params,
1209 self.diag_metadata.current_self_item.is_some(),
1210 );
1211 }
1212 }
1213 }
1214
1215 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1216 debug!("visit_generic_arg({:?})", arg);
1217 let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1218 match arg {
1219 GenericArg::Type(ty) => {
1220 if let TyKind::Path(None, ref path) = ty.kind
1226 && path.is_potential_trivial_const_arg(false)
1229 {
1230 let mut check_ns = |ns| {
1231 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1232 .is_some()
1233 };
1234 if !check_ns(TypeNS) && check_ns(ValueNS) {
1235 self.resolve_anon_const_manual(
1236 true,
1237 AnonConstKind::ConstArg(IsRepeatExpr::No),
1238 |this| {
1239 this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1240 this.visit_path(path);
1241 },
1242 );
1243
1244 self.diag_metadata.currently_processing_generic_args = prev;
1245 return;
1246 }
1247 }
1248
1249 self.visit_ty(ty);
1250 }
1251 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1252 GenericArg::Const(ct) => {
1253 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1254 }
1255 }
1256 self.diag_metadata.currently_processing_generic_args = prev;
1257 }
1258
1259 fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1260 self.visit_ident(&constraint.ident);
1261 if let Some(ref gen_args) = constraint.gen_args {
1262 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1264 this.visit_generic_args(gen_args)
1265 });
1266 }
1267 match constraint.kind {
1268 AssocItemConstraintKind::Equality { ref term } => match term {
1269 Term::Ty(ty) => self.visit_ty(ty),
1270 Term::Const(c) => {
1271 self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1272 }
1273 },
1274 AssocItemConstraintKind::Bound { ref bounds } => {
1275 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1276 }
1277 }
1278 }
1279
1280 fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1281 let Some(ref args) = path_segment.args else {
1282 return;
1283 };
1284
1285 match &**args {
1286 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1287 GenericArgs::Parenthesized(p_args) => {
1288 for rib in self.lifetime_ribs.iter().rev() {
1290 match rib.kind {
1291 LifetimeRibKind::Generics {
1294 binder,
1295 kind: LifetimeBinderKind::PolyTrait,
1296 ..
1297 } => {
1298 self.resolve_fn_signature(
1299 binder,
1300 false,
1301 p_args.inputs.iter().map(|ty| (None, &**ty)),
1302 &p_args.output,
1303 false,
1304 );
1305 break;
1306 }
1307 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1310 visit::walk_generic_args(self, args);
1311 break;
1312 }
1313 LifetimeRibKind::AnonymousCreateParameter { .. }
1314 | LifetimeRibKind::AnonymousReportError
1315 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1316 | LifetimeRibKind::Elided(_)
1317 | LifetimeRibKind::ElisionFailure
1318 | LifetimeRibKind::ConcreteAnonConst(_)
1319 | LifetimeRibKind::ConstParamTy => {}
1320 }
1321 }
1322 }
1323 GenericArgs::ParenthesizedElided(_) => {}
1324 }
1325 }
1326
1327 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1328 debug!("visit_where_predicate {:?}", p);
1329 let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1330 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1331 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1332 bounded_ty,
1333 bounds,
1334 bound_generic_params,
1335 ..
1336 }) = &p.kind
1337 {
1338 let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1339 this.with_generic_param_rib(
1340 bound_generic_params,
1341 RibKind::Normal,
1342 bounded_ty.id,
1343 LifetimeBinderKind::WhereBound,
1344 span,
1345 |this| {
1346 this.visit_generic_params(bound_generic_params, false);
1347 this.visit_ty(bounded_ty);
1348 for bound in bounds {
1349 this.visit_param_bound(bound, BoundKind::Bound)
1350 }
1351 },
1352 );
1353 } else {
1354 visit::walk_where_predicate(this, p);
1355 }
1356 });
1357 self.diag_metadata.current_where_predicate = previous_value;
1358 }
1359
1360 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1361 for (op, _) in &asm.operands {
1362 match op {
1363 InlineAsmOperand::In { expr, .. }
1364 | InlineAsmOperand::Out { expr: Some(expr), .. }
1365 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1366 InlineAsmOperand::Out { expr: None, .. } => {}
1367 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1368 self.visit_expr(in_expr);
1369 if let Some(out_expr) = out_expr {
1370 self.visit_expr(out_expr);
1371 }
1372 }
1373 InlineAsmOperand::Const { anon_const, .. } => {
1374 self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1377 }
1378 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1379 InlineAsmOperand::Label { block } => self.visit_block(block),
1380 }
1381 }
1382 }
1383
1384 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1385 self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1387 this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1388 this.with_label_rib(RibKind::InlineAsmSym, |this| {
1389 this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1390 visit::walk_inline_asm_sym(this, sym);
1391 });
1392 })
1393 });
1394 }
1395
1396 fn visit_variant(&mut self, v: &'ast Variant) {
1397 self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1398 self.visit_id(v.id);
1399 walk_list!(self, visit_attribute, &v.attrs);
1400 self.visit_vis(&v.vis);
1401 self.visit_ident(&v.ident);
1402 self.visit_variant_data(&v.data);
1403 if let Some(discr) = &v.disr_expr {
1404 self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1405 }
1406 }
1407
1408 fn visit_field_def(&mut self, f: &'ast FieldDef) {
1409 self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1410 let FieldDef {
1411 attrs,
1412 id: _,
1413 span: _,
1414 vis,
1415 ident,
1416 ty,
1417 is_placeholder: _,
1418 default,
1419 safety: _,
1420 } = f;
1421 walk_list!(self, visit_attribute, attrs);
1422 try_visit!(self.visit_vis(vis));
1423 visit_opt!(self, visit_ident, ident);
1424 try_visit!(self.visit_ty(ty));
1425 if let Some(v) = &default {
1426 self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1427 }
1428 }
1429}
1430
1431impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1432 fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1433 let graph_root = resolver.graph_root;
1436 let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1437 let start_rib_kind = RibKind::Module(graph_root);
1438 LateResolutionVisitor {
1439 r: resolver,
1440 parent_scope,
1441 ribs: PerNS {
1442 value_ns: vec![Rib::new(start_rib_kind)],
1443 type_ns: vec![Rib::new(start_rib_kind)],
1444 macro_ns: vec![Rib::new(start_rib_kind)],
1445 },
1446 last_block_rib: None,
1447 label_ribs: Vec::new(),
1448 lifetime_ribs: Vec::new(),
1449 lifetime_elision_candidates: None,
1450 current_trait_ref: None,
1451 diag_metadata: Default::default(),
1452 in_func_body: false,
1454 lifetime_uses: Default::default(),
1455 }
1456 }
1457
1458 fn maybe_resolve_ident_in_lexical_scope(
1459 &mut self,
1460 ident: Ident,
1461 ns: Namespace,
1462 ) -> Option<LexicalScopeBinding<'ra>> {
1463 self.r.resolve_ident_in_lexical_scope(
1464 ident,
1465 ns,
1466 &self.parent_scope,
1467 None,
1468 &self.ribs[ns],
1469 None,
1470 Some(&self.diag_metadata),
1471 )
1472 }
1473
1474 fn resolve_ident_in_lexical_scope(
1475 &mut self,
1476 ident: Ident,
1477 ns: Namespace,
1478 finalize: Option<Finalize>,
1479 ignore_binding: Option<NameBinding<'ra>>,
1480 ) -> Option<LexicalScopeBinding<'ra>> {
1481 self.r.resolve_ident_in_lexical_scope(
1482 ident,
1483 ns,
1484 &self.parent_scope,
1485 finalize,
1486 &self.ribs[ns],
1487 ignore_binding,
1488 Some(&self.diag_metadata),
1489 )
1490 }
1491
1492 fn resolve_path(
1493 &mut self,
1494 path: &[Segment],
1495 opt_ns: Option<Namespace>, finalize: Option<Finalize>,
1497 source: PathSource<'_, 'ast, 'ra>,
1498 ) -> PathResult<'ra> {
1499 self.r.cm().resolve_path_with_ribs(
1500 path,
1501 opt_ns,
1502 &self.parent_scope,
1503 Some(source),
1504 finalize,
1505 Some(&self.ribs),
1506 None,
1507 None,
1508 Some(&self.diag_metadata),
1509 )
1510 }
1511
1512 fn with_rib<T>(
1532 &mut self,
1533 ns: Namespace,
1534 kind: RibKind<'ra>,
1535 work: impl FnOnce(&mut Self) -> T,
1536 ) -> T {
1537 self.ribs[ns].push(Rib::new(kind));
1538 let ret = work(self);
1539 self.ribs[ns].pop();
1540 ret
1541 }
1542
1543 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1544 let mut forward_ty_ban_rib =
1550 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1551 let mut forward_const_ban_rib =
1552 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1553 for param in params.iter() {
1554 match param.kind {
1555 GenericParamKind::Type { .. } => {
1556 forward_ty_ban_rib
1557 .bindings
1558 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1559 }
1560 GenericParamKind::Const { .. } => {
1561 forward_const_ban_rib
1562 .bindings
1563 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1564 }
1565 GenericParamKind::Lifetime => {}
1566 }
1567 }
1568
1569 if add_self_upper {
1579 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1581 }
1582
1583 let mut forward_ty_ban_rib_const_param_ty = Rib {
1586 bindings: forward_ty_ban_rib.bindings.clone(),
1587 patterns_with_skipped_bindings: Default::default(),
1588 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1589 };
1590 let mut forward_const_ban_rib_const_param_ty = Rib {
1591 bindings: forward_const_ban_rib.bindings.clone(),
1592 patterns_with_skipped_bindings: Default::default(),
1593 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1594 };
1595 if !self.r.tcx.features().generic_const_parameter_types() {
1598 forward_ty_ban_rib_const_param_ty.bindings.clear();
1599 forward_const_ban_rib_const_param_ty.bindings.clear();
1600 }
1601
1602 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1603 for param in params {
1604 match param.kind {
1605 GenericParamKind::Lifetime => {
1606 for bound in ¶m.bounds {
1607 this.visit_param_bound(bound, BoundKind::Bound);
1608 }
1609 }
1610 GenericParamKind::Type { ref default } => {
1611 for bound in ¶m.bounds {
1612 this.visit_param_bound(bound, BoundKind::Bound);
1613 }
1614
1615 if let Some(ty) = default {
1616 this.ribs[TypeNS].push(forward_ty_ban_rib);
1617 this.ribs[ValueNS].push(forward_const_ban_rib);
1618 this.visit_ty(ty);
1619 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1620 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1621 }
1622
1623 let i = &Ident::with_dummy_span(param.ident.name);
1625 forward_ty_ban_rib.bindings.swap_remove(i);
1626 forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1627 }
1628 GenericParamKind::Const { ref ty, span: _, ref default } => {
1629 assert!(param.bounds.is_empty());
1631
1632 this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1633 this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1634 if this.r.tcx.features().generic_const_parameter_types() {
1635 this.visit_ty(ty)
1636 } else {
1637 this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1638 this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1639 this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1640 this.visit_ty(ty)
1641 });
1642 this.ribs[TypeNS].pop().unwrap();
1643 this.ribs[ValueNS].pop().unwrap();
1644 }
1645 forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1646 forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1647
1648 if let Some(expr) = default {
1649 this.ribs[TypeNS].push(forward_ty_ban_rib);
1650 this.ribs[ValueNS].push(forward_const_ban_rib);
1651 this.resolve_anon_const(
1652 expr,
1653 AnonConstKind::ConstArg(IsRepeatExpr::No),
1654 );
1655 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1656 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1657 }
1658
1659 let i = &Ident::with_dummy_span(param.ident.name);
1661 forward_const_ban_rib.bindings.swap_remove(i);
1662 forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1663 }
1664 }
1665 }
1666 })
1667 }
1668
1669 #[instrument(level = "debug", skip(self, work))]
1670 fn with_lifetime_rib<T>(
1671 &mut self,
1672 kind: LifetimeRibKind,
1673 work: impl FnOnce(&mut Self) -> T,
1674 ) -> T {
1675 self.lifetime_ribs.push(LifetimeRib::new(kind));
1676 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1677 let ret = work(self);
1678 self.lifetime_elision_candidates = outer_elision_candidates;
1679 self.lifetime_ribs.pop();
1680 ret
1681 }
1682
1683 #[instrument(level = "debug", skip(self))]
1684 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1685 let ident = lifetime.ident;
1686
1687 if ident.name == kw::StaticLifetime {
1688 self.record_lifetime_res(
1689 lifetime.id,
1690 LifetimeRes::Static,
1691 LifetimeElisionCandidate::Named,
1692 );
1693 return;
1694 }
1695
1696 if ident.name == kw::UnderscoreLifetime {
1697 return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1698 }
1699
1700 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1701 while let Some(rib) = lifetime_rib_iter.next() {
1702 let normalized_ident = ident.normalize_to_macros_2_0();
1703 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1704 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1705
1706 if let LifetimeRes::Param { param, binder } = res {
1707 match self.lifetime_uses.entry(param) {
1708 Entry::Vacant(v) => {
1709 debug!("First use of {:?} at {:?}", res, ident.span);
1710 let use_set = self
1711 .lifetime_ribs
1712 .iter()
1713 .rev()
1714 .find_map(|rib| match rib.kind {
1715 LifetimeRibKind::Item
1718 | LifetimeRibKind::AnonymousReportError
1719 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1720 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1721 LifetimeRibKind::AnonymousCreateParameter {
1724 binder: anon_binder,
1725 ..
1726 } => Some(if binder == anon_binder {
1727 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1728 } else {
1729 LifetimeUseSet::Many
1730 }),
1731 LifetimeRibKind::Elided(r) => Some(if res == r {
1734 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1735 } else {
1736 LifetimeUseSet::Many
1737 }),
1738 LifetimeRibKind::Generics { .. }
1739 | LifetimeRibKind::ConstParamTy => None,
1740 LifetimeRibKind::ConcreteAnonConst(_) => {
1741 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1742 }
1743 })
1744 .unwrap_or(LifetimeUseSet::Many);
1745 debug!(?use_ctxt, ?use_set);
1746 v.insert(use_set);
1747 }
1748 Entry::Occupied(mut o) => {
1749 debug!("Many uses of {:?} at {:?}", res, ident.span);
1750 *o.get_mut() = LifetimeUseSet::Many;
1751 }
1752 }
1753 }
1754 return;
1755 }
1756
1757 match rib.kind {
1758 LifetimeRibKind::Item => break,
1759 LifetimeRibKind::ConstParamTy => {
1760 self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1761 self.record_lifetime_res(
1762 lifetime.id,
1763 LifetimeRes::Error,
1764 LifetimeElisionCandidate::Ignore,
1765 );
1766 return;
1767 }
1768 LifetimeRibKind::ConcreteAnonConst(cause) => {
1769 self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1770 self.record_lifetime_res(
1771 lifetime.id,
1772 LifetimeRes::Error,
1773 LifetimeElisionCandidate::Ignore,
1774 );
1775 return;
1776 }
1777 LifetimeRibKind::AnonymousCreateParameter { .. }
1778 | LifetimeRibKind::Elided(_)
1779 | LifetimeRibKind::Generics { .. }
1780 | LifetimeRibKind::ElisionFailure
1781 | LifetimeRibKind::AnonymousReportError
1782 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1783 }
1784 }
1785
1786 let normalized_ident = ident.normalize_to_macros_2_0();
1787 let outer_res = lifetime_rib_iter
1788 .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1789
1790 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1791 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1792 }
1793
1794 #[instrument(level = "debug", skip(self))]
1795 fn resolve_anonymous_lifetime(
1796 &mut self,
1797 lifetime: &Lifetime,
1798 id_for_lint: NodeId,
1799 elided: bool,
1800 ) {
1801 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1802
1803 let kind =
1804 if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1805 let missing_lifetime = MissingLifetime {
1806 id: lifetime.id,
1807 span: lifetime.ident.span,
1808 kind,
1809 count: 1,
1810 id_for_lint,
1811 };
1812 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1813 for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1814 debug!(?rib.kind);
1815 match rib.kind {
1816 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1817 let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1818 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1819 return;
1820 }
1821 LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1822 let mut lifetimes_in_scope = vec![];
1823 for rib in self.lifetime_ribs[..i].iter().rev() {
1824 lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1825 if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1827 && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1828 {
1829 lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1830 }
1831 if let LifetimeRibKind::Item = rib.kind {
1832 break;
1833 }
1834 }
1835 if lifetimes_in_scope.is_empty() {
1836 self.record_lifetime_res(
1837 lifetime.id,
1838 LifetimeRes::Static,
1839 elision_candidate,
1840 );
1841 return;
1842 } else if emit_lint {
1843 self.r.lint_buffer.buffer_lint(
1844 lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1845 node_id,
1846 lifetime.ident.span,
1847 lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1848 elided,
1849 span: lifetime.ident.span,
1850 lifetimes_in_scope: lifetimes_in_scope.into(),
1851 },
1852 );
1853 }
1854 }
1855 LifetimeRibKind::AnonymousReportError => {
1856 if elided {
1857 let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1858 if let LifetimeRibKind::Generics {
1859 span,
1860 kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1861 ..
1862 } = rib.kind
1863 {
1864 Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
1865 lo: span.shrink_to_lo(),
1866 hi: lifetime.ident.span.shrink_to_hi(),
1867 })
1868 } else {
1869 None
1870 }
1871 });
1872 if !self.in_func_body
1875 && let Some((module, _)) = &self.current_trait_ref
1876 && let Some(ty) = &self.diag_metadata.current_self_type
1877 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1878 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1879 {
1880 if def_id_matches_path(
1881 self.r.tcx,
1882 trait_id,
1883 &["core", "iter", "traits", "iterator", "Iterator"],
1884 ) {
1885 self.r.dcx().emit_err(errors::LendingIteratorReportError {
1886 lifetime: lifetime.ident.span,
1887 ty: ty.span,
1888 });
1889 } else {
1890 let decl = if !trait_id.is_local()
1891 && let Some(assoc) = self.diag_metadata.current_impl_item
1892 && let AssocItemKind::Type(_) = assoc.kind
1893 && let assocs = self.r.tcx.associated_items(trait_id)
1894 && let Some(ident) = assoc.kind.ident()
1895 && let Some(assoc) = assocs.find_by_ident_and_kind(
1896 self.r.tcx,
1897 ident,
1898 AssocTag::Type,
1899 trait_id,
1900 ) {
1901 let mut decl: MultiSpan =
1902 self.r.tcx.def_span(assoc.def_id).into();
1903 decl.push_span_label(
1904 self.r.tcx.def_span(trait_id),
1905 String::new(),
1906 );
1907 decl
1908 } else {
1909 DUMMY_SP.into()
1910 };
1911 let mut err = self.r.dcx().create_err(
1912 errors::AnonymousLifetimeNonGatReportError {
1913 lifetime: lifetime.ident.span,
1914 decl,
1915 },
1916 );
1917 self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
1918 err.emit();
1919 }
1920 } else {
1921 self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
1922 span: lifetime.ident.span,
1923 suggestion,
1924 });
1925 }
1926 } else {
1927 self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
1928 span: lifetime.ident.span,
1929 });
1930 };
1931 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1932 return;
1933 }
1934 LifetimeRibKind::Elided(res) => {
1935 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1936 return;
1937 }
1938 LifetimeRibKind::ElisionFailure => {
1939 self.diag_metadata.current_elision_failures.push(missing_lifetime);
1940 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1941 return;
1942 }
1943 LifetimeRibKind::Item => break,
1944 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1945 LifetimeRibKind::ConcreteAnonConst(_) => {
1946 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1948 }
1949 }
1950 }
1951 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1952 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1953 }
1954
1955 fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
1956 let Some((rib, span)) =
1957 self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
1958 LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
1959 Some((rib, span))
1960 }
1961 _ => None,
1962 })
1963 else {
1964 return;
1965 };
1966 if !rib.bindings.is_empty() {
1967 err.span_label(
1968 span,
1969 format!(
1970 "there {} named lifetime{} specified on the impl block you could use",
1971 if rib.bindings.len() == 1 { "is a" } else { "are" },
1972 pluralize!(rib.bindings.len()),
1973 ),
1974 );
1975 if rib.bindings.len() == 1 {
1976 err.span_suggestion_verbose(
1977 lifetime.shrink_to_hi(),
1978 "consider using the lifetime from the impl block",
1979 format!("{} ", rib.bindings.keys().next().unwrap()),
1980 Applicability::MaybeIncorrect,
1981 );
1982 }
1983 } else {
1984 struct AnonRefFinder;
1985 impl<'ast> Visitor<'ast> for AnonRefFinder {
1986 type Result = ControlFlow<Span>;
1987
1988 fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
1989 if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
1990 return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
1991 }
1992 visit::walk_ty(self, ty)
1993 }
1994
1995 fn visit_lifetime(
1996 &mut self,
1997 lt: &'ast ast::Lifetime,
1998 _cx: visit::LifetimeCtxt,
1999 ) -> Self::Result {
2000 if lt.ident.name == kw::UnderscoreLifetime {
2001 return ControlFlow::Break(lt.ident.span);
2002 }
2003 visit::walk_lifetime(self, lt)
2004 }
2005 }
2006
2007 if let Some(ty) = &self.diag_metadata.current_self_type
2008 && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2009 {
2010 err.multipart_suggestion_verbose(
2011 "add a lifetime to the impl block and use it in the self type and associated \
2012 type",
2013 vec![
2014 (span, "<'a>".to_string()),
2015 (sp, "'a ".to_string()),
2016 (lifetime.shrink_to_hi(), "'a ".to_string()),
2017 ],
2018 Applicability::MaybeIncorrect,
2019 );
2020 } else if let Some(item) = &self.diag_metadata.current_item
2021 && let ItemKind::Impl(impl_) = &item.kind
2022 && let Some(of_trait) = &impl_.of_trait
2023 && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2024 {
2025 err.multipart_suggestion_verbose(
2026 "add a lifetime to the impl block and use it in the trait and associated type",
2027 vec![
2028 (span, "<'a>".to_string()),
2029 (sp, "'a".to_string()),
2030 (lifetime.shrink_to_hi(), "'a ".to_string()),
2031 ],
2032 Applicability::MaybeIncorrect,
2033 );
2034 } else {
2035 err.span_label(
2036 span,
2037 "you could add a lifetime on the impl block, if the trait or the self type \
2038 could have one",
2039 );
2040 }
2041 }
2042 }
2043
2044 #[instrument(level = "debug", skip(self))]
2045 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2046 let id = self.r.next_node_id();
2047 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2048
2049 self.record_lifetime_res(
2050 anchor_id,
2051 LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2052 LifetimeElisionCandidate::Ignore,
2053 );
2054 self.resolve_anonymous_lifetime(<, anchor_id, true);
2055 }
2056
2057 #[instrument(level = "debug", skip(self))]
2058 fn create_fresh_lifetime(
2059 &mut self,
2060 ident: Ident,
2061 binder: NodeId,
2062 kind: MissingLifetimeKind,
2063 ) -> LifetimeRes {
2064 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2065 debug!(?ident.span);
2066
2067 let param = self.r.next_node_id();
2069 let res = LifetimeRes::Fresh { param, binder, kind };
2070 self.record_lifetime_param(param, res);
2071
2072 self.r
2074 .extra_lifetime_params_map
2075 .entry(binder)
2076 .or_insert_with(Vec::new)
2077 .push((ident, param, res));
2078 res
2079 }
2080
2081 #[instrument(level = "debug", skip(self))]
2082 fn resolve_elided_lifetimes_in_path(
2083 &mut self,
2084 partial_res: PartialRes,
2085 path: &[Segment],
2086 source: PathSource<'_, 'ast, 'ra>,
2087 path_span: Span,
2088 ) {
2089 let proj_start = path.len() - partial_res.unresolved_segments();
2090 for (i, segment) in path.iter().enumerate() {
2091 if segment.has_lifetime_args {
2092 continue;
2093 }
2094 let Some(segment_id) = segment.id else {
2095 continue;
2096 };
2097
2098 let type_def_id = match partial_res.base_res() {
2101 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2102 self.r.tcx.parent(def_id)
2103 }
2104 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2105 self.r.tcx.parent(def_id)
2106 }
2107 Res::Def(DefKind::Struct, def_id)
2108 | Res::Def(DefKind::Union, def_id)
2109 | Res::Def(DefKind::Enum, def_id)
2110 | Res::Def(DefKind::TyAlias, def_id)
2111 | Res::Def(DefKind::Trait, def_id)
2112 if i + 1 == proj_start =>
2113 {
2114 def_id
2115 }
2116 _ => continue,
2117 };
2118
2119 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2120 if expected_lifetimes == 0 {
2121 continue;
2122 }
2123
2124 let node_ids = self.r.next_node_ids(expected_lifetimes);
2125 self.record_lifetime_res(
2126 segment_id,
2127 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2128 LifetimeElisionCandidate::Ignore,
2129 );
2130
2131 let inferred = match source {
2132 PathSource::Trait(..)
2133 | PathSource::TraitItem(..)
2134 | PathSource::Type
2135 | PathSource::PreciseCapturingArg(..)
2136 | PathSource::ReturnTypeNotation => false,
2137 PathSource::Expr(..)
2138 | PathSource::Pat
2139 | PathSource::Struct(_)
2140 | PathSource::TupleStruct(..)
2141 | PathSource::DefineOpaques
2142 | PathSource::Delegation => true,
2143 };
2144 if inferred {
2145 for id in node_ids {
2148 self.record_lifetime_res(
2149 id,
2150 LifetimeRes::Infer,
2151 LifetimeElisionCandidate::Named,
2152 );
2153 }
2154 continue;
2155 }
2156
2157 let elided_lifetime_span = if segment.has_generic_args {
2158 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2160 } else {
2161 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2165 };
2166 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2167
2168 let kind = if segment.has_generic_args {
2169 MissingLifetimeKind::Comma
2170 } else {
2171 MissingLifetimeKind::Brackets
2172 };
2173 let missing_lifetime = MissingLifetime {
2174 id: node_ids.start,
2175 id_for_lint: segment_id,
2176 span: elided_lifetime_span,
2177 kind,
2178 count: expected_lifetimes,
2179 };
2180 let mut should_lint = true;
2181 for rib in self.lifetime_ribs.iter().rev() {
2182 match rib.kind {
2183 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2190 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2191 let sess = self.r.tcx.sess;
2192 let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2193 sess.source_map(),
2194 expected_lifetimes,
2195 path_span,
2196 !segment.has_generic_args,
2197 elided_lifetime_span,
2198 );
2199 self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2200 span: path_span,
2201 subdiag,
2202 });
2203 should_lint = false;
2204
2205 for id in node_ids {
2206 self.record_lifetime_res(
2207 id,
2208 LifetimeRes::Error,
2209 LifetimeElisionCandidate::Named,
2210 );
2211 }
2212 break;
2213 }
2214 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2216 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2218 for id in node_ids {
2219 let res = self.create_fresh_lifetime(ident, binder, kind);
2220 self.record_lifetime_res(
2221 id,
2222 res,
2223 replace(&mut candidate, LifetimeElisionCandidate::Named),
2224 );
2225 }
2226 break;
2227 }
2228 LifetimeRibKind::Elided(res) => {
2229 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2230 for id in node_ids {
2231 self.record_lifetime_res(
2232 id,
2233 res,
2234 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2235 );
2236 }
2237 break;
2238 }
2239 LifetimeRibKind::ElisionFailure => {
2240 self.diag_metadata.current_elision_failures.push(missing_lifetime);
2241 for id in node_ids {
2242 self.record_lifetime_res(
2243 id,
2244 LifetimeRes::Error,
2245 LifetimeElisionCandidate::Ignore,
2246 );
2247 }
2248 break;
2249 }
2250 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2255 for id in node_ids {
2256 self.record_lifetime_res(
2257 id,
2258 LifetimeRes::Error,
2259 LifetimeElisionCandidate::Ignore,
2260 );
2261 }
2262 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2263 break;
2264 }
2265 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2266 LifetimeRibKind::ConcreteAnonConst(_) => {
2267 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2269 }
2270 }
2271 }
2272
2273 if should_lint {
2274 self.r.lint_buffer.buffer_lint(
2275 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2276 segment_id,
2277 elided_lifetime_span,
2278 lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2279 expected_lifetimes,
2280 path_span,
2281 !segment.has_generic_args,
2282 elided_lifetime_span,
2283 ),
2284 );
2285 }
2286 }
2287 }
2288
2289 #[instrument(level = "debug", skip(self))]
2290 fn record_lifetime_res(
2291 &mut self,
2292 id: NodeId,
2293 res: LifetimeRes,
2294 candidate: LifetimeElisionCandidate,
2295 ) {
2296 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2297 panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2298 }
2299
2300 match res {
2301 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2302 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2303 candidates.push((res, candidate));
2304 }
2305 }
2306 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2307 }
2308 }
2309
2310 #[instrument(level = "debug", skip(self))]
2311 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2312 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2313 panic!(
2314 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2315 )
2316 }
2317 }
2318
2319 #[instrument(level = "debug", skip(self, inputs))]
2321 fn resolve_fn_signature(
2322 &mut self,
2323 fn_id: NodeId,
2324 has_self: bool,
2325 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2326 output_ty: &'ast FnRetTy,
2327 report_elided_lifetimes_in_path: bool,
2328 ) {
2329 let rib = LifetimeRibKind::AnonymousCreateParameter {
2330 binder: fn_id,
2331 report_in_path: report_elided_lifetimes_in_path,
2332 };
2333 self.with_lifetime_rib(rib, |this| {
2334 let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2336 debug!(?elision_lifetime);
2337
2338 let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2339 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2340 this.r.lifetime_elision_allowed.insert(fn_id);
2341 LifetimeRibKind::Elided(*res)
2342 } else {
2343 LifetimeRibKind::ElisionFailure
2344 };
2345 this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2346 let elision_failures =
2347 replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2348 if !elision_failures.is_empty() {
2349 let Err(failure_info) = elision_lifetime else { bug!() };
2350 this.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2351 }
2352 });
2353 }
2354
2355 fn resolve_fn_params(
2359 &mut self,
2360 has_self: bool,
2361 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2362 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2363 enum Elision {
2364 None,
2366 Self_(LifetimeRes),
2368 Param(LifetimeRes),
2370 Err,
2372 }
2373
2374 let outer_candidates = self.lifetime_elision_candidates.take();
2376
2377 let mut elision_lifetime = Elision::None;
2379 let mut parameter_info = Vec::new();
2381 let mut all_candidates = Vec::new();
2382
2383 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2385 for (pat, _) in inputs.clone() {
2386 debug!("resolving bindings in pat = {pat:?}");
2387 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2388 if let Some(pat) = pat {
2389 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2390 }
2391 });
2392 }
2393 self.apply_pattern_bindings(bindings);
2394
2395 for (index, (pat, ty)) in inputs.enumerate() {
2396 debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2397 debug_assert_matches!(self.lifetime_elision_candidates, None);
2399 self.lifetime_elision_candidates = Some(Default::default());
2400 self.visit_ty(ty);
2401 let local_candidates = self.lifetime_elision_candidates.take();
2402
2403 if let Some(candidates) = local_candidates {
2404 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2405 let lifetime_count = distinct.len();
2406 if lifetime_count != 0 {
2407 parameter_info.push(ElisionFnParameter {
2408 index,
2409 ident: if let Some(pat) = pat
2410 && let PatKind::Ident(_, ident, _) = pat.kind
2411 {
2412 Some(ident)
2413 } else {
2414 None
2415 },
2416 lifetime_count,
2417 span: ty.span,
2418 });
2419 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2420 match candidate {
2421 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2422 None
2423 }
2424 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2425 }
2426 }));
2427 }
2428 if !distinct.is_empty() {
2429 match elision_lifetime {
2430 Elision::None => {
2432 if let Some(res) = distinct.get_only() {
2433 elision_lifetime = Elision::Param(*res)
2435 } else {
2436 elision_lifetime = Elision::Err;
2438 }
2439 }
2440 Elision::Param(_) => elision_lifetime = Elision::Err,
2442 Elision::Self_(_) | Elision::Err => {}
2444 }
2445 }
2446 }
2447
2448 if index == 0 && has_self {
2450 let self_lifetime = self.find_lifetime_for_self(ty);
2451 elision_lifetime = match self_lifetime {
2452 Set1::One(lifetime) => Elision::Self_(lifetime),
2454 Set1::Many => Elision::Err,
2459 Set1::Empty => Elision::None,
2462 }
2463 }
2464 debug!("(resolving function / closure) recorded parameter");
2465 }
2466
2467 debug_assert_matches!(self.lifetime_elision_candidates, None);
2469 self.lifetime_elision_candidates = outer_candidates;
2470
2471 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2472 return Ok(res);
2473 }
2474
2475 Err((all_candidates, parameter_info))
2477 }
2478
2479 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2481 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2485 r: &'a Resolver<'ra, 'tcx>,
2486 impl_self: Option<Res>,
2487 lifetime: Set1<LifetimeRes>,
2488 }
2489
2490 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2491 fn visit_ty(&mut self, ty: &'ra Ty) {
2492 trace!("FindReferenceVisitor considering ty={:?}", ty);
2493 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2494 let mut visitor =
2496 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2497 visitor.visit_ty(ty);
2498 trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2499 if visitor.self_found {
2500 let lt_id = if let Some(lt) = lt {
2501 lt.id
2502 } else {
2503 let res = self.r.lifetimes_res_map[&ty.id];
2504 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2505 start
2506 };
2507 let lt_res = self.r.lifetimes_res_map[<_id];
2508 trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2509 self.lifetime.insert(lt_res);
2510 }
2511 }
2512 visit::walk_ty(self, ty)
2513 }
2514
2515 fn visit_expr(&mut self, _: &'ra Expr) {}
2518 }
2519
2520 struct SelfVisitor<'a, 'ra, 'tcx> {
2523 r: &'a Resolver<'ra, 'tcx>,
2524 impl_self: Option<Res>,
2525 self_found: bool,
2526 }
2527
2528 impl SelfVisitor<'_, '_, '_> {
2529 fn is_self_ty(&self, ty: &Ty) -> bool {
2531 match ty.kind {
2532 TyKind::ImplicitSelf => true,
2533 TyKind::Path(None, _) => {
2534 let path_res = self.r.partial_res_map[&ty.id].full_res();
2535 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2536 return true;
2537 }
2538 self.impl_self.is_some() && path_res == self.impl_self
2539 }
2540 _ => false,
2541 }
2542 }
2543 }
2544
2545 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2546 fn visit_ty(&mut self, ty: &'ra Ty) {
2547 trace!("SelfVisitor considering ty={:?}", ty);
2548 if self.is_self_ty(ty) {
2549 trace!("SelfVisitor found Self");
2550 self.self_found = true;
2551 }
2552 visit::walk_ty(self, ty)
2553 }
2554
2555 fn visit_expr(&mut self, _: &'ra Expr) {}
2558 }
2559
2560 let impl_self = self
2561 .diag_metadata
2562 .current_self_type
2563 .as_ref()
2564 .and_then(|ty| {
2565 if let TyKind::Path(None, _) = ty.kind {
2566 self.r.partial_res_map.get(&ty.id)
2567 } else {
2568 None
2569 }
2570 })
2571 .and_then(|res| res.full_res())
2572 .filter(|res| {
2573 matches!(
2577 res,
2578 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2579 )
2580 });
2581 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2582 visitor.visit_ty(ty);
2583 trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2584 visitor.lifetime
2585 }
2586
2587 fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2590 let mut suggestion = None;
2591
2592 for i in (0..self.label_ribs.len()).rev() {
2593 let rib = &self.label_ribs[i];
2594
2595 if let RibKind::MacroDefinition(def) = rib.kind
2596 && def == self.r.macro_def(label.span.ctxt())
2599 {
2600 label.span.remove_mark();
2601 }
2602
2603 let ident = label.normalize_to_macro_rules();
2604 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2605 let definition_span = ident.span;
2606 return if self.is_label_valid_from_rib(i) {
2607 Ok((*id, definition_span))
2608 } else {
2609 Err(ResolutionError::UnreachableLabel {
2610 name: label.name,
2611 definition_span,
2612 suggestion,
2613 })
2614 };
2615 }
2616
2617 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2620 }
2621
2622 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2623 }
2624
2625 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2627 let ribs = &self.label_ribs[rib_index + 1..];
2628 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2629 }
2630
2631 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2632 debug!("resolve_adt");
2633 let kind = self.r.local_def_kind(item.id);
2634 self.with_current_self_item(item, |this| {
2635 this.with_generic_param_rib(
2636 &generics.params,
2637 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2638 item.id,
2639 LifetimeBinderKind::Item,
2640 generics.span,
2641 |this| {
2642 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2643 this.with_self_rib(
2644 Res::SelfTyAlias {
2645 alias_to: item_def_id,
2646 forbid_generic: false,
2647 is_trait_impl: false,
2648 },
2649 |this| {
2650 visit::walk_item(this, item);
2651 },
2652 );
2653 },
2654 );
2655 });
2656 }
2657
2658 fn future_proof_import(&mut self, use_tree: &UseTree) {
2659 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2660 let ident = segment.ident;
2661 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2662 return;
2663 }
2664
2665 let nss = match use_tree.kind {
2666 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2667 _ => &[TypeNS],
2668 };
2669 let report_error = |this: &Self, ns| {
2670 if this.should_report_errs() {
2671 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2672 this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2673 }
2674 };
2675
2676 for &ns in nss {
2677 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2678 Some(LexicalScopeBinding::Res(..)) => {
2679 report_error(self, ns);
2680 }
2681 Some(LexicalScopeBinding::Item(binding)) => {
2682 if let Some(LexicalScopeBinding::Res(..)) =
2683 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2684 {
2685 report_error(self, ns);
2686 }
2687 }
2688 None => {}
2689 }
2690 }
2691 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2692 for (use_tree, _) in items {
2693 self.future_proof_import(use_tree);
2694 }
2695 }
2696 }
2697
2698 fn resolve_item(&mut self, item: &'ast Item) {
2699 let mod_inner_docs =
2700 matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2701 if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2702 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2703 }
2704
2705 debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2706
2707 let def_kind = self.r.local_def_kind(item.id);
2708 match item.kind {
2709 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2710 self.with_generic_param_rib(
2711 &generics.params,
2712 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2713 item.id,
2714 LifetimeBinderKind::Item,
2715 generics.span,
2716 |this| visit::walk_item(this, item),
2717 );
2718 }
2719
2720 ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2721 self.with_generic_param_rib(
2722 &generics.params,
2723 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2724 item.id,
2725 LifetimeBinderKind::Function,
2726 generics.span,
2727 |this| visit::walk_item(this, item),
2728 );
2729 self.resolve_define_opaques(define_opaque);
2730 }
2731
2732 ItemKind::Enum(_, ref generics, _)
2733 | ItemKind::Struct(_, ref generics, _)
2734 | ItemKind::Union(_, ref generics, _) => {
2735 self.resolve_adt(item, generics);
2736 }
2737
2738 ItemKind::Impl(Impl {
2739 ref generics,
2740 ref of_trait,
2741 ref self_ty,
2742 items: ref impl_items,
2743 ..
2744 }) => {
2745 self.diag_metadata.current_impl_items = Some(impl_items);
2746 self.resolve_implementation(
2747 &item.attrs,
2748 generics,
2749 of_trait.as_deref(),
2750 self_ty,
2751 item.id,
2752 impl_items,
2753 );
2754 self.diag_metadata.current_impl_items = None;
2755 }
2756
2757 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2758 self.with_generic_param_rib(
2760 &generics.params,
2761 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2762 item.id,
2763 LifetimeBinderKind::Item,
2764 generics.span,
2765 |this| {
2766 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2767 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2768 this.visit_generics(generics);
2769 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2770 this.resolve_trait_items(items);
2771 });
2772 },
2773 );
2774 }
2775
2776 ItemKind::TraitAlias(box TraitAlias { ref generics, ref bounds, .. }) => {
2777 self.with_generic_param_rib(
2779 &generics.params,
2780 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2781 item.id,
2782 LifetimeBinderKind::Item,
2783 generics.span,
2784 |this| {
2785 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2786 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2787 this.visit_generics(generics);
2788 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2789 });
2790 },
2791 );
2792 }
2793
2794 ItemKind::Mod(..) => {
2795 let module = self.r.expect_module(self.r.local_def_id(item.id).to_def_id());
2796 let orig_module = replace(&mut self.parent_scope.module, module);
2797 self.with_rib(ValueNS, RibKind::Module(module), |this| {
2798 this.with_rib(TypeNS, RibKind::Module(module), |this| {
2799 if mod_inner_docs {
2800 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2801 }
2802 let old_macro_rules = this.parent_scope.macro_rules;
2803 visit::walk_item(this, item);
2804 if item.attrs.iter().all(|attr| {
2807 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2808 }) {
2809 this.parent_scope.macro_rules = old_macro_rules;
2810 }
2811 })
2812 });
2813 self.parent_scope.module = orig_module;
2814 }
2815
2816 ItemKind::Static(box ast::StaticItem {
2817 ident,
2818 ref ty,
2819 ref expr,
2820 ref define_opaque,
2821 ..
2822 }) => {
2823 self.with_static_rib(def_kind, |this| {
2824 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2825 this.visit_ty(ty);
2826 });
2827 if let Some(expr) = expr {
2828 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Static)));
2831 }
2832 });
2833 self.resolve_define_opaques(define_opaque);
2834 }
2835
2836 ItemKind::Const(box ast::ConstItem {
2837 ident,
2838 ref generics,
2839 ref ty,
2840 ref expr,
2841 ref define_opaque,
2842 ..
2843 }) => {
2844 self.with_generic_param_rib(
2845 &generics.params,
2846 RibKind::Item(
2847 if self.r.tcx.features().generic_const_items() {
2848 HasGenericParams::Yes(generics.span)
2849 } else {
2850 HasGenericParams::No
2851 },
2852 def_kind,
2853 ),
2854 item.id,
2855 LifetimeBinderKind::ConstItem,
2856 generics.span,
2857 |this| {
2858 this.visit_generics(generics);
2859
2860 this.with_lifetime_rib(
2861 LifetimeRibKind::Elided(LifetimeRes::Static),
2862 |this| this.visit_ty(ty),
2863 );
2864
2865 if let Some(expr) = expr {
2866 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Const)));
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<'c, F>(
2917 &'c mut self,
2918 params: &'c [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 expr,
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(expr) = expr {
3207 this.resolve_const_body(expr, 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 expr,
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(expr) = expr {
3434 this.resolve_const_body(expr, 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_const_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_delegation(&mut self, delegation: &'ast Delegation) {
3659 self.smart_resolve_path(
3660 delegation.id,
3661 &delegation.qself,
3662 &delegation.path,
3663 PathSource::Delegation,
3664 );
3665 if let Some(qself) = &delegation.qself {
3666 self.visit_ty(&qself.ty);
3667 }
3668 self.visit_path(&delegation.path);
3669 let Some(body) = &delegation.body else { return };
3670 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3671 let span = delegation.path.segments.last().unwrap().ident.span;
3672 let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3673 let res = Res::Local(delegation.id);
3674 this.innermost_rib_bindings(ValueNS).insert(ident, res);
3675 this.visit_block(body);
3676 });
3677 }
3678
3679 fn resolve_params(&mut self, params: &'ast [Param]) {
3680 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3681 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3682 for Param { pat, .. } in params {
3683 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3684 }
3685 this.apply_pattern_bindings(bindings);
3686 });
3687 for Param { ty, .. } in params {
3688 self.visit_ty(ty);
3689 }
3690 }
3691
3692 fn resolve_local(&mut self, local: &'ast Local) {
3693 debug!("resolving local ({:?})", local);
3694 visit_opt!(self, visit_ty, &local.ty);
3696
3697 if let Some((init, els)) = local.kind.init_else_opt() {
3699 self.visit_expr(init);
3700
3701 if let Some(els) = els {
3703 self.visit_block(els);
3704 }
3705 }
3706
3707 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3709 }
3710
3711 fn compute_and_check_binding_map(
3731 &mut self,
3732 pat: &Pat,
3733 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3734 let mut binding_map = FxIndexMap::default();
3735 let mut is_never_pat = false;
3736
3737 pat.walk(&mut |pat| {
3738 match pat.kind {
3739 PatKind::Ident(annotation, ident, ref sub_pat)
3740 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3741 {
3742 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3743 }
3744 PatKind::Or(ref ps) => {
3745 match self.compute_and_check_or_pat_binding_map(ps) {
3748 Ok(bm) => binding_map.extend(bm),
3749 Err(IsNeverPattern) => is_never_pat = true,
3750 }
3751 return false;
3752 }
3753 PatKind::Never => is_never_pat = true,
3754 _ => {}
3755 }
3756
3757 true
3758 });
3759
3760 if is_never_pat {
3761 for (_, binding) in binding_map {
3762 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3763 }
3764 Err(IsNeverPattern)
3765 } else {
3766 Ok(binding_map)
3767 }
3768 }
3769
3770 fn is_base_res_local(&self, nid: NodeId) -> bool {
3771 matches!(
3772 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3773 Some(Res::Local(..))
3774 )
3775 }
3776
3777 fn compute_and_check_or_pat_binding_map(
3797 &mut self,
3798 pats: &[Pat],
3799 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3800 let mut missing_vars = FxIndexMap::default();
3801 let mut inconsistent_vars = FxIndexMap::default();
3802
3803 let not_never_pats = pats
3805 .iter()
3806 .filter_map(|pat| {
3807 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3808 Some((binding_map, pat))
3809 })
3810 .collect::<Vec<_>>();
3811
3812 for &(ref map_outer, pat_outer) in not_never_pats.iter() {
3814 let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
3816
3817 for &(ref map, pat) in inners {
3818 for (&name, binding_inner) in map {
3819 match map_outer.get(&name) {
3820 None => {
3821 let binding_error =
3823 missing_vars.entry(name).or_insert_with(|| BindingError {
3824 name,
3825 origin: Default::default(),
3826 target: Default::default(),
3827 could_be_path: name.as_str().starts_with(char::is_uppercase),
3828 });
3829 binding_error.origin.push((binding_inner.span, pat.clone()));
3830 binding_error.target.push(pat_outer.clone());
3831 }
3832 Some(binding_outer) => {
3833 if binding_outer.annotation != binding_inner.annotation {
3834 inconsistent_vars
3836 .entry(name)
3837 .or_insert((binding_inner.span, binding_outer.span));
3838 }
3839 }
3840 }
3841 }
3842 }
3843 }
3844
3845 for (name, mut v) in missing_vars {
3847 if inconsistent_vars.contains_key(&name) {
3848 v.could_be_path = false;
3849 }
3850 self.report_error(
3851 v.origin.iter().next().unwrap().0,
3852 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3853 );
3854 }
3855
3856 for (name, v) in inconsistent_vars {
3858 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3859 }
3860
3861 if not_never_pats.is_empty() {
3863 Err(IsNeverPattern)
3865 } else {
3866 let mut binding_map = FxIndexMap::default();
3867 for (bm, _) in not_never_pats {
3868 binding_map.extend(bm);
3869 }
3870 Ok(binding_map)
3871 }
3872 }
3873
3874 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3876 let mut is_or_or_never = false;
3877 pat.walk(&mut |pat| match pat.kind {
3878 PatKind::Or(..) | PatKind::Never => {
3879 is_or_or_never = true;
3880 false
3881 }
3882 _ => true,
3883 });
3884 if is_or_or_never {
3885 let _ = self.compute_and_check_binding_map(pat);
3886 }
3887 }
3888
3889 fn resolve_arm(&mut self, arm: &'ast Arm) {
3890 self.with_rib(ValueNS, RibKind::Normal, |this| {
3891 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3892 visit_opt!(this, visit_expr, &arm.guard);
3893 visit_opt!(this, visit_expr, &arm.body);
3894 });
3895 }
3896
3897 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3899 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3900 self.resolve_pattern(pat, pat_src, &mut bindings);
3901 self.apply_pattern_bindings(bindings);
3902 }
3903
3904 fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3906 let rib_bindings = self.innermost_rib_bindings(ValueNS);
3907 let Some((_, pat_bindings)) = pat_bindings.pop() else {
3908 bug!("tried applying nonexistent bindings from pattern");
3909 };
3910
3911 if rib_bindings.is_empty() {
3912 *rib_bindings = pat_bindings;
3915 } else {
3916 rib_bindings.extend(pat_bindings);
3917 }
3918 }
3919
3920 fn resolve_pattern(
3923 &mut self,
3924 pat: &'ast Pat,
3925 pat_src: PatternSource,
3926 bindings: &mut PatternBindings,
3927 ) {
3928 self.visit_pat(pat);
3934 self.resolve_pattern_inner(pat, pat_src, bindings);
3935 self.check_consistent_bindings(pat);
3937 }
3938
3939 #[tracing::instrument(skip(self, bindings), level = "debug")]
3959 fn resolve_pattern_inner(
3960 &mut self,
3961 pat: &'ast Pat,
3962 pat_src: PatternSource,
3963 bindings: &mut PatternBindings,
3964 ) {
3965 pat.walk(&mut |pat| {
3967 match pat.kind {
3968 PatKind::Ident(bmode, ident, ref sub) => {
3969 let has_sub = sub.is_some();
3972 let res = self
3973 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3974 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3975 self.r.record_partial_res(pat.id, PartialRes::new(res));
3976 self.r.record_pat_span(pat.id, pat.span);
3977 }
3978 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3979 self.smart_resolve_path(
3980 pat.id,
3981 qself,
3982 path,
3983 PathSource::TupleStruct(
3984 pat.span,
3985 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3986 ),
3987 );
3988 }
3989 PatKind::Path(ref qself, ref path) => {
3990 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3991 }
3992 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3993 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
3994 self.record_patterns_with_skipped_bindings(pat, rest);
3995 }
3996 PatKind::Or(ref ps) => {
3997 bindings.push((PatBoundCtx::Or, Default::default()));
4001 for p in ps {
4002 bindings.push((PatBoundCtx::Product, Default::default()));
4006 self.resolve_pattern_inner(p, pat_src, bindings);
4007 let collected = bindings.pop().unwrap().1;
4010 bindings.last_mut().unwrap().1.extend(collected);
4011 }
4012 let collected = bindings.pop().unwrap().1;
4016 bindings.last_mut().unwrap().1.extend(collected);
4017
4018 return false;
4020 }
4021 PatKind::Guard(ref subpat, ref guard) => {
4022 bindings.push((PatBoundCtx::Product, Default::default()));
4024 let binding_ctx_stack_len = bindings.len();
4027 self.resolve_pattern_inner(subpat, pat_src, bindings);
4028 assert_eq!(bindings.len(), binding_ctx_stack_len);
4029 let subpat_bindings = bindings.pop().unwrap().1;
4032 self.with_rib(ValueNS, RibKind::Normal, |this| {
4033 *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4034 this.resolve_expr(guard, None);
4035 });
4036 bindings.last_mut().unwrap().1.extend(subpat_bindings);
4043 return false;
4045 }
4046 _ => {}
4047 }
4048 true
4049 });
4050 }
4051
4052 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4053 match rest {
4054 ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4055 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4057 && let Some(res) = partial_res.full_res()
4058 && let Some(def_id) = res.opt_def_id()
4059 {
4060 self.ribs[ValueNS]
4061 .last_mut()
4062 .unwrap()
4063 .patterns_with_skipped_bindings
4064 .entry(def_id)
4065 .or_default()
4066 .push((
4067 pat.span,
4068 match rest {
4069 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4070 _ => Ok(()),
4071 },
4072 ));
4073 }
4074 }
4075 ast::PatFieldsRest::None => {}
4076 }
4077 }
4078
4079 fn fresh_binding(
4080 &mut self,
4081 ident: Ident,
4082 pat_id: NodeId,
4083 pat_src: PatternSource,
4084 bindings: &mut PatternBindings,
4085 ) -> Res {
4086 let ident = ident.normalize_to_macro_rules();
4090
4091 let already_bound_and = bindings
4093 .iter()
4094 .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4095 if already_bound_and {
4096 use ResolutionError::*;
4098 let error = match pat_src {
4099 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4101 _ => IdentifierBoundMoreThanOnceInSamePattern,
4103 };
4104 self.report_error(ident.span, error(ident));
4105 }
4106
4107 let already_bound_or = bindings
4110 .iter()
4111 .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4112 let res = if let Some(&res) = already_bound_or {
4113 res
4116 } else {
4117 Res::Local(pat_id)
4119 };
4120
4121 bindings.last_mut().unwrap().1.insert(ident, res);
4123 res
4124 }
4125
4126 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4127 &mut self.ribs[ns].last_mut().unwrap().bindings
4128 }
4129
4130 fn try_resolve_as_non_binding(
4131 &mut self,
4132 pat_src: PatternSource,
4133 ann: BindingMode,
4134 ident: Ident,
4135 has_sub: bool,
4136 ) -> Option<Res> {
4137 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4141
4142 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4143 let (res, binding) = match ls_binding {
4144 LexicalScopeBinding::Item(binding)
4145 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4146 {
4147 self.r.record_use(ident, binding, Used::Other);
4152 return None;
4153 }
4154 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4155 LexicalScopeBinding::Res(res) => (res, None),
4156 };
4157
4158 match res {
4159 Res::SelfCtor(_) | Res::Def(
4161 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4162 _,
4163 ) if is_syntactic_ambiguity => {
4164 if let Some(binding) = binding {
4166 self.r.record_use(ident, binding, Used::Other);
4167 }
4168 Some(res)
4169 }
4170 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4171 let binding = binding.expect("no binding for a ctor or static");
4177 self.report_error(
4178 ident.span,
4179 ResolutionError::BindingShadowsSomethingUnacceptable {
4180 shadowing_binding: pat_src,
4181 name: ident.name,
4182 participle: if binding.is_import() { "imported" } else { "defined" },
4183 article: binding.res().article(),
4184 shadowed_binding: binding.res(),
4185 shadowed_binding_span: binding.span,
4186 },
4187 );
4188 None
4189 }
4190 Res::Def(DefKind::ConstParam, def_id) => {
4191 self.report_error(
4194 ident.span,
4195 ResolutionError::BindingShadowsSomethingUnacceptable {
4196 shadowing_binding: pat_src,
4197 name: ident.name,
4198 participle: "defined",
4199 article: res.article(),
4200 shadowed_binding: res,
4201 shadowed_binding_span: self.r.def_span(def_id),
4202 }
4203 );
4204 None
4205 }
4206 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4207 None
4209 }
4210 Res::SelfCtor(_) => {
4211 self.r.dcx().span_delayed_bug(
4214 ident.span,
4215 "unexpected `SelfCtor` in pattern, expected identifier"
4216 );
4217 None
4218 }
4219 _ => span_bug!(
4220 ident.span,
4221 "unexpected resolution for an identifier in pattern: {:?}",
4222 res,
4223 ),
4224 }
4225 }
4226
4227 fn smart_resolve_path(
4233 &mut self,
4234 id: NodeId,
4235 qself: &Option<Box<QSelf>>,
4236 path: &Path,
4237 source: PathSource<'_, 'ast, 'ra>,
4238 ) {
4239 self.smart_resolve_path_fragment(
4240 qself,
4241 &Segment::from_path(path),
4242 source,
4243 Finalize::new(id, path.span),
4244 RecordPartialRes::Yes,
4245 None,
4246 );
4247 }
4248
4249 #[instrument(level = "debug", skip(self))]
4250 fn smart_resolve_path_fragment(
4251 &mut self,
4252 qself: &Option<Box<QSelf>>,
4253 path: &[Segment],
4254 source: PathSource<'_, 'ast, 'ra>,
4255 finalize: Finalize,
4256 record_partial_res: RecordPartialRes,
4257 parent_qself: Option<&QSelf>,
4258 ) -> PartialRes {
4259 let ns = source.namespace();
4260
4261 let Finalize { node_id, path_span, .. } = finalize;
4262 let report_errors = |this: &mut Self, res: Option<Res>| {
4263 if this.should_report_errs() {
4264 let (err, candidates) = this.smart_resolve_report_errors(
4265 path,
4266 None,
4267 path_span,
4268 source,
4269 res,
4270 parent_qself,
4271 );
4272
4273 let def_id = this.parent_scope.module.nearest_parent_mod();
4274 let instead = res.is_some();
4275 let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4276 && path[0].ident.span.lo() == end.span.lo()
4277 && !matches!(start.kind, ExprKind::Lit(_))
4278 {
4279 let mut sugg = ".";
4280 let mut span = start.span.between(end.span);
4281 if span.lo() + BytePos(2) == span.hi() {
4282 span = span.with_lo(span.lo() + BytePos(1));
4285 sugg = "";
4286 }
4287 Some((
4288 span,
4289 "you might have meant to write `.` instead of `..`",
4290 sugg.to_string(),
4291 Applicability::MaybeIncorrect,
4292 ))
4293 } else if res.is_none()
4294 && let PathSource::Type
4295 | PathSource::Expr(_)
4296 | PathSource::PreciseCapturingArg(..) = source
4297 {
4298 this.suggest_adding_generic_parameter(path, source)
4299 } else {
4300 None
4301 };
4302
4303 let ue = UseError {
4304 err,
4305 candidates,
4306 def_id,
4307 instead,
4308 suggestion,
4309 path: path.into(),
4310 is_call: source.is_call(),
4311 };
4312
4313 this.r.use_injections.push(ue);
4314 }
4315
4316 PartialRes::new(Res::Err)
4317 };
4318
4319 let report_errors_for_call =
4325 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4326 let (following_seg, prefix_path) = match path.split_last() {
4330 Some((last, path)) if !path.is_empty() => (Some(last), path),
4331 _ => return Some(parent_err),
4332 };
4333
4334 let (mut err, candidates) = this.smart_resolve_report_errors(
4335 prefix_path,
4336 following_seg,
4337 path_span,
4338 PathSource::Type,
4339 None,
4340 parent_qself,
4341 );
4342
4343 let failed_to_resolve = match parent_err.node {
4358 ResolutionError::FailedToResolve { .. } => true,
4359 _ => false,
4360 };
4361 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4362
4363 err.messages = take(&mut parent_err.messages);
4365 err.code = take(&mut parent_err.code);
4366 swap(&mut err.span, &mut parent_err.span);
4367 if failed_to_resolve {
4368 err.children = take(&mut parent_err.children);
4369 } else {
4370 err.children.append(&mut parent_err.children);
4371 }
4372 err.sort_span = parent_err.sort_span;
4373 err.is_lint = parent_err.is_lint.clone();
4374
4375 match &mut err.suggestions {
4377 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4378 Suggestions::Enabled(parent_suggestions) => {
4379 typo_suggestions.append(parent_suggestions)
4381 }
4382 Suggestions::Sealed(_) | Suggestions::Disabled => {
4383 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4388 }
4389 },
4390 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4391 }
4392
4393 parent_err.cancel();
4394
4395 let def_id = this.parent_scope.module.nearest_parent_mod();
4396
4397 if this.should_report_errs() {
4398 if candidates.is_empty() {
4399 if path.len() == 2
4400 && let [segment] = prefix_path
4401 {
4402 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4408 } else {
4409 err.emit();
4414 }
4415 } else {
4416 this.r.use_injections.push(UseError {
4418 err,
4419 candidates,
4420 def_id,
4421 instead: false,
4422 suggestion: None,
4423 path: prefix_path.into(),
4424 is_call: source.is_call(),
4425 });
4426 }
4427 } else {
4428 err.cancel();
4429 }
4430
4431 None
4434 };
4435
4436 let partial_res = match self.resolve_qpath_anywhere(
4437 qself,
4438 path,
4439 ns,
4440 source.defer_to_typeck(),
4441 finalize,
4442 source,
4443 ) {
4444 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4445 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4447 && let [Segment { ident, .. }] = path
4448 && items.iter().any(|item| {
4449 if let AssocItemKind::Type(alias) = &item.kind
4450 && alias.ident == *ident
4451 {
4452 true
4453 } else {
4454 false
4455 }
4456 })
4457 {
4458 let mut diag = self.r.tcx.dcx().struct_allow("");
4459 diag.span_suggestion_verbose(
4460 path_span.shrink_to_lo(),
4461 "there is an associated type with the same name",
4462 "Self::",
4463 Applicability::MaybeIncorrect,
4464 );
4465 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4466 }
4467
4468 if source.is_expected(res) || res == Res::Err {
4469 partial_res
4470 } else {
4471 report_errors(self, Some(res))
4472 }
4473 }
4474
4475 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4476 if ns == ValueNS {
4480 let item_name = path.last().unwrap().ident;
4481 let traits = self.traits_in_scope(item_name, ns);
4482 self.r.trait_map.insert(node_id, traits);
4483 }
4484
4485 if PrimTy::from_name(path[0].ident.name).is_some() {
4486 let mut std_path = Vec::with_capacity(1 + path.len());
4487
4488 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4489 std_path.extend(path);
4490 if let PathResult::Module(_) | PathResult::NonModule(_) =
4491 self.resolve_path(&std_path, Some(ns), None, source)
4492 {
4493 let item_span =
4495 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4496
4497 self.r.confused_type_with_std_module.insert(item_span, path_span);
4498 self.r.confused_type_with_std_module.insert(path_span, path_span);
4499 }
4500 }
4501
4502 partial_res
4503 }
4504
4505 Err(err) => {
4506 if let Some(err) = report_errors_for_call(self, err) {
4507 self.report_error(err.span, err.node);
4508 }
4509
4510 PartialRes::new(Res::Err)
4511 }
4512
4513 _ => report_errors(self, None),
4514 };
4515
4516 if record_partial_res == RecordPartialRes::Yes {
4517 self.r.record_partial_res(node_id, partial_res);
4519 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4520 self.lint_unused_qualifications(path, ns, finalize);
4521 }
4522
4523 partial_res
4524 }
4525
4526 fn self_type_is_available(&mut self) -> bool {
4527 let binding = self
4528 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4529 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4530 }
4531
4532 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4533 let ident = Ident::new(kw::SelfLower, self_span);
4534 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4535 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4536 }
4537
4538 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4542 if self.should_report_errs() {
4543 self.r.report_error(span, resolution_error);
4544 }
4545 }
4546
4547 #[inline]
4548 fn should_report_errs(&self) -> bool {
4552 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4553 && !self.r.glob_error.is_some()
4554 }
4555
4556 fn resolve_qpath_anywhere(
4558 &mut self,
4559 qself: &Option<Box<QSelf>>,
4560 path: &[Segment],
4561 primary_ns: Namespace,
4562 defer_to_typeck: bool,
4563 finalize: Finalize,
4564 source: PathSource<'_, 'ast, 'ra>,
4565 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4566 let mut fin_res = None;
4567
4568 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4569 if i == 0 || ns != primary_ns {
4570 match self.resolve_qpath(qself, path, ns, finalize, source)? {
4571 Some(partial_res)
4572 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4573 {
4574 return Ok(Some(partial_res));
4575 }
4576 partial_res => {
4577 if fin_res.is_none() {
4578 fin_res = partial_res;
4579 }
4580 }
4581 }
4582 }
4583 }
4584
4585 assert!(primary_ns != MacroNS);
4586 if qself.is_none()
4587 && let PathResult::NonModule(res) =
4588 self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4589 {
4590 return Ok(Some(res));
4591 }
4592
4593 Ok(fin_res)
4594 }
4595
4596 fn resolve_qpath(
4598 &mut self,
4599 qself: &Option<Box<QSelf>>,
4600 path: &[Segment],
4601 ns: Namespace,
4602 finalize: Finalize,
4603 source: PathSource<'_, 'ast, 'ra>,
4604 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4605 debug!(
4606 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4607 qself, path, ns, finalize,
4608 );
4609
4610 if let Some(qself) = qself {
4611 if qself.position == 0 {
4612 return Ok(Some(PartialRes::with_unresolved_segments(
4616 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4617 path.len(),
4618 )));
4619 }
4620
4621 let num_privacy_errors = self.r.privacy_errors.len();
4622 let trait_res = self.smart_resolve_path_fragment(
4624 &None,
4625 &path[..qself.position],
4626 PathSource::Trait(AliasPossibility::No),
4627 Finalize::new(finalize.node_id, qself.path_span),
4628 RecordPartialRes::No,
4629 Some(&qself),
4630 );
4631
4632 if trait_res.expect_full_res() == Res::Err {
4633 return Ok(Some(trait_res));
4634 }
4635
4636 self.r.privacy_errors.truncate(num_privacy_errors);
4639
4640 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4648 let partial_res = self.smart_resolve_path_fragment(
4649 &None,
4650 &path[..=qself.position],
4651 PathSource::TraitItem(ns, &source),
4652 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4653 RecordPartialRes::No,
4654 Some(&qself),
4655 );
4656
4657 return Ok(Some(PartialRes::with_unresolved_segments(
4661 partial_res.base_res(),
4662 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4663 )));
4664 }
4665
4666 let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4667 PathResult::NonModule(path_res) => path_res,
4668 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4669 PartialRes::new(module.res().unwrap())
4670 }
4671 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4675 PartialRes::new(Res::Err)
4676 }
4677 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4690 if (ns == TypeNS || path.len() > 1)
4691 && PrimTy::from_name(path[0].ident.name).is_some() =>
4692 {
4693 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4694 let tcx = self.r.tcx();
4695
4696 let gate_err_sym_msg = match prim {
4697 PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4698 Some((sym::f16, "the type `f16` is unstable"))
4699 }
4700 PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4701 Some((sym::f128, "the type `f128` is unstable"))
4702 }
4703 _ => None,
4704 };
4705
4706 if let Some((sym, msg)) = gate_err_sym_msg {
4707 let span = path[0].ident.span;
4708 if !span.allows_unstable(sym) {
4709 feature_err(tcx.sess, sym, span, msg).emit();
4710 }
4711 };
4712
4713 if let Some(id) = path[0].id {
4715 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4716 }
4717
4718 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4719 }
4720 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4721 PartialRes::new(module.res().unwrap())
4722 }
4723 PathResult::Failed {
4724 is_error_from_last_segment: false,
4725 span,
4726 label,
4727 suggestion,
4728 module,
4729 segment_name,
4730 error_implied_by_parse_error: _,
4731 } => {
4732 return Err(respan(
4733 span,
4734 ResolutionError::FailedToResolve {
4735 segment: Some(segment_name),
4736 label,
4737 suggestion,
4738 module,
4739 },
4740 ));
4741 }
4742 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4743 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4744 };
4745
4746 Ok(Some(result))
4747 }
4748
4749 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4750 if let Some(label) = label {
4751 if label.ident.as_str().as_bytes()[1] != b'_' {
4752 self.diag_metadata.unused_labels.insert(id, label.ident.span);
4753 }
4754
4755 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4756 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4757 }
4758
4759 self.with_label_rib(RibKind::Normal, |this| {
4760 let ident = label.ident.normalize_to_macro_rules();
4761 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4762 f(this);
4763 });
4764 } else {
4765 f(self);
4766 }
4767 }
4768
4769 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4770 self.with_resolved_label(label, id, |this| this.visit_block(block));
4771 }
4772
4773 fn resolve_block(&mut self, block: &'ast Block) {
4774 debug!("(resolving block) entering block");
4775 let orig_module = self.parent_scope.module;
4777 let anonymous_module = self.r.block_map.get(&block.id).copied();
4778
4779 let mut num_macro_definition_ribs = 0;
4780 if let Some(anonymous_module) = anonymous_module {
4781 debug!("(resolving block) found anonymous module, moving down");
4782 self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4783 self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4784 self.parent_scope.module = anonymous_module;
4785 } else {
4786 self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
4787 }
4788
4789 for stmt in &block.stmts {
4791 if let StmtKind::Item(ref item) = stmt.kind
4792 && let ItemKind::MacroDef(..) = item.kind
4793 {
4794 num_macro_definition_ribs += 1;
4795 let res = self.r.local_def_id(item.id).to_def_id();
4796 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4797 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4798 }
4799
4800 self.visit_stmt(stmt);
4801 }
4802
4803 self.parent_scope.module = orig_module;
4805 for _ in 0..num_macro_definition_ribs {
4806 self.ribs[ValueNS].pop();
4807 self.label_ribs.pop();
4808 }
4809 self.last_block_rib = self.ribs[ValueNS].pop();
4810 if anonymous_module.is_some() {
4811 self.ribs[TypeNS].pop();
4812 }
4813 debug!("(resolving block) leaving block");
4814 }
4815
4816 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4817 debug!(
4818 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4819 constant, anon_const_kind
4820 );
4821
4822 let is_trivial_const_arg = constant
4823 .value
4824 .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4825 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4826 this.resolve_expr(&constant.value, None)
4827 })
4828 }
4829
4830 fn resolve_anon_const_manual(
4837 &mut self,
4838 is_trivial_const_arg: bool,
4839 anon_const_kind: AnonConstKind,
4840 resolve_expr: impl FnOnce(&mut Self),
4841 ) {
4842 let is_repeat_expr = match anon_const_kind {
4843 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4844 _ => IsRepeatExpr::No,
4845 };
4846
4847 let may_use_generics = match anon_const_kind {
4848 AnonConstKind::EnumDiscriminant => {
4849 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4850 }
4851 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4852 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4853 AnonConstKind::ConstArg(_) => {
4854 if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4855 ConstantHasGenerics::Yes
4856 } else {
4857 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4858 }
4859 }
4860 };
4861
4862 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4863 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4864 resolve_expr(this);
4865 });
4866 });
4867 }
4868
4869 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4870 self.resolve_expr(&f.expr, Some(e));
4871 self.visit_ident(&f.ident);
4872 walk_list!(self, visit_attribute, f.attrs.iter());
4873 }
4874
4875 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4876 self.record_candidate_traits_for_expr_if_necessary(expr);
4880
4881 match expr.kind {
4883 ExprKind::Path(ref qself, ref path) => {
4884 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4885 visit::walk_expr(self, expr);
4886 }
4887
4888 ExprKind::Struct(ref se) => {
4889 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
4890 if let Some(qself) = &se.qself {
4894 self.visit_ty(&qself.ty);
4895 }
4896 self.visit_path(&se.path);
4897 walk_list!(self, resolve_expr_field, &se.fields, expr);
4898 match &se.rest {
4899 StructRest::Base(expr) => self.visit_expr(expr),
4900 StructRest::Rest(_span) => {}
4901 StructRest::None => {}
4902 }
4903 }
4904
4905 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4906 match self.resolve_label(label.ident) {
4907 Ok((node_id, _)) => {
4908 self.r.label_res_map.insert(expr.id, node_id);
4910 self.diag_metadata.unused_labels.swap_remove(&node_id);
4911 }
4912 Err(error) => {
4913 self.report_error(label.ident.span, error);
4914 }
4915 }
4916
4917 visit::walk_expr(self, expr);
4919 }
4920
4921 ExprKind::Break(None, Some(ref e)) => {
4922 self.resolve_expr(e, Some(expr));
4925 }
4926
4927 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
4928 self.visit_expr(scrutinee);
4929 self.resolve_pattern_top(pat, PatternSource::Let);
4930 }
4931
4932 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
4933 self.visit_expr(scrutinee);
4934 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4936 self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
4937 for (_, bindings) in &mut bindings {
4942 for (_, binding) in bindings {
4943 *binding = Res::Err;
4944 }
4945 }
4946 self.apply_pattern_bindings(bindings);
4947 }
4948
4949 ExprKind::If(ref cond, ref then, ref opt_else) => {
4950 self.with_rib(ValueNS, RibKind::Normal, |this| {
4951 let old = this.diag_metadata.in_if_condition.replace(cond);
4952 this.visit_expr(cond);
4953 this.diag_metadata.in_if_condition = old;
4954 this.visit_block(then);
4955 });
4956 if let Some(expr) = opt_else {
4957 self.visit_expr(expr);
4958 }
4959 }
4960
4961 ExprKind::Loop(ref block, label, _) => {
4962 self.resolve_labeled_block(label, expr.id, block)
4963 }
4964
4965 ExprKind::While(ref cond, ref block, label) => {
4966 self.with_resolved_label(label, expr.id, |this| {
4967 this.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(block);
4972 })
4973 });
4974 }
4975
4976 ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4977 self.visit_expr(iter);
4978 self.with_rib(ValueNS, RibKind::Normal, |this| {
4979 this.resolve_pattern_top(pat, PatternSource::For);
4980 this.resolve_labeled_block(label, expr.id, body);
4981 });
4982 }
4983
4984 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4985
4986 ExprKind::Field(ref subexpression, _) => {
4988 self.resolve_expr(subexpression, Some(expr));
4989 }
4990 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
4991 self.resolve_expr(receiver, Some(expr));
4992 for arg in args {
4993 self.resolve_expr(arg, None);
4994 }
4995 self.visit_path_segment(seg);
4996 }
4997
4998 ExprKind::Call(ref callee, ref arguments) => {
4999 self.resolve_expr(callee, Some(expr));
5000 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5001 for (idx, argument) in arguments.iter().enumerate() {
5002 if const_args.contains(&idx) {
5005 let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
5006 self.r.tcx.features().min_generic_const_args(),
5007 );
5008 self.resolve_anon_const_manual(
5009 is_trivial_const_arg,
5010 AnonConstKind::ConstArg(IsRepeatExpr::No),
5011 |this| this.resolve_expr(argument, None),
5012 );
5013 } else {
5014 self.resolve_expr(argument, None);
5015 }
5016 }
5017 }
5018 ExprKind::Type(ref _type_expr, ref _ty) => {
5019 visit::walk_expr(self, expr);
5020 }
5021 ExprKind::Closure(box ast::Closure {
5023 binder: ClosureBinder::For { ref generic_params, span },
5024 ..
5025 }) => {
5026 self.with_generic_param_rib(
5027 generic_params,
5028 RibKind::Normal,
5029 expr.id,
5030 LifetimeBinderKind::Closure,
5031 span,
5032 |this| visit::walk_expr(this, expr),
5033 );
5034 }
5035 ExprKind::Closure(..) => visit::walk_expr(self, expr),
5036 ExprKind::Gen(..) => {
5037 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5038 }
5039 ExprKind::Repeat(ref elem, ref ct) => {
5040 self.visit_expr(elem);
5041 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5042 }
5043 ExprKind::ConstBlock(ref ct) => {
5044 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5045 }
5046 ExprKind::Index(ref elem, ref idx, _) => {
5047 self.resolve_expr(elem, Some(expr));
5048 self.visit_expr(idx);
5049 }
5050 ExprKind::Assign(ref lhs, ref rhs, _) => {
5051 if !self.diag_metadata.is_assign_rhs {
5052 self.diag_metadata.in_assignment = Some(expr);
5053 }
5054 self.visit_expr(lhs);
5055 self.diag_metadata.is_assign_rhs = true;
5056 self.diag_metadata.in_assignment = None;
5057 self.visit_expr(rhs);
5058 self.diag_metadata.is_assign_rhs = false;
5059 }
5060 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5061 self.diag_metadata.in_range = Some((start, end));
5062 self.resolve_expr(start, Some(expr));
5063 self.resolve_expr(end, Some(expr));
5064 self.diag_metadata.in_range = None;
5065 }
5066 _ => {
5067 visit::walk_expr(self, expr);
5068 }
5069 }
5070 }
5071
5072 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5073 match expr.kind {
5074 ExprKind::Field(_, ident) => {
5075 let traits = self.traits_in_scope(ident, ValueNS);
5080 self.r.trait_map.insert(expr.id, traits);
5081 }
5082 ExprKind::MethodCall(ref call) => {
5083 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
5084 let traits = self.traits_in_scope(call.seg.ident, ValueNS);
5085 self.r.trait_map.insert(expr.id, traits);
5086 }
5087 _ => {
5088 }
5090 }
5091 }
5092
5093 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
5094 self.r.traits_in_scope(
5095 self.current_trait_ref.as_ref().map(|(module, _)| *module),
5096 &self.parent_scope,
5097 ident.span.ctxt(),
5098 Some((ident.name, ns)),
5099 )
5100 }
5101
5102 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5103 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5107 let res = *doc_link_resolutions
5108 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5109 .or_default()
5110 .entry((Symbol::intern(path_str), ns))
5111 .or_insert_with_key(|(path, ns)| {
5112 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5113 if let Some(res) = res
5114 && let Some(def_id) = res.opt_def_id()
5115 && self.is_invalid_proc_macro_item_for_doc(def_id)
5116 {
5117 return None;
5120 }
5121 res
5122 });
5123 self.r.doc_link_resolutions = doc_link_resolutions;
5124 res
5125 }
5126
5127 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5128 if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5129 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5130 {
5131 return false;
5132 }
5133 let Some(local_did) = did.as_local() else { return true };
5134 !self.r.proc_macros.contains(&local_did)
5135 }
5136
5137 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5138 match self.r.tcx.sess.opts.resolve_doc_links {
5139 ResolveDocLinks::None => return,
5140 ResolveDocLinks::ExportedMetadata
5141 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5142 || !maybe_exported.eval(self.r) =>
5143 {
5144 return;
5145 }
5146 ResolveDocLinks::Exported
5147 if !maybe_exported.eval(self.r)
5148 && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5149 {
5150 return;
5151 }
5152 ResolveDocLinks::ExportedMetadata
5153 | ResolveDocLinks::Exported
5154 | ResolveDocLinks::All => {}
5155 }
5156
5157 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5158 return;
5159 }
5160
5161 let mut need_traits_in_scope = false;
5162 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5163 let mut any_resolved = false;
5165 let mut need_assoc = false;
5166 for ns in [TypeNS, ValueNS, MacroNS] {
5167 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5168 any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5171 } else if ns != MacroNS {
5172 need_assoc = true;
5173 }
5174 }
5175
5176 if need_assoc || !any_resolved {
5178 let mut path = &path_str[..];
5179 while let Some(idx) = path.rfind("::") {
5180 path = &path[..idx];
5181 need_traits_in_scope = true;
5182 for ns in [TypeNS, ValueNS, MacroNS] {
5183 self.resolve_and_cache_rustdoc_path(path, ns);
5184 }
5185 }
5186 }
5187 }
5188
5189 if need_traits_in_scope {
5190 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5192 doc_link_traits_in_scope
5193 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5194 .or_insert_with(|| {
5195 self.r
5196 .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5197 .into_iter()
5198 .filter_map(|tr| {
5199 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5200 return None;
5203 }
5204 Some(tr.def_id)
5205 })
5206 .collect()
5207 });
5208 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5209 }
5210 }
5211
5212 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5213 if let Some(seg) = path.first()
5215 && seg.ident.name == kw::PathRoot
5216 {
5217 return;
5218 }
5219
5220 if finalize.path_span.from_expansion()
5221 || path.iter().any(|seg| seg.ident.span.from_expansion())
5222 {
5223 return;
5224 }
5225
5226 let end_pos =
5227 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5228 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5229 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5238 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5239 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5240 (res == binding.res()).then_some((seg, binding))
5241 });
5242
5243 if let Some((seg, binding)) = unqualified {
5244 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5245 binding,
5246 node_id: finalize.node_id,
5247 path_span: finalize.path_span,
5248 removal_span: path[0].ident.span.until(seg.ident.span),
5249 });
5250 }
5251 }
5252
5253 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5254 if let Some(define_opaque) = define_opaque {
5255 for (id, path) in define_opaque {
5256 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5257 }
5258 }
5259 }
5260}
5261
5262struct ItemInfoCollector<'a, 'ra, 'tcx> {
5265 r: &'a mut Resolver<'ra, 'tcx>,
5266}
5267
5268impl ItemInfoCollector<'_, '_, '_> {
5269 fn collect_fn_info(
5270 &mut self,
5271 header: FnHeader,
5272 decl: &FnDecl,
5273 id: NodeId,
5274 attrs: &[Attribute],
5275 ) {
5276 let sig = DelegationFnSig {
5277 header,
5278 param_count: decl.inputs.len(),
5279 has_self: decl.has_self(),
5280 c_variadic: decl.c_variadic(),
5281 target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5282 };
5283 self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5284 }
5285}
5286
5287impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5288 fn visit_item(&mut self, item: &'ast Item) {
5289 match &item.kind {
5290 ItemKind::TyAlias(box TyAlias { generics, .. })
5291 | ItemKind::Const(box ConstItem { generics, .. })
5292 | ItemKind::Fn(box Fn { generics, .. })
5293 | ItemKind::Enum(_, generics, _)
5294 | ItemKind::Struct(_, generics, _)
5295 | ItemKind::Union(_, generics, _)
5296 | ItemKind::Impl(Impl { generics, .. })
5297 | ItemKind::Trait(box Trait { generics, .. })
5298 | ItemKind::TraitAlias(box TraitAlias { generics, .. }) => {
5299 if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5300 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5301 }
5302
5303 let def_id = self.r.local_def_id(item.id);
5304 let count = generics
5305 .params
5306 .iter()
5307 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5308 .count();
5309 self.r.item_generics_num_lifetimes.insert(def_id, count);
5310 }
5311
5312 ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5313 for foreign_item in items {
5314 if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5315 let new_header =
5316 FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5317 self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5318 }
5319 }
5320 }
5321
5322 ItemKind::Mod(..)
5323 | ItemKind::Static(..)
5324 | ItemKind::Use(..)
5325 | ItemKind::ExternCrate(..)
5326 | ItemKind::MacroDef(..)
5327 | ItemKind::GlobalAsm(..)
5328 | ItemKind::MacCall(..)
5329 | ItemKind::DelegationMac(..) => {}
5330 ItemKind::Delegation(..) => {
5331 }
5336 }
5337 visit::walk_item(self, item)
5338 }
5339
5340 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5341 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5342 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5343 }
5344 visit::walk_assoc_item(self, item, ctxt);
5345 }
5346}
5347
5348impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5349 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5350 visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5351 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5352 late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5353 visit::walk_crate(&mut late_resolution_visitor, krate);
5354 for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5355 self.lint_buffer.buffer_lint(
5356 lint::builtin::UNUSED_LABELS,
5357 *id,
5358 *span,
5359 errors::UnusedLabel,
5360 );
5361 }
5362 }
5363}
5364
5365fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5367 let mut path = expected_path.iter().rev();
5368 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5369 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5370 return false;
5371 }
5372 def_id = parent;
5373 }
5374 true
5375}