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