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>, _: &AttrVec, 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_static_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 rhs,
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(rhs) = rhs {
2866 this.resolve_const_item_rhs(
2867 rhs,
2868 Some((ident, ConstantItemKind::Const)),
2869 );
2870 }
2871 },
2872 );
2873 self.resolve_define_opaques(define_opaque);
2874 }
2875
2876 ItemKind::Use(ref use_tree) => {
2877 let maybe_exported = match use_tree.kind {
2878 UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2879 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2880 };
2881 self.resolve_doc_links(&item.attrs, maybe_exported);
2882
2883 self.future_proof_import(use_tree);
2884 }
2885
2886 ItemKind::MacroDef(_, ref macro_def) => {
2887 if macro_def.macro_rules {
2890 let def_id = self.r.local_def_id(item.id);
2891 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2892 }
2893 }
2894
2895 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2896 visit::walk_item(self, item);
2897 }
2898
2899 ItemKind::Delegation(ref delegation) => {
2900 let span = delegation.path.segments.last().unwrap().ident.span;
2901 self.with_generic_param_rib(
2902 &[],
2903 RibKind::Item(HasGenericParams::Yes(span), def_kind),
2904 item.id,
2905 LifetimeBinderKind::Function,
2906 span,
2907 |this| this.resolve_delegation(delegation),
2908 );
2909 }
2910
2911 ItemKind::ExternCrate(..) => {}
2912
2913 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2914 panic!("unexpanded macro in resolve!")
2915 }
2916 }
2917 }
2918
2919 fn with_generic_param_rib<F>(
2920 &mut self,
2921 params: &[GenericParam],
2922 kind: RibKind<'ra>,
2923 binder: NodeId,
2924 generics_kind: LifetimeBinderKind,
2925 generics_span: Span,
2926 f: F,
2927 ) where
2928 F: FnOnce(&mut Self),
2929 {
2930 debug!("with_generic_param_rib");
2931 let lifetime_kind =
2932 LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
2933
2934 let mut function_type_rib = Rib::new(kind);
2935 let mut function_value_rib = Rib::new(kind);
2936 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2937
2938 if !params.is_empty() {
2940 let mut seen_bindings = FxHashMap::default();
2941 let mut seen_lifetimes = FxHashSet::default();
2943
2944 for ns in [ValueNS, TypeNS] {
2946 for parent_rib in self.ribs[ns].iter().rev() {
2947 if matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
2950 break;
2951 }
2952
2953 seen_bindings
2954 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2955 }
2956 }
2957
2958 for rib in self.lifetime_ribs.iter().rev() {
2960 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2961 if let LifetimeRibKind::Item = rib.kind {
2962 break;
2963 }
2964 }
2965
2966 for param in params {
2967 let ident = param.ident.normalize_to_macros_2_0();
2968 debug!("with_generic_param_rib: {}", param.id);
2969
2970 if let GenericParamKind::Lifetime = param.kind
2971 && let Some(&original) = seen_lifetimes.get(&ident)
2972 {
2973 diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
2974 self.record_lifetime_param(param.id, LifetimeRes::Error);
2976 continue;
2977 }
2978
2979 match seen_bindings.entry(ident) {
2980 Entry::Occupied(entry) => {
2981 let span = *entry.get();
2982 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
2983 self.report_error(param.ident.span, err);
2984 let rib = match param.kind {
2985 GenericParamKind::Lifetime => {
2986 self.record_lifetime_param(param.id, LifetimeRes::Error);
2988 continue;
2989 }
2990 GenericParamKind::Type { .. } => &mut function_type_rib,
2991 GenericParamKind::Const { .. } => &mut function_value_rib,
2992 };
2993
2994 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
2996 rib.bindings.insert(ident, Res::Err);
2997 continue;
2998 }
2999 Entry::Vacant(entry) => {
3000 entry.insert(param.ident.span);
3001 }
3002 }
3003
3004 if param.ident.name == kw::UnderscoreLifetime {
3005 let is_raw_underscore_lifetime = self
3008 .r
3009 .tcx
3010 .sess
3011 .psess
3012 .raw_identifier_spans
3013 .iter()
3014 .any(|span| span == param.span());
3015
3016 self.r
3017 .dcx()
3018 .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
3019 .emit_unless_delay(is_raw_underscore_lifetime);
3020 self.record_lifetime_param(param.id, LifetimeRes::Error);
3022 continue;
3023 }
3024
3025 if param.ident.name == kw::StaticLifetime {
3026 self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
3027 span: param.ident.span,
3028 lifetime: param.ident,
3029 });
3030 self.record_lifetime_param(param.id, LifetimeRes::Error);
3032 continue;
3033 }
3034
3035 let def_id = self.r.local_def_id(param.id);
3036
3037 let (rib, def_kind) = match param.kind {
3039 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3040 GenericParamKind::Const { .. } => {
3041 (&mut function_value_rib, DefKind::ConstParam)
3042 }
3043 GenericParamKind::Lifetime => {
3044 let res = LifetimeRes::Param { param: def_id, binder };
3045 self.record_lifetime_param(param.id, res);
3046 function_lifetime_rib.bindings.insert(ident, (param.id, res));
3047 continue;
3048 }
3049 };
3050
3051 let res = match kind {
3052 RibKind::Item(..) | RibKind::AssocItem => {
3053 Res::Def(def_kind, def_id.to_def_id())
3054 }
3055 RibKind::Normal => {
3056 if self.r.tcx.features().non_lifetime_binders()
3059 && matches!(param.kind, GenericParamKind::Type { .. })
3060 {
3061 Res::Def(def_kind, def_id.to_def_id())
3062 } else {
3063 Res::Err
3064 }
3065 }
3066 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
3067 };
3068 self.r.record_partial_res(param.id, PartialRes::new(res));
3069 rib.bindings.insert(ident, res);
3070 }
3071 }
3072
3073 self.lifetime_ribs.push(function_lifetime_rib);
3074 self.ribs[ValueNS].push(function_value_rib);
3075 self.ribs[TypeNS].push(function_type_rib);
3076
3077 f(self);
3078
3079 self.ribs[TypeNS].pop();
3080 self.ribs[ValueNS].pop();
3081 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3082
3083 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3085 for (_, res) in function_lifetime_rib.bindings.values() {
3086 candidates.retain(|(r, _)| r != res);
3087 }
3088 }
3089
3090 if let LifetimeBinderKind::FnPtrType
3091 | LifetimeBinderKind::WhereBound
3092 | LifetimeBinderKind::Function
3093 | LifetimeBinderKind::ImplBlock = generics_kind
3094 {
3095 self.maybe_report_lifetime_uses(generics_span, params)
3096 }
3097 }
3098
3099 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3100 self.label_ribs.push(Rib::new(kind));
3101 f(self);
3102 self.label_ribs.pop();
3103 }
3104
3105 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3106 let kind = RibKind::Item(HasGenericParams::No, def_kind);
3107 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3108 }
3109
3110 #[instrument(level = "debug", skip(self, f))]
3119 fn with_constant_rib(
3120 &mut self,
3121 is_repeat: IsRepeatExpr,
3122 may_use_generics: ConstantHasGenerics,
3123 item: Option<(Ident, ConstantItemKind)>,
3124 f: impl FnOnce(&mut Self),
3125 ) {
3126 let f = |this: &mut Self| {
3127 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3128 this.with_rib(
3129 TypeNS,
3130 RibKind::ConstantItem(
3131 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3132 item,
3133 ),
3134 |this| {
3135 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3136 },
3137 )
3138 })
3139 };
3140
3141 if let ConstantHasGenerics::No(cause) = may_use_generics {
3142 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3143 } else {
3144 f(self)
3145 }
3146 }
3147
3148 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3149 let previous_value =
3151 replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3152 let result = f(self);
3153 self.diag_metadata.current_self_type = previous_value;
3154 result
3155 }
3156
3157 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3158 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3159 let result = f(self);
3160 self.diag_metadata.current_self_item = previous_value;
3161 result
3162 }
3163
3164 fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3166 let trait_assoc_items =
3167 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3168
3169 let walk_assoc_item =
3170 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3171 this.with_generic_param_rib(
3172 &generics.params,
3173 RibKind::AssocItem,
3174 item.id,
3175 kind,
3176 generics.span,
3177 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3178 );
3179 };
3180
3181 for item in trait_items {
3182 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3183 match &item.kind {
3184 AssocItemKind::Const(box ast::ConstItem {
3185 generics,
3186 ty,
3187 rhs,
3188 define_opaque,
3189 ..
3190 }) => {
3191 self.with_generic_param_rib(
3192 &generics.params,
3193 RibKind::AssocItem,
3194 item.id,
3195 LifetimeBinderKind::ConstItem,
3196 generics.span,
3197 |this| {
3198 this.with_lifetime_rib(
3199 LifetimeRibKind::StaticIfNoLifetimeInScope {
3200 lint_id: item.id,
3201 emit_lint: false,
3202 },
3203 |this| {
3204 this.visit_generics(generics);
3205 this.visit_ty(ty);
3206
3207 if let Some(rhs) = rhs {
3210 this.resolve_const_item_rhs(rhs, None);
3216 }
3217 },
3218 )
3219 },
3220 );
3221
3222 self.resolve_define_opaques(define_opaque);
3223 }
3224 AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3225 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3226
3227 self.resolve_define_opaques(define_opaque);
3228 }
3229 AssocItemKind::Delegation(delegation) => {
3230 self.with_generic_param_rib(
3231 &[],
3232 RibKind::AssocItem,
3233 item.id,
3234 LifetimeBinderKind::Function,
3235 delegation.path.segments.last().unwrap().ident.span,
3236 |this| this.resolve_delegation(delegation),
3237 );
3238 }
3239 AssocItemKind::Type(box TyAlias { generics, .. }) => self
3240 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3241 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3242 }),
3243 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3244 panic!("unexpanded macro in resolve!")
3245 }
3246 };
3247 }
3248
3249 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3250 }
3251
3252 fn with_optional_trait_ref<T>(
3254 &mut self,
3255 opt_trait_ref: Option<&TraitRef>,
3256 self_type: &'ast Ty,
3257 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3258 ) -> T {
3259 let mut new_val = None;
3260 let mut new_id = None;
3261 if let Some(trait_ref) = opt_trait_ref {
3262 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3263 self.diag_metadata.currently_processing_impl_trait =
3264 Some((trait_ref.clone(), self_type.clone()));
3265 let res = self.smart_resolve_path_fragment(
3266 &None,
3267 &path,
3268 PathSource::Trait(AliasPossibility::No),
3269 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3270 RecordPartialRes::Yes,
3271 None,
3272 );
3273 self.diag_metadata.currently_processing_impl_trait = None;
3274 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3275 new_id = Some(def_id);
3276 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3277 }
3278 }
3279 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3280 let result = f(self, new_id);
3281 self.current_trait_ref = original_trait_ref;
3282 result
3283 }
3284
3285 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3286 let mut self_type_rib = Rib::new(RibKind::Normal);
3287
3288 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3290 self.ribs[ns].push(self_type_rib);
3291 f(self);
3292 self.ribs[ns].pop();
3293 }
3294
3295 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3296 self.with_self_rib_ns(TypeNS, self_res, f)
3297 }
3298
3299 fn resolve_implementation(
3300 &mut self,
3301 attrs: &[ast::Attribute],
3302 generics: &'ast Generics,
3303 of_trait: Option<&'ast ast::TraitImplHeader>,
3304 self_type: &'ast Ty,
3305 item_id: NodeId,
3306 impl_items: &'ast [Box<AssocItem>],
3307 ) {
3308 debug!("resolve_implementation");
3309 self.with_generic_param_rib(
3311 &generics.params,
3312 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3313 item_id,
3314 LifetimeBinderKind::ImplBlock,
3315 generics.span,
3316 |this| {
3317 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3319 this.with_lifetime_rib(
3320 LifetimeRibKind::AnonymousCreateParameter {
3321 binder: item_id,
3322 report_in_path: true
3323 },
3324 |this| {
3325 this.with_optional_trait_ref(
3327 of_trait.map(|t| &t.trait_ref),
3328 self_type,
3329 |this, trait_id| {
3330 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3331
3332 let item_def_id = this.r.local_def_id(item_id);
3333
3334 if let Some(trait_id) = trait_id {
3336 this.r
3337 .trait_impls
3338 .entry(trait_id)
3339 .or_default()
3340 .push(item_def_id);
3341 }
3342
3343 let item_def_id = item_def_id.to_def_id();
3344 let res = Res::SelfTyAlias {
3345 alias_to: item_def_id,
3346 forbid_generic: false,
3347 is_trait_impl: trait_id.is_some()
3348 };
3349 this.with_self_rib(res, |this| {
3350 if let Some(of_trait) = of_trait {
3351 visit::walk_trait_ref(this, &of_trait.trait_ref);
3353 }
3354 this.visit_ty(self_type);
3356 this.visit_generics(generics);
3358
3359 this.with_current_self_type(self_type, |this| {
3361 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3362 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3363 let mut seen_trait_items = Default::default();
3364 for item in impl_items {
3365 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3366 }
3367 });
3368 });
3369 });
3370 },
3371 )
3372 },
3373 );
3374 });
3375 },
3376 );
3377 }
3378
3379 fn resolve_impl_item(
3380 &mut self,
3381 item: &'ast AssocItem,
3382 seen_trait_items: &mut FxHashMap<DefId, Span>,
3383 trait_id: Option<DefId>,
3384 ) {
3385 use crate::ResolutionError::*;
3386 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3387 let prev = self.diag_metadata.current_impl_item.take();
3388 self.diag_metadata.current_impl_item = Some(&item);
3389 match &item.kind {
3390 AssocItemKind::Const(box ast::ConstItem {
3391 ident,
3392 generics,
3393 ty,
3394 rhs,
3395 define_opaque,
3396 ..
3397 }) => {
3398 debug!("resolve_implementation AssocItemKind::Const");
3399 self.with_generic_param_rib(
3400 &generics.params,
3401 RibKind::AssocItem,
3402 item.id,
3403 LifetimeBinderKind::ConstItem,
3404 generics.span,
3405 |this| {
3406 this.with_lifetime_rib(
3407 LifetimeRibKind::AnonymousCreateParameter {
3411 binder: item.id,
3412 report_in_path: true,
3413 },
3414 |this| {
3415 this.with_lifetime_rib(
3416 LifetimeRibKind::StaticIfNoLifetimeInScope {
3417 lint_id: item.id,
3418 emit_lint: true,
3420 },
3421 |this| {
3422 this.check_trait_item(
3425 item.id,
3426 *ident,
3427 &item.kind,
3428 ValueNS,
3429 item.span,
3430 seen_trait_items,
3431 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3432 );
3433
3434 this.visit_generics(generics);
3435 this.visit_ty(ty);
3436 if let Some(rhs) = rhs {
3437 this.resolve_const_item_rhs(rhs, None);
3443 }
3444 },
3445 )
3446 },
3447 );
3448 },
3449 );
3450 self.resolve_define_opaques(define_opaque);
3451 }
3452 AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3453 debug!("resolve_implementation AssocItemKind::Fn");
3454 self.with_generic_param_rib(
3456 &generics.params,
3457 RibKind::AssocItem,
3458 item.id,
3459 LifetimeBinderKind::Function,
3460 generics.span,
3461 |this| {
3462 this.check_trait_item(
3465 item.id,
3466 *ident,
3467 &item.kind,
3468 ValueNS,
3469 item.span,
3470 seen_trait_items,
3471 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3472 );
3473
3474 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3475 },
3476 );
3477
3478 self.resolve_define_opaques(define_opaque);
3479 }
3480 AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3481 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3482 debug!("resolve_implementation AssocItemKind::Type");
3483 self.with_generic_param_rib(
3485 &generics.params,
3486 RibKind::AssocItem,
3487 item.id,
3488 LifetimeBinderKind::ImplAssocType,
3489 generics.span,
3490 |this| {
3491 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3492 this.check_trait_item(
3495 item.id,
3496 *ident,
3497 &item.kind,
3498 TypeNS,
3499 item.span,
3500 seen_trait_items,
3501 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3502 );
3503
3504 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3505 });
3506 },
3507 );
3508 self.diag_metadata.in_non_gat_assoc_type = None;
3509 }
3510 AssocItemKind::Delegation(box delegation) => {
3511 debug!("resolve_implementation AssocItemKind::Delegation");
3512 self.with_generic_param_rib(
3513 &[],
3514 RibKind::AssocItem,
3515 item.id,
3516 LifetimeBinderKind::Function,
3517 delegation.path.segments.last().unwrap().ident.span,
3518 |this| {
3519 this.check_trait_item(
3520 item.id,
3521 delegation.ident,
3522 &item.kind,
3523 ValueNS,
3524 item.span,
3525 seen_trait_items,
3526 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3527 );
3528
3529 this.resolve_delegation(delegation)
3530 },
3531 );
3532 }
3533 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3534 panic!("unexpanded macro in resolve!")
3535 }
3536 }
3537 self.diag_metadata.current_impl_item = prev;
3538 }
3539
3540 fn check_trait_item<F>(
3541 &mut self,
3542 id: NodeId,
3543 mut ident: Ident,
3544 kind: &AssocItemKind,
3545 ns: Namespace,
3546 span: Span,
3547 seen_trait_items: &mut FxHashMap<DefId, Span>,
3548 err: F,
3549 ) where
3550 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3551 {
3552 let Some((module, _)) = self.current_trait_ref else {
3554 return;
3555 };
3556 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3557 let key = BindingKey::new(ident, ns);
3558 let mut binding = self.r.resolution(module, key).and_then(|r| r.best_binding());
3559 debug!(?binding);
3560 if binding.is_none() {
3561 let ns = match ns {
3564 ValueNS => TypeNS,
3565 TypeNS => ValueNS,
3566 _ => ns,
3567 };
3568 let key = BindingKey::new(ident, ns);
3569 binding = self.r.resolution(module, key).and_then(|r| r.best_binding());
3570 debug!(?binding);
3571 }
3572
3573 let feed_visibility = |this: &mut Self, def_id| {
3574 let vis = this.r.tcx.visibility(def_id);
3575 let vis = if vis.is_visible_locally() {
3576 vis.expect_local()
3577 } else {
3578 this.r.dcx().span_delayed_bug(
3579 span,
3580 "error should be emitted when an unexpected trait item is used",
3581 );
3582 Visibility::Public
3583 };
3584 this.r.feed_visibility(this.r.feed(id), vis);
3585 };
3586
3587 let Some(binding) = binding else {
3588 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3590 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3591 let path_names = path_names_to_string(path);
3592 self.report_error(span, err(ident, path_names, candidate));
3593 feed_visibility(self, module.def_id());
3594 return;
3595 };
3596
3597 let res = binding.res();
3598 let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3599 feed_visibility(self, id_in_trait);
3600
3601 match seen_trait_items.entry(id_in_trait) {
3602 Entry::Occupied(entry) => {
3603 self.report_error(
3604 span,
3605 ResolutionError::TraitImplDuplicate {
3606 name: ident,
3607 old_span: *entry.get(),
3608 trait_item_span: binding.span,
3609 },
3610 );
3611 return;
3612 }
3613 Entry::Vacant(entry) => {
3614 entry.insert(span);
3615 }
3616 };
3617
3618 match (def_kind, kind) {
3619 (DefKind::AssocTy, AssocItemKind::Type(..))
3620 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3621 | (DefKind::AssocConst, AssocItemKind::Const(..))
3622 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3623 self.r.record_partial_res(id, PartialRes::new(res));
3624 return;
3625 }
3626 _ => {}
3627 }
3628
3629 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3631 let (code, kind) = match kind {
3632 AssocItemKind::Const(..) => (E0323, "const"),
3633 AssocItemKind::Fn(..) => (E0324, "method"),
3634 AssocItemKind::Type(..) => (E0325, "type"),
3635 AssocItemKind::Delegation(..) => (E0324, "method"),
3636 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3637 span_bug!(span, "unexpanded macro")
3638 }
3639 };
3640 let trait_path = path_names_to_string(path);
3641 self.report_error(
3642 span,
3643 ResolutionError::TraitImplMismatch {
3644 name: ident,
3645 kind,
3646 code,
3647 trait_path,
3648 trait_item_span: binding.span,
3649 },
3650 );
3651 }
3652
3653 fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3654 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3655 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3656 this.visit_expr(expr)
3657 });
3658 })
3659 }
3660
3661 fn resolve_const_item_rhs(
3662 &mut self,
3663 rhs: &'ast ConstItemRhs,
3664 item: Option<(Ident, ConstantItemKind)>,
3665 ) {
3666 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| match rhs {
3667 ConstItemRhs::TypeConst(anon_const) => {
3668 this.resolve_anon_const(anon_const, AnonConstKind::ConstArg(IsRepeatExpr::No));
3669 }
3670 ConstItemRhs::Body(expr) => {
3671 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3672 this.visit_expr(expr)
3673 });
3674 }
3675 })
3676 }
3677
3678 fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3679 self.smart_resolve_path(
3680 delegation.id,
3681 &delegation.qself,
3682 &delegation.path,
3683 PathSource::Delegation,
3684 );
3685 if let Some(qself) = &delegation.qself {
3686 self.visit_ty(&qself.ty);
3687 }
3688 self.visit_path(&delegation.path);
3689 let Some(body) = &delegation.body else { return };
3690 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3691 let span = delegation.path.segments.last().unwrap().ident.span;
3692 let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3693 let res = Res::Local(delegation.id);
3694 this.innermost_rib_bindings(ValueNS).insert(ident, res);
3695 this.visit_block(body);
3696 });
3697 }
3698
3699 fn resolve_params(&mut self, params: &'ast [Param]) {
3700 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3701 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3702 for Param { pat, .. } in params {
3703 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3704 }
3705 this.apply_pattern_bindings(bindings);
3706 });
3707 for Param { ty, .. } in params {
3708 self.visit_ty(ty);
3709 }
3710 }
3711
3712 fn resolve_local(&mut self, local: &'ast Local) {
3713 debug!("resolving local ({:?})", local);
3714 visit_opt!(self, visit_ty, &local.ty);
3716
3717 if let Some((init, els)) = local.kind.init_else_opt() {
3719 self.visit_expr(init);
3720
3721 if let Some(els) = els {
3723 self.visit_block(els);
3724 }
3725 }
3726
3727 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3729 }
3730
3731 fn compute_and_check_binding_map(
3751 &mut self,
3752 pat: &Pat,
3753 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3754 let mut binding_map = FxIndexMap::default();
3755 let mut is_never_pat = false;
3756
3757 pat.walk(&mut |pat| {
3758 match pat.kind {
3759 PatKind::Ident(annotation, ident, ref sub_pat)
3760 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3761 {
3762 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3763 }
3764 PatKind::Or(ref ps) => {
3765 match self.compute_and_check_or_pat_binding_map(ps) {
3768 Ok(bm) => binding_map.extend(bm),
3769 Err(IsNeverPattern) => is_never_pat = true,
3770 }
3771 return false;
3772 }
3773 PatKind::Never => is_never_pat = true,
3774 _ => {}
3775 }
3776
3777 true
3778 });
3779
3780 if is_never_pat {
3781 for (_, binding) in binding_map {
3782 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3783 }
3784 Err(IsNeverPattern)
3785 } else {
3786 Ok(binding_map)
3787 }
3788 }
3789
3790 fn is_base_res_local(&self, nid: NodeId) -> bool {
3791 matches!(
3792 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3793 Some(Res::Local(..))
3794 )
3795 }
3796
3797 fn compute_and_check_or_pat_binding_map(
3817 &mut self,
3818 pats: &[Pat],
3819 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3820 let mut missing_vars = FxIndexMap::default();
3821 let mut inconsistent_vars = FxIndexMap::default();
3822
3823 let not_never_pats = pats
3825 .iter()
3826 .filter_map(|pat| {
3827 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3828 Some((binding_map, pat))
3829 })
3830 .collect::<Vec<_>>();
3831
3832 for &(ref map_outer, pat_outer) in not_never_pats.iter() {
3834 let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
3836
3837 for &(ref map, pat) in inners {
3838 for (&name, binding_inner) in map {
3839 match map_outer.get(&name) {
3840 None => {
3841 let binding_error =
3843 missing_vars.entry(name).or_insert_with(|| BindingError {
3844 name,
3845 origin: Default::default(),
3846 target: Default::default(),
3847 could_be_path: name.as_str().starts_with(char::is_uppercase),
3848 });
3849 binding_error.origin.push((binding_inner.span, pat.clone()));
3850 binding_error.target.push(pat_outer.clone());
3851 }
3852 Some(binding_outer) => {
3853 if binding_outer.annotation != binding_inner.annotation {
3854 inconsistent_vars
3856 .entry(name)
3857 .or_insert((binding_inner.span, binding_outer.span));
3858 }
3859 }
3860 }
3861 }
3862 }
3863 }
3864
3865 for (name, mut v) in missing_vars {
3867 if inconsistent_vars.contains_key(&name) {
3868 v.could_be_path = false;
3869 }
3870 self.report_error(
3871 v.origin.iter().next().unwrap().0,
3872 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3873 );
3874 }
3875
3876 for (name, v) in inconsistent_vars {
3878 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3879 }
3880
3881 if not_never_pats.is_empty() {
3883 Err(IsNeverPattern)
3885 } else {
3886 let mut binding_map = FxIndexMap::default();
3887 for (bm, _) in not_never_pats {
3888 binding_map.extend(bm);
3889 }
3890 Ok(binding_map)
3891 }
3892 }
3893
3894 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3896 let mut is_or_or_never = false;
3897 pat.walk(&mut |pat| match pat.kind {
3898 PatKind::Or(..) | PatKind::Never => {
3899 is_or_or_never = true;
3900 false
3901 }
3902 _ => true,
3903 });
3904 if is_or_or_never {
3905 let _ = self.compute_and_check_binding_map(pat);
3906 }
3907 }
3908
3909 fn resolve_arm(&mut self, arm: &'ast Arm) {
3910 self.with_rib(ValueNS, RibKind::Normal, |this| {
3911 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3912 visit_opt!(this, visit_expr, &arm.guard);
3913 visit_opt!(this, visit_expr, &arm.body);
3914 });
3915 }
3916
3917 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3919 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3920 self.resolve_pattern(pat, pat_src, &mut bindings);
3921 self.apply_pattern_bindings(bindings);
3922 }
3923
3924 fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3926 let rib_bindings = self.innermost_rib_bindings(ValueNS);
3927 let Some((_, pat_bindings)) = pat_bindings.pop() else {
3928 bug!("tried applying nonexistent bindings from pattern");
3929 };
3930
3931 if rib_bindings.is_empty() {
3932 *rib_bindings = pat_bindings;
3935 } else {
3936 rib_bindings.extend(pat_bindings);
3937 }
3938 }
3939
3940 fn resolve_pattern(
3943 &mut self,
3944 pat: &'ast Pat,
3945 pat_src: PatternSource,
3946 bindings: &mut PatternBindings,
3947 ) {
3948 self.visit_pat(pat);
3954 self.resolve_pattern_inner(pat, pat_src, bindings);
3955 self.check_consistent_bindings(pat);
3957 }
3958
3959 #[tracing::instrument(skip(self, bindings), level = "debug")]
3979 fn resolve_pattern_inner(
3980 &mut self,
3981 pat: &'ast Pat,
3982 pat_src: PatternSource,
3983 bindings: &mut PatternBindings,
3984 ) {
3985 pat.walk(&mut |pat| {
3987 match pat.kind {
3988 PatKind::Ident(bmode, ident, ref sub) => {
3989 let has_sub = sub.is_some();
3992 let res = self
3993 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3994 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3995 self.r.record_partial_res(pat.id, PartialRes::new(res));
3996 self.r.record_pat_span(pat.id, pat.span);
3997 }
3998 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3999 self.smart_resolve_path(
4000 pat.id,
4001 qself,
4002 path,
4003 PathSource::TupleStruct(
4004 pat.span,
4005 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4006 ),
4007 );
4008 }
4009 PatKind::Path(ref qself, ref path) => {
4010 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4011 }
4012 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4013 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4014 self.record_patterns_with_skipped_bindings(pat, rest);
4015 }
4016 PatKind::Or(ref ps) => {
4017 bindings.push((PatBoundCtx::Or, Default::default()));
4021 for p in ps {
4022 bindings.push((PatBoundCtx::Product, Default::default()));
4026 self.resolve_pattern_inner(p, pat_src, bindings);
4027 let collected = bindings.pop().unwrap().1;
4030 bindings.last_mut().unwrap().1.extend(collected);
4031 }
4032 let collected = bindings.pop().unwrap().1;
4036 bindings.last_mut().unwrap().1.extend(collected);
4037
4038 return false;
4040 }
4041 PatKind::Guard(ref subpat, ref guard) => {
4042 bindings.push((PatBoundCtx::Product, Default::default()));
4044 let binding_ctx_stack_len = bindings.len();
4047 self.resolve_pattern_inner(subpat, pat_src, bindings);
4048 assert_eq!(bindings.len(), binding_ctx_stack_len);
4049 let subpat_bindings = bindings.pop().unwrap().1;
4052 self.with_rib(ValueNS, RibKind::Normal, |this| {
4053 *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4054 this.resolve_expr(guard, None);
4055 });
4056 bindings.last_mut().unwrap().1.extend(subpat_bindings);
4063 return false;
4065 }
4066 _ => {}
4067 }
4068 true
4069 });
4070 }
4071
4072 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4073 match rest {
4074 ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4075 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4077 && let Some(res) = partial_res.full_res()
4078 && let Some(def_id) = res.opt_def_id()
4079 {
4080 self.ribs[ValueNS]
4081 .last_mut()
4082 .unwrap()
4083 .patterns_with_skipped_bindings
4084 .entry(def_id)
4085 .or_default()
4086 .push((
4087 pat.span,
4088 match rest {
4089 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4090 _ => Ok(()),
4091 },
4092 ));
4093 }
4094 }
4095 ast::PatFieldsRest::None => {}
4096 }
4097 }
4098
4099 fn fresh_binding(
4100 &mut self,
4101 ident: Ident,
4102 pat_id: NodeId,
4103 pat_src: PatternSource,
4104 bindings: &mut PatternBindings,
4105 ) -> Res {
4106 let ident = ident.normalize_to_macro_rules();
4110
4111 let already_bound_and = bindings
4113 .iter()
4114 .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4115 if already_bound_and {
4116 use ResolutionError::*;
4118 let error = match pat_src {
4119 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4121 _ => IdentifierBoundMoreThanOnceInSamePattern,
4123 };
4124 self.report_error(ident.span, error(ident));
4125 }
4126
4127 let already_bound_or = bindings
4130 .iter()
4131 .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4132 let res = if let Some(&res) = already_bound_or {
4133 res
4136 } else {
4137 Res::Local(pat_id)
4139 };
4140
4141 bindings.last_mut().unwrap().1.insert(ident, res);
4143 res
4144 }
4145
4146 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4147 &mut self.ribs[ns].last_mut().unwrap().bindings
4148 }
4149
4150 fn try_resolve_as_non_binding(
4151 &mut self,
4152 pat_src: PatternSource,
4153 ann: BindingMode,
4154 ident: Ident,
4155 has_sub: bool,
4156 ) -> Option<Res> {
4157 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4161
4162 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4163 let (res, binding) = match ls_binding {
4164 LexicalScopeBinding::Item(binding)
4165 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4166 {
4167 self.r.record_use(ident, binding, Used::Other);
4172 return None;
4173 }
4174 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4175 LexicalScopeBinding::Res(res) => (res, None),
4176 };
4177
4178 match res {
4179 Res::SelfCtor(_) | Res::Def(
4181 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4182 _,
4183 ) if is_syntactic_ambiguity => {
4184 if let Some(binding) = binding {
4186 self.r.record_use(ident, binding, Used::Other);
4187 }
4188 Some(res)
4189 }
4190 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4191 let binding = binding.expect("no binding for a ctor or static");
4197 self.report_error(
4198 ident.span,
4199 ResolutionError::BindingShadowsSomethingUnacceptable {
4200 shadowing_binding: pat_src,
4201 name: ident.name,
4202 participle: if binding.is_import() { "imported" } else { "defined" },
4203 article: binding.res().article(),
4204 shadowed_binding: binding.res(),
4205 shadowed_binding_span: binding.span,
4206 },
4207 );
4208 None
4209 }
4210 Res::Def(DefKind::ConstParam, def_id) => {
4211 self.report_error(
4214 ident.span,
4215 ResolutionError::BindingShadowsSomethingUnacceptable {
4216 shadowing_binding: pat_src,
4217 name: ident.name,
4218 participle: "defined",
4219 article: res.article(),
4220 shadowed_binding: res,
4221 shadowed_binding_span: self.r.def_span(def_id),
4222 }
4223 );
4224 None
4225 }
4226 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4227 None
4229 }
4230 Res::SelfCtor(_) => {
4231 self.r.dcx().span_delayed_bug(
4234 ident.span,
4235 "unexpected `SelfCtor` in pattern, expected identifier"
4236 );
4237 None
4238 }
4239 _ => span_bug!(
4240 ident.span,
4241 "unexpected resolution for an identifier in pattern: {:?}",
4242 res,
4243 ),
4244 }
4245 }
4246
4247 fn smart_resolve_path(
4253 &mut self,
4254 id: NodeId,
4255 qself: &Option<Box<QSelf>>,
4256 path: &Path,
4257 source: PathSource<'_, 'ast, 'ra>,
4258 ) {
4259 self.smart_resolve_path_fragment(
4260 qself,
4261 &Segment::from_path(path),
4262 source,
4263 Finalize::new(id, path.span),
4264 RecordPartialRes::Yes,
4265 None,
4266 );
4267 }
4268
4269 #[instrument(level = "debug", skip(self))]
4270 fn smart_resolve_path_fragment(
4271 &mut self,
4272 qself: &Option<Box<QSelf>>,
4273 path: &[Segment],
4274 source: PathSource<'_, 'ast, 'ra>,
4275 finalize: Finalize,
4276 record_partial_res: RecordPartialRes,
4277 parent_qself: Option<&QSelf>,
4278 ) -> PartialRes {
4279 let ns = source.namespace();
4280
4281 let Finalize { node_id, path_span, .. } = finalize;
4282 let report_errors = |this: &mut Self, res: Option<Res>| {
4283 if this.should_report_errs() {
4284 let (err, candidates) = this.smart_resolve_report_errors(
4285 path,
4286 None,
4287 path_span,
4288 source,
4289 res,
4290 parent_qself,
4291 );
4292
4293 let def_id = this.parent_scope.module.nearest_parent_mod();
4294 let instead = res.is_some();
4295 let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4296 && path[0].ident.span.lo() == end.span.lo()
4297 && !matches!(start.kind, ExprKind::Lit(_))
4298 {
4299 let mut sugg = ".";
4300 let mut span = start.span.between(end.span);
4301 if span.lo() + BytePos(2) == span.hi() {
4302 span = span.with_lo(span.lo() + BytePos(1));
4305 sugg = "";
4306 }
4307 Some((
4308 span,
4309 "you might have meant to write `.` instead of `..`",
4310 sugg.to_string(),
4311 Applicability::MaybeIncorrect,
4312 ))
4313 } else if res.is_none()
4314 && let PathSource::Type
4315 | PathSource::Expr(_)
4316 | PathSource::PreciseCapturingArg(..) = source
4317 {
4318 this.suggest_adding_generic_parameter(path, source)
4319 } else {
4320 None
4321 };
4322
4323 let ue = UseError {
4324 err,
4325 candidates,
4326 def_id,
4327 instead,
4328 suggestion,
4329 path: path.into(),
4330 is_call: source.is_call(),
4331 };
4332
4333 this.r.use_injections.push(ue);
4334 }
4335
4336 PartialRes::new(Res::Err)
4337 };
4338
4339 let report_errors_for_call =
4345 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4346 let (following_seg, prefix_path) = match path.split_last() {
4350 Some((last, path)) if !path.is_empty() => (Some(last), path),
4351 _ => return Some(parent_err),
4352 };
4353
4354 let (mut err, candidates) = this.smart_resolve_report_errors(
4355 prefix_path,
4356 following_seg,
4357 path_span,
4358 PathSource::Type,
4359 None,
4360 parent_qself,
4361 );
4362
4363 let failed_to_resolve = match parent_err.node {
4378 ResolutionError::FailedToResolve { .. } => true,
4379 _ => false,
4380 };
4381 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4382
4383 err.messages = take(&mut parent_err.messages);
4385 err.code = take(&mut parent_err.code);
4386 swap(&mut err.span, &mut parent_err.span);
4387 if failed_to_resolve {
4388 err.children = take(&mut parent_err.children);
4389 } else {
4390 err.children.append(&mut parent_err.children);
4391 }
4392 err.sort_span = parent_err.sort_span;
4393 err.is_lint = parent_err.is_lint.clone();
4394
4395 match &mut err.suggestions {
4397 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4398 Suggestions::Enabled(parent_suggestions) => {
4399 typo_suggestions.append(parent_suggestions)
4401 }
4402 Suggestions::Sealed(_) | Suggestions::Disabled => {
4403 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4408 }
4409 },
4410 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4411 }
4412
4413 parent_err.cancel();
4414
4415 let def_id = this.parent_scope.module.nearest_parent_mod();
4416
4417 if this.should_report_errs() {
4418 if candidates.is_empty() {
4419 if path.len() == 2
4420 && let [segment] = prefix_path
4421 {
4422 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4428 } else {
4429 err.emit();
4434 }
4435 } else {
4436 this.r.use_injections.push(UseError {
4438 err,
4439 candidates,
4440 def_id,
4441 instead: false,
4442 suggestion: None,
4443 path: prefix_path.into(),
4444 is_call: source.is_call(),
4445 });
4446 }
4447 } else {
4448 err.cancel();
4449 }
4450
4451 None
4454 };
4455
4456 let partial_res = match self.resolve_qpath_anywhere(
4457 qself,
4458 path,
4459 ns,
4460 source.defer_to_typeck(),
4461 finalize,
4462 source,
4463 ) {
4464 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4465 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4467 && let [Segment { ident, .. }] = path
4468 && items.iter().any(|item| {
4469 if let AssocItemKind::Type(alias) = &item.kind
4470 && alias.ident == *ident
4471 {
4472 true
4473 } else {
4474 false
4475 }
4476 })
4477 {
4478 let mut diag = self.r.tcx.dcx().struct_allow("");
4479 diag.span_suggestion_verbose(
4480 path_span.shrink_to_lo(),
4481 "there is an associated type with the same name",
4482 "Self::",
4483 Applicability::MaybeIncorrect,
4484 );
4485 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4486 }
4487
4488 if source.is_expected(res) || res == Res::Err {
4489 partial_res
4490 } else {
4491 report_errors(self, Some(res))
4492 }
4493 }
4494
4495 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4496 if ns == ValueNS {
4500 let item_name = path.last().unwrap().ident;
4501 let traits = self.traits_in_scope(item_name, ns);
4502 self.r.trait_map.insert(node_id, traits);
4503 }
4504
4505 if PrimTy::from_name(path[0].ident.name).is_some() {
4506 let mut std_path = Vec::with_capacity(1 + path.len());
4507
4508 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4509 std_path.extend(path);
4510 if let PathResult::Module(_) | PathResult::NonModule(_) =
4511 self.resolve_path(&std_path, Some(ns), None, source)
4512 {
4513 let item_span =
4515 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4516
4517 self.r.confused_type_with_std_module.insert(item_span, path_span);
4518 self.r.confused_type_with_std_module.insert(path_span, path_span);
4519 }
4520 }
4521
4522 partial_res
4523 }
4524
4525 Err(err) => {
4526 if let Some(err) = report_errors_for_call(self, err) {
4527 self.report_error(err.span, err.node);
4528 }
4529
4530 PartialRes::new(Res::Err)
4531 }
4532
4533 _ => report_errors(self, None),
4534 };
4535
4536 if record_partial_res == RecordPartialRes::Yes {
4537 self.r.record_partial_res(node_id, partial_res);
4539 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4540 self.lint_unused_qualifications(path, ns, finalize);
4541 }
4542
4543 partial_res
4544 }
4545
4546 fn self_type_is_available(&mut self) -> bool {
4547 let binding = self
4548 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4549 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4550 }
4551
4552 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4553 let ident = Ident::new(kw::SelfLower, self_span);
4554 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4555 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4556 }
4557
4558 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4562 if self.should_report_errs() {
4563 self.r.report_error(span, resolution_error);
4564 }
4565 }
4566
4567 #[inline]
4568 fn should_report_errs(&self) -> bool {
4572 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4573 && !self.r.glob_error.is_some()
4574 }
4575
4576 fn resolve_qpath_anywhere(
4578 &mut self,
4579 qself: &Option<Box<QSelf>>,
4580 path: &[Segment],
4581 primary_ns: Namespace,
4582 defer_to_typeck: bool,
4583 finalize: Finalize,
4584 source: PathSource<'_, 'ast, 'ra>,
4585 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4586 let mut fin_res = None;
4587
4588 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4589 if i == 0 || ns != primary_ns {
4590 match self.resolve_qpath(qself, path, ns, finalize, source)? {
4591 Some(partial_res)
4592 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4593 {
4594 return Ok(Some(partial_res));
4595 }
4596 partial_res => {
4597 if fin_res.is_none() {
4598 fin_res = partial_res;
4599 }
4600 }
4601 }
4602 }
4603 }
4604
4605 assert!(primary_ns != MacroNS);
4606 if qself.is_none()
4607 && let PathResult::NonModule(res) =
4608 self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4609 {
4610 return Ok(Some(res));
4611 }
4612
4613 Ok(fin_res)
4614 }
4615
4616 fn resolve_qpath(
4618 &mut self,
4619 qself: &Option<Box<QSelf>>,
4620 path: &[Segment],
4621 ns: Namespace,
4622 finalize: Finalize,
4623 source: PathSource<'_, 'ast, 'ra>,
4624 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4625 debug!(
4626 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4627 qself, path, ns, finalize,
4628 );
4629
4630 if let Some(qself) = qself {
4631 if qself.position == 0 {
4632 return Ok(Some(PartialRes::with_unresolved_segments(
4636 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4637 path.len(),
4638 )));
4639 }
4640
4641 let num_privacy_errors = self.r.privacy_errors.len();
4642 let trait_res = self.smart_resolve_path_fragment(
4644 &None,
4645 &path[..qself.position],
4646 PathSource::Trait(AliasPossibility::No),
4647 Finalize::new(finalize.node_id, qself.path_span),
4648 RecordPartialRes::No,
4649 Some(&qself),
4650 );
4651
4652 if trait_res.expect_full_res() == Res::Err {
4653 return Ok(Some(trait_res));
4654 }
4655
4656 self.r.privacy_errors.truncate(num_privacy_errors);
4659
4660 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4668 let partial_res = self.smart_resolve_path_fragment(
4669 &None,
4670 &path[..=qself.position],
4671 PathSource::TraitItem(ns, &source),
4672 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4673 RecordPartialRes::No,
4674 Some(&qself),
4675 );
4676
4677 return Ok(Some(PartialRes::with_unresolved_segments(
4681 partial_res.base_res(),
4682 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4683 )));
4684 }
4685
4686 let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4687 PathResult::NonModule(path_res) => path_res,
4688 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4689 PartialRes::new(module.res().unwrap())
4690 }
4691 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4695 PartialRes::new(Res::Err)
4696 }
4697 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4710 if (ns == TypeNS || path.len() > 1)
4711 && PrimTy::from_name(path[0].ident.name).is_some() =>
4712 {
4713 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4714 let tcx = self.r.tcx();
4715
4716 let gate_err_sym_msg = match prim {
4717 PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4718 Some((sym::f16, "the type `f16` is unstable"))
4719 }
4720 PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4721 Some((sym::f128, "the type `f128` is unstable"))
4722 }
4723 _ => None,
4724 };
4725
4726 if let Some((sym, msg)) = gate_err_sym_msg {
4727 let span = path[0].ident.span;
4728 if !span.allows_unstable(sym) {
4729 feature_err(tcx.sess, sym, span, msg).emit();
4730 }
4731 };
4732
4733 if let Some(id) = path[0].id {
4735 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4736 }
4737
4738 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4739 }
4740 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4741 PartialRes::new(module.res().unwrap())
4742 }
4743 PathResult::Failed {
4744 is_error_from_last_segment: false,
4745 span,
4746 label,
4747 suggestion,
4748 module,
4749 segment_name,
4750 error_implied_by_parse_error: _,
4751 } => {
4752 return Err(respan(
4753 span,
4754 ResolutionError::FailedToResolve {
4755 segment: Some(segment_name),
4756 label,
4757 suggestion,
4758 module,
4759 },
4760 ));
4761 }
4762 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4763 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4764 };
4765
4766 Ok(Some(result))
4767 }
4768
4769 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4770 if let Some(label) = label {
4771 if label.ident.as_str().as_bytes()[1] != b'_' {
4772 self.diag_metadata.unused_labels.insert(id, label.ident.span);
4773 }
4774
4775 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4776 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4777 }
4778
4779 self.with_label_rib(RibKind::Normal, |this| {
4780 let ident = label.ident.normalize_to_macro_rules();
4781 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4782 f(this);
4783 });
4784 } else {
4785 f(self);
4786 }
4787 }
4788
4789 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4790 self.with_resolved_label(label, id, |this| this.visit_block(block));
4791 }
4792
4793 fn resolve_block(&mut self, block: &'ast Block) {
4794 debug!("(resolving block) entering block");
4795 let orig_module = self.parent_scope.module;
4797 let anonymous_module = self.r.block_map.get(&block.id).copied();
4798
4799 let mut num_macro_definition_ribs = 0;
4800 if let Some(anonymous_module) = anonymous_module {
4801 debug!("(resolving block) found anonymous module, moving down");
4802 self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4803 self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4804 self.parent_scope.module = anonymous_module;
4805 } else {
4806 self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
4807 }
4808
4809 for stmt in &block.stmts {
4811 if let StmtKind::Item(ref item) = stmt.kind
4812 && let ItemKind::MacroDef(..) = item.kind
4813 {
4814 num_macro_definition_ribs += 1;
4815 let res = self.r.local_def_id(item.id).to_def_id();
4816 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4817 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4818 }
4819
4820 self.visit_stmt(stmt);
4821 }
4822
4823 self.parent_scope.module = orig_module;
4825 for _ in 0..num_macro_definition_ribs {
4826 self.ribs[ValueNS].pop();
4827 self.label_ribs.pop();
4828 }
4829 self.last_block_rib = self.ribs[ValueNS].pop();
4830 if anonymous_module.is_some() {
4831 self.ribs[TypeNS].pop();
4832 }
4833 debug!("(resolving block) leaving block");
4834 }
4835
4836 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4837 debug!(
4838 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4839 constant, anon_const_kind
4840 );
4841
4842 let is_trivial_const_arg = constant
4843 .value
4844 .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4845 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4846 this.resolve_expr(&constant.value, None)
4847 })
4848 }
4849
4850 fn resolve_anon_const_manual(
4857 &mut self,
4858 is_trivial_const_arg: bool,
4859 anon_const_kind: AnonConstKind,
4860 resolve_expr: impl FnOnce(&mut Self),
4861 ) {
4862 let is_repeat_expr = match anon_const_kind {
4863 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4864 _ => IsRepeatExpr::No,
4865 };
4866
4867 let may_use_generics = match anon_const_kind {
4868 AnonConstKind::EnumDiscriminant => {
4869 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4870 }
4871 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4872 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4873 AnonConstKind::ConstArg(_) => {
4874 if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4875 ConstantHasGenerics::Yes
4876 } else {
4877 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4878 }
4879 }
4880 };
4881
4882 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4883 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4884 resolve_expr(this);
4885 });
4886 });
4887 }
4888
4889 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4890 self.resolve_expr(&f.expr, Some(e));
4891 self.visit_ident(&f.ident);
4892 walk_list!(self, visit_attribute, f.attrs.iter());
4893 }
4894
4895 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4896 self.record_candidate_traits_for_expr_if_necessary(expr);
4900
4901 match expr.kind {
4903 ExprKind::Path(ref qself, ref path) => {
4904 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4905 visit::walk_expr(self, expr);
4906 }
4907
4908 ExprKind::Struct(ref se) => {
4909 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
4910 if let Some(qself) = &se.qself {
4914 self.visit_ty(&qself.ty);
4915 }
4916 self.visit_path(&se.path);
4917 walk_list!(self, resolve_expr_field, &se.fields, expr);
4918 match &se.rest {
4919 StructRest::Base(expr) => self.visit_expr(expr),
4920 StructRest::Rest(_span) => {}
4921 StructRest::None => {}
4922 }
4923 }
4924
4925 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4926 match self.resolve_label(label.ident) {
4927 Ok((node_id, _)) => {
4928 self.r.label_res_map.insert(expr.id, node_id);
4930 self.diag_metadata.unused_labels.swap_remove(&node_id);
4931 }
4932 Err(error) => {
4933 self.report_error(label.ident.span, error);
4934 }
4935 }
4936
4937 visit::walk_expr(self, expr);
4939 }
4940
4941 ExprKind::Break(None, Some(ref e)) => {
4942 self.resolve_expr(e, Some(expr));
4945 }
4946
4947 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
4948 self.visit_expr(scrutinee);
4949 self.resolve_pattern_top(pat, PatternSource::Let);
4950 }
4951
4952 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
4953 self.visit_expr(scrutinee);
4954 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4956 self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
4957 for (_, bindings) in &mut bindings {
4962 for (_, binding) in bindings {
4963 *binding = Res::Err;
4964 }
4965 }
4966 self.apply_pattern_bindings(bindings);
4967 }
4968
4969 ExprKind::If(ref cond, ref then, ref opt_else) => {
4970 self.with_rib(ValueNS, RibKind::Normal, |this| {
4971 let old = this.diag_metadata.in_if_condition.replace(cond);
4972 this.visit_expr(cond);
4973 this.diag_metadata.in_if_condition = old;
4974 this.visit_block(then);
4975 });
4976 if let Some(expr) = opt_else {
4977 self.visit_expr(expr);
4978 }
4979 }
4980
4981 ExprKind::Loop(ref block, label, _) => {
4982 self.resolve_labeled_block(label, expr.id, block)
4983 }
4984
4985 ExprKind::While(ref cond, ref block, label) => {
4986 self.with_resolved_label(label, expr.id, |this| {
4987 this.with_rib(ValueNS, RibKind::Normal, |this| {
4988 let old = this.diag_metadata.in_if_condition.replace(cond);
4989 this.visit_expr(cond);
4990 this.diag_metadata.in_if_condition = old;
4991 this.visit_block(block);
4992 })
4993 });
4994 }
4995
4996 ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4997 self.visit_expr(iter);
4998 self.with_rib(ValueNS, RibKind::Normal, |this| {
4999 this.resolve_pattern_top(pat, PatternSource::For);
5000 this.resolve_labeled_block(label, expr.id, body);
5001 });
5002 }
5003
5004 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5005
5006 ExprKind::Field(ref subexpression, _) => {
5008 self.resolve_expr(subexpression, Some(expr));
5009 }
5010 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
5011 self.resolve_expr(receiver, Some(expr));
5012 for arg in args {
5013 self.resolve_expr(arg, None);
5014 }
5015 self.visit_path_segment(seg);
5016 }
5017
5018 ExprKind::Call(ref callee, ref arguments) => {
5019 self.resolve_expr(callee, Some(expr));
5020 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5021 for (idx, argument) in arguments.iter().enumerate() {
5022 if const_args.contains(&idx) {
5025 let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
5026 self.r.tcx.features().min_generic_const_args(),
5027 );
5028 self.resolve_anon_const_manual(
5029 is_trivial_const_arg,
5030 AnonConstKind::ConstArg(IsRepeatExpr::No),
5031 |this| this.resolve_expr(argument, None),
5032 );
5033 } else {
5034 self.resolve_expr(argument, None);
5035 }
5036 }
5037 }
5038 ExprKind::Type(ref _type_expr, ref _ty) => {
5039 visit::walk_expr(self, expr);
5040 }
5041 ExprKind::Closure(box ast::Closure {
5043 binder: ClosureBinder::For { ref generic_params, span },
5044 ..
5045 }) => {
5046 self.with_generic_param_rib(
5047 generic_params,
5048 RibKind::Normal,
5049 expr.id,
5050 LifetimeBinderKind::Closure,
5051 span,
5052 |this| visit::walk_expr(this, expr),
5053 );
5054 }
5055 ExprKind::Closure(..) => visit::walk_expr(self, expr),
5056 ExprKind::Gen(..) => {
5057 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5058 }
5059 ExprKind::Repeat(ref elem, ref ct) => {
5060 self.visit_expr(elem);
5061 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5062 }
5063 ExprKind::ConstBlock(ref ct) => {
5064 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5065 }
5066 ExprKind::Index(ref elem, ref idx, _) => {
5067 self.resolve_expr(elem, Some(expr));
5068 self.visit_expr(idx);
5069 }
5070 ExprKind::Assign(ref lhs, ref rhs, _) => {
5071 if !self.diag_metadata.is_assign_rhs {
5072 self.diag_metadata.in_assignment = Some(expr);
5073 }
5074 self.visit_expr(lhs);
5075 self.diag_metadata.is_assign_rhs = true;
5076 self.diag_metadata.in_assignment = None;
5077 self.visit_expr(rhs);
5078 self.diag_metadata.is_assign_rhs = false;
5079 }
5080 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5081 self.diag_metadata.in_range = Some((start, end));
5082 self.resolve_expr(start, Some(expr));
5083 self.resolve_expr(end, Some(expr));
5084 self.diag_metadata.in_range = None;
5085 }
5086 _ => {
5087 visit::walk_expr(self, expr);
5088 }
5089 }
5090 }
5091
5092 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5093 match expr.kind {
5094 ExprKind::Field(_, ident) => {
5095 let traits = self.traits_in_scope(ident, ValueNS);
5100 self.r.trait_map.insert(expr.id, traits);
5101 }
5102 ExprKind::MethodCall(ref call) => {
5103 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
5104 let traits = self.traits_in_scope(call.seg.ident, ValueNS);
5105 self.r.trait_map.insert(expr.id, traits);
5106 }
5107 _ => {
5108 }
5110 }
5111 }
5112
5113 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
5114 self.r.traits_in_scope(
5115 self.current_trait_ref.as_ref().map(|(module, _)| *module),
5116 &self.parent_scope,
5117 ident.span.ctxt(),
5118 Some((ident.name, ns)),
5119 )
5120 }
5121
5122 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5123 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5127 let res = *doc_link_resolutions
5128 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5129 .or_default()
5130 .entry((Symbol::intern(path_str), ns))
5131 .or_insert_with_key(|(path, ns)| {
5132 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5133 if let Some(res) = res
5134 && let Some(def_id) = res.opt_def_id()
5135 && self.is_invalid_proc_macro_item_for_doc(def_id)
5136 {
5137 return None;
5140 }
5141 res
5142 });
5143 self.r.doc_link_resolutions = doc_link_resolutions;
5144 res
5145 }
5146
5147 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5148 if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5149 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5150 {
5151 return false;
5152 }
5153 let Some(local_did) = did.as_local() else { return true };
5154 !self.r.proc_macros.contains(&local_did)
5155 }
5156
5157 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5158 match self.r.tcx.sess.opts.resolve_doc_links {
5159 ResolveDocLinks::None => return,
5160 ResolveDocLinks::ExportedMetadata
5161 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5162 || !maybe_exported.eval(self.r) =>
5163 {
5164 return;
5165 }
5166 ResolveDocLinks::Exported
5167 if !maybe_exported.eval(self.r)
5168 && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5169 {
5170 return;
5171 }
5172 ResolveDocLinks::ExportedMetadata
5173 | ResolveDocLinks::Exported
5174 | ResolveDocLinks::All => {}
5175 }
5176
5177 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5178 return;
5179 }
5180
5181 let mut need_traits_in_scope = false;
5182 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5183 let mut any_resolved = false;
5185 let mut need_assoc = false;
5186 for ns in [TypeNS, ValueNS, MacroNS] {
5187 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5188 any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5191 } else if ns != MacroNS {
5192 need_assoc = true;
5193 }
5194 }
5195
5196 if need_assoc || !any_resolved {
5198 let mut path = &path_str[..];
5199 while let Some(idx) = path.rfind("::") {
5200 path = &path[..idx];
5201 need_traits_in_scope = true;
5202 for ns in [TypeNS, ValueNS, MacroNS] {
5203 self.resolve_and_cache_rustdoc_path(path, ns);
5204 }
5205 }
5206 }
5207 }
5208
5209 if need_traits_in_scope {
5210 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5212 doc_link_traits_in_scope
5213 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5214 .or_insert_with(|| {
5215 self.r
5216 .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5217 .into_iter()
5218 .filter_map(|tr| {
5219 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5220 return None;
5223 }
5224 Some(tr.def_id)
5225 })
5226 .collect()
5227 });
5228 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5229 }
5230 }
5231
5232 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5233 if let Some(seg) = path.first()
5235 && seg.ident.name == kw::PathRoot
5236 {
5237 return;
5238 }
5239
5240 if finalize.path_span.from_expansion()
5241 || path.iter().any(|seg| seg.ident.span.from_expansion())
5242 {
5243 return;
5244 }
5245
5246 let end_pos =
5247 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5248 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5249 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5258 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5259 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5260 (res == binding.res()).then_some((seg, binding))
5261 });
5262
5263 if let Some((seg, binding)) = unqualified {
5264 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5265 binding,
5266 node_id: finalize.node_id,
5267 path_span: finalize.path_span,
5268 removal_span: path[0].ident.span.until(seg.ident.span),
5269 });
5270 }
5271 }
5272
5273 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5274 if let Some(define_opaque) = define_opaque {
5275 for (id, path) in define_opaque {
5276 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5277 }
5278 }
5279 }
5280}
5281
5282struct ItemInfoCollector<'a, 'ra, 'tcx> {
5285 r: &'a mut Resolver<'ra, 'tcx>,
5286}
5287
5288impl ItemInfoCollector<'_, '_, '_> {
5289 fn collect_fn_info(
5290 &mut self,
5291 header: FnHeader,
5292 decl: &FnDecl,
5293 id: NodeId,
5294 attrs: &[Attribute],
5295 ) {
5296 let sig = DelegationFnSig {
5297 header,
5298 param_count: decl.inputs.len(),
5299 has_self: decl.has_self(),
5300 c_variadic: decl.c_variadic(),
5301 target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5302 };
5303 self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5304 }
5305}
5306
5307impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5308 fn visit_item(&mut self, item: &'ast Item) {
5309 match &item.kind {
5310 ItemKind::TyAlias(box TyAlias { generics, .. })
5311 | ItemKind::Const(box ConstItem { generics, .. })
5312 | ItemKind::Fn(box Fn { generics, .. })
5313 | ItemKind::Enum(_, generics, _)
5314 | ItemKind::Struct(_, generics, _)
5315 | ItemKind::Union(_, generics, _)
5316 | ItemKind::Impl(Impl { generics, .. })
5317 | ItemKind::Trait(box Trait { generics, .. })
5318 | ItemKind::TraitAlias(box TraitAlias { generics, .. }) => {
5319 if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5320 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5321 }
5322
5323 let def_id = self.r.local_def_id(item.id);
5324 let count = generics
5325 .params
5326 .iter()
5327 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5328 .count();
5329 self.r.item_generics_num_lifetimes.insert(def_id, count);
5330 }
5331
5332 ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5333 for foreign_item in items {
5334 if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5335 let new_header =
5336 FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5337 self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5338 }
5339 }
5340 }
5341
5342 ItemKind::Mod(..)
5343 | ItemKind::Static(..)
5344 | ItemKind::Use(..)
5345 | ItemKind::ExternCrate(..)
5346 | ItemKind::MacroDef(..)
5347 | ItemKind::GlobalAsm(..)
5348 | ItemKind::MacCall(..)
5349 | ItemKind::DelegationMac(..) => {}
5350 ItemKind::Delegation(..) => {
5351 }
5356 }
5357 visit::walk_item(self, item)
5358 }
5359
5360 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5361 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5362 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5363 }
5364 visit::walk_assoc_item(self, item, ctxt);
5365 }
5366}
5367
5368impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5369 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5370 visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5371 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5372 late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5373 visit::walk_crate(&mut late_resolution_visitor, krate);
5374 for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5375 self.lint_buffer.buffer_lint(
5376 lint::builtin::UNUSED_LABELS,
5377 *id,
5378 *span,
5379 errors::UnusedLabel,
5380 );
5381 }
5382 }
5383}
5384
5385fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5387 let mut path = expected_path.iter().rev();
5388 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5389 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5390 return false;
5391 }
5392 def_id = parent;
5393 }
5394 true
5395}