1use std::assert_matches::debug_assert_matches;
10use std::borrow::Cow;
11use std::collections::BTreeSet;
12use std::collections::hash_map::Entry;
13use std::mem::{replace, swap, take};
14
15use rustc_ast::ptr::P;
16use rustc_ast::visit::{
17 AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,
18};
19use rustc_ast::*;
20use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
21use rustc_data_structures::unord::{UnordMap, UnordSet};
22use rustc_errors::codes::*;
23use rustc_errors::{
24 Applicability, DiagArgValue, ErrorGuaranteed, IntoDiagArg, StashKey, Suggestions,
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::DelegationFnSig;
32use rustc_middle::{bug, span_bug};
33use rustc_session::config::{CrateType, ResolveDocLinks};
34use rustc_session::lint::{self, BuiltinLintDiag};
35use rustc_session::parse::feature_err;
36use rustc_span::source_map::{Spanned, respan};
37use rustc_span::{BytePos, Ident, Span, Symbol, SyntaxContext, kw, sym};
38use smallvec::{SmallVec, smallvec};
39use thin_vec::ThinVec;
40use tracing::{debug, instrument, trace};
41
42use crate::{
43 BindingError, BindingKey, Finalize, LexicalScopeBinding, Module, ModuleOrUniformRoot,
44 NameBinding, ParentScope, PathResult, ResolutionError, Resolver, Segment, TyCtxt, UseError,
45 Used, errors, path_names_to_string, rustdoc,
46};
47
48mod diagnostics;
49
50type Res = def::Res<NodeId>;
51
52use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
53
54#[derive(Copy, Clone, Debug)]
55struct BindingInfo {
56 span: Span,
57 annotation: BindingMode,
58}
59
60#[derive(Copy, Clone, PartialEq, Eq, Debug)]
61pub(crate) enum PatternSource {
62 Match,
63 Let,
64 For,
65 FnParam,
66}
67
68#[derive(Copy, Clone, Debug, PartialEq, Eq)]
69enum IsRepeatExpr {
70 No,
71 Yes,
72}
73
74struct IsNeverPattern;
75
76#[derive(Copy, Clone, Debug, PartialEq, Eq)]
79enum AnonConstKind {
80 EnumDiscriminant,
81 FieldDefaultValue,
82 InlineConst,
83 ConstArg(IsRepeatExpr),
84}
85
86impl PatternSource {
87 fn descr(self) -> &'static str {
88 match self {
89 PatternSource::Match => "match binding",
90 PatternSource::Let => "let binding",
91 PatternSource::For => "for binding",
92 PatternSource::FnParam => "function parameter",
93 }
94 }
95}
96
97impl IntoDiagArg for PatternSource {
98 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
99 DiagArgValue::Str(Cow::Borrowed(self.descr()))
100 }
101}
102
103#[derive(PartialEq)]
107enum PatBoundCtx {
108 Product,
110 Or,
112}
113
114type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;
126
127#[derive(Copy, Clone, Debug)]
129pub(crate) enum HasGenericParams {
130 Yes(Span),
131 No,
132}
133
134#[derive(Copy, Clone, Debug, Eq, PartialEq)]
136pub(crate) enum ConstantHasGenerics {
137 Yes,
138 No(NoConstantGenericsReason),
139}
140
141impl ConstantHasGenerics {
142 fn force_yes_if(self, b: bool) -> Self {
143 if b { Self::Yes } else { self }
144 }
145}
146
147#[derive(Copy, Clone, Debug, Eq, PartialEq)]
149pub(crate) enum NoConstantGenericsReason {
150 NonTrivialConstArg,
157 IsEnumDiscriminant,
166}
167
168#[derive(Copy, Clone, Debug, Eq, PartialEq)]
169pub(crate) enum ConstantItemKind {
170 Const,
171 Static,
172}
173
174impl ConstantItemKind {
175 pub(crate) fn as_str(&self) -> &'static str {
176 match self {
177 Self::Const => "const",
178 Self::Static => "static",
179 }
180 }
181}
182
183#[derive(Debug, Copy, Clone, PartialEq, Eq)]
184enum RecordPartialRes {
185 Yes,
186 No,
187}
188
189#[derive(Copy, Clone, Debug)]
192pub(crate) enum RibKind<'ra> {
193 Normal,
195
196 AssocItem,
201
202 FnOrCoroutine,
204
205 Item(HasGenericParams, DefKind),
207
208 ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
213
214 Module(Module<'ra>),
216
217 MacroDefinition(DefId),
219
220 ForwardGenericParamBan(ForwardGenericParamBanReason),
224
225 ConstParamTy,
228
229 InlineAsmSym,
232}
233
234#[derive(Copy, Clone, PartialEq, Eq, Debug)]
235pub(crate) enum ForwardGenericParamBanReason {
236 Default,
237 ConstParamTy,
238}
239
240impl RibKind<'_> {
241 pub(crate) fn contains_params(&self) -> bool {
244 match self {
245 RibKind::Normal
246 | RibKind::FnOrCoroutine
247 | RibKind::ConstantItem(..)
248 | RibKind::Module(_)
249 | RibKind::MacroDefinition(_)
250 | RibKind::InlineAsmSym => false,
251 RibKind::ConstParamTy
252 | RibKind::AssocItem
253 | RibKind::Item(..)
254 | RibKind::ForwardGenericParamBan(_) => true,
255 }
256 }
257
258 fn is_label_barrier(self) -> bool {
260 match self {
261 RibKind::Normal | RibKind::MacroDefinition(..) => false,
262
263 RibKind::AssocItem
264 | RibKind::FnOrCoroutine
265 | RibKind::Item(..)
266 | RibKind::ConstantItem(..)
267 | RibKind::Module(..)
268 | RibKind::ForwardGenericParamBan(_)
269 | RibKind::ConstParamTy
270 | RibKind::InlineAsmSym => true,
271 }
272 }
273}
274
275#[derive(Debug)]
288pub(crate) struct Rib<'ra, R = Res> {
289 pub bindings: FxIndexMap<Ident, R>,
290 pub patterns_with_skipped_bindings: UnordMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>,
291 pub kind: RibKind<'ra>,
292}
293
294impl<'ra, R> Rib<'ra, R> {
295 fn new(kind: RibKind<'ra>) -> Rib<'ra, R> {
296 Rib {
297 bindings: Default::default(),
298 patterns_with_skipped_bindings: Default::default(),
299 kind,
300 }
301 }
302}
303
304#[derive(Clone, Copy, Debug)]
305enum LifetimeUseSet {
306 One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
307 Many,
308}
309
310#[derive(Copy, Clone, Debug)]
311enum LifetimeRibKind {
312 Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
317
318 AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
335
336 Elided(LifetimeRes),
338
339 AnonymousReportError,
345
346 StaticIfNoLifetimeInScope { lint_id: NodeId, emit_lint: bool },
350
351 ElisionFailure,
353
354 ConstParamTy,
359
360 ConcreteAnonConst(NoConstantGenericsReason),
366
367 Item,
369}
370
371#[derive(Copy, Clone, Debug)]
372enum LifetimeBinderKind {
373 BareFnType,
374 PolyTrait,
375 WhereBound,
376 Item,
377 ConstItem,
378 Function,
379 Closure,
380 ImplBlock,
381}
382
383impl LifetimeBinderKind {
384 fn descr(self) -> &'static str {
385 use LifetimeBinderKind::*;
386 match self {
387 BareFnType => "type",
388 PolyTrait => "bound",
389 WhereBound => "bound",
390 Item | ConstItem => "item",
391 ImplBlock => "impl block",
392 Function => "function",
393 Closure => "closure",
394 }
395 }
396}
397
398#[derive(Debug)]
399struct LifetimeRib {
400 kind: LifetimeRibKind,
401 bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
403}
404
405impl LifetimeRib {
406 fn new(kind: LifetimeRibKind) -> LifetimeRib {
407 LifetimeRib { bindings: Default::default(), kind }
408 }
409}
410
411#[derive(Copy, Clone, PartialEq, Eq, Debug)]
412pub(crate) enum AliasPossibility {
413 No,
414 Maybe,
415}
416
417#[derive(Copy, Clone, Debug)]
418pub(crate) enum PathSource<'a, 'ast, 'ra> {
419 Type,
421 Trait(AliasPossibility),
423 Expr(Option<&'ast Expr>),
425 Pat,
427 Struct,
429 TupleStruct(Span, &'ra [Span]),
431 TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),
436 Delegation,
438 PreciseCapturingArg(Namespace),
440 ReturnTypeNotation,
442 DefineOpaques,
444}
445
446impl PathSource<'_, '_, '_> {
447 fn namespace(self) -> Namespace {
448 match self {
449 PathSource::Type
450 | PathSource::Trait(_)
451 | PathSource::Struct
452 | PathSource::DefineOpaques => TypeNS,
453 PathSource::Expr(..)
454 | PathSource::Pat
455 | PathSource::TupleStruct(..)
456 | PathSource::Delegation
457 | PathSource::ReturnTypeNotation => ValueNS,
458 PathSource::TraitItem(ns, _) => ns,
459 PathSource::PreciseCapturingArg(ns) => ns,
460 }
461 }
462
463 fn defer_to_typeck(self) -> bool {
464 match self {
465 PathSource::Type
466 | PathSource::Expr(..)
467 | PathSource::Pat
468 | PathSource::Struct
469 | PathSource::TupleStruct(..)
470 | PathSource::ReturnTypeNotation => true,
471 PathSource::Trait(_)
472 | PathSource::TraitItem(..)
473 | PathSource::DefineOpaques
474 | PathSource::Delegation
475 | PathSource::PreciseCapturingArg(..) => false,
476 }
477 }
478
479 fn descr_expected(self) -> &'static str {
480 match &self {
481 PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
482 PathSource::Type => "type",
483 PathSource::Trait(_) => "trait",
484 PathSource::Pat => "unit struct, unit variant or constant",
485 PathSource::Struct => "struct, variant or union type",
486 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
487 | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
488 PathSource::TraitItem(ns, _) => match ns {
489 TypeNS => "associated type",
490 ValueNS => "method or associated constant",
491 MacroNS => bug!("associated macro"),
492 },
493 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
494 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
497 ExprKind::Path(_, path)
499 if let [segment, _] = path.segments.as_slice()
500 && segment.ident.name == kw::PathRoot =>
501 {
502 "external crate"
503 }
504 ExprKind::Path(_, path)
505 if let Some(segment) = path.segments.last()
506 && let Some(c) = segment.ident.to_string().chars().next()
507 && c.is_uppercase() =>
508 {
509 "function, tuple struct or tuple variant"
510 }
511 _ => "function",
512 },
513 _ => "value",
514 },
515 PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
516 PathSource::PreciseCapturingArg(..) => "type or const parameter",
517 }
518 }
519
520 fn is_call(self) -> bool {
521 matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
522 }
523
524 pub(crate) fn is_expected(self, res: Res) -> bool {
525 match self {
526 PathSource::DefineOpaques => {
527 matches!(
528 res,
529 Res::Def(
530 DefKind::Struct
531 | DefKind::Union
532 | DefKind::Enum
533 | DefKind::TyAlias
534 | DefKind::AssocTy,
535 _
536 ) | Res::SelfTyAlias { .. }
537 )
538 }
539 PathSource::Type => matches!(
540 res,
541 Res::Def(
542 DefKind::Struct
543 | DefKind::Union
544 | DefKind::Enum
545 | DefKind::Trait
546 | DefKind::TraitAlias
547 | DefKind::TyAlias
548 | DefKind::AssocTy
549 | DefKind::TyParam
550 | DefKind::OpaqueTy
551 | DefKind::ForeignTy,
552 _,
553 ) | Res::PrimTy(..)
554 | Res::SelfTyParam { .. }
555 | Res::SelfTyAlias { .. }
556 ),
557 PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
558 PathSource::Trait(AliasPossibility::Maybe) => {
559 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
560 }
561 PathSource::Expr(..) => matches!(
562 res,
563 Res::Def(
564 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
565 | DefKind::Const
566 | DefKind::Static { .. }
567 | DefKind::Fn
568 | DefKind::AssocFn
569 | DefKind::AssocConst
570 | DefKind::ConstParam,
571 _,
572 ) | Res::Local(..)
573 | Res::SelfCtor(..)
574 ),
575 PathSource::Pat => {
576 res.expected_in_unit_struct_pat()
577 || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
578 }
579 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
580 PathSource::Struct => matches!(
581 res,
582 Res::Def(
583 DefKind::Struct
584 | DefKind::Union
585 | DefKind::Variant
586 | DefKind::TyAlias
587 | DefKind::AssocTy,
588 _,
589 ) | Res::SelfTyParam { .. }
590 | Res::SelfTyAlias { .. }
591 ),
592 PathSource::TraitItem(ns, _) => match res {
593 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
594 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
595 _ => false,
596 },
597 PathSource::ReturnTypeNotation => match res {
598 Res::Def(DefKind::AssocFn, _) => true,
599 _ => false,
600 },
601 PathSource::Delegation => matches!(res, Res::Def(DefKind::Fn | DefKind::AssocFn, _)),
602 PathSource::PreciseCapturingArg(ValueNS) => {
603 matches!(res, Res::Def(DefKind::ConstParam, _))
604 }
605 PathSource::PreciseCapturingArg(TypeNS) => matches!(
607 res,
608 Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
609 ),
610 PathSource::PreciseCapturingArg(MacroNS) => false,
611 }
612 }
613
614 fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
615 match (self, has_unexpected_resolution) {
616 (PathSource::Trait(_), true) => E0404,
617 (PathSource::Trait(_), false) => E0405,
618 (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
619 (PathSource::Type | PathSource::DefineOpaques, false) => E0412,
620 (PathSource::Struct, true) => E0574,
621 (PathSource::Struct, false) => E0422,
622 (PathSource::Expr(..), true) | (PathSource::Delegation, true) => E0423,
623 (PathSource::Expr(..), false) | (PathSource::Delegation, false) => E0425,
624 (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
625 (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
626 (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
627 (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
628 (PathSource::PreciseCapturingArg(..), true) => E0799,
629 (PathSource::PreciseCapturingArg(..), false) => E0800,
630 }
631 }
632}
633
634#[derive(Clone, Copy)]
638enum MaybeExported<'a> {
639 Ok(NodeId),
640 Impl(Option<DefId>),
641 ImplItem(Result<DefId, &'a Visibility>),
642 NestedUse(&'a Visibility),
643}
644
645impl MaybeExported<'_> {
646 fn eval(self, r: &Resolver<'_, '_>) -> bool {
647 let def_id = match self {
648 MaybeExported::Ok(node_id) => Some(r.local_def_id(node_id)),
649 MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
650 trait_def_id.as_local()
651 }
652 MaybeExported::Impl(None) => return true,
653 MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
654 return vis.kind.is_pub();
655 }
656 };
657 def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
658 }
659}
660
661#[derive(Debug)]
663pub(crate) struct UnnecessaryQualification<'ra> {
664 pub binding: LexicalScopeBinding<'ra>,
665 pub node_id: NodeId,
666 pub path_span: Span,
667 pub removal_span: Span,
668}
669
670#[derive(Default, Debug)]
671struct DiagMetadata<'ast> {
672 current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
674
675 current_self_type: Option<Ty>,
677
678 current_self_item: Option<NodeId>,
680
681 current_item: Option<&'ast Item>,
683
684 currently_processing_generic_args: bool,
687
688 current_function: Option<(FnKind<'ast>, Span)>,
690
691 unused_labels: FxIndexMap<NodeId, Span>,
694
695 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
697
698 current_pat: Option<&'ast Pat>,
699
700 in_if_condition: Option<&'ast Expr>,
702
703 in_assignment: Option<&'ast Expr>,
705 is_assign_rhs: bool,
706
707 in_non_gat_assoc_type: Option<bool>,
709
710 in_range: Option<(&'ast Expr, &'ast Expr)>,
712
713 current_trait_object: Option<&'ast [ast::GenericBound]>,
716
717 current_where_predicate: Option<&'ast WherePredicate>,
719
720 current_type_path: Option<&'ast Ty>,
721
722 current_impl_items: Option<&'ast [P<AssocItem>]>,
724
725 currently_processing_impl_trait: Option<(TraitRef, Ty)>,
727
728 current_elision_failures: Vec<MissingLifetime>,
731}
732
733struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
734 r: &'a mut Resolver<'ra, 'tcx>,
735
736 parent_scope: ParentScope<'ra>,
738
739 ribs: PerNS<Vec<Rib<'ra>>>,
741
742 last_block_rib: Option<Rib<'ra>>,
744
745 label_ribs: Vec<Rib<'ra, NodeId>>,
747
748 lifetime_ribs: Vec<LifetimeRib>,
750
751 lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
757
758 current_trait_ref: Option<(Module<'ra>, TraitRef)>,
760
761 diag_metadata: Box<DiagMetadata<'ast>>,
763
764 in_func_body: bool,
770
771 lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
773}
774
775impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
777 fn visit_attribute(&mut self, _: &'ast Attribute) {
778 }
781 fn visit_item(&mut self, item: &'ast Item) {
782 let prev = replace(&mut self.diag_metadata.current_item, Some(item));
783 let old_ignore = replace(&mut self.in_func_body, false);
785 self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
786 self.in_func_body = old_ignore;
787 self.diag_metadata.current_item = prev;
788 }
789 fn visit_arm(&mut self, arm: &'ast Arm) {
790 self.resolve_arm(arm);
791 }
792 fn visit_block(&mut self, block: &'ast Block) {
793 let old_macro_rules = self.parent_scope.macro_rules;
794 self.resolve_block(block);
795 self.parent_scope.macro_rules = old_macro_rules;
796 }
797 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
798 bug!("encountered anon const without a manual call to `resolve_anon_const`: {constant:#?}");
799 }
800 fn visit_expr(&mut self, expr: &'ast Expr) {
801 self.resolve_expr(expr, None);
802 }
803 fn visit_pat(&mut self, p: &'ast Pat) {
804 let prev = self.diag_metadata.current_pat;
805 self.diag_metadata.current_pat = Some(p);
806
807 if let PatKind::Guard(subpat, _) = &p.kind {
808 self.visit_pat(subpat);
810 } else {
811 visit::walk_pat(self, p);
812 }
813
814 self.diag_metadata.current_pat = prev;
815 }
816 fn visit_local(&mut self, local: &'ast Local) {
817 let local_spans = match local.pat.kind {
818 PatKind::Wild => None,
820 _ => Some((
821 local.pat.span,
822 local.ty.as_ref().map(|ty| ty.span),
823 local.kind.init().map(|init| init.span),
824 )),
825 };
826 let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
827 self.resolve_local(local);
828 self.diag_metadata.current_let_binding = original;
829 }
830 fn visit_ty(&mut self, ty: &'ast Ty) {
831 let prev = self.diag_metadata.current_trait_object;
832 let prev_ty = self.diag_metadata.current_type_path;
833 match &ty.kind {
834 TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
835 let span = self.r.tcx.sess.source_map().start_point(ty.span);
839 self.resolve_elided_lifetime(ty.id, span);
840 visit::walk_ty(self, ty);
841 }
842 TyKind::Path(qself, path) => {
843 self.diag_metadata.current_type_path = Some(ty);
844
845 let source = if let Some(seg) = path.segments.last()
849 && let Some(args) = &seg.args
850 && matches!(**args, GenericArgs::ParenthesizedElided(..))
851 {
852 PathSource::ReturnTypeNotation
853 } else {
854 PathSource::Type
855 };
856
857 self.smart_resolve_path(ty.id, qself, path, source);
858
859 if qself.is_none()
861 && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
862 && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
863 partial_res.full_res()
864 {
865 let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
869 self.with_generic_param_rib(
870 &[],
871 RibKind::Normal,
872 ty.id,
873 LifetimeBinderKind::PolyTrait,
874 span,
875 |this| this.visit_path(path),
876 );
877 } else {
878 visit::walk_ty(self, ty)
879 }
880 }
881 TyKind::ImplicitSelf => {
882 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
883 let res = self
884 .resolve_ident_in_lexical_scope(
885 self_ty,
886 TypeNS,
887 Some(Finalize::new(ty.id, ty.span)),
888 None,
889 )
890 .map_or(Res::Err, |d| d.res());
891 self.r.record_partial_res(ty.id, PartialRes::new(res));
892 visit::walk_ty(self, ty)
893 }
894 TyKind::ImplTrait(..) => {
895 let candidates = self.lifetime_elision_candidates.take();
896 visit::walk_ty(self, ty);
897 self.lifetime_elision_candidates = candidates;
898 }
899 TyKind::TraitObject(bounds, ..) => {
900 self.diag_metadata.current_trait_object = Some(&bounds[..]);
901 visit::walk_ty(self, ty)
902 }
903 TyKind::BareFn(bare_fn) => {
904 let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo());
905 self.with_generic_param_rib(
906 &bare_fn.generic_params,
907 RibKind::Normal,
908 ty.id,
909 LifetimeBinderKind::BareFnType,
910 span,
911 |this| {
912 this.visit_generic_params(&bare_fn.generic_params, false);
913 this.with_lifetime_rib(
914 LifetimeRibKind::AnonymousCreateParameter {
915 binder: ty.id,
916 report_in_path: false,
917 },
918 |this| {
919 this.resolve_fn_signature(
920 ty.id,
921 false,
922 bare_fn
925 .decl
926 .inputs
927 .iter()
928 .map(|Param { ty, .. }| (None, &**ty)),
929 &bare_fn.decl.output,
930 )
931 },
932 );
933 },
934 )
935 }
936 TyKind::UnsafeBinder(unsafe_binder) => {
937 let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
938 self.with_generic_param_rib(
939 &unsafe_binder.generic_params,
940 RibKind::Normal,
941 ty.id,
942 LifetimeBinderKind::BareFnType,
943 span,
944 |this| {
945 this.visit_generic_params(&unsafe_binder.generic_params, false);
946 this.with_lifetime_rib(
947 LifetimeRibKind::AnonymousReportError,
950 |this| this.visit_ty(&unsafe_binder.inner_ty),
951 );
952 },
953 )
954 }
955 TyKind::Array(element_ty, length) => {
956 self.visit_ty(element_ty);
957 self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
958 }
959 TyKind::Typeof(ct) => {
960 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
961 }
962 _ => visit::walk_ty(self, ty),
963 }
964 self.diag_metadata.current_trait_object = prev;
965 self.diag_metadata.current_type_path = prev_ty;
966 }
967
968 fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
969 match &t.kind {
970 TyPatKind::Range(start, end, _) => {
971 if let Some(start) = start {
972 self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
973 }
974 if let Some(end) = end {
975 self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
976 }
977 }
978 TyPatKind::Or(patterns) => {
979 for pat in patterns {
980 self.visit_ty_pat(pat)
981 }
982 }
983 TyPatKind::Err(_) => {}
984 }
985 }
986
987 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
988 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
989 self.with_generic_param_rib(
990 &tref.bound_generic_params,
991 RibKind::Normal,
992 tref.trait_ref.ref_id,
993 LifetimeBinderKind::PolyTrait,
994 span,
995 |this| {
996 this.visit_generic_params(&tref.bound_generic_params, false);
997 this.smart_resolve_path(
998 tref.trait_ref.ref_id,
999 &None,
1000 &tref.trait_ref.path,
1001 PathSource::Trait(AliasPossibility::Maybe),
1002 );
1003 this.visit_trait_ref(&tref.trait_ref);
1004 },
1005 );
1006 }
1007 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1008 self.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1009 let def_kind = self.r.local_def_kind(foreign_item.id);
1010 match foreign_item.kind {
1011 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
1012 self.with_generic_param_rib(
1013 &generics.params,
1014 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1015 foreign_item.id,
1016 LifetimeBinderKind::Item,
1017 generics.span,
1018 |this| visit::walk_item(this, foreign_item),
1019 );
1020 }
1021 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
1022 self.with_generic_param_rib(
1023 &generics.params,
1024 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1025 foreign_item.id,
1026 LifetimeBinderKind::Function,
1027 generics.span,
1028 |this| visit::walk_item(this, foreign_item),
1029 );
1030 }
1031 ForeignItemKind::Static(..) => {
1032 self.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1033 }
1034 ForeignItemKind::MacCall(..) => {
1035 panic!("unexpanded macro in resolve!")
1036 }
1037 }
1038 }
1039 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
1040 let previous_value = self.diag_metadata.current_function;
1041 match fn_kind {
1042 FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1045 | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1046 self.visit_fn_header(&sig.header);
1047 self.visit_ident(ident);
1048 self.visit_generics(generics);
1049 self.with_lifetime_rib(
1050 LifetimeRibKind::AnonymousCreateParameter {
1051 binder: fn_id,
1052 report_in_path: false,
1053 },
1054 |this| {
1055 this.resolve_fn_signature(
1056 fn_id,
1057 sig.decl.has_self(),
1058 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1059 &sig.decl.output,
1060 );
1061 },
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 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1075 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1077 match fn_kind {
1078 FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1079 this.visit_generics(generics);
1080
1081 let declaration = &sig.decl;
1082 let coro_node_id = sig
1083 .header
1084 .coroutine_kind
1085 .map(|coroutine_kind| coroutine_kind.return_id());
1086
1087 this.with_lifetime_rib(
1088 LifetimeRibKind::AnonymousCreateParameter {
1089 binder: fn_id,
1090 report_in_path: coro_node_id.is_some(),
1091 },
1092 |this| {
1093 this.resolve_fn_signature(
1094 fn_id,
1095 declaration.has_self(),
1096 declaration
1097 .inputs
1098 .iter()
1099 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1100 &declaration.output,
1101 );
1102 },
1103 );
1104
1105 if let Some(contract) = contract {
1106 this.visit_contract(contract);
1107 }
1108
1109 if let Some(body) = body {
1110 let previous_state = replace(&mut this.in_func_body, true);
1113 this.last_block_rib = None;
1115 this.with_lifetime_rib(
1117 LifetimeRibKind::Elided(LifetimeRes::Infer),
1118 |this| this.visit_block(body),
1119 );
1120
1121 debug!("(resolving function) leaving function");
1122 this.in_func_body = previous_state;
1123 }
1124 }
1125 FnKind::Closure(binder, _, declaration, body) => {
1126 this.visit_closure_binder(binder);
1127
1128 this.with_lifetime_rib(
1129 match binder {
1130 ClosureBinder::NotPresent => {
1132 LifetimeRibKind::AnonymousCreateParameter {
1133 binder: fn_id,
1134 report_in_path: false,
1135 }
1136 }
1137 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1138 },
1139 |this| this.resolve_params(&declaration.inputs),
1141 );
1142 this.with_lifetime_rib(
1143 match binder {
1144 ClosureBinder::NotPresent => {
1145 LifetimeRibKind::Elided(LifetimeRes::Infer)
1146 }
1147 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1148 },
1149 |this| visit::walk_fn_ret_ty(this, &declaration.output),
1150 );
1151
1152 let previous_state = replace(&mut this.in_func_body, true);
1155 this.with_lifetime_rib(
1157 LifetimeRibKind::Elided(LifetimeRes::Infer),
1158 |this| this.visit_expr(body),
1159 );
1160
1161 debug!("(resolving function) leaving function");
1162 this.in_func_body = previous_state;
1163 }
1164 }
1165 })
1166 });
1167 self.diag_metadata.current_function = previous_value;
1168 }
1169
1170 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1171 self.resolve_lifetime(lifetime, use_ctxt)
1172 }
1173
1174 fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1175 match arg {
1176 PreciseCapturingArg::Lifetime(_) => {}
1179
1180 PreciseCapturingArg::Arg(path, id) => {
1181 let mut check_ns = |ns| {
1188 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1189 };
1190 if !check_ns(TypeNS) && check_ns(ValueNS) {
1192 self.smart_resolve_path(
1193 *id,
1194 &None,
1195 path,
1196 PathSource::PreciseCapturingArg(ValueNS),
1197 );
1198 } else {
1199 self.smart_resolve_path(
1200 *id,
1201 &None,
1202 path,
1203 PathSource::PreciseCapturingArg(TypeNS),
1204 );
1205 }
1206 }
1207 }
1208
1209 visit::walk_precise_capturing_arg(self, arg)
1210 }
1211
1212 fn visit_generics(&mut self, generics: &'ast Generics) {
1213 self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1214 for p in &generics.where_clause.predicates {
1215 self.visit_where_predicate(p);
1216 }
1217 }
1218
1219 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1220 match b {
1221 ClosureBinder::NotPresent => {}
1222 ClosureBinder::For { generic_params, .. } => {
1223 self.visit_generic_params(
1224 generic_params,
1225 self.diag_metadata.current_self_item.is_some(),
1226 );
1227 }
1228 }
1229 }
1230
1231 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1232 debug!("visit_generic_arg({:?})", arg);
1233 let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1234 match arg {
1235 GenericArg::Type(ty) => {
1236 if let TyKind::Path(None, ref path) = ty.kind
1242 && path.is_potential_trivial_const_arg(false)
1245 {
1246 let mut check_ns = |ns| {
1247 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1248 .is_some()
1249 };
1250 if !check_ns(TypeNS) && check_ns(ValueNS) {
1251 self.resolve_anon_const_manual(
1252 true,
1253 AnonConstKind::ConstArg(IsRepeatExpr::No),
1254 |this| {
1255 this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1256 this.visit_path(path);
1257 },
1258 );
1259
1260 self.diag_metadata.currently_processing_generic_args = prev;
1261 return;
1262 }
1263 }
1264
1265 self.visit_ty(ty);
1266 }
1267 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1268 GenericArg::Const(ct) => {
1269 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1270 }
1271 }
1272 self.diag_metadata.currently_processing_generic_args = prev;
1273 }
1274
1275 fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1276 self.visit_ident(&constraint.ident);
1277 if let Some(ref gen_args) = constraint.gen_args {
1278 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1280 this.visit_generic_args(gen_args)
1281 });
1282 }
1283 match constraint.kind {
1284 AssocItemConstraintKind::Equality { ref term } => match term {
1285 Term::Ty(ty) => self.visit_ty(ty),
1286 Term::Const(c) => {
1287 self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1288 }
1289 },
1290 AssocItemConstraintKind::Bound { ref bounds } => {
1291 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1292 }
1293 }
1294 }
1295
1296 fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1297 let Some(ref args) = path_segment.args else {
1298 return;
1299 };
1300
1301 match &**args {
1302 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1303 GenericArgs::Parenthesized(p_args) => {
1304 for rib in self.lifetime_ribs.iter().rev() {
1306 match rib.kind {
1307 LifetimeRibKind::Generics {
1310 binder,
1311 kind: LifetimeBinderKind::PolyTrait,
1312 ..
1313 } => {
1314 self.with_lifetime_rib(
1315 LifetimeRibKind::AnonymousCreateParameter {
1316 binder,
1317 report_in_path: false,
1318 },
1319 |this| {
1320 this.resolve_fn_signature(
1321 binder,
1322 false,
1323 p_args.inputs.iter().map(|ty| (None, &**ty)),
1324 &p_args.output,
1325 )
1326 },
1327 );
1328 break;
1329 }
1330 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1333 visit::walk_generic_args(self, args);
1334 break;
1335 }
1336 LifetimeRibKind::AnonymousCreateParameter { .. }
1337 | LifetimeRibKind::AnonymousReportError
1338 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1339 | LifetimeRibKind::Elided(_)
1340 | LifetimeRibKind::ElisionFailure
1341 | LifetimeRibKind::ConcreteAnonConst(_)
1342 | LifetimeRibKind::ConstParamTy => {}
1343 }
1344 }
1345 }
1346 GenericArgs::ParenthesizedElided(_) => {}
1347 }
1348 }
1349
1350 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1351 debug!("visit_where_predicate {:?}", p);
1352 let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1353 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1354 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1355 bounded_ty,
1356 bounds,
1357 bound_generic_params,
1358 ..
1359 }) = &p.kind
1360 {
1361 let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1362 this.with_generic_param_rib(
1363 bound_generic_params,
1364 RibKind::Normal,
1365 bounded_ty.id,
1366 LifetimeBinderKind::WhereBound,
1367 span,
1368 |this| {
1369 this.visit_generic_params(bound_generic_params, false);
1370 this.visit_ty(bounded_ty);
1371 for bound in bounds {
1372 this.visit_param_bound(bound, BoundKind::Bound)
1373 }
1374 },
1375 );
1376 } else {
1377 visit::walk_where_predicate(this, p);
1378 }
1379 });
1380 self.diag_metadata.current_where_predicate = previous_value;
1381 }
1382
1383 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1384 for (op, _) in &asm.operands {
1385 match op {
1386 InlineAsmOperand::In { expr, .. }
1387 | InlineAsmOperand::Out { expr: Some(expr), .. }
1388 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1389 InlineAsmOperand::Out { expr: None, .. } => {}
1390 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1391 self.visit_expr(in_expr);
1392 if let Some(out_expr) = out_expr {
1393 self.visit_expr(out_expr);
1394 }
1395 }
1396 InlineAsmOperand::Const { anon_const, .. } => {
1397 self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1400 }
1401 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1402 InlineAsmOperand::Label { block } => self.visit_block(block),
1403 }
1404 }
1405 }
1406
1407 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1408 self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1410 this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1411 this.with_label_rib(RibKind::InlineAsmSym, |this| {
1412 this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1413 visit::walk_inline_asm_sym(this, sym);
1414 });
1415 })
1416 });
1417 }
1418
1419 fn visit_variant(&mut self, v: &'ast Variant) {
1420 self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1421 self.visit_id(v.id);
1422 walk_list!(self, visit_attribute, &v.attrs);
1423 self.visit_vis(&v.vis);
1424 self.visit_ident(&v.ident);
1425 self.visit_variant_data(&v.data);
1426 if let Some(discr) = &v.disr_expr {
1427 self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1428 }
1429 }
1430
1431 fn visit_field_def(&mut self, f: &'ast FieldDef) {
1432 self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1433 let FieldDef {
1434 attrs,
1435 id: _,
1436 span: _,
1437 vis,
1438 ident,
1439 ty,
1440 is_placeholder: _,
1441 default,
1442 safety: _,
1443 } = f;
1444 walk_list!(self, visit_attribute, attrs);
1445 try_visit!(self.visit_vis(vis));
1446 visit_opt!(self, visit_ident, ident);
1447 try_visit!(self.visit_ty(ty));
1448 if let Some(v) = &default {
1449 self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1450 }
1451 }
1452}
1453
1454impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1455 fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1456 let graph_root = resolver.graph_root;
1459 let parent_scope = ParentScope::module(graph_root, resolver);
1460 let start_rib_kind = RibKind::Module(graph_root);
1461 LateResolutionVisitor {
1462 r: resolver,
1463 parent_scope,
1464 ribs: PerNS {
1465 value_ns: vec![Rib::new(start_rib_kind)],
1466 type_ns: vec![Rib::new(start_rib_kind)],
1467 macro_ns: vec![Rib::new(start_rib_kind)],
1468 },
1469 last_block_rib: None,
1470 label_ribs: Vec::new(),
1471 lifetime_ribs: Vec::new(),
1472 lifetime_elision_candidates: None,
1473 current_trait_ref: None,
1474 diag_metadata: Default::default(),
1475 in_func_body: false,
1477 lifetime_uses: Default::default(),
1478 }
1479 }
1480
1481 fn maybe_resolve_ident_in_lexical_scope(
1482 &mut self,
1483 ident: Ident,
1484 ns: Namespace,
1485 ) -> Option<LexicalScopeBinding<'ra>> {
1486 self.r.resolve_ident_in_lexical_scope(
1487 ident,
1488 ns,
1489 &self.parent_scope,
1490 None,
1491 &self.ribs[ns],
1492 None,
1493 )
1494 }
1495
1496 fn resolve_ident_in_lexical_scope(
1497 &mut self,
1498 ident: Ident,
1499 ns: Namespace,
1500 finalize: Option<Finalize>,
1501 ignore_binding: Option<NameBinding<'ra>>,
1502 ) -> Option<LexicalScopeBinding<'ra>> {
1503 self.r.resolve_ident_in_lexical_scope(
1504 ident,
1505 ns,
1506 &self.parent_scope,
1507 finalize,
1508 &self.ribs[ns],
1509 ignore_binding,
1510 )
1511 }
1512
1513 fn resolve_path(
1514 &mut self,
1515 path: &[Segment],
1516 opt_ns: Option<Namespace>, finalize: Option<Finalize>,
1518 ) -> PathResult<'ra> {
1519 self.r.resolve_path_with_ribs(
1520 path,
1521 opt_ns,
1522 &self.parent_scope,
1523 finalize,
1524 Some(&self.ribs),
1525 None,
1526 None,
1527 )
1528 }
1529
1530 fn with_rib<T>(
1550 &mut self,
1551 ns: Namespace,
1552 kind: RibKind<'ra>,
1553 work: impl FnOnce(&mut Self) -> T,
1554 ) -> T {
1555 self.ribs[ns].push(Rib::new(kind));
1556 let ret = work(self);
1557 self.ribs[ns].pop();
1558 ret
1559 }
1560
1561 fn with_mod_rib<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1562 let module = self.r.expect_module(self.r.local_def_id(id).to_def_id());
1563 let orig_module = replace(&mut self.parent_scope.module, module);
1565 self.with_rib(ValueNS, RibKind::Module(module), |this| {
1566 this.with_rib(TypeNS, RibKind::Module(module), |this| {
1567 let ret = f(this);
1568 this.parent_scope.module = orig_module;
1569 ret
1570 })
1571 })
1572 }
1573
1574 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1575 let mut forward_ty_ban_rib =
1581 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1582 let mut forward_const_ban_rib =
1583 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1584 for param in params.iter() {
1585 match param.kind {
1586 GenericParamKind::Type { .. } => {
1587 forward_ty_ban_rib
1588 .bindings
1589 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1590 }
1591 GenericParamKind::Const { .. } => {
1592 forward_const_ban_rib
1593 .bindings
1594 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1595 }
1596 GenericParamKind::Lifetime => {}
1597 }
1598 }
1599
1600 if add_self_upper {
1610 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1612 }
1613
1614 let mut forward_ty_ban_rib_const_param_ty = Rib {
1617 bindings: forward_ty_ban_rib.bindings.clone(),
1618 patterns_with_skipped_bindings: Default::default(),
1619 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1620 };
1621 let mut forward_const_ban_rib_const_param_ty = Rib {
1622 bindings: forward_const_ban_rib.bindings.clone(),
1623 patterns_with_skipped_bindings: Default::default(),
1624 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1625 };
1626 if !self.r.tcx.features().generic_const_parameter_types() {
1629 forward_ty_ban_rib_const_param_ty.bindings.clear();
1630 forward_const_ban_rib_const_param_ty.bindings.clear();
1631 }
1632
1633 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1634 for param in params {
1635 match param.kind {
1636 GenericParamKind::Lifetime => {
1637 for bound in ¶m.bounds {
1638 this.visit_param_bound(bound, BoundKind::Bound);
1639 }
1640 }
1641 GenericParamKind::Type { ref default } => {
1642 for bound in ¶m.bounds {
1643 this.visit_param_bound(bound, BoundKind::Bound);
1644 }
1645
1646 if let Some(ty) = default {
1647 this.ribs[TypeNS].push(forward_ty_ban_rib);
1648 this.ribs[ValueNS].push(forward_const_ban_rib);
1649 this.visit_ty(ty);
1650 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1651 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1652 }
1653
1654 let i = &Ident::with_dummy_span(param.ident.name);
1656 forward_ty_ban_rib.bindings.swap_remove(i);
1657 forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1658 }
1659 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1660 assert!(param.bounds.is_empty());
1662
1663 this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1664 this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1665 if this.r.tcx.features().generic_const_parameter_types() {
1666 this.visit_ty(ty)
1667 } else {
1668 this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1669 this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1670 this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1671 this.visit_ty(ty)
1672 });
1673 this.ribs[TypeNS].pop().unwrap();
1674 this.ribs[ValueNS].pop().unwrap();
1675 }
1676 forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1677 forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1678
1679 if let Some(expr) = default {
1680 this.ribs[TypeNS].push(forward_ty_ban_rib);
1681 this.ribs[ValueNS].push(forward_const_ban_rib);
1682 this.resolve_anon_const(
1683 expr,
1684 AnonConstKind::ConstArg(IsRepeatExpr::No),
1685 );
1686 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1687 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1688 }
1689
1690 let i = &Ident::with_dummy_span(param.ident.name);
1692 forward_const_ban_rib.bindings.swap_remove(i);
1693 forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1694 }
1695 }
1696 }
1697 })
1698 }
1699
1700 #[instrument(level = "debug", skip(self, work))]
1701 fn with_lifetime_rib<T>(
1702 &mut self,
1703 kind: LifetimeRibKind,
1704 work: impl FnOnce(&mut Self) -> T,
1705 ) -> T {
1706 self.lifetime_ribs.push(LifetimeRib::new(kind));
1707 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1708 let ret = work(self);
1709 self.lifetime_elision_candidates = outer_elision_candidates;
1710 self.lifetime_ribs.pop();
1711 ret
1712 }
1713
1714 #[instrument(level = "debug", skip(self))]
1715 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1716 let ident = lifetime.ident;
1717
1718 if ident.name == kw::StaticLifetime {
1719 self.record_lifetime_res(
1720 lifetime.id,
1721 LifetimeRes::Static,
1722 LifetimeElisionCandidate::Named,
1723 );
1724 return;
1725 }
1726
1727 if ident.name == kw::UnderscoreLifetime {
1728 return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1729 }
1730
1731 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1732 while let Some(rib) = lifetime_rib_iter.next() {
1733 let normalized_ident = ident.normalize_to_macros_2_0();
1734 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1735 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1736
1737 if let LifetimeRes::Param { param, binder } = res {
1738 match self.lifetime_uses.entry(param) {
1739 Entry::Vacant(v) => {
1740 debug!("First use of {:?} at {:?}", res, ident.span);
1741 let use_set = self
1742 .lifetime_ribs
1743 .iter()
1744 .rev()
1745 .find_map(|rib| match rib.kind {
1746 LifetimeRibKind::Item
1749 | LifetimeRibKind::AnonymousReportError
1750 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1751 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1752 LifetimeRibKind::AnonymousCreateParameter {
1755 binder: anon_binder,
1756 ..
1757 } => Some(if binder == anon_binder {
1758 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1759 } else {
1760 LifetimeUseSet::Many
1761 }),
1762 LifetimeRibKind::Elided(r) => Some(if res == r {
1765 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1766 } else {
1767 LifetimeUseSet::Many
1768 }),
1769 LifetimeRibKind::Generics { .. }
1770 | LifetimeRibKind::ConstParamTy => None,
1771 LifetimeRibKind::ConcreteAnonConst(_) => {
1772 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1773 }
1774 })
1775 .unwrap_or(LifetimeUseSet::Many);
1776 debug!(?use_ctxt, ?use_set);
1777 v.insert(use_set);
1778 }
1779 Entry::Occupied(mut o) => {
1780 debug!("Many uses of {:?} at {:?}", res, ident.span);
1781 *o.get_mut() = LifetimeUseSet::Many;
1782 }
1783 }
1784 }
1785 return;
1786 }
1787
1788 match rib.kind {
1789 LifetimeRibKind::Item => break,
1790 LifetimeRibKind::ConstParamTy => {
1791 self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1792 self.record_lifetime_res(
1793 lifetime.id,
1794 LifetimeRes::Error,
1795 LifetimeElisionCandidate::Ignore,
1796 );
1797 return;
1798 }
1799 LifetimeRibKind::ConcreteAnonConst(cause) => {
1800 self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1801 self.record_lifetime_res(
1802 lifetime.id,
1803 LifetimeRes::Error,
1804 LifetimeElisionCandidate::Ignore,
1805 );
1806 return;
1807 }
1808 LifetimeRibKind::AnonymousCreateParameter { .. }
1809 | LifetimeRibKind::Elided(_)
1810 | LifetimeRibKind::Generics { .. }
1811 | LifetimeRibKind::ElisionFailure
1812 | LifetimeRibKind::AnonymousReportError
1813 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1814 }
1815 }
1816
1817 let normalized_ident = ident.normalize_to_macros_2_0();
1818 let outer_res = lifetime_rib_iter
1819 .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1820
1821 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1822 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1823 }
1824
1825 #[instrument(level = "debug", skip(self))]
1826 fn resolve_anonymous_lifetime(
1827 &mut self,
1828 lifetime: &Lifetime,
1829 id_for_lint: NodeId,
1830 elided: bool,
1831 ) {
1832 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1833
1834 let kind =
1835 if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1836 let missing_lifetime = MissingLifetime {
1837 id: lifetime.id,
1838 span: lifetime.ident.span,
1839 kind,
1840 count: 1,
1841 id_for_lint,
1842 };
1843 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1844 for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1845 debug!(?rib.kind);
1846 match rib.kind {
1847 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1848 let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1849 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1850 return;
1851 }
1852 LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1853 let mut lifetimes_in_scope = vec![];
1854 for rib in self.lifetime_ribs[..i].iter().rev() {
1855 lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1856 if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1858 && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1859 {
1860 lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1861 }
1862 if let LifetimeRibKind::Item = rib.kind {
1863 break;
1864 }
1865 }
1866 if lifetimes_in_scope.is_empty() {
1867 self.record_lifetime_res(
1868 lifetime.id,
1869 LifetimeRes::Static,
1870 elision_candidate,
1871 );
1872 return;
1873 } else if emit_lint {
1874 self.r.lint_buffer.buffer_lint(
1875 lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1876 node_id,
1877 lifetime.ident.span,
1878 lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1879 elided,
1880 span: lifetime.ident.span,
1881 lifetimes_in_scope: lifetimes_in_scope.into(),
1882 },
1883 );
1884 }
1885 }
1886 LifetimeRibKind::AnonymousReportError => {
1887 if elided {
1888 let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1889 if let LifetimeRibKind::Generics {
1890 span,
1891 kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1892 ..
1893 } = rib.kind
1894 {
1895 Some(errors::ElidedAnonymousLivetimeReportErrorSuggestion {
1896 lo: span.shrink_to_lo(),
1897 hi: lifetime.ident.span.shrink_to_hi(),
1898 })
1899 } else {
1900 None
1901 }
1902 });
1903 if !self.in_func_body
1906 && let Some((module, _)) = &self.current_trait_ref
1907 && let Some(ty) = &self.diag_metadata.current_self_type
1908 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1909 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1910 {
1911 if def_id_matches_path(
1912 self.r.tcx,
1913 trait_id,
1914 &["core", "iter", "traits", "iterator", "Iterator"],
1915 ) {
1916 self.r.dcx().emit_err(errors::LendingIteratorReportError {
1917 lifetime: lifetime.ident.span,
1918 ty: ty.span,
1919 });
1920 } else {
1921 self.r.dcx().emit_err(errors::AnonymousLivetimeNonGatReportError {
1922 lifetime: lifetime.ident.span,
1923 });
1924 }
1925 } else {
1926 self.r.dcx().emit_err(errors::ElidedAnonymousLivetimeReportError {
1927 span: lifetime.ident.span,
1928 suggestion,
1929 });
1930 }
1931 } else {
1932 self.r.dcx().emit_err(errors::ExplicitAnonymousLivetimeReportError {
1933 span: lifetime.ident.span,
1934 });
1935 };
1936 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1937 return;
1938 }
1939 LifetimeRibKind::Elided(res) => {
1940 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1941 return;
1942 }
1943 LifetimeRibKind::ElisionFailure => {
1944 self.diag_metadata.current_elision_failures.push(missing_lifetime);
1945 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1946 return;
1947 }
1948 LifetimeRibKind::Item => break,
1949 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1950 LifetimeRibKind::ConcreteAnonConst(_) => {
1951 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1953 }
1954 }
1955 }
1956 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1957 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1958 }
1959
1960 #[instrument(level = "debug", skip(self))]
1961 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1962 let id = self.r.next_node_id();
1963 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1964
1965 self.record_lifetime_res(
1966 anchor_id,
1967 LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
1968 LifetimeElisionCandidate::Ignore,
1969 );
1970 self.resolve_anonymous_lifetime(<, anchor_id, true);
1971 }
1972
1973 #[instrument(level = "debug", skip(self))]
1974 fn create_fresh_lifetime(
1975 &mut self,
1976 ident: Ident,
1977 binder: NodeId,
1978 kind: MissingLifetimeKind,
1979 ) -> LifetimeRes {
1980 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1981 debug!(?ident.span);
1982
1983 let param = self.r.next_node_id();
1985 let res = LifetimeRes::Fresh { param, binder, kind };
1986 self.record_lifetime_param(param, res);
1987
1988 self.r
1990 .extra_lifetime_params_map
1991 .entry(binder)
1992 .or_insert_with(Vec::new)
1993 .push((ident, param, res));
1994 res
1995 }
1996
1997 #[instrument(level = "debug", skip(self))]
1998 fn resolve_elided_lifetimes_in_path(
1999 &mut self,
2000 partial_res: PartialRes,
2001 path: &[Segment],
2002 source: PathSource<'_, '_, '_>,
2003 path_span: Span,
2004 ) {
2005 let proj_start = path.len() - partial_res.unresolved_segments();
2006 for (i, segment) in path.iter().enumerate() {
2007 if segment.has_lifetime_args {
2008 continue;
2009 }
2010 let Some(segment_id) = segment.id else {
2011 continue;
2012 };
2013
2014 let type_def_id = match partial_res.base_res() {
2017 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2018 self.r.tcx.parent(def_id)
2019 }
2020 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2021 self.r.tcx.parent(def_id)
2022 }
2023 Res::Def(DefKind::Struct, def_id)
2024 | Res::Def(DefKind::Union, def_id)
2025 | Res::Def(DefKind::Enum, def_id)
2026 | Res::Def(DefKind::TyAlias, def_id)
2027 | Res::Def(DefKind::Trait, def_id)
2028 if i + 1 == proj_start =>
2029 {
2030 def_id
2031 }
2032 _ => continue,
2033 };
2034
2035 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2036 if expected_lifetimes == 0 {
2037 continue;
2038 }
2039
2040 let node_ids = self.r.next_node_ids(expected_lifetimes);
2041 self.record_lifetime_res(
2042 segment_id,
2043 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2044 LifetimeElisionCandidate::Ignore,
2045 );
2046
2047 let inferred = match source {
2048 PathSource::Trait(..)
2049 | PathSource::TraitItem(..)
2050 | PathSource::Type
2051 | PathSource::PreciseCapturingArg(..)
2052 | PathSource::ReturnTypeNotation => false,
2053 PathSource::Expr(..)
2054 | PathSource::Pat
2055 | PathSource::Struct
2056 | PathSource::TupleStruct(..)
2057 | PathSource::DefineOpaques
2058 | PathSource::Delegation => true,
2059 };
2060 if inferred {
2061 for id in node_ids {
2064 self.record_lifetime_res(
2065 id,
2066 LifetimeRes::Infer,
2067 LifetimeElisionCandidate::Named,
2068 );
2069 }
2070 continue;
2071 }
2072
2073 let elided_lifetime_span = if segment.has_generic_args {
2074 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2076 } else {
2077 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2081 };
2082 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2083
2084 let kind = if segment.has_generic_args {
2085 MissingLifetimeKind::Comma
2086 } else {
2087 MissingLifetimeKind::Brackets
2088 };
2089 let missing_lifetime = MissingLifetime {
2090 id: node_ids.start,
2091 id_for_lint: segment_id,
2092 span: elided_lifetime_span,
2093 kind,
2094 count: expected_lifetimes,
2095 };
2096 let mut should_lint = true;
2097 for rib in self.lifetime_ribs.iter().rev() {
2098 match rib.kind {
2099 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2106 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2107 let sess = self.r.tcx.sess;
2108 let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2109 sess.source_map(),
2110 expected_lifetimes,
2111 path_span,
2112 !segment.has_generic_args,
2113 elided_lifetime_span,
2114 );
2115 self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2116 span: path_span,
2117 subdiag,
2118 });
2119 should_lint = false;
2120
2121 for id in node_ids {
2122 self.record_lifetime_res(
2123 id,
2124 LifetimeRes::Error,
2125 LifetimeElisionCandidate::Named,
2126 );
2127 }
2128 break;
2129 }
2130 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2132 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2134 for id in node_ids {
2135 let res = self.create_fresh_lifetime(ident, binder, kind);
2136 self.record_lifetime_res(
2137 id,
2138 res,
2139 replace(&mut candidate, LifetimeElisionCandidate::Named),
2140 );
2141 }
2142 break;
2143 }
2144 LifetimeRibKind::Elided(res) => {
2145 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2146 for id in node_ids {
2147 self.record_lifetime_res(
2148 id,
2149 res,
2150 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2151 );
2152 }
2153 break;
2154 }
2155 LifetimeRibKind::ElisionFailure => {
2156 self.diag_metadata.current_elision_failures.push(missing_lifetime);
2157 for id in node_ids {
2158 self.record_lifetime_res(
2159 id,
2160 LifetimeRes::Error,
2161 LifetimeElisionCandidate::Ignore,
2162 );
2163 }
2164 break;
2165 }
2166 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2171 for id in node_ids {
2172 self.record_lifetime_res(
2173 id,
2174 LifetimeRes::Error,
2175 LifetimeElisionCandidate::Ignore,
2176 );
2177 }
2178 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2179 break;
2180 }
2181 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2182 LifetimeRibKind::ConcreteAnonConst(_) => {
2183 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2185 }
2186 }
2187 }
2188
2189 if should_lint {
2190 self.r.lint_buffer.buffer_lint(
2191 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2192 segment_id,
2193 elided_lifetime_span,
2194 lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2195 expected_lifetimes,
2196 path_span,
2197 !segment.has_generic_args,
2198 elided_lifetime_span,
2199 ),
2200 );
2201 }
2202 }
2203 }
2204
2205 #[instrument(level = "debug", skip(self))]
2206 fn record_lifetime_res(
2207 &mut self,
2208 id: NodeId,
2209 res: LifetimeRes,
2210 candidate: LifetimeElisionCandidate,
2211 ) {
2212 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2213 panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2214 }
2215
2216 match res {
2217 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2218 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2219 candidates.push((res, candidate));
2220 }
2221 }
2222 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2223 }
2224 }
2225
2226 #[instrument(level = "debug", skip(self))]
2227 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2228 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2229 panic!(
2230 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2231 )
2232 }
2233 }
2234
2235 #[instrument(level = "debug", skip(self, inputs))]
2237 fn resolve_fn_signature(
2238 &mut self,
2239 fn_id: NodeId,
2240 has_self: bool,
2241 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2242 output_ty: &'ast FnRetTy,
2243 ) {
2244 let elision_lifetime = self.resolve_fn_params(has_self, inputs);
2246 debug!(?elision_lifetime);
2247
2248 let outer_failures = take(&mut self.diag_metadata.current_elision_failures);
2249 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2250 self.r.lifetime_elision_allowed.insert(fn_id);
2251 LifetimeRibKind::Elided(*res)
2252 } else {
2253 LifetimeRibKind::ElisionFailure
2254 };
2255 self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2256 let elision_failures =
2257 replace(&mut self.diag_metadata.current_elision_failures, outer_failures);
2258 if !elision_failures.is_empty() {
2259 let Err(failure_info) = elision_lifetime else { bug!() };
2260 self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2261 }
2262 }
2263
2264 fn resolve_fn_params(
2268 &mut self,
2269 has_self: bool,
2270 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2271 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2272 enum Elision {
2273 None,
2275 Self_(LifetimeRes),
2277 Param(LifetimeRes),
2279 Err,
2281 }
2282
2283 let outer_candidates = self.lifetime_elision_candidates.take();
2285
2286 let mut elision_lifetime = Elision::None;
2288 let mut parameter_info = Vec::new();
2290 let mut all_candidates = Vec::new();
2291
2292 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2294 for (pat, _) in inputs.clone() {
2295 debug!("resolving bindings in pat = {pat:?}");
2296 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2297 if let Some(pat) = pat {
2298 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2299 }
2300 });
2301 }
2302 self.apply_pattern_bindings(bindings);
2303
2304 for (index, (pat, ty)) in inputs.enumerate() {
2305 debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2306 debug_assert_matches!(self.lifetime_elision_candidates, None);
2308 self.lifetime_elision_candidates = Some(Default::default());
2309 self.visit_ty(ty);
2310 let local_candidates = self.lifetime_elision_candidates.take();
2311
2312 if let Some(candidates) = local_candidates {
2313 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2314 let lifetime_count = distinct.len();
2315 if lifetime_count != 0 {
2316 parameter_info.push(ElisionFnParameter {
2317 index,
2318 ident: if let Some(pat) = pat
2319 && let PatKind::Ident(_, ident, _) = pat.kind
2320 {
2321 Some(ident)
2322 } else {
2323 None
2324 },
2325 lifetime_count,
2326 span: ty.span,
2327 });
2328 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2329 match candidate {
2330 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2331 None
2332 }
2333 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2334 }
2335 }));
2336 }
2337 if !distinct.is_empty() {
2338 match elision_lifetime {
2339 Elision::None => {
2341 if let Some(res) = distinct.get_only() {
2342 elision_lifetime = Elision::Param(*res)
2344 } else {
2345 elision_lifetime = Elision::Err;
2347 }
2348 }
2349 Elision::Param(_) => elision_lifetime = Elision::Err,
2351 Elision::Self_(_) | Elision::Err => {}
2353 }
2354 }
2355 }
2356
2357 if index == 0 && has_self {
2359 let self_lifetime = self.find_lifetime_for_self(ty);
2360 elision_lifetime = match self_lifetime {
2361 Set1::One(lifetime) => Elision::Self_(lifetime),
2363 Set1::Many => Elision::Err,
2368 Set1::Empty => Elision::None,
2371 }
2372 }
2373 debug!("(resolving function / closure) recorded parameter");
2374 }
2375
2376 debug_assert_matches!(self.lifetime_elision_candidates, None);
2378 self.lifetime_elision_candidates = outer_candidates;
2379
2380 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2381 return Ok(res);
2382 }
2383
2384 Err((all_candidates, parameter_info))
2386 }
2387
2388 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2390 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2394 r: &'a Resolver<'ra, 'tcx>,
2395 impl_self: Option<Res>,
2396 lifetime: Set1<LifetimeRes>,
2397 }
2398
2399 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2400 fn visit_ty(&mut self, ty: &'ra Ty) {
2401 trace!("FindReferenceVisitor considering ty={:?}", ty);
2402 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2403 let mut visitor =
2405 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2406 visitor.visit_ty(ty);
2407 trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2408 if visitor.self_found {
2409 let lt_id = if let Some(lt) = lt {
2410 lt.id
2411 } else {
2412 let res = self.r.lifetimes_res_map[&ty.id];
2413 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2414 start
2415 };
2416 let lt_res = self.r.lifetimes_res_map[<_id];
2417 trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2418 self.lifetime.insert(lt_res);
2419 }
2420 }
2421 visit::walk_ty(self, ty)
2422 }
2423
2424 fn visit_expr(&mut self, _: &'ra Expr) {}
2427 }
2428
2429 struct SelfVisitor<'a, 'ra, 'tcx> {
2432 r: &'a Resolver<'ra, 'tcx>,
2433 impl_self: Option<Res>,
2434 self_found: bool,
2435 }
2436
2437 impl SelfVisitor<'_, '_, '_> {
2438 fn is_self_ty(&self, ty: &Ty) -> bool {
2440 match ty.kind {
2441 TyKind::ImplicitSelf => true,
2442 TyKind::Path(None, _) => {
2443 let path_res = self.r.partial_res_map[&ty.id].full_res();
2444 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2445 return true;
2446 }
2447 self.impl_self.is_some() && path_res == self.impl_self
2448 }
2449 _ => false,
2450 }
2451 }
2452 }
2453
2454 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2455 fn visit_ty(&mut self, ty: &'ra Ty) {
2456 trace!("SelfVisitor considering ty={:?}", ty);
2457 if self.is_self_ty(ty) {
2458 trace!("SelfVisitor found Self");
2459 self.self_found = true;
2460 }
2461 visit::walk_ty(self, ty)
2462 }
2463
2464 fn visit_expr(&mut self, _: &'ra Expr) {}
2467 }
2468
2469 let impl_self = self
2470 .diag_metadata
2471 .current_self_type
2472 .as_ref()
2473 .and_then(|ty| {
2474 if let TyKind::Path(None, _) = ty.kind {
2475 self.r.partial_res_map.get(&ty.id)
2476 } else {
2477 None
2478 }
2479 })
2480 .and_then(|res| res.full_res())
2481 .filter(|res| {
2482 matches!(
2486 res,
2487 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2488 )
2489 });
2490 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2491 visitor.visit_ty(ty);
2492 trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2493 visitor.lifetime
2494 }
2495
2496 fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2499 let mut suggestion = None;
2500
2501 for i in (0..self.label_ribs.len()).rev() {
2502 let rib = &self.label_ribs[i];
2503
2504 if let RibKind::MacroDefinition(def) = rib.kind
2505 && def == self.r.macro_def(label.span.ctxt())
2508 {
2509 label.span.remove_mark();
2510 }
2511
2512 let ident = label.normalize_to_macro_rules();
2513 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2514 let definition_span = ident.span;
2515 return if self.is_label_valid_from_rib(i) {
2516 Ok((*id, definition_span))
2517 } else {
2518 Err(ResolutionError::UnreachableLabel {
2519 name: label.name,
2520 definition_span,
2521 suggestion,
2522 })
2523 };
2524 }
2525
2526 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2529 }
2530
2531 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2532 }
2533
2534 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2536 let ribs = &self.label_ribs[rib_index + 1..];
2537 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2538 }
2539
2540 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2541 debug!("resolve_adt");
2542 let kind = self.r.local_def_kind(item.id);
2543 self.with_current_self_item(item, |this| {
2544 this.with_generic_param_rib(
2545 &generics.params,
2546 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2547 item.id,
2548 LifetimeBinderKind::Item,
2549 generics.span,
2550 |this| {
2551 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2552 this.with_self_rib(
2553 Res::SelfTyAlias {
2554 alias_to: item_def_id,
2555 forbid_generic: false,
2556 is_trait_impl: false,
2557 },
2558 |this| {
2559 visit::walk_item(this, item);
2560 },
2561 );
2562 },
2563 );
2564 });
2565 }
2566
2567 fn future_proof_import(&mut self, use_tree: &UseTree) {
2568 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2569 let ident = segment.ident;
2570 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2571 return;
2572 }
2573
2574 let nss = match use_tree.kind {
2575 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2576 _ => &[TypeNS],
2577 };
2578 let report_error = |this: &Self, ns| {
2579 if this.should_report_errs() {
2580 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2581 this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2582 }
2583 };
2584
2585 for &ns in nss {
2586 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2587 Some(LexicalScopeBinding::Res(..)) => {
2588 report_error(self, ns);
2589 }
2590 Some(LexicalScopeBinding::Item(binding)) => {
2591 if let Some(LexicalScopeBinding::Res(..)) =
2592 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2593 {
2594 report_error(self, ns);
2595 }
2596 }
2597 None => {}
2598 }
2599 }
2600 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2601 for (use_tree, _) in items {
2602 self.future_proof_import(use_tree);
2603 }
2604 }
2605 }
2606
2607 fn resolve_item(&mut self, item: &'ast Item) {
2608 let mod_inner_docs =
2609 matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2610 if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2611 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2612 }
2613
2614 debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2615
2616 let def_kind = self.r.local_def_kind(item.id);
2617 match item.kind {
2618 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2619 self.with_generic_param_rib(
2620 &generics.params,
2621 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2622 item.id,
2623 LifetimeBinderKind::Item,
2624 generics.span,
2625 |this| visit::walk_item(this, item),
2626 );
2627 }
2628
2629 ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2630 self.with_generic_param_rib(
2631 &generics.params,
2632 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2633 item.id,
2634 LifetimeBinderKind::Function,
2635 generics.span,
2636 |this| visit::walk_item(this, item),
2637 );
2638 self.resolve_define_opaques(define_opaque);
2639 }
2640
2641 ItemKind::Enum(_, ref generics, _)
2642 | ItemKind::Struct(_, ref generics, _)
2643 | ItemKind::Union(_, ref generics, _) => {
2644 self.resolve_adt(item, generics);
2645 }
2646
2647 ItemKind::Impl(box Impl {
2648 ref generics,
2649 ref of_trait,
2650 ref self_ty,
2651 items: ref impl_items,
2652 ..
2653 }) => {
2654 self.diag_metadata.current_impl_items = Some(impl_items);
2655 self.resolve_implementation(
2656 &item.attrs,
2657 generics,
2658 of_trait,
2659 self_ty,
2660 item.id,
2661 impl_items,
2662 );
2663 self.diag_metadata.current_impl_items = None;
2664 }
2665
2666 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2667 self.with_generic_param_rib(
2669 &generics.params,
2670 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2671 item.id,
2672 LifetimeBinderKind::Item,
2673 generics.span,
2674 |this| {
2675 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2676 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2677 this.visit_generics(generics);
2678 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2679 this.resolve_trait_items(items);
2680 });
2681 },
2682 );
2683 }
2684
2685 ItemKind::TraitAlias(_, ref generics, ref bounds) => {
2686 self.with_generic_param_rib(
2688 &generics.params,
2689 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2690 item.id,
2691 LifetimeBinderKind::Item,
2692 generics.span,
2693 |this| {
2694 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2695 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2696 this.visit_generics(generics);
2697 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2698 });
2699 },
2700 );
2701 }
2702
2703 ItemKind::Mod(..) => {
2704 self.with_mod_rib(item.id, |this| {
2705 if mod_inner_docs {
2706 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2707 }
2708 let old_macro_rules = this.parent_scope.macro_rules;
2709 visit::walk_item(this, item);
2710 if item.attrs.iter().all(|attr| {
2713 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2714 }) {
2715 this.parent_scope.macro_rules = old_macro_rules;
2716 }
2717 });
2718 }
2719
2720 ItemKind::Static(box ast::StaticItem {
2721 ident,
2722 ref ty,
2723 ref expr,
2724 ref define_opaque,
2725 ..
2726 }) => {
2727 self.with_static_rib(def_kind, |this| {
2728 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2729 this.visit_ty(ty);
2730 });
2731 if let Some(expr) = expr {
2732 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Static)));
2735 }
2736 });
2737 self.resolve_define_opaques(define_opaque);
2738 }
2739
2740 ItemKind::Const(box ast::ConstItem {
2741 ident,
2742 ref generics,
2743 ref ty,
2744 ref expr,
2745 ref define_opaque,
2746 ..
2747 }) => {
2748 self.with_generic_param_rib(
2749 &generics.params,
2750 RibKind::Item(
2751 if self.r.tcx.features().generic_const_items() {
2752 HasGenericParams::Yes(generics.span)
2753 } else {
2754 HasGenericParams::No
2755 },
2756 def_kind,
2757 ),
2758 item.id,
2759 LifetimeBinderKind::ConstItem,
2760 generics.span,
2761 |this| {
2762 this.visit_generics(generics);
2763
2764 this.with_lifetime_rib(
2765 LifetimeRibKind::Elided(LifetimeRes::Static),
2766 |this| this.visit_ty(ty),
2767 );
2768
2769 if let Some(expr) = expr {
2770 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Const)));
2771 }
2772 },
2773 );
2774 self.resolve_define_opaques(define_opaque);
2775 }
2776
2777 ItemKind::Use(ref use_tree) => {
2778 let maybe_exported = match use_tree.kind {
2779 UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2780 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2781 };
2782 self.resolve_doc_links(&item.attrs, maybe_exported);
2783
2784 self.future_proof_import(use_tree);
2785 }
2786
2787 ItemKind::MacroDef(_, ref macro_def) => {
2788 if macro_def.macro_rules {
2791 let def_id = self.r.local_def_id(item.id);
2792 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2793 }
2794 }
2795
2796 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2797 visit::walk_item(self, item);
2798 }
2799
2800 ItemKind::Delegation(ref delegation) => {
2801 let span = delegation.path.segments.last().unwrap().ident.span;
2802 self.with_generic_param_rib(
2803 &[],
2804 RibKind::Item(HasGenericParams::Yes(span), def_kind),
2805 item.id,
2806 LifetimeBinderKind::Function,
2807 span,
2808 |this| this.resolve_delegation(delegation),
2809 );
2810 }
2811
2812 ItemKind::ExternCrate(..) => {}
2813
2814 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2815 panic!("unexpanded macro in resolve!")
2816 }
2817 }
2818 }
2819
2820 fn with_generic_param_rib<'c, F>(
2821 &'c mut self,
2822 params: &'c [GenericParam],
2823 kind: RibKind<'ra>,
2824 binder: NodeId,
2825 generics_kind: LifetimeBinderKind,
2826 generics_span: Span,
2827 f: F,
2828 ) where
2829 F: FnOnce(&mut Self),
2830 {
2831 debug!("with_generic_param_rib");
2832 let lifetime_kind =
2833 LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
2834
2835 let mut function_type_rib = Rib::new(kind);
2836 let mut function_value_rib = Rib::new(kind);
2837 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2838
2839 if !params.is_empty() {
2841 let mut seen_bindings = FxHashMap::default();
2842 let mut seen_lifetimes = FxHashSet::default();
2844
2845 for ns in [ValueNS, TypeNS] {
2847 for parent_rib in self.ribs[ns].iter().rev() {
2848 if matches!(parent_rib.kind, RibKind::Module(..)) {
2851 break;
2852 }
2853
2854 seen_bindings
2855 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2856 }
2857 }
2858
2859 for rib in self.lifetime_ribs.iter().rev() {
2861 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2862 if let LifetimeRibKind::Item = rib.kind {
2863 break;
2864 }
2865 }
2866
2867 for param in params {
2868 let ident = param.ident.normalize_to_macros_2_0();
2869 debug!("with_generic_param_rib: {}", param.id);
2870
2871 if let GenericParamKind::Lifetime = param.kind
2872 && let Some(&original) = seen_lifetimes.get(&ident)
2873 {
2874 diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
2875 self.record_lifetime_param(param.id, LifetimeRes::Error);
2877 continue;
2878 }
2879
2880 match seen_bindings.entry(ident) {
2881 Entry::Occupied(entry) => {
2882 let span = *entry.get();
2883 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
2884 self.report_error(param.ident.span, err);
2885 let rib = match param.kind {
2886 GenericParamKind::Lifetime => {
2887 self.record_lifetime_param(param.id, LifetimeRes::Error);
2889 continue;
2890 }
2891 GenericParamKind::Type { .. } => &mut function_type_rib,
2892 GenericParamKind::Const { .. } => &mut function_value_rib,
2893 };
2894
2895 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
2897 rib.bindings.insert(ident, Res::Err);
2898 continue;
2899 }
2900 Entry::Vacant(entry) => {
2901 entry.insert(param.ident.span);
2902 }
2903 }
2904
2905 if param.ident.name == kw::UnderscoreLifetime {
2906 self.r
2907 .dcx()
2908 .emit_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span });
2909 self.record_lifetime_param(param.id, LifetimeRes::Error);
2911 continue;
2912 }
2913
2914 if param.ident.name == kw::StaticLifetime {
2915 self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
2916 span: param.ident.span,
2917 lifetime: param.ident,
2918 });
2919 self.record_lifetime_param(param.id, LifetimeRes::Error);
2921 continue;
2922 }
2923
2924 let def_id = self.r.local_def_id(param.id);
2925
2926 let (rib, def_kind) = match param.kind {
2928 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2929 GenericParamKind::Const { .. } => {
2930 (&mut function_value_rib, DefKind::ConstParam)
2931 }
2932 GenericParamKind::Lifetime => {
2933 let res = LifetimeRes::Param { param: def_id, binder };
2934 self.record_lifetime_param(param.id, res);
2935 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2936 continue;
2937 }
2938 };
2939
2940 let res = match kind {
2941 RibKind::Item(..) | RibKind::AssocItem => {
2942 Res::Def(def_kind, def_id.to_def_id())
2943 }
2944 RibKind::Normal => {
2945 if self.r.tcx.features().non_lifetime_binders()
2948 && matches!(param.kind, GenericParamKind::Type { .. })
2949 {
2950 Res::Def(def_kind, def_id.to_def_id())
2951 } else {
2952 Res::Err
2953 }
2954 }
2955 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2956 };
2957 self.r.record_partial_res(param.id, PartialRes::new(res));
2958 rib.bindings.insert(ident, res);
2959 }
2960 }
2961
2962 self.lifetime_ribs.push(function_lifetime_rib);
2963 self.ribs[ValueNS].push(function_value_rib);
2964 self.ribs[TypeNS].push(function_type_rib);
2965
2966 f(self);
2967
2968 self.ribs[TypeNS].pop();
2969 self.ribs[ValueNS].pop();
2970 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2971
2972 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2974 for (_, res) in function_lifetime_rib.bindings.values() {
2975 candidates.retain(|(r, _)| r != res);
2976 }
2977 }
2978
2979 if let LifetimeBinderKind::BareFnType
2980 | LifetimeBinderKind::WhereBound
2981 | LifetimeBinderKind::Function
2982 | LifetimeBinderKind::ImplBlock = generics_kind
2983 {
2984 self.maybe_report_lifetime_uses(generics_span, params)
2985 }
2986 }
2987
2988 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
2989 self.label_ribs.push(Rib::new(kind));
2990 f(self);
2991 self.label_ribs.pop();
2992 }
2993
2994 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
2995 let kind = RibKind::Item(HasGenericParams::No, def_kind);
2996 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
2997 }
2998
2999 #[instrument(level = "debug", skip(self, f))]
3008 fn with_constant_rib(
3009 &mut self,
3010 is_repeat: IsRepeatExpr,
3011 may_use_generics: ConstantHasGenerics,
3012 item: Option<(Ident, ConstantItemKind)>,
3013 f: impl FnOnce(&mut Self),
3014 ) {
3015 let f = |this: &mut Self| {
3016 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3017 this.with_rib(
3018 TypeNS,
3019 RibKind::ConstantItem(
3020 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3021 item,
3022 ),
3023 |this| {
3024 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3025 },
3026 )
3027 })
3028 };
3029
3030 if let ConstantHasGenerics::No(cause) = may_use_generics {
3031 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3032 } else {
3033 f(self)
3034 }
3035 }
3036
3037 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3038 let previous_value =
3040 replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3041 let result = f(self);
3042 self.diag_metadata.current_self_type = previous_value;
3043 result
3044 }
3045
3046 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3047 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3048 let result = f(self);
3049 self.diag_metadata.current_self_item = previous_value;
3050 result
3051 }
3052
3053 fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
3055 let trait_assoc_items =
3056 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3057
3058 let walk_assoc_item =
3059 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3060 this.with_generic_param_rib(
3061 &generics.params,
3062 RibKind::AssocItem,
3063 item.id,
3064 kind,
3065 generics.span,
3066 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3067 );
3068 };
3069
3070 for item in trait_items {
3071 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3072 match &item.kind {
3073 AssocItemKind::Const(box ast::ConstItem {
3074 generics,
3075 ty,
3076 expr,
3077 define_opaque,
3078 ..
3079 }) => {
3080 self.with_generic_param_rib(
3081 &generics.params,
3082 RibKind::AssocItem,
3083 item.id,
3084 LifetimeBinderKind::ConstItem,
3085 generics.span,
3086 |this| {
3087 this.with_lifetime_rib(
3088 LifetimeRibKind::StaticIfNoLifetimeInScope {
3089 lint_id: item.id,
3090 emit_lint: false,
3091 },
3092 |this| {
3093 this.visit_generics(generics);
3094 this.visit_ty(ty);
3095
3096 if let Some(expr) = expr {
3099 this.resolve_const_body(expr, None);
3105 }
3106 },
3107 )
3108 },
3109 );
3110
3111 self.resolve_define_opaques(define_opaque);
3112 }
3113 AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3114 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3115
3116 self.resolve_define_opaques(define_opaque);
3117 }
3118 AssocItemKind::Delegation(delegation) => {
3119 self.with_generic_param_rib(
3120 &[],
3121 RibKind::AssocItem,
3122 item.id,
3123 LifetimeBinderKind::Function,
3124 delegation.path.segments.last().unwrap().ident.span,
3125 |this| this.resolve_delegation(delegation),
3126 );
3127 }
3128 AssocItemKind::Type(box TyAlias { generics, .. }) => self
3129 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3130 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3131 }),
3132 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3133 panic!("unexpanded macro in resolve!")
3134 }
3135 };
3136 }
3137
3138 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3139 }
3140
3141 fn with_optional_trait_ref<T>(
3143 &mut self,
3144 opt_trait_ref: Option<&TraitRef>,
3145 self_type: &'ast Ty,
3146 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3147 ) -> T {
3148 let mut new_val = None;
3149 let mut new_id = None;
3150 if let Some(trait_ref) = opt_trait_ref {
3151 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3152 self.diag_metadata.currently_processing_impl_trait =
3153 Some((trait_ref.clone(), self_type.clone()));
3154 let res = self.smart_resolve_path_fragment(
3155 &None,
3156 &path,
3157 PathSource::Trait(AliasPossibility::No),
3158 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3159 RecordPartialRes::Yes,
3160 None,
3161 );
3162 self.diag_metadata.currently_processing_impl_trait = None;
3163 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3164 new_id = Some(def_id);
3165 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3166 }
3167 }
3168 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3169 let result = f(self, new_id);
3170 self.current_trait_ref = original_trait_ref;
3171 result
3172 }
3173
3174 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3175 let mut self_type_rib = Rib::new(RibKind::Normal);
3176
3177 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3179 self.ribs[ns].push(self_type_rib);
3180 f(self);
3181 self.ribs[ns].pop();
3182 }
3183
3184 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3185 self.with_self_rib_ns(TypeNS, self_res, f)
3186 }
3187
3188 fn resolve_implementation(
3189 &mut self,
3190 attrs: &[ast::Attribute],
3191 generics: &'ast Generics,
3192 opt_trait_reference: &'ast Option<TraitRef>,
3193 self_type: &'ast Ty,
3194 item_id: NodeId,
3195 impl_items: &'ast [P<AssocItem>],
3196 ) {
3197 debug!("resolve_implementation");
3198 self.with_generic_param_rib(
3200 &generics.params,
3201 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3202 item_id,
3203 LifetimeBinderKind::ImplBlock,
3204 generics.span,
3205 |this| {
3206 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3208 this.with_lifetime_rib(
3209 LifetimeRibKind::AnonymousCreateParameter {
3210 binder: item_id,
3211 report_in_path: true
3212 },
3213 |this| {
3214 this.with_optional_trait_ref(
3216 opt_trait_reference.as_ref(),
3217 self_type,
3218 |this, trait_id| {
3219 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3220
3221 let item_def_id = this.r.local_def_id(item_id);
3222
3223 if let Some(trait_id) = trait_id {
3225 this.r
3226 .trait_impls
3227 .entry(trait_id)
3228 .or_default()
3229 .push(item_def_id);
3230 }
3231
3232 let item_def_id = item_def_id.to_def_id();
3233 let res = Res::SelfTyAlias {
3234 alias_to: item_def_id,
3235 forbid_generic: false,
3236 is_trait_impl: trait_id.is_some()
3237 };
3238 this.with_self_rib(res, |this| {
3239 if let Some(trait_ref) = opt_trait_reference.as_ref() {
3240 visit::walk_trait_ref(this, trait_ref);
3242 }
3243 this.visit_ty(self_type);
3245 this.visit_generics(generics);
3247
3248 this.with_current_self_type(self_type, |this| {
3250 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3251 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3252 let mut seen_trait_items = Default::default();
3253 for item in impl_items {
3254 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3255 }
3256 });
3257 });
3258 });
3259 },
3260 )
3261 },
3262 );
3263 });
3264 },
3265 );
3266 }
3267
3268 fn resolve_impl_item(
3269 &mut self,
3270 item: &'ast AssocItem,
3271 seen_trait_items: &mut FxHashMap<DefId, Span>,
3272 trait_id: Option<DefId>,
3273 ) {
3274 use crate::ResolutionError::*;
3275 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3276 match &item.kind {
3277 AssocItemKind::Const(box ast::ConstItem {
3278 ident,
3279 generics,
3280 ty,
3281 expr,
3282 define_opaque,
3283 ..
3284 }) => {
3285 debug!("resolve_implementation AssocItemKind::Const");
3286 self.with_generic_param_rib(
3287 &generics.params,
3288 RibKind::AssocItem,
3289 item.id,
3290 LifetimeBinderKind::ConstItem,
3291 generics.span,
3292 |this| {
3293 this.with_lifetime_rib(
3294 LifetimeRibKind::AnonymousCreateParameter {
3298 binder: item.id,
3299 report_in_path: true,
3300 },
3301 |this| {
3302 this.with_lifetime_rib(
3303 LifetimeRibKind::StaticIfNoLifetimeInScope {
3304 lint_id: item.id,
3305 emit_lint: true,
3307 },
3308 |this| {
3309 this.check_trait_item(
3312 item.id,
3313 *ident,
3314 &item.kind,
3315 ValueNS,
3316 item.span,
3317 seen_trait_items,
3318 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3319 );
3320
3321 this.visit_generics(generics);
3322 this.visit_ty(ty);
3323 if let Some(expr) = expr {
3324 this.resolve_const_body(expr, None);
3330 }
3331 },
3332 )
3333 },
3334 );
3335 },
3336 );
3337 self.resolve_define_opaques(define_opaque);
3338 }
3339 AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3340 debug!("resolve_implementation AssocItemKind::Fn");
3341 self.with_generic_param_rib(
3343 &generics.params,
3344 RibKind::AssocItem,
3345 item.id,
3346 LifetimeBinderKind::Function,
3347 generics.span,
3348 |this| {
3349 this.check_trait_item(
3352 item.id,
3353 *ident,
3354 &item.kind,
3355 ValueNS,
3356 item.span,
3357 seen_trait_items,
3358 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3359 );
3360
3361 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3362 },
3363 );
3364
3365 self.resolve_define_opaques(define_opaque);
3366 }
3367 AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3368 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3369 debug!("resolve_implementation AssocItemKind::Type");
3370 self.with_generic_param_rib(
3372 &generics.params,
3373 RibKind::AssocItem,
3374 item.id,
3375 LifetimeBinderKind::Item,
3376 generics.span,
3377 |this| {
3378 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3379 this.check_trait_item(
3382 item.id,
3383 *ident,
3384 &item.kind,
3385 TypeNS,
3386 item.span,
3387 seen_trait_items,
3388 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3389 );
3390
3391 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3392 });
3393 },
3394 );
3395 self.diag_metadata.in_non_gat_assoc_type = None;
3396 }
3397 AssocItemKind::Delegation(box delegation) => {
3398 debug!("resolve_implementation AssocItemKind::Delegation");
3399 self.with_generic_param_rib(
3400 &[],
3401 RibKind::AssocItem,
3402 item.id,
3403 LifetimeBinderKind::Function,
3404 delegation.path.segments.last().unwrap().ident.span,
3405 |this| {
3406 this.check_trait_item(
3407 item.id,
3408 delegation.ident,
3409 &item.kind,
3410 ValueNS,
3411 item.span,
3412 seen_trait_items,
3413 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3414 );
3415
3416 this.resolve_delegation(delegation)
3417 },
3418 );
3419 }
3420 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3421 panic!("unexpanded macro in resolve!")
3422 }
3423 }
3424 }
3425
3426 fn check_trait_item<F>(
3427 &mut self,
3428 id: NodeId,
3429 mut ident: Ident,
3430 kind: &AssocItemKind,
3431 ns: Namespace,
3432 span: Span,
3433 seen_trait_items: &mut FxHashMap<DefId, Span>,
3434 err: F,
3435 ) where
3436 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3437 {
3438 let Some((module, _)) = self.current_trait_ref else {
3440 return;
3441 };
3442 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3443 let key = BindingKey::new(ident, ns);
3444 let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
3445 debug!(?binding);
3446 if binding.is_none() {
3447 let ns = match ns {
3450 ValueNS => TypeNS,
3451 TypeNS => ValueNS,
3452 _ => ns,
3453 };
3454 let key = BindingKey::new(ident, ns);
3455 binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
3456 debug!(?binding);
3457 }
3458
3459 let feed_visibility = |this: &mut Self, def_id| {
3460 let vis = this.r.tcx.visibility(def_id);
3461 let vis = if vis.is_visible_locally() {
3462 vis.expect_local()
3463 } else {
3464 this.r.dcx().span_delayed_bug(
3465 span,
3466 "error should be emitted when an unexpected trait item is used",
3467 );
3468 rustc_middle::ty::Visibility::Public
3469 };
3470 this.r.feed_visibility(this.r.feed(id), vis);
3471 };
3472
3473 let Some(binding) = binding else {
3474 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3476 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3477 let path_names = path_names_to_string(path);
3478 self.report_error(span, err(ident, path_names, candidate));
3479 feed_visibility(self, module.def_id());
3480 return;
3481 };
3482
3483 let res = binding.res();
3484 let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3485 feed_visibility(self, id_in_trait);
3486
3487 match seen_trait_items.entry(id_in_trait) {
3488 Entry::Occupied(entry) => {
3489 self.report_error(
3490 span,
3491 ResolutionError::TraitImplDuplicate {
3492 name: ident,
3493 old_span: *entry.get(),
3494 trait_item_span: binding.span,
3495 },
3496 );
3497 return;
3498 }
3499 Entry::Vacant(entry) => {
3500 entry.insert(span);
3501 }
3502 };
3503
3504 match (def_kind, kind) {
3505 (DefKind::AssocTy, AssocItemKind::Type(..))
3506 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3507 | (DefKind::AssocConst, AssocItemKind::Const(..))
3508 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3509 self.r.record_partial_res(id, PartialRes::new(res));
3510 return;
3511 }
3512 _ => {}
3513 }
3514
3515 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3517 let (code, kind) = match kind {
3518 AssocItemKind::Const(..) => (E0323, "const"),
3519 AssocItemKind::Fn(..) => (E0324, "method"),
3520 AssocItemKind::Type(..) => (E0325, "type"),
3521 AssocItemKind::Delegation(..) => (E0324, "method"),
3522 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3523 span_bug!(span, "unexpanded macro")
3524 }
3525 };
3526 let trait_path = path_names_to_string(path);
3527 self.report_error(
3528 span,
3529 ResolutionError::TraitImplMismatch {
3530 name: ident,
3531 kind,
3532 code,
3533 trait_path,
3534 trait_item_span: binding.span,
3535 },
3536 );
3537 }
3538
3539 fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3540 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3541 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3542 this.visit_expr(expr)
3543 });
3544 })
3545 }
3546
3547 fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3548 self.smart_resolve_path(
3549 delegation.id,
3550 &delegation.qself,
3551 &delegation.path,
3552 PathSource::Delegation,
3553 );
3554 if let Some(qself) = &delegation.qself {
3555 self.visit_ty(&qself.ty);
3556 }
3557 self.visit_path(&delegation.path);
3558 let Some(body) = &delegation.body else { return };
3559 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3560 let span = delegation.path.segments.last().unwrap().ident.span;
3561 let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3562 let res = Res::Local(delegation.id);
3563 this.innermost_rib_bindings(ValueNS).insert(ident, res);
3564 this.visit_block(body);
3565 });
3566 }
3567
3568 fn resolve_params(&mut self, params: &'ast [Param]) {
3569 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3570 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3571 for Param { pat, .. } in params {
3572 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3573 }
3574 this.apply_pattern_bindings(bindings);
3575 });
3576 for Param { ty, .. } in params {
3577 self.visit_ty(ty);
3578 }
3579 }
3580
3581 fn resolve_local(&mut self, local: &'ast Local) {
3582 debug!("resolving local ({:?})", local);
3583 visit_opt!(self, visit_ty, &local.ty);
3585
3586 if let Some((init, els)) = local.kind.init_else_opt() {
3588 self.visit_expr(init);
3589
3590 if let Some(els) = els {
3592 self.visit_block(els);
3593 }
3594 }
3595
3596 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3598 }
3599
3600 fn compute_and_check_binding_map(
3620 &mut self,
3621 pat: &Pat,
3622 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3623 let mut binding_map = FxIndexMap::default();
3624 let mut is_never_pat = false;
3625
3626 pat.walk(&mut |pat| {
3627 match pat.kind {
3628 PatKind::Ident(annotation, ident, ref sub_pat)
3629 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3630 {
3631 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3632 }
3633 PatKind::Or(ref ps) => {
3634 match self.compute_and_check_or_pat_binding_map(ps) {
3637 Ok(bm) => binding_map.extend(bm),
3638 Err(IsNeverPattern) => is_never_pat = true,
3639 }
3640 return false;
3641 }
3642 PatKind::Never => is_never_pat = true,
3643 _ => {}
3644 }
3645
3646 true
3647 });
3648
3649 if is_never_pat {
3650 for (_, binding) in binding_map {
3651 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3652 }
3653 Err(IsNeverPattern)
3654 } else {
3655 Ok(binding_map)
3656 }
3657 }
3658
3659 fn is_base_res_local(&self, nid: NodeId) -> bool {
3660 matches!(
3661 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3662 Some(Res::Local(..))
3663 )
3664 }
3665
3666 fn compute_and_check_or_pat_binding_map(
3686 &mut self,
3687 pats: &[P<Pat>],
3688 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3689 let mut missing_vars = FxIndexMap::default();
3690 let mut inconsistent_vars = FxIndexMap::default();
3691
3692 let not_never_pats = pats
3694 .iter()
3695 .filter_map(|pat| {
3696 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3697 Some((binding_map, pat))
3698 })
3699 .collect::<Vec<_>>();
3700
3701 for (map_outer, pat_outer) in not_never_pats.iter() {
3703 let inners = not_never_pats
3705 .iter()
3706 .filter(|(_, pat)| pat.id != pat_outer.id)
3707 .flat_map(|(map, _)| map);
3708
3709 for (&name, binding_inner) in inners {
3710 match map_outer.get(&name) {
3711 None => {
3712 let binding_error =
3714 missing_vars.entry(name).or_insert_with(|| BindingError {
3715 name,
3716 origin: BTreeSet::new(),
3717 target: BTreeSet::new(),
3718 could_be_path: name.as_str().starts_with(char::is_uppercase),
3719 });
3720 binding_error.origin.insert(binding_inner.span);
3721 binding_error.target.insert(pat_outer.span);
3722 }
3723 Some(binding_outer) => {
3724 if binding_outer.annotation != binding_inner.annotation {
3725 inconsistent_vars
3727 .entry(name)
3728 .or_insert((binding_inner.span, binding_outer.span));
3729 }
3730 }
3731 }
3732 }
3733 }
3734
3735 for (name, mut v) in missing_vars {
3737 if inconsistent_vars.contains_key(&name) {
3738 v.could_be_path = false;
3739 }
3740 self.report_error(
3741 *v.origin.iter().next().unwrap(),
3742 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3743 );
3744 }
3745
3746 for (name, v) in inconsistent_vars {
3748 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3749 }
3750
3751 if not_never_pats.is_empty() {
3753 Err(IsNeverPattern)
3755 } else {
3756 let mut binding_map = FxIndexMap::default();
3757 for (bm, _) in not_never_pats {
3758 binding_map.extend(bm);
3759 }
3760 Ok(binding_map)
3761 }
3762 }
3763
3764 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3766 let mut is_or_or_never = false;
3767 pat.walk(&mut |pat| match pat.kind {
3768 PatKind::Or(..) | PatKind::Never => {
3769 is_or_or_never = true;
3770 false
3771 }
3772 _ => true,
3773 });
3774 if is_or_or_never {
3775 let _ = self.compute_and_check_binding_map(pat);
3776 }
3777 }
3778
3779 fn resolve_arm(&mut self, arm: &'ast Arm) {
3780 self.with_rib(ValueNS, RibKind::Normal, |this| {
3781 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3782 visit_opt!(this, visit_expr, &arm.guard);
3783 visit_opt!(this, visit_expr, &arm.body);
3784 });
3785 }
3786
3787 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3789 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3790 self.resolve_pattern(pat, pat_src, &mut bindings);
3791 self.apply_pattern_bindings(bindings);
3792 }
3793
3794 fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3796 let rib_bindings = self.innermost_rib_bindings(ValueNS);
3797 let Some((_, pat_bindings)) = pat_bindings.pop() else {
3798 bug!("tried applying nonexistent bindings from pattern");
3799 };
3800
3801 if rib_bindings.is_empty() {
3802 *rib_bindings = pat_bindings;
3805 } else {
3806 rib_bindings.extend(pat_bindings);
3807 }
3808 }
3809
3810 fn resolve_pattern(
3813 &mut self,
3814 pat: &'ast Pat,
3815 pat_src: PatternSource,
3816 bindings: &mut PatternBindings,
3817 ) {
3818 self.visit_pat(pat);
3824 self.resolve_pattern_inner(pat, pat_src, bindings);
3825 self.check_consistent_bindings(pat);
3827 }
3828
3829 #[tracing::instrument(skip(self, bindings), level = "debug")]
3849 fn resolve_pattern_inner(
3850 &mut self,
3851 pat: &'ast Pat,
3852 pat_src: PatternSource,
3853 bindings: &mut PatternBindings,
3854 ) {
3855 pat.walk(&mut |pat| {
3857 match pat.kind {
3858 PatKind::Ident(bmode, ident, ref sub) => {
3859 let has_sub = sub.is_some();
3862 let res = self
3863 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3864 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3865 self.r.record_partial_res(pat.id, PartialRes::new(res));
3866 self.r.record_pat_span(pat.id, pat.span);
3867 }
3868 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3869 self.smart_resolve_path(
3870 pat.id,
3871 qself,
3872 path,
3873 PathSource::TupleStruct(
3874 pat.span,
3875 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3876 ),
3877 );
3878 }
3879 PatKind::Path(ref qself, ref path) => {
3880 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3881 }
3882 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3883 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3884 self.record_patterns_with_skipped_bindings(pat, rest);
3885 }
3886 PatKind::Or(ref ps) => {
3887 bindings.push((PatBoundCtx::Or, Default::default()));
3891 for p in ps {
3892 bindings.push((PatBoundCtx::Product, Default::default()));
3896 self.resolve_pattern_inner(p, pat_src, bindings);
3897 let collected = bindings.pop().unwrap().1;
3900 bindings.last_mut().unwrap().1.extend(collected);
3901 }
3902 let collected = bindings.pop().unwrap().1;
3906 bindings.last_mut().unwrap().1.extend(collected);
3907
3908 return false;
3910 }
3911 PatKind::Guard(ref subpat, ref guard) => {
3912 bindings.push((PatBoundCtx::Product, Default::default()));
3914 let binding_ctx_stack_len = bindings.len();
3917 self.resolve_pattern_inner(subpat, pat_src, bindings);
3918 assert_eq!(bindings.len(), binding_ctx_stack_len);
3919 let subpat_bindings = bindings.pop().unwrap().1;
3922 self.with_rib(ValueNS, RibKind::Normal, |this| {
3923 *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
3924 this.resolve_expr(guard, None);
3925 });
3926 bindings.last_mut().unwrap().1.extend(subpat_bindings);
3933 return false;
3935 }
3936 _ => {}
3937 }
3938 true
3939 });
3940 }
3941
3942 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
3943 match rest {
3944 ast::PatFieldsRest::Rest | ast::PatFieldsRest::Recovered(_) => {
3945 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
3947 && let Some(res) = partial_res.full_res()
3948 && let Some(def_id) = res.opt_def_id()
3949 {
3950 self.ribs[ValueNS]
3951 .last_mut()
3952 .unwrap()
3953 .patterns_with_skipped_bindings
3954 .entry(def_id)
3955 .or_default()
3956 .push((
3957 pat.span,
3958 match rest {
3959 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
3960 _ => Ok(()),
3961 },
3962 ));
3963 }
3964 }
3965 ast::PatFieldsRest::None => {}
3966 }
3967 }
3968
3969 fn fresh_binding(
3970 &mut self,
3971 ident: Ident,
3972 pat_id: NodeId,
3973 pat_src: PatternSource,
3974 bindings: &mut PatternBindings,
3975 ) -> Res {
3976 let ident = ident.normalize_to_macro_rules();
3980
3981 let already_bound_and = bindings
3983 .iter()
3984 .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
3985 if already_bound_and {
3986 use ResolutionError::*;
3988 let error = match pat_src {
3989 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
3991 _ => IdentifierBoundMoreThanOnceInSamePattern,
3993 };
3994 self.report_error(ident.span, error(ident));
3995 }
3996
3997 let already_bound_or = bindings
4000 .iter()
4001 .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4002 let res = if let Some(&res) = already_bound_or {
4003 res
4006 } else {
4007 Res::Local(pat_id)
4009 };
4010
4011 bindings.last_mut().unwrap().1.insert(ident, res);
4013 res
4014 }
4015
4016 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4017 &mut self.ribs[ns].last_mut().unwrap().bindings
4018 }
4019
4020 fn try_resolve_as_non_binding(
4021 &mut self,
4022 pat_src: PatternSource,
4023 ann: BindingMode,
4024 ident: Ident,
4025 has_sub: bool,
4026 ) -> Option<Res> {
4027 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4031
4032 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4033 let (res, binding) = match ls_binding {
4034 LexicalScopeBinding::Item(binding)
4035 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4036 {
4037 self.r.record_use(ident, binding, Used::Other);
4042 return None;
4043 }
4044 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4045 LexicalScopeBinding::Res(res) => (res, None),
4046 };
4047
4048 match res {
4049 Res::SelfCtor(_) | Res::Def(
4051 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4052 _,
4053 ) if is_syntactic_ambiguity => {
4054 if let Some(binding) = binding {
4056 self.r.record_use(ident, binding, Used::Other);
4057 }
4058 Some(res)
4059 }
4060 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4061 let binding = binding.expect("no binding for a ctor or static");
4067 self.report_error(
4068 ident.span,
4069 ResolutionError::BindingShadowsSomethingUnacceptable {
4070 shadowing_binding: pat_src,
4071 name: ident.name,
4072 participle: if binding.is_import() { "imported" } else { "defined" },
4073 article: binding.res().article(),
4074 shadowed_binding: binding.res(),
4075 shadowed_binding_span: binding.span,
4076 },
4077 );
4078 None
4079 }
4080 Res::Def(DefKind::ConstParam, def_id) => {
4081 self.report_error(
4084 ident.span,
4085 ResolutionError::BindingShadowsSomethingUnacceptable {
4086 shadowing_binding: pat_src,
4087 name: ident.name,
4088 participle: "defined",
4089 article: res.article(),
4090 shadowed_binding: res,
4091 shadowed_binding_span: self.r.def_span(def_id),
4092 }
4093 );
4094 None
4095 }
4096 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4097 None
4099 }
4100 Res::SelfCtor(_) => {
4101 self.r.dcx().span_delayed_bug(
4104 ident.span,
4105 "unexpected `SelfCtor` in pattern, expected identifier"
4106 );
4107 None
4108 }
4109 _ => span_bug!(
4110 ident.span,
4111 "unexpected resolution for an identifier in pattern: {:?}",
4112 res,
4113 ),
4114 }
4115 }
4116
4117 fn smart_resolve_path(
4123 &mut self,
4124 id: NodeId,
4125 qself: &Option<P<QSelf>>,
4126 path: &Path,
4127 source: PathSource<'_, 'ast, '_>,
4128 ) {
4129 self.smart_resolve_path_fragment(
4130 qself,
4131 &Segment::from_path(path),
4132 source,
4133 Finalize::new(id, path.span),
4134 RecordPartialRes::Yes,
4135 None,
4136 );
4137 }
4138
4139 #[instrument(level = "debug", skip(self))]
4140 fn smart_resolve_path_fragment(
4141 &mut self,
4142 qself: &Option<P<QSelf>>,
4143 path: &[Segment],
4144 source: PathSource<'_, 'ast, '_>,
4145 finalize: Finalize,
4146 record_partial_res: RecordPartialRes,
4147 parent_qself: Option<&QSelf>,
4148 ) -> PartialRes {
4149 let ns = source.namespace();
4150
4151 let Finalize { node_id, path_span, .. } = finalize;
4152 let report_errors = |this: &mut Self, res: Option<Res>| {
4153 if this.should_report_errs() {
4154 let (err, candidates) = this.smart_resolve_report_errors(
4155 path,
4156 None,
4157 path_span,
4158 source,
4159 res,
4160 parent_qself,
4161 );
4162
4163 let def_id = this.parent_scope.module.nearest_parent_mod();
4164 let instead = res.is_some();
4165 let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4166 && path[0].ident.span.lo() == end.span.lo()
4167 && !matches!(start.kind, ExprKind::Lit(_))
4168 {
4169 let mut sugg = ".";
4170 let mut span = start.span.between(end.span);
4171 if span.lo() + BytePos(2) == span.hi() {
4172 span = span.with_lo(span.lo() + BytePos(1));
4175 sugg = "";
4176 }
4177 Some((
4178 span,
4179 "you might have meant to write `.` instead of `..`",
4180 sugg.to_string(),
4181 Applicability::MaybeIncorrect,
4182 ))
4183 } else if res.is_none()
4184 && let PathSource::Type
4185 | PathSource::Expr(_)
4186 | PathSource::PreciseCapturingArg(..) = source
4187 {
4188 this.suggest_adding_generic_parameter(path, source)
4189 } else {
4190 None
4191 };
4192
4193 let ue = UseError {
4194 err,
4195 candidates,
4196 def_id,
4197 instead,
4198 suggestion,
4199 path: path.into(),
4200 is_call: source.is_call(),
4201 };
4202
4203 this.r.use_injections.push(ue);
4204 }
4205
4206 PartialRes::new(Res::Err)
4207 };
4208
4209 let report_errors_for_call =
4215 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4216 let (following_seg, prefix_path) = match path.split_last() {
4220 Some((last, path)) if !path.is_empty() => (Some(last), path),
4221 _ => return Some(parent_err),
4222 };
4223
4224 let (mut err, candidates) = this.smart_resolve_report_errors(
4225 prefix_path,
4226 following_seg,
4227 path_span,
4228 PathSource::Type,
4229 None,
4230 parent_qself,
4231 );
4232
4233 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4248
4249 err.messages = take(&mut parent_err.messages);
4251 err.code = take(&mut parent_err.code);
4252 swap(&mut err.span, &mut parent_err.span);
4253 err.children = take(&mut parent_err.children);
4254 err.sort_span = parent_err.sort_span;
4255 err.is_lint = parent_err.is_lint.clone();
4256
4257 match &mut err.suggestions {
4259 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4260 Suggestions::Enabled(parent_suggestions) => {
4261 typo_suggestions.append(parent_suggestions)
4263 }
4264 Suggestions::Sealed(_) | Suggestions::Disabled => {
4265 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4270 }
4271 },
4272 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4273 }
4274
4275 parent_err.cancel();
4276
4277 let def_id = this.parent_scope.module.nearest_parent_mod();
4278
4279 if this.should_report_errs() {
4280 if candidates.is_empty() {
4281 if path.len() == 2
4282 && let [segment] = prefix_path
4283 {
4284 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4290 } else {
4291 err.emit();
4296 }
4297 } else {
4298 this.r.use_injections.push(UseError {
4300 err,
4301 candidates,
4302 def_id,
4303 instead: false,
4304 suggestion: None,
4305 path: prefix_path.into(),
4306 is_call: source.is_call(),
4307 });
4308 }
4309 } else {
4310 err.cancel();
4311 }
4312
4313 None
4316 };
4317
4318 let partial_res = match self.resolve_qpath_anywhere(
4319 qself,
4320 path,
4321 ns,
4322 path_span,
4323 source.defer_to_typeck(),
4324 finalize,
4325 source,
4326 ) {
4327 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4328 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4330 && let [Segment { ident, .. }] = path
4331 && items.iter().any(|item| {
4332 if let AssocItemKind::Type(alias) = &item.kind
4333 && alias.ident == *ident
4334 {
4335 true
4336 } else {
4337 false
4338 }
4339 })
4340 {
4341 let mut diag = self.r.tcx.dcx().struct_allow("");
4342 diag.span_suggestion_verbose(
4343 path_span.shrink_to_lo(),
4344 "there is an associated type with the same name",
4345 "Self::",
4346 Applicability::MaybeIncorrect,
4347 );
4348 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4349 }
4350
4351 if source.is_expected(res) || res == Res::Err {
4352 partial_res
4353 } else {
4354 report_errors(self, Some(res))
4355 }
4356 }
4357
4358 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4359 if ns == ValueNS {
4363 let item_name = path.last().unwrap().ident;
4364 let traits = self.traits_in_scope(item_name, ns);
4365 self.r.trait_map.insert(node_id, traits);
4366 }
4367
4368 if PrimTy::from_name(path[0].ident.name).is_some() {
4369 let mut std_path = Vec::with_capacity(1 + path.len());
4370
4371 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4372 std_path.extend(path);
4373 if let PathResult::Module(_) | PathResult::NonModule(_) =
4374 self.resolve_path(&std_path, Some(ns), None)
4375 {
4376 let item_span =
4378 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4379
4380 self.r.confused_type_with_std_module.insert(item_span, path_span);
4381 self.r.confused_type_with_std_module.insert(path_span, path_span);
4382 }
4383 }
4384
4385 partial_res
4386 }
4387
4388 Err(err) => {
4389 if let Some(err) = report_errors_for_call(self, err) {
4390 self.report_error(err.span, err.node);
4391 }
4392
4393 PartialRes::new(Res::Err)
4394 }
4395
4396 _ => report_errors(self, None),
4397 };
4398
4399 if record_partial_res == RecordPartialRes::Yes {
4400 self.r.record_partial_res(node_id, partial_res);
4402 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4403 self.lint_unused_qualifications(path, ns, finalize);
4404 }
4405
4406 partial_res
4407 }
4408
4409 fn self_type_is_available(&mut self) -> bool {
4410 let binding = self
4411 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4412 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4413 }
4414
4415 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4416 let ident = Ident::new(kw::SelfLower, self_span);
4417 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4418 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4419 }
4420
4421 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4425 if self.should_report_errs() {
4426 self.r.report_error(span, resolution_error);
4427 }
4428 }
4429
4430 #[inline]
4431 fn should_report_errs(&self) -> bool {
4435 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4436 && !self.r.glob_error.is_some()
4437 }
4438
4439 fn resolve_qpath_anywhere(
4441 &mut self,
4442 qself: &Option<P<QSelf>>,
4443 path: &[Segment],
4444 primary_ns: Namespace,
4445 span: Span,
4446 defer_to_typeck: bool,
4447 finalize: Finalize,
4448 source: PathSource<'_, 'ast, '_>,
4449 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4450 let mut fin_res = None;
4451
4452 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4453 if i == 0 || ns != primary_ns {
4454 match self.resolve_qpath(qself, path, ns, finalize, source)? {
4455 Some(partial_res)
4456 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4457 {
4458 return Ok(Some(partial_res));
4459 }
4460 partial_res => {
4461 if fin_res.is_none() {
4462 fin_res = partial_res;
4463 }
4464 }
4465 }
4466 }
4467 }
4468
4469 assert!(primary_ns != MacroNS);
4470
4471 if qself.is_none() {
4472 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
4473 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
4474 if let Ok((_, res)) =
4475 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false, None, None)
4476 {
4477 return Ok(Some(PartialRes::new(res)));
4478 }
4479 }
4480
4481 Ok(fin_res)
4482 }
4483
4484 fn resolve_qpath(
4486 &mut self,
4487 qself: &Option<P<QSelf>>,
4488 path: &[Segment],
4489 ns: Namespace,
4490 finalize: Finalize,
4491 source: PathSource<'_, 'ast, '_>,
4492 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4493 debug!(
4494 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4495 qself, path, ns, finalize,
4496 );
4497
4498 if let Some(qself) = qself {
4499 if qself.position == 0 {
4500 return Ok(Some(PartialRes::with_unresolved_segments(
4504 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4505 path.len(),
4506 )));
4507 }
4508
4509 let num_privacy_errors = self.r.privacy_errors.len();
4510 let trait_res = self.smart_resolve_path_fragment(
4512 &None,
4513 &path[..qself.position],
4514 PathSource::Trait(AliasPossibility::No),
4515 Finalize::new(finalize.node_id, qself.path_span),
4516 RecordPartialRes::No,
4517 Some(&qself),
4518 );
4519
4520 if trait_res.expect_full_res() == Res::Err {
4521 return Ok(Some(trait_res));
4522 }
4523
4524 self.r.privacy_errors.truncate(num_privacy_errors);
4527
4528 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4536 let partial_res = self.smart_resolve_path_fragment(
4537 &None,
4538 &path[..=qself.position],
4539 PathSource::TraitItem(ns, &source),
4540 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4541 RecordPartialRes::No,
4542 Some(&qself),
4543 );
4544
4545 return Ok(Some(PartialRes::with_unresolved_segments(
4549 partial_res.base_res(),
4550 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4551 )));
4552 }
4553
4554 let result = match self.resolve_path(path, Some(ns), Some(finalize)) {
4555 PathResult::NonModule(path_res) => path_res,
4556 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4557 PartialRes::new(module.res().unwrap())
4558 }
4559 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4563 PartialRes::new(Res::Err)
4564 }
4565 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4578 if (ns == TypeNS || path.len() > 1)
4579 && PrimTy::from_name(path[0].ident.name).is_some() =>
4580 {
4581 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4582 let tcx = self.r.tcx();
4583
4584 let gate_err_sym_msg = match prim {
4585 PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4586 Some((sym::f16, "the type `f16` is unstable"))
4587 }
4588 PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4589 Some((sym::f128, "the type `f128` is unstable"))
4590 }
4591 _ => None,
4592 };
4593
4594 if let Some((sym, msg)) = gate_err_sym_msg {
4595 let span = path[0].ident.span;
4596 if !span.allows_unstable(sym) {
4597 feature_err(tcx.sess, sym, span, msg).emit();
4598 }
4599 };
4600
4601 if let Some(id) = path[0].id {
4603 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4604 }
4605
4606 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4607 }
4608 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4609 PartialRes::new(module.res().unwrap())
4610 }
4611 PathResult::Failed {
4612 is_error_from_last_segment: false,
4613 span,
4614 label,
4615 suggestion,
4616 module,
4617 segment_name,
4618 error_implied_by_parse_error: _,
4619 } => {
4620 return Err(respan(
4621 span,
4622 ResolutionError::FailedToResolve {
4623 segment: Some(segment_name),
4624 label,
4625 suggestion,
4626 module,
4627 },
4628 ));
4629 }
4630 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4631 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4632 };
4633
4634 Ok(Some(result))
4635 }
4636
4637 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4638 if let Some(label) = label {
4639 if label.ident.as_str().as_bytes()[1] != b'_' {
4640 self.diag_metadata.unused_labels.insert(id, label.ident.span);
4641 }
4642
4643 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4644 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4645 }
4646
4647 self.with_label_rib(RibKind::Normal, |this| {
4648 let ident = label.ident.normalize_to_macro_rules();
4649 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4650 f(this);
4651 });
4652 } else {
4653 f(self);
4654 }
4655 }
4656
4657 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4658 self.with_resolved_label(label, id, |this| this.visit_block(block));
4659 }
4660
4661 fn resolve_block(&mut self, block: &'ast Block) {
4662 debug!("(resolving block) entering block");
4663 let orig_module = self.parent_scope.module;
4665 let anonymous_module = self.r.block_map.get(&block.id).cloned(); let mut num_macro_definition_ribs = 0;
4668 if let Some(anonymous_module) = anonymous_module {
4669 debug!("(resolving block) found anonymous module, moving down");
4670 self.ribs[ValueNS].push(Rib::new(RibKind::Module(anonymous_module)));
4671 self.ribs[TypeNS].push(Rib::new(RibKind::Module(anonymous_module)));
4672 self.parent_scope.module = anonymous_module;
4673 } else {
4674 self.ribs[ValueNS].push(Rib::new(RibKind::Normal));
4675 }
4676
4677 for stmt in &block.stmts {
4679 if let StmtKind::Item(ref item) = stmt.kind
4680 && let ItemKind::MacroDef(..) = item.kind
4681 {
4682 num_macro_definition_ribs += 1;
4683 let res = self.r.local_def_id(item.id).to_def_id();
4684 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4685 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4686 }
4687
4688 self.visit_stmt(stmt);
4689 }
4690
4691 self.parent_scope.module = orig_module;
4693 for _ in 0..num_macro_definition_ribs {
4694 self.ribs[ValueNS].pop();
4695 self.label_ribs.pop();
4696 }
4697 self.last_block_rib = self.ribs[ValueNS].pop();
4698 if anonymous_module.is_some() {
4699 self.ribs[TypeNS].pop();
4700 }
4701 debug!("(resolving block) leaving block");
4702 }
4703
4704 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4705 debug!(
4706 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4707 constant, anon_const_kind
4708 );
4709
4710 let is_trivial_const_arg = constant
4711 .value
4712 .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4713 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4714 this.resolve_expr(&constant.value, None)
4715 })
4716 }
4717
4718 fn resolve_anon_const_manual(
4725 &mut self,
4726 is_trivial_const_arg: bool,
4727 anon_const_kind: AnonConstKind,
4728 resolve_expr: impl FnOnce(&mut Self),
4729 ) {
4730 let is_repeat_expr = match anon_const_kind {
4731 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4732 _ => IsRepeatExpr::No,
4733 };
4734
4735 let may_use_generics = match anon_const_kind {
4736 AnonConstKind::EnumDiscriminant => {
4737 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4738 }
4739 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4740 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4741 AnonConstKind::ConstArg(_) => {
4742 if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4743 ConstantHasGenerics::Yes
4744 } else {
4745 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4746 }
4747 }
4748 };
4749
4750 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4751 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4752 resolve_expr(this);
4753 });
4754 });
4755 }
4756
4757 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4758 self.resolve_expr(&f.expr, Some(e));
4759 self.visit_ident(&f.ident);
4760 walk_list!(self, visit_attribute, f.attrs.iter());
4761 }
4762
4763 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4764 self.record_candidate_traits_for_expr_if_necessary(expr);
4768
4769 match expr.kind {
4771 ExprKind::Path(ref qself, ref path) => {
4772 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4773 visit::walk_expr(self, expr);
4774 }
4775
4776 ExprKind::Struct(ref se) => {
4777 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct);
4778 if let Some(qself) = &se.qself {
4782 self.visit_ty(&qself.ty);
4783 }
4784 self.visit_path(&se.path);
4785 walk_list!(self, resolve_expr_field, &se.fields, expr);
4786 match &se.rest {
4787 StructRest::Base(expr) => self.visit_expr(expr),
4788 StructRest::Rest(_span) => {}
4789 StructRest::None => {}
4790 }
4791 }
4792
4793 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4794 match self.resolve_label(label.ident) {
4795 Ok((node_id, _)) => {
4796 self.r.label_res_map.insert(expr.id, node_id);
4798 self.diag_metadata.unused_labels.swap_remove(&node_id);
4799 }
4800 Err(error) => {
4801 self.report_error(label.ident.span, error);
4802 }
4803 }
4804
4805 visit::walk_expr(self, expr);
4807 }
4808
4809 ExprKind::Break(None, Some(ref e)) => {
4810 self.resolve_expr(e, Some(expr));
4813 }
4814
4815 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
4816 self.visit_expr(scrutinee);
4817 self.resolve_pattern_top(pat, PatternSource::Let);
4818 }
4819
4820 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
4821 self.visit_expr(scrutinee);
4822 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4824 self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
4825 for (_, bindings) in &mut bindings {
4830 for (_, binding) in bindings {
4831 *binding = Res::Err;
4832 }
4833 }
4834 self.apply_pattern_bindings(bindings);
4835 }
4836
4837 ExprKind::If(ref cond, ref then, ref opt_else) => {
4838 self.with_rib(ValueNS, RibKind::Normal, |this| {
4839 let old = this.diag_metadata.in_if_condition.replace(cond);
4840 this.visit_expr(cond);
4841 this.diag_metadata.in_if_condition = old;
4842 this.visit_block(then);
4843 });
4844 if let Some(expr) = opt_else {
4845 self.visit_expr(expr);
4846 }
4847 }
4848
4849 ExprKind::Loop(ref block, label, _) => {
4850 self.resolve_labeled_block(label, expr.id, block)
4851 }
4852
4853 ExprKind::While(ref cond, ref block, label) => {
4854 self.with_resolved_label(label, expr.id, |this| {
4855 this.with_rib(ValueNS, RibKind::Normal, |this| {
4856 let old = this.diag_metadata.in_if_condition.replace(cond);
4857 this.visit_expr(cond);
4858 this.diag_metadata.in_if_condition = old;
4859 this.visit_block(block);
4860 })
4861 });
4862 }
4863
4864 ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4865 self.visit_expr(iter);
4866 self.with_rib(ValueNS, RibKind::Normal, |this| {
4867 this.resolve_pattern_top(pat, PatternSource::For);
4868 this.resolve_labeled_block(label, expr.id, body);
4869 });
4870 }
4871
4872 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4873
4874 ExprKind::Field(ref subexpression, _) => {
4876 self.resolve_expr(subexpression, Some(expr));
4877 }
4878 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
4879 self.resolve_expr(receiver, Some(expr));
4880 for arg in args {
4881 self.resolve_expr(arg, None);
4882 }
4883 self.visit_path_segment(seg);
4884 }
4885
4886 ExprKind::Call(ref callee, ref arguments) => {
4887 self.resolve_expr(callee, Some(expr));
4888 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
4889 for (idx, argument) in arguments.iter().enumerate() {
4890 if const_args.contains(&idx) {
4893 let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
4894 self.r.tcx.features().min_generic_const_args(),
4895 );
4896 self.resolve_anon_const_manual(
4897 is_trivial_const_arg,
4898 AnonConstKind::ConstArg(IsRepeatExpr::No),
4899 |this| this.resolve_expr(argument, None),
4900 );
4901 } else {
4902 self.resolve_expr(argument, None);
4903 }
4904 }
4905 }
4906 ExprKind::Type(ref _type_expr, ref _ty) => {
4907 visit::walk_expr(self, expr);
4908 }
4909 ExprKind::Closure(box ast::Closure {
4911 binder: ClosureBinder::For { ref generic_params, span },
4912 ..
4913 }) => {
4914 self.with_generic_param_rib(
4915 generic_params,
4916 RibKind::Normal,
4917 expr.id,
4918 LifetimeBinderKind::Closure,
4919 span,
4920 |this| visit::walk_expr(this, expr),
4921 );
4922 }
4923 ExprKind::Closure(..) => visit::walk_expr(self, expr),
4924 ExprKind::Gen(..) => {
4925 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
4926 }
4927 ExprKind::Repeat(ref elem, ref ct) => {
4928 self.visit_expr(elem);
4929 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
4930 }
4931 ExprKind::ConstBlock(ref ct) => {
4932 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
4933 }
4934 ExprKind::Index(ref elem, ref idx, _) => {
4935 self.resolve_expr(elem, Some(expr));
4936 self.visit_expr(idx);
4937 }
4938 ExprKind::Assign(ref lhs, ref rhs, _) => {
4939 if !self.diag_metadata.is_assign_rhs {
4940 self.diag_metadata.in_assignment = Some(expr);
4941 }
4942 self.visit_expr(lhs);
4943 self.diag_metadata.is_assign_rhs = true;
4944 self.diag_metadata.in_assignment = None;
4945 self.visit_expr(rhs);
4946 self.diag_metadata.is_assign_rhs = false;
4947 }
4948 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
4949 self.diag_metadata.in_range = Some((start, end));
4950 self.resolve_expr(start, Some(expr));
4951 self.resolve_expr(end, Some(expr));
4952 self.diag_metadata.in_range = None;
4953 }
4954 _ => {
4955 visit::walk_expr(self, expr);
4956 }
4957 }
4958 }
4959
4960 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
4961 match expr.kind {
4962 ExprKind::Field(_, ident) => {
4963 let traits = self.traits_in_scope(ident, ValueNS);
4968 self.r.trait_map.insert(expr.id, traits);
4969 }
4970 ExprKind::MethodCall(ref call) => {
4971 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
4972 let traits = self.traits_in_scope(call.seg.ident, ValueNS);
4973 self.r.trait_map.insert(expr.id, traits);
4974 }
4975 _ => {
4976 }
4978 }
4979 }
4980
4981 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
4982 self.r.traits_in_scope(
4983 self.current_trait_ref.as_ref().map(|(module, _)| *module),
4984 &self.parent_scope,
4985 ident.span.ctxt(),
4986 Some((ident.name, ns)),
4987 )
4988 }
4989
4990 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
4991 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
4995 let res = *doc_link_resolutions
4996 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
4997 .or_default()
4998 .entry((Symbol::intern(path_str), ns))
4999 .or_insert_with_key(|(path, ns)| {
5000 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5001 if let Some(res) = res
5002 && let Some(def_id) = res.opt_def_id()
5003 && self.is_invalid_proc_macro_item_for_doc(def_id)
5004 {
5005 return None;
5008 }
5009 res
5010 });
5011 self.r.doc_link_resolutions = doc_link_resolutions;
5012 res
5013 }
5014
5015 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5016 if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5017 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5018 {
5019 return false;
5020 }
5021 let Some(local_did) = did.as_local() else { return true };
5022 !self.r.proc_macros.contains(&local_did)
5023 }
5024
5025 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5026 match self.r.tcx.sess.opts.resolve_doc_links {
5027 ResolveDocLinks::None => return,
5028 ResolveDocLinks::ExportedMetadata
5029 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5030 || !maybe_exported.eval(self.r) =>
5031 {
5032 return;
5033 }
5034 ResolveDocLinks::Exported
5035 if !maybe_exported.eval(self.r)
5036 && !rustdoc::has_primitive_or_keyword_docs(attrs) =>
5037 {
5038 return;
5039 }
5040 ResolveDocLinks::ExportedMetadata
5041 | ResolveDocLinks::Exported
5042 | ResolveDocLinks::All => {}
5043 }
5044
5045 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5046 return;
5047 }
5048
5049 let mut need_traits_in_scope = false;
5050 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5051 let mut any_resolved = false;
5053 let mut need_assoc = false;
5054 for ns in [TypeNS, ValueNS, MacroNS] {
5055 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5056 any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5059 } else if ns != MacroNS {
5060 need_assoc = true;
5061 }
5062 }
5063
5064 if need_assoc || !any_resolved {
5066 let mut path = &path_str[..];
5067 while let Some(idx) = path.rfind("::") {
5068 path = &path[..idx];
5069 need_traits_in_scope = true;
5070 for ns in [TypeNS, ValueNS, MacroNS] {
5071 self.resolve_and_cache_rustdoc_path(path, ns);
5072 }
5073 }
5074 }
5075 }
5076
5077 if need_traits_in_scope {
5078 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5080 doc_link_traits_in_scope
5081 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5082 .or_insert_with(|| {
5083 self.r
5084 .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5085 .into_iter()
5086 .filter_map(|tr| {
5087 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5088 return None;
5091 }
5092 Some(tr.def_id)
5093 })
5094 .collect()
5095 });
5096 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5097 }
5098 }
5099
5100 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5101 if let Some(seg) = path.first()
5103 && seg.ident.name == kw::PathRoot
5104 {
5105 return;
5106 }
5107
5108 if finalize.path_span.from_expansion()
5109 || path.iter().any(|seg| seg.ident.span.from_expansion())
5110 {
5111 return;
5112 }
5113
5114 let end_pos =
5115 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5116 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5117 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5126 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5127 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5128 (res == binding.res()).then_some((seg, binding))
5129 });
5130
5131 if let Some((seg, binding)) = unqualified {
5132 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5133 binding,
5134 node_id: finalize.node_id,
5135 path_span: finalize.path_span,
5136 removal_span: path[0].ident.span.until(seg.ident.span),
5137 });
5138 }
5139 }
5140
5141 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5142 if let Some(define_opaque) = define_opaque {
5143 for (id, path) in define_opaque {
5144 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5145 }
5146 }
5147 }
5148}
5149
5150struct ItemInfoCollector<'a, 'ra, 'tcx> {
5153 r: &'a mut Resolver<'ra, 'tcx>,
5154}
5155
5156impl ItemInfoCollector<'_, '_, '_> {
5157 fn collect_fn_info(
5158 &mut self,
5159 header: FnHeader,
5160 decl: &FnDecl,
5161 id: NodeId,
5162 attrs: &[Attribute],
5163 ) {
5164 let sig = DelegationFnSig {
5165 header,
5166 param_count: decl.inputs.len(),
5167 has_self: decl.has_self(),
5168 c_variadic: decl.c_variadic(),
5169 target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5170 };
5171 self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5172 }
5173}
5174
5175impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5176 fn visit_item(&mut self, item: &'ast Item) {
5177 match &item.kind {
5178 ItemKind::TyAlias(box TyAlias { generics, .. })
5179 | ItemKind::Const(box ConstItem { generics, .. })
5180 | ItemKind::Fn(box Fn { generics, .. })
5181 | ItemKind::Enum(_, generics, _)
5182 | ItemKind::Struct(_, generics, _)
5183 | ItemKind::Union(_, generics, _)
5184 | ItemKind::Impl(box Impl { generics, .. })
5185 | ItemKind::Trait(box Trait { generics, .. })
5186 | ItemKind::TraitAlias(_, generics, _) => {
5187 if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5188 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5189 }
5190
5191 let def_id = self.r.local_def_id(item.id);
5192 let count = generics
5193 .params
5194 .iter()
5195 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5196 .count();
5197 self.r.item_generics_num_lifetimes.insert(def_id, count);
5198 }
5199
5200 ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5201 for foreign_item in items {
5202 if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5203 let new_header =
5204 FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5205 self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5206 }
5207 }
5208 }
5209
5210 ItemKind::Mod(..)
5211 | ItemKind::Static(..)
5212 | ItemKind::Use(..)
5213 | ItemKind::ExternCrate(..)
5214 | ItemKind::MacroDef(..)
5215 | ItemKind::GlobalAsm(..)
5216 | ItemKind::MacCall(..)
5217 | ItemKind::DelegationMac(..) => {}
5218 ItemKind::Delegation(..) => {
5219 }
5224 }
5225 visit::walk_item(self, item)
5226 }
5227
5228 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5229 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5230 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5231 }
5232 visit::walk_assoc_item(self, item, ctxt);
5233 }
5234}
5235
5236impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5237 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5238 visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5239 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5240 late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5241 visit::walk_crate(&mut late_resolution_visitor, krate);
5242 for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5243 self.lint_buffer.buffer_lint(
5244 lint::builtin::UNUSED_LABELS,
5245 *id,
5246 *span,
5247 BuiltinLintDiag::UnusedLabel,
5248 );
5249 }
5250 }
5251}
5252
5253fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5255 let mut path = expected_path.iter().rev();
5256 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5257 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5258 return false;
5259 }
5260 def_id = parent;
5261 }
5262 true
5263}