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::visit::{
16 AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,
17};
18use rustc_ast::*;
19use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
20use rustc_data_structures::unord::{UnordMap, UnordSet};
21use rustc_errors::codes::*;
22use rustc_errors::{
23 Applicability, DiagArgValue, ErrorGuaranteed, IntoDiagArg, StashKey, Suggestions,
24};
25use rustc_hir::def::Namespace::{self, *};
26use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS};
27use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId};
28use rustc_hir::{MissingLifetimeKind, PrimTy, TraitCandidate};
29use rustc_middle::middle::resolve_bound_vars::Set1;
30use rustc_middle::ty::{DelegationFnSig, Visibility};
31use rustc_middle::{bug, span_bug};
32use rustc_session::config::{CrateType, ResolveDocLinks};
33use rustc_session::lint::{self, BuiltinLintDiag};
34use rustc_session::parse::feature_err;
35use rustc_span::source_map::{Spanned, respan};
36use rustc_span::{BytePos, Ident, Span, Symbol, SyntaxContext, kw, sym};
37use smallvec::{SmallVec, smallvec};
38use thin_vec::ThinVec;
39use tracing::{debug, instrument, trace};
40
41use crate::{
42 BindingError, BindingKey, Finalize, LexicalScopeBinding, Module, ModuleOrUniformRoot,
43 NameBinding, ParentScope, PathResult, ResolutionError, Resolver, Segment, TyCtxt, UseError,
44 Used, errors, path_names_to_string, rustdoc,
45};
46
47mod diagnostics;
48
49type Res = def::Res<NodeId>;
50
51use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
52
53#[derive(Copy, Clone, Debug)]
54struct BindingInfo {
55 span: Span,
56 annotation: BindingMode,
57}
58
59#[derive(Copy, Clone, PartialEq, Eq, Debug)]
60pub(crate) enum PatternSource {
61 Match,
62 Let,
63 For,
64 FnParam,
65}
66
67#[derive(Copy, Clone, Debug, PartialEq, Eq)]
68enum IsRepeatExpr {
69 No,
70 Yes,
71}
72
73struct IsNeverPattern;
74
75#[derive(Copy, Clone, Debug, PartialEq, Eq)]
78enum AnonConstKind {
79 EnumDiscriminant,
80 FieldDefaultValue,
81 InlineConst,
82 ConstArg(IsRepeatExpr),
83}
84
85impl PatternSource {
86 fn descr(self) -> &'static str {
87 match self {
88 PatternSource::Match => "match binding",
89 PatternSource::Let => "let binding",
90 PatternSource::For => "for binding",
91 PatternSource::FnParam => "function parameter",
92 }
93 }
94}
95
96impl IntoDiagArg for PatternSource {
97 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
98 DiagArgValue::Str(Cow::Borrowed(self.descr()))
99 }
100}
101
102#[derive(PartialEq)]
106enum PatBoundCtx {
107 Product,
109 Or,
111}
112
113type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;
125
126#[derive(Copy, Clone, Debug)]
128pub(crate) enum HasGenericParams {
129 Yes(Span),
130 No,
131}
132
133#[derive(Copy, Clone, Debug, Eq, PartialEq)]
135pub(crate) enum ConstantHasGenerics {
136 Yes,
137 No(NoConstantGenericsReason),
138}
139
140impl ConstantHasGenerics {
141 fn force_yes_if(self, b: bool) -> Self {
142 if b { Self::Yes } else { self }
143 }
144}
145
146#[derive(Copy, Clone, Debug, Eq, PartialEq)]
148pub(crate) enum NoConstantGenericsReason {
149 NonTrivialConstArg,
156 IsEnumDiscriminant,
165}
166
167#[derive(Copy, Clone, Debug, Eq, PartialEq)]
168pub(crate) enum ConstantItemKind {
169 Const,
170 Static,
171}
172
173impl ConstantItemKind {
174 pub(crate) fn as_str(&self) -> &'static str {
175 match self {
176 Self::Const => "const",
177 Self::Static => "static",
178 }
179 }
180}
181
182#[derive(Debug, Copy, Clone, PartialEq, Eq)]
183enum RecordPartialRes {
184 Yes,
185 No,
186}
187
188#[derive(Copy, Clone, Debug)]
191pub(crate) enum RibKind<'ra> {
192 Normal,
194
195 Block(Option<Module<'ra>>),
201
202 AssocItem,
207
208 FnOrCoroutine,
210
211 Item(HasGenericParams, DefKind),
213
214 ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
219
220 Module(Module<'ra>),
222
223 MacroDefinition(DefId),
225
226 ForwardGenericParamBan(ForwardGenericParamBanReason),
230
231 ConstParamTy,
234
235 InlineAsmSym,
238}
239
240#[derive(Copy, Clone, PartialEq, Eq, Debug)]
241pub(crate) enum ForwardGenericParamBanReason {
242 Default,
243 ConstParamTy,
244}
245
246impl RibKind<'_> {
247 pub(crate) fn contains_params(&self) -> bool {
250 match self {
251 RibKind::Normal
252 | RibKind::Block(..)
253 | RibKind::FnOrCoroutine
254 | RibKind::ConstantItem(..)
255 | RibKind::Module(_)
256 | RibKind::MacroDefinition(_)
257 | RibKind::InlineAsmSym => false,
258 RibKind::ConstParamTy
259 | RibKind::AssocItem
260 | RibKind::Item(..)
261 | RibKind::ForwardGenericParamBan(_) => true,
262 }
263 }
264
265 fn is_label_barrier(self) -> bool {
267 match self {
268 RibKind::Normal | RibKind::MacroDefinition(..) => false,
269 RibKind::FnOrCoroutine | RibKind::ConstantItem(..) => true,
270 kind => bug!("unexpected rib kind: {kind:?}"),
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 FnPtrType,
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 FnPtrType => "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(Option<&'a Expr>),
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 ast::Visibility>),
642 NestedUse(&'a ast::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 [Box<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 [Box<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::FnPtr(fn_ptr) => {
904 let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());
905 self.with_generic_param_rib(
906 &fn_ptr.generic_params,
907 RibKind::Normal,
908 ty.id,
909 LifetimeBinderKind::FnPtrType,
910 span,
911 |this| {
912 this.visit_generic_params(&fn_ptr.generic_params, false);
913 this.resolve_fn_signature(
914 ty.id,
915 false,
916 fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
919 &fn_ptr.decl.output,
920 false,
921 )
922 },
923 )
924 }
925 TyKind::UnsafeBinder(unsafe_binder) => {
926 let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
927 self.with_generic_param_rib(
928 &unsafe_binder.generic_params,
929 RibKind::Normal,
930 ty.id,
931 LifetimeBinderKind::FnPtrType,
932 span,
933 |this| {
934 this.visit_generic_params(&unsafe_binder.generic_params, false);
935 this.with_lifetime_rib(
936 LifetimeRibKind::AnonymousReportError,
939 |this| this.visit_ty(&unsafe_binder.inner_ty),
940 );
941 },
942 )
943 }
944 TyKind::Array(element_ty, length) => {
945 self.visit_ty(element_ty);
946 self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
947 }
948 TyKind::Typeof(ct) => {
949 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
950 }
951 _ => visit::walk_ty(self, ty),
952 }
953 self.diag_metadata.current_trait_object = prev;
954 self.diag_metadata.current_type_path = prev_ty;
955 }
956
957 fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
958 match &t.kind {
959 TyPatKind::Range(start, end, _) => {
960 if let Some(start) = start {
961 self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
962 }
963 if let Some(end) = end {
964 self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
965 }
966 }
967 TyPatKind::Or(patterns) => {
968 for pat in patterns {
969 self.visit_ty_pat(pat)
970 }
971 }
972 TyPatKind::Err(_) => {}
973 }
974 }
975
976 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
977 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
978 self.with_generic_param_rib(
979 &tref.bound_generic_params,
980 RibKind::Normal,
981 tref.trait_ref.ref_id,
982 LifetimeBinderKind::PolyTrait,
983 span,
984 |this| {
985 this.visit_generic_params(&tref.bound_generic_params, false);
986 this.smart_resolve_path(
987 tref.trait_ref.ref_id,
988 &None,
989 &tref.trait_ref.path,
990 PathSource::Trait(AliasPossibility::Maybe),
991 );
992 this.visit_trait_ref(&tref.trait_ref);
993 },
994 );
995 }
996 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
997 self.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
998 let def_kind = self.r.local_def_kind(foreign_item.id);
999 match foreign_item.kind {
1000 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
1001 self.with_generic_param_rib(
1002 &generics.params,
1003 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1004 foreign_item.id,
1005 LifetimeBinderKind::Item,
1006 generics.span,
1007 |this| visit::walk_item(this, foreign_item),
1008 );
1009 }
1010 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
1011 self.with_generic_param_rib(
1012 &generics.params,
1013 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1014 foreign_item.id,
1015 LifetimeBinderKind::Function,
1016 generics.span,
1017 |this| visit::walk_item(this, foreign_item),
1018 );
1019 }
1020 ForeignItemKind::Static(..) => {
1021 self.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1022 }
1023 ForeignItemKind::MacCall(..) => {
1024 panic!("unexpanded macro in resolve!")
1025 }
1026 }
1027 }
1028 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
1029 let previous_value = self.diag_metadata.current_function;
1030 match fn_kind {
1031 FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1034 | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1035 self.visit_fn_header(&sig.header);
1036 self.visit_ident(ident);
1037 self.visit_generics(generics);
1038 self.resolve_fn_signature(
1039 fn_id,
1040 sig.decl.has_self(),
1041 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1042 &sig.decl.output,
1043 false,
1044 );
1045 return;
1046 }
1047 FnKind::Fn(..) => {
1048 self.diag_metadata.current_function = Some((fn_kind, sp));
1049 }
1050 FnKind::Closure(..) => {}
1052 };
1053 debug!("(resolving function) entering function");
1054
1055 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1057 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1059 match fn_kind {
1060 FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1061 this.visit_generics(generics);
1062
1063 let declaration = &sig.decl;
1064 let coro_node_id = sig
1065 .header
1066 .coroutine_kind
1067 .map(|coroutine_kind| coroutine_kind.return_id());
1068
1069 this.resolve_fn_signature(
1070 fn_id,
1071 declaration.has_self(),
1072 declaration
1073 .inputs
1074 .iter()
1075 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1076 &declaration.output,
1077 coro_node_id.is_some(),
1078 );
1079
1080 if let Some(contract) = contract {
1081 this.visit_contract(contract);
1082 }
1083
1084 if let Some(body) = body {
1085 let previous_state = replace(&mut this.in_func_body, true);
1088 this.last_block_rib = None;
1090 this.with_lifetime_rib(
1092 LifetimeRibKind::Elided(LifetimeRes::Infer),
1093 |this| this.visit_block(body),
1094 );
1095
1096 debug!("(resolving function) leaving function");
1097 this.in_func_body = previous_state;
1098 }
1099 }
1100 FnKind::Closure(binder, _, declaration, body) => {
1101 this.visit_closure_binder(binder);
1102
1103 this.with_lifetime_rib(
1104 match binder {
1105 ClosureBinder::NotPresent => {
1107 LifetimeRibKind::AnonymousCreateParameter {
1108 binder: fn_id,
1109 report_in_path: false,
1110 }
1111 }
1112 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1113 },
1114 |this| this.resolve_params(&declaration.inputs),
1116 );
1117 this.with_lifetime_rib(
1118 match binder {
1119 ClosureBinder::NotPresent => {
1120 LifetimeRibKind::Elided(LifetimeRes::Infer)
1121 }
1122 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1123 },
1124 |this| visit::walk_fn_ret_ty(this, &declaration.output),
1125 );
1126
1127 let previous_state = replace(&mut this.in_func_body, true);
1130 this.with_lifetime_rib(
1132 LifetimeRibKind::Elided(LifetimeRes::Infer),
1133 |this| this.visit_expr(body),
1134 );
1135
1136 debug!("(resolving function) leaving function");
1137 this.in_func_body = previous_state;
1138 }
1139 }
1140 })
1141 });
1142 self.diag_metadata.current_function = previous_value;
1143 }
1144
1145 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1146 self.resolve_lifetime(lifetime, use_ctxt)
1147 }
1148
1149 fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1150 match arg {
1151 PreciseCapturingArg::Lifetime(_) => {}
1154
1155 PreciseCapturingArg::Arg(path, id) => {
1156 let mut check_ns = |ns| {
1163 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1164 };
1165 if !check_ns(TypeNS) && check_ns(ValueNS) {
1167 self.smart_resolve_path(
1168 *id,
1169 &None,
1170 path,
1171 PathSource::PreciseCapturingArg(ValueNS),
1172 );
1173 } else {
1174 self.smart_resolve_path(
1175 *id,
1176 &None,
1177 path,
1178 PathSource::PreciseCapturingArg(TypeNS),
1179 );
1180 }
1181 }
1182 }
1183
1184 visit::walk_precise_capturing_arg(self, arg)
1185 }
1186
1187 fn visit_generics(&mut self, generics: &'ast Generics) {
1188 self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1189 for p in &generics.where_clause.predicates {
1190 self.visit_where_predicate(p);
1191 }
1192 }
1193
1194 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1195 match b {
1196 ClosureBinder::NotPresent => {}
1197 ClosureBinder::For { generic_params, .. } => {
1198 self.visit_generic_params(
1199 generic_params,
1200 self.diag_metadata.current_self_item.is_some(),
1201 );
1202 }
1203 }
1204 }
1205
1206 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1207 debug!("visit_generic_arg({:?})", arg);
1208 let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1209 match arg {
1210 GenericArg::Type(ty) => {
1211 if let TyKind::Path(None, ref path) = ty.kind
1217 && path.is_potential_trivial_const_arg(false)
1220 {
1221 let mut check_ns = |ns| {
1222 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1223 .is_some()
1224 };
1225 if !check_ns(TypeNS) && check_ns(ValueNS) {
1226 self.resolve_anon_const_manual(
1227 true,
1228 AnonConstKind::ConstArg(IsRepeatExpr::No),
1229 |this| {
1230 this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1231 this.visit_path(path);
1232 },
1233 );
1234
1235 self.diag_metadata.currently_processing_generic_args = prev;
1236 return;
1237 }
1238 }
1239
1240 self.visit_ty(ty);
1241 }
1242 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1243 GenericArg::Const(ct) => {
1244 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1245 }
1246 }
1247 self.diag_metadata.currently_processing_generic_args = prev;
1248 }
1249
1250 fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1251 self.visit_ident(&constraint.ident);
1252 if let Some(ref gen_args) = constraint.gen_args {
1253 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1255 this.visit_generic_args(gen_args)
1256 });
1257 }
1258 match constraint.kind {
1259 AssocItemConstraintKind::Equality { ref term } => match term {
1260 Term::Ty(ty) => self.visit_ty(ty),
1261 Term::Const(c) => {
1262 self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1263 }
1264 },
1265 AssocItemConstraintKind::Bound { ref bounds } => {
1266 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1267 }
1268 }
1269 }
1270
1271 fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1272 let Some(ref args) = path_segment.args else {
1273 return;
1274 };
1275
1276 match &**args {
1277 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1278 GenericArgs::Parenthesized(p_args) => {
1279 for rib in self.lifetime_ribs.iter().rev() {
1281 match rib.kind {
1282 LifetimeRibKind::Generics {
1285 binder,
1286 kind: LifetimeBinderKind::PolyTrait,
1287 ..
1288 } => {
1289 self.resolve_fn_signature(
1290 binder,
1291 false,
1292 p_args.inputs.iter().map(|ty| (None, &**ty)),
1293 &p_args.output,
1294 false,
1295 );
1296 break;
1297 }
1298 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1301 visit::walk_generic_args(self, args);
1302 break;
1303 }
1304 LifetimeRibKind::AnonymousCreateParameter { .. }
1305 | LifetimeRibKind::AnonymousReportError
1306 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1307 | LifetimeRibKind::Elided(_)
1308 | LifetimeRibKind::ElisionFailure
1309 | LifetimeRibKind::ConcreteAnonConst(_)
1310 | LifetimeRibKind::ConstParamTy => {}
1311 }
1312 }
1313 }
1314 GenericArgs::ParenthesizedElided(_) => {}
1315 }
1316 }
1317
1318 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1319 debug!("visit_where_predicate {:?}", p);
1320 let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1321 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1322 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1323 bounded_ty,
1324 bounds,
1325 bound_generic_params,
1326 ..
1327 }) = &p.kind
1328 {
1329 let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1330 this.with_generic_param_rib(
1331 bound_generic_params,
1332 RibKind::Normal,
1333 bounded_ty.id,
1334 LifetimeBinderKind::WhereBound,
1335 span,
1336 |this| {
1337 this.visit_generic_params(bound_generic_params, false);
1338 this.visit_ty(bounded_ty);
1339 for bound in bounds {
1340 this.visit_param_bound(bound, BoundKind::Bound)
1341 }
1342 },
1343 );
1344 } else {
1345 visit::walk_where_predicate(this, p);
1346 }
1347 });
1348 self.diag_metadata.current_where_predicate = previous_value;
1349 }
1350
1351 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1352 for (op, _) in &asm.operands {
1353 match op {
1354 InlineAsmOperand::In { expr, .. }
1355 | InlineAsmOperand::Out { expr: Some(expr), .. }
1356 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1357 InlineAsmOperand::Out { expr: None, .. } => {}
1358 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1359 self.visit_expr(in_expr);
1360 if let Some(out_expr) = out_expr {
1361 self.visit_expr(out_expr);
1362 }
1363 }
1364 InlineAsmOperand::Const { anon_const, .. } => {
1365 self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1368 }
1369 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1370 InlineAsmOperand::Label { block } => self.visit_block(block),
1371 }
1372 }
1373 }
1374
1375 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1376 self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1378 this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1379 this.with_label_rib(RibKind::InlineAsmSym, |this| {
1380 this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1381 visit::walk_inline_asm_sym(this, sym);
1382 });
1383 })
1384 });
1385 }
1386
1387 fn visit_variant(&mut self, v: &'ast Variant) {
1388 self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1389 self.visit_id(v.id);
1390 walk_list!(self, visit_attribute, &v.attrs);
1391 self.visit_vis(&v.vis);
1392 self.visit_ident(&v.ident);
1393 self.visit_variant_data(&v.data);
1394 if let Some(discr) = &v.disr_expr {
1395 self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1396 }
1397 }
1398
1399 fn visit_field_def(&mut self, f: &'ast FieldDef) {
1400 self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1401 let FieldDef {
1402 attrs,
1403 id: _,
1404 span: _,
1405 vis,
1406 ident,
1407 ty,
1408 is_placeholder: _,
1409 default,
1410 safety: _,
1411 } = f;
1412 walk_list!(self, visit_attribute, attrs);
1413 try_visit!(self.visit_vis(vis));
1414 visit_opt!(self, visit_ident, ident);
1415 try_visit!(self.visit_ty(ty));
1416 if let Some(v) = &default {
1417 self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1418 }
1419 }
1420}
1421
1422impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1423 fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1424 let graph_root = resolver.graph_root;
1427 let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1428 let start_rib_kind = RibKind::Module(graph_root);
1429 LateResolutionVisitor {
1430 r: resolver,
1431 parent_scope,
1432 ribs: PerNS {
1433 value_ns: vec![Rib::new(start_rib_kind)],
1434 type_ns: vec![Rib::new(start_rib_kind)],
1435 macro_ns: vec![Rib::new(start_rib_kind)],
1436 },
1437 last_block_rib: None,
1438 label_ribs: Vec::new(),
1439 lifetime_ribs: Vec::new(),
1440 lifetime_elision_candidates: None,
1441 current_trait_ref: None,
1442 diag_metadata: Default::default(),
1443 in_func_body: false,
1445 lifetime_uses: Default::default(),
1446 }
1447 }
1448
1449 fn maybe_resolve_ident_in_lexical_scope(
1450 &mut self,
1451 ident: Ident,
1452 ns: Namespace,
1453 ) -> Option<LexicalScopeBinding<'ra>> {
1454 self.r.resolve_ident_in_lexical_scope(
1455 ident,
1456 ns,
1457 &self.parent_scope,
1458 None,
1459 &self.ribs[ns],
1460 None,
1461 )
1462 }
1463
1464 fn resolve_ident_in_lexical_scope(
1465 &mut self,
1466 ident: Ident,
1467 ns: Namespace,
1468 finalize: Option<Finalize>,
1469 ignore_binding: Option<NameBinding<'ra>>,
1470 ) -> Option<LexicalScopeBinding<'ra>> {
1471 self.r.resolve_ident_in_lexical_scope(
1472 ident,
1473 ns,
1474 &self.parent_scope,
1475 finalize,
1476 &self.ribs[ns],
1477 ignore_binding,
1478 )
1479 }
1480
1481 fn resolve_path(
1482 &mut self,
1483 path: &[Segment],
1484 opt_ns: Option<Namespace>, finalize: Option<Finalize>,
1486 source: PathSource<'_, 'ast, 'ra>,
1487 ) -> PathResult<'ra> {
1488 self.r.cm().resolve_path_with_ribs(
1489 path,
1490 opt_ns,
1491 &self.parent_scope,
1492 Some(source),
1493 finalize,
1494 Some(&self.ribs),
1495 None,
1496 None,
1497 )
1498 }
1499
1500 fn with_rib<T>(
1520 &mut self,
1521 ns: Namespace,
1522 kind: RibKind<'ra>,
1523 work: impl FnOnce(&mut Self) -> T,
1524 ) -> T {
1525 self.ribs[ns].push(Rib::new(kind));
1526 let ret = work(self);
1527 self.ribs[ns].pop();
1528 ret
1529 }
1530
1531 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1532 let mut forward_ty_ban_rib =
1538 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1539 let mut forward_const_ban_rib =
1540 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1541 for param in params.iter() {
1542 match param.kind {
1543 GenericParamKind::Type { .. } => {
1544 forward_ty_ban_rib
1545 .bindings
1546 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1547 }
1548 GenericParamKind::Const { .. } => {
1549 forward_const_ban_rib
1550 .bindings
1551 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1552 }
1553 GenericParamKind::Lifetime => {}
1554 }
1555 }
1556
1557 if add_self_upper {
1567 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1569 }
1570
1571 let mut forward_ty_ban_rib_const_param_ty = Rib {
1574 bindings: forward_ty_ban_rib.bindings.clone(),
1575 patterns_with_skipped_bindings: Default::default(),
1576 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1577 };
1578 let mut forward_const_ban_rib_const_param_ty = Rib {
1579 bindings: forward_const_ban_rib.bindings.clone(),
1580 patterns_with_skipped_bindings: Default::default(),
1581 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1582 };
1583 if !self.r.tcx.features().generic_const_parameter_types() {
1586 forward_ty_ban_rib_const_param_ty.bindings.clear();
1587 forward_const_ban_rib_const_param_ty.bindings.clear();
1588 }
1589
1590 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1591 for param in params {
1592 match param.kind {
1593 GenericParamKind::Lifetime => {
1594 for bound in ¶m.bounds {
1595 this.visit_param_bound(bound, BoundKind::Bound);
1596 }
1597 }
1598 GenericParamKind::Type { ref default } => {
1599 for bound in ¶m.bounds {
1600 this.visit_param_bound(bound, BoundKind::Bound);
1601 }
1602
1603 if let Some(ty) = default {
1604 this.ribs[TypeNS].push(forward_ty_ban_rib);
1605 this.ribs[ValueNS].push(forward_const_ban_rib);
1606 this.visit_ty(ty);
1607 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1608 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1609 }
1610
1611 let i = &Ident::with_dummy_span(param.ident.name);
1613 forward_ty_ban_rib.bindings.swap_remove(i);
1614 forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1615 }
1616 GenericParamKind::Const { ref ty, span: _, ref default } => {
1617 assert!(param.bounds.is_empty());
1619
1620 this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1621 this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1622 if this.r.tcx.features().generic_const_parameter_types() {
1623 this.visit_ty(ty)
1624 } else {
1625 this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1626 this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1627 this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1628 this.visit_ty(ty)
1629 });
1630 this.ribs[TypeNS].pop().unwrap();
1631 this.ribs[ValueNS].pop().unwrap();
1632 }
1633 forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1634 forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1635
1636 if let Some(expr) = default {
1637 this.ribs[TypeNS].push(forward_ty_ban_rib);
1638 this.ribs[ValueNS].push(forward_const_ban_rib);
1639 this.resolve_anon_const(
1640 expr,
1641 AnonConstKind::ConstArg(IsRepeatExpr::No),
1642 );
1643 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1644 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1645 }
1646
1647 let i = &Ident::with_dummy_span(param.ident.name);
1649 forward_const_ban_rib.bindings.swap_remove(i);
1650 forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1651 }
1652 }
1653 }
1654 })
1655 }
1656
1657 #[instrument(level = "debug", skip(self, work))]
1658 fn with_lifetime_rib<T>(
1659 &mut self,
1660 kind: LifetimeRibKind,
1661 work: impl FnOnce(&mut Self) -> T,
1662 ) -> T {
1663 self.lifetime_ribs.push(LifetimeRib::new(kind));
1664 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1665 let ret = work(self);
1666 self.lifetime_elision_candidates = outer_elision_candidates;
1667 self.lifetime_ribs.pop();
1668 ret
1669 }
1670
1671 #[instrument(level = "debug", skip(self))]
1672 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1673 let ident = lifetime.ident;
1674
1675 if ident.name == kw::StaticLifetime {
1676 self.record_lifetime_res(
1677 lifetime.id,
1678 LifetimeRes::Static,
1679 LifetimeElisionCandidate::Named,
1680 );
1681 return;
1682 }
1683
1684 if ident.name == kw::UnderscoreLifetime {
1685 return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1686 }
1687
1688 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1689 while let Some(rib) = lifetime_rib_iter.next() {
1690 let normalized_ident = ident.normalize_to_macros_2_0();
1691 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1692 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1693
1694 if let LifetimeRes::Param { param, binder } = res {
1695 match self.lifetime_uses.entry(param) {
1696 Entry::Vacant(v) => {
1697 debug!("First use of {:?} at {:?}", res, ident.span);
1698 let use_set = self
1699 .lifetime_ribs
1700 .iter()
1701 .rev()
1702 .find_map(|rib| match rib.kind {
1703 LifetimeRibKind::Item
1706 | LifetimeRibKind::AnonymousReportError
1707 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1708 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1709 LifetimeRibKind::AnonymousCreateParameter {
1712 binder: anon_binder,
1713 ..
1714 } => Some(if binder == anon_binder {
1715 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1716 } else {
1717 LifetimeUseSet::Many
1718 }),
1719 LifetimeRibKind::Elided(r) => Some(if res == r {
1722 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1723 } else {
1724 LifetimeUseSet::Many
1725 }),
1726 LifetimeRibKind::Generics { .. }
1727 | LifetimeRibKind::ConstParamTy => None,
1728 LifetimeRibKind::ConcreteAnonConst(_) => {
1729 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1730 }
1731 })
1732 .unwrap_or(LifetimeUseSet::Many);
1733 debug!(?use_ctxt, ?use_set);
1734 v.insert(use_set);
1735 }
1736 Entry::Occupied(mut o) => {
1737 debug!("Many uses of {:?} at {:?}", res, ident.span);
1738 *o.get_mut() = LifetimeUseSet::Many;
1739 }
1740 }
1741 }
1742 return;
1743 }
1744
1745 match rib.kind {
1746 LifetimeRibKind::Item => break,
1747 LifetimeRibKind::ConstParamTy => {
1748 self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1749 self.record_lifetime_res(
1750 lifetime.id,
1751 LifetimeRes::Error,
1752 LifetimeElisionCandidate::Ignore,
1753 );
1754 return;
1755 }
1756 LifetimeRibKind::ConcreteAnonConst(cause) => {
1757 self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1758 self.record_lifetime_res(
1759 lifetime.id,
1760 LifetimeRes::Error,
1761 LifetimeElisionCandidate::Ignore,
1762 );
1763 return;
1764 }
1765 LifetimeRibKind::AnonymousCreateParameter { .. }
1766 | LifetimeRibKind::Elided(_)
1767 | LifetimeRibKind::Generics { .. }
1768 | LifetimeRibKind::ElisionFailure
1769 | LifetimeRibKind::AnonymousReportError
1770 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1771 }
1772 }
1773
1774 let normalized_ident = ident.normalize_to_macros_2_0();
1775 let outer_res = lifetime_rib_iter
1776 .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1777
1778 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1779 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1780 }
1781
1782 #[instrument(level = "debug", skip(self))]
1783 fn resolve_anonymous_lifetime(
1784 &mut self,
1785 lifetime: &Lifetime,
1786 id_for_lint: NodeId,
1787 elided: bool,
1788 ) {
1789 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1790
1791 let kind =
1792 if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1793 let missing_lifetime = MissingLifetime {
1794 id: lifetime.id,
1795 span: lifetime.ident.span,
1796 kind,
1797 count: 1,
1798 id_for_lint,
1799 };
1800 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1801 for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1802 debug!(?rib.kind);
1803 match rib.kind {
1804 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1805 let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1806 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1807 return;
1808 }
1809 LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1810 let mut lifetimes_in_scope = vec![];
1811 for rib in self.lifetime_ribs[..i].iter().rev() {
1812 lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1813 if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1815 && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1816 {
1817 lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1818 }
1819 if let LifetimeRibKind::Item = rib.kind {
1820 break;
1821 }
1822 }
1823 if lifetimes_in_scope.is_empty() {
1824 self.record_lifetime_res(
1825 lifetime.id,
1826 LifetimeRes::Static,
1827 elision_candidate,
1828 );
1829 return;
1830 } else if emit_lint {
1831 self.r.lint_buffer.buffer_lint(
1832 lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1833 node_id,
1834 lifetime.ident.span,
1835 lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1836 elided,
1837 span: lifetime.ident.span,
1838 lifetimes_in_scope: lifetimes_in_scope.into(),
1839 },
1840 );
1841 }
1842 }
1843 LifetimeRibKind::AnonymousReportError => {
1844 if elided {
1845 let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1846 if let LifetimeRibKind::Generics {
1847 span,
1848 kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1849 ..
1850 } = rib.kind
1851 {
1852 Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
1853 lo: span.shrink_to_lo(),
1854 hi: lifetime.ident.span.shrink_to_hi(),
1855 })
1856 } else {
1857 None
1858 }
1859 });
1860 if !self.in_func_body
1863 && let Some((module, _)) = &self.current_trait_ref
1864 && let Some(ty) = &self.diag_metadata.current_self_type
1865 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1866 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1867 {
1868 if def_id_matches_path(
1869 self.r.tcx,
1870 trait_id,
1871 &["core", "iter", "traits", "iterator", "Iterator"],
1872 ) {
1873 self.r.dcx().emit_err(errors::LendingIteratorReportError {
1874 lifetime: lifetime.ident.span,
1875 ty: ty.span,
1876 });
1877 } else {
1878 self.r.dcx().emit_err(errors::AnonymousLifetimeNonGatReportError {
1879 lifetime: lifetime.ident.span,
1880 });
1881 }
1882 } else {
1883 self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
1884 span: lifetime.ident.span,
1885 suggestion,
1886 });
1887 }
1888 } else {
1889 self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
1890 span: lifetime.ident.span,
1891 });
1892 };
1893 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1894 return;
1895 }
1896 LifetimeRibKind::Elided(res) => {
1897 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1898 return;
1899 }
1900 LifetimeRibKind::ElisionFailure => {
1901 self.diag_metadata.current_elision_failures.push(missing_lifetime);
1902 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1903 return;
1904 }
1905 LifetimeRibKind::Item => break,
1906 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1907 LifetimeRibKind::ConcreteAnonConst(_) => {
1908 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1910 }
1911 }
1912 }
1913 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1914 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1915 }
1916
1917 #[instrument(level = "debug", skip(self))]
1918 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1919 let id = self.r.next_node_id();
1920 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1921
1922 self.record_lifetime_res(
1923 anchor_id,
1924 LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
1925 LifetimeElisionCandidate::Ignore,
1926 );
1927 self.resolve_anonymous_lifetime(<, anchor_id, true);
1928 }
1929
1930 #[instrument(level = "debug", skip(self))]
1931 fn create_fresh_lifetime(
1932 &mut self,
1933 ident: Ident,
1934 binder: NodeId,
1935 kind: MissingLifetimeKind,
1936 ) -> LifetimeRes {
1937 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1938 debug!(?ident.span);
1939
1940 let param = self.r.next_node_id();
1942 let res = LifetimeRes::Fresh { param, binder, kind };
1943 self.record_lifetime_param(param, res);
1944
1945 self.r
1947 .extra_lifetime_params_map
1948 .entry(binder)
1949 .or_insert_with(Vec::new)
1950 .push((ident, param, res));
1951 res
1952 }
1953
1954 #[instrument(level = "debug", skip(self))]
1955 fn resolve_elided_lifetimes_in_path(
1956 &mut self,
1957 partial_res: PartialRes,
1958 path: &[Segment],
1959 source: PathSource<'_, 'ast, 'ra>,
1960 path_span: Span,
1961 ) {
1962 let proj_start = path.len() - partial_res.unresolved_segments();
1963 for (i, segment) in path.iter().enumerate() {
1964 if segment.has_lifetime_args {
1965 continue;
1966 }
1967 let Some(segment_id) = segment.id else {
1968 continue;
1969 };
1970
1971 let type_def_id = match partial_res.base_res() {
1974 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1975 self.r.tcx.parent(def_id)
1976 }
1977 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1978 self.r.tcx.parent(def_id)
1979 }
1980 Res::Def(DefKind::Struct, def_id)
1981 | Res::Def(DefKind::Union, def_id)
1982 | Res::Def(DefKind::Enum, def_id)
1983 | Res::Def(DefKind::TyAlias, def_id)
1984 | Res::Def(DefKind::Trait, def_id)
1985 if i + 1 == proj_start =>
1986 {
1987 def_id
1988 }
1989 _ => continue,
1990 };
1991
1992 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
1993 if expected_lifetimes == 0 {
1994 continue;
1995 }
1996
1997 let node_ids = self.r.next_node_ids(expected_lifetimes);
1998 self.record_lifetime_res(
1999 segment_id,
2000 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2001 LifetimeElisionCandidate::Ignore,
2002 );
2003
2004 let inferred = match source {
2005 PathSource::Trait(..)
2006 | PathSource::TraitItem(..)
2007 | PathSource::Type
2008 | PathSource::PreciseCapturingArg(..)
2009 | PathSource::ReturnTypeNotation => false,
2010 PathSource::Expr(..)
2011 | PathSource::Pat
2012 | PathSource::Struct(_)
2013 | PathSource::TupleStruct(..)
2014 | PathSource::DefineOpaques
2015 | PathSource::Delegation => true,
2016 };
2017 if inferred {
2018 for id in node_ids {
2021 self.record_lifetime_res(
2022 id,
2023 LifetimeRes::Infer,
2024 LifetimeElisionCandidate::Named,
2025 );
2026 }
2027 continue;
2028 }
2029
2030 let elided_lifetime_span = if segment.has_generic_args {
2031 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2033 } else {
2034 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2038 };
2039 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2040
2041 let kind = if segment.has_generic_args {
2042 MissingLifetimeKind::Comma
2043 } else {
2044 MissingLifetimeKind::Brackets
2045 };
2046 let missing_lifetime = MissingLifetime {
2047 id: node_ids.start,
2048 id_for_lint: segment_id,
2049 span: elided_lifetime_span,
2050 kind,
2051 count: expected_lifetimes,
2052 };
2053 let mut should_lint = true;
2054 for rib in self.lifetime_ribs.iter().rev() {
2055 match rib.kind {
2056 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2063 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2064 let sess = self.r.tcx.sess;
2065 let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2066 sess.source_map(),
2067 expected_lifetimes,
2068 path_span,
2069 !segment.has_generic_args,
2070 elided_lifetime_span,
2071 );
2072 self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2073 span: path_span,
2074 subdiag,
2075 });
2076 should_lint = false;
2077
2078 for id in node_ids {
2079 self.record_lifetime_res(
2080 id,
2081 LifetimeRes::Error,
2082 LifetimeElisionCandidate::Named,
2083 );
2084 }
2085 break;
2086 }
2087 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2089 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2091 for id in node_ids {
2092 let res = self.create_fresh_lifetime(ident, binder, kind);
2093 self.record_lifetime_res(
2094 id,
2095 res,
2096 replace(&mut candidate, LifetimeElisionCandidate::Named),
2097 );
2098 }
2099 break;
2100 }
2101 LifetimeRibKind::Elided(res) => {
2102 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2103 for id in node_ids {
2104 self.record_lifetime_res(
2105 id,
2106 res,
2107 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2108 );
2109 }
2110 break;
2111 }
2112 LifetimeRibKind::ElisionFailure => {
2113 self.diag_metadata.current_elision_failures.push(missing_lifetime);
2114 for id in node_ids {
2115 self.record_lifetime_res(
2116 id,
2117 LifetimeRes::Error,
2118 LifetimeElisionCandidate::Ignore,
2119 );
2120 }
2121 break;
2122 }
2123 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2128 for id in node_ids {
2129 self.record_lifetime_res(
2130 id,
2131 LifetimeRes::Error,
2132 LifetimeElisionCandidate::Ignore,
2133 );
2134 }
2135 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2136 break;
2137 }
2138 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2139 LifetimeRibKind::ConcreteAnonConst(_) => {
2140 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2142 }
2143 }
2144 }
2145
2146 if should_lint {
2147 self.r.lint_buffer.buffer_lint(
2148 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2149 segment_id,
2150 elided_lifetime_span,
2151 lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2152 expected_lifetimes,
2153 path_span,
2154 !segment.has_generic_args,
2155 elided_lifetime_span,
2156 ),
2157 );
2158 }
2159 }
2160 }
2161
2162 #[instrument(level = "debug", skip(self))]
2163 fn record_lifetime_res(
2164 &mut self,
2165 id: NodeId,
2166 res: LifetimeRes,
2167 candidate: LifetimeElisionCandidate,
2168 ) {
2169 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2170 panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2171 }
2172
2173 match res {
2174 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2175 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2176 candidates.push((res, candidate));
2177 }
2178 }
2179 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2180 }
2181 }
2182
2183 #[instrument(level = "debug", skip(self))]
2184 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2185 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2186 panic!(
2187 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2188 )
2189 }
2190 }
2191
2192 #[instrument(level = "debug", skip(self, inputs))]
2194 fn resolve_fn_signature(
2195 &mut self,
2196 fn_id: NodeId,
2197 has_self: bool,
2198 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2199 output_ty: &'ast FnRetTy,
2200 report_elided_lifetimes_in_path: bool,
2201 ) {
2202 let rib = LifetimeRibKind::AnonymousCreateParameter {
2203 binder: fn_id,
2204 report_in_path: report_elided_lifetimes_in_path,
2205 };
2206 self.with_lifetime_rib(rib, |this| {
2207 let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2209 debug!(?elision_lifetime);
2210
2211 let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2212 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2213 this.r.lifetime_elision_allowed.insert(fn_id);
2214 LifetimeRibKind::Elided(*res)
2215 } else {
2216 LifetimeRibKind::ElisionFailure
2217 };
2218 this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2219 let elision_failures =
2220 replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2221 if !elision_failures.is_empty() {
2222 let Err(failure_info) = elision_lifetime else { bug!() };
2223 this.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2224 }
2225 });
2226 }
2227
2228 fn resolve_fn_params(
2232 &mut self,
2233 has_self: bool,
2234 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2235 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2236 enum Elision {
2237 None,
2239 Self_(LifetimeRes),
2241 Param(LifetimeRes),
2243 Err,
2245 }
2246
2247 let outer_candidates = self.lifetime_elision_candidates.take();
2249
2250 let mut elision_lifetime = Elision::None;
2252 let mut parameter_info = Vec::new();
2254 let mut all_candidates = Vec::new();
2255
2256 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2258 for (pat, _) in inputs.clone() {
2259 debug!("resolving bindings in pat = {pat:?}");
2260 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2261 if let Some(pat) = pat {
2262 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2263 }
2264 });
2265 }
2266 self.apply_pattern_bindings(bindings);
2267
2268 for (index, (pat, ty)) in inputs.enumerate() {
2269 debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2270 debug_assert_matches!(self.lifetime_elision_candidates, None);
2272 self.lifetime_elision_candidates = Some(Default::default());
2273 self.visit_ty(ty);
2274 let local_candidates = self.lifetime_elision_candidates.take();
2275
2276 if let Some(candidates) = local_candidates {
2277 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2278 let lifetime_count = distinct.len();
2279 if lifetime_count != 0 {
2280 parameter_info.push(ElisionFnParameter {
2281 index,
2282 ident: if let Some(pat) = pat
2283 && let PatKind::Ident(_, ident, _) = pat.kind
2284 {
2285 Some(ident)
2286 } else {
2287 None
2288 },
2289 lifetime_count,
2290 span: ty.span,
2291 });
2292 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2293 match candidate {
2294 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2295 None
2296 }
2297 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2298 }
2299 }));
2300 }
2301 if !distinct.is_empty() {
2302 match elision_lifetime {
2303 Elision::None => {
2305 if let Some(res) = distinct.get_only() {
2306 elision_lifetime = Elision::Param(*res)
2308 } else {
2309 elision_lifetime = Elision::Err;
2311 }
2312 }
2313 Elision::Param(_) => elision_lifetime = Elision::Err,
2315 Elision::Self_(_) | Elision::Err => {}
2317 }
2318 }
2319 }
2320
2321 if index == 0 && has_self {
2323 let self_lifetime = self.find_lifetime_for_self(ty);
2324 elision_lifetime = match self_lifetime {
2325 Set1::One(lifetime) => Elision::Self_(lifetime),
2327 Set1::Many => Elision::Err,
2332 Set1::Empty => Elision::None,
2335 }
2336 }
2337 debug!("(resolving function / closure) recorded parameter");
2338 }
2339
2340 debug_assert_matches!(self.lifetime_elision_candidates, None);
2342 self.lifetime_elision_candidates = outer_candidates;
2343
2344 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2345 return Ok(res);
2346 }
2347
2348 Err((all_candidates, parameter_info))
2350 }
2351
2352 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2354 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2358 r: &'a Resolver<'ra, 'tcx>,
2359 impl_self: Option<Res>,
2360 lifetime: Set1<LifetimeRes>,
2361 }
2362
2363 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2364 fn visit_ty(&mut self, ty: &'ra Ty) {
2365 trace!("FindReferenceVisitor considering ty={:?}", ty);
2366 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2367 let mut visitor =
2369 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2370 visitor.visit_ty(ty);
2371 trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2372 if visitor.self_found {
2373 let lt_id = if let Some(lt) = lt {
2374 lt.id
2375 } else {
2376 let res = self.r.lifetimes_res_map[&ty.id];
2377 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2378 start
2379 };
2380 let lt_res = self.r.lifetimes_res_map[<_id];
2381 trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2382 self.lifetime.insert(lt_res);
2383 }
2384 }
2385 visit::walk_ty(self, ty)
2386 }
2387
2388 fn visit_expr(&mut self, _: &'ra Expr) {}
2391 }
2392
2393 struct SelfVisitor<'a, 'ra, 'tcx> {
2396 r: &'a Resolver<'ra, 'tcx>,
2397 impl_self: Option<Res>,
2398 self_found: bool,
2399 }
2400
2401 impl SelfVisitor<'_, '_, '_> {
2402 fn is_self_ty(&self, ty: &Ty) -> bool {
2404 match ty.kind {
2405 TyKind::ImplicitSelf => true,
2406 TyKind::Path(None, _) => {
2407 let path_res = self.r.partial_res_map[&ty.id].full_res();
2408 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2409 return true;
2410 }
2411 self.impl_self.is_some() && path_res == self.impl_self
2412 }
2413 _ => false,
2414 }
2415 }
2416 }
2417
2418 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2419 fn visit_ty(&mut self, ty: &'ra Ty) {
2420 trace!("SelfVisitor considering ty={:?}", ty);
2421 if self.is_self_ty(ty) {
2422 trace!("SelfVisitor found Self");
2423 self.self_found = true;
2424 }
2425 visit::walk_ty(self, ty)
2426 }
2427
2428 fn visit_expr(&mut self, _: &'ra Expr) {}
2431 }
2432
2433 let impl_self = self
2434 .diag_metadata
2435 .current_self_type
2436 .as_ref()
2437 .and_then(|ty| {
2438 if let TyKind::Path(None, _) = ty.kind {
2439 self.r.partial_res_map.get(&ty.id)
2440 } else {
2441 None
2442 }
2443 })
2444 .and_then(|res| res.full_res())
2445 .filter(|res| {
2446 matches!(
2450 res,
2451 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2452 )
2453 });
2454 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2455 visitor.visit_ty(ty);
2456 trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2457 visitor.lifetime
2458 }
2459
2460 fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2463 let mut suggestion = None;
2464
2465 for i in (0..self.label_ribs.len()).rev() {
2466 let rib = &self.label_ribs[i];
2467
2468 if let RibKind::MacroDefinition(def) = rib.kind
2469 && def == self.r.macro_def(label.span.ctxt())
2472 {
2473 label.span.remove_mark();
2474 }
2475
2476 let ident = label.normalize_to_macro_rules();
2477 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2478 let definition_span = ident.span;
2479 return if self.is_label_valid_from_rib(i) {
2480 Ok((*id, definition_span))
2481 } else {
2482 Err(ResolutionError::UnreachableLabel {
2483 name: label.name,
2484 definition_span,
2485 suggestion,
2486 })
2487 };
2488 }
2489
2490 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2493 }
2494
2495 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2496 }
2497
2498 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2500 let ribs = &self.label_ribs[rib_index + 1..];
2501 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2502 }
2503
2504 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2505 debug!("resolve_adt");
2506 let kind = self.r.local_def_kind(item.id);
2507 self.with_current_self_item(item, |this| {
2508 this.with_generic_param_rib(
2509 &generics.params,
2510 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2511 item.id,
2512 LifetimeBinderKind::Item,
2513 generics.span,
2514 |this| {
2515 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2516 this.with_self_rib(
2517 Res::SelfTyAlias {
2518 alias_to: item_def_id,
2519 forbid_generic: false,
2520 is_trait_impl: false,
2521 },
2522 |this| {
2523 visit::walk_item(this, item);
2524 },
2525 );
2526 },
2527 );
2528 });
2529 }
2530
2531 fn future_proof_import(&mut self, use_tree: &UseTree) {
2532 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2533 let ident = segment.ident;
2534 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2535 return;
2536 }
2537
2538 let nss = match use_tree.kind {
2539 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2540 _ => &[TypeNS],
2541 };
2542 let report_error = |this: &Self, ns| {
2543 if this.should_report_errs() {
2544 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2545 this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2546 }
2547 };
2548
2549 for &ns in nss {
2550 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2551 Some(LexicalScopeBinding::Res(..)) => {
2552 report_error(self, ns);
2553 }
2554 Some(LexicalScopeBinding::Item(binding)) => {
2555 if let Some(LexicalScopeBinding::Res(..)) =
2556 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2557 {
2558 report_error(self, ns);
2559 }
2560 }
2561 None => {}
2562 }
2563 }
2564 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2565 for (use_tree, _) in items {
2566 self.future_proof_import(use_tree);
2567 }
2568 }
2569 }
2570
2571 fn resolve_item(&mut self, item: &'ast Item) {
2572 let mod_inner_docs =
2573 matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2574 if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2575 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2576 }
2577
2578 debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2579
2580 let def_kind = self.r.local_def_kind(item.id);
2581 match item.kind {
2582 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2583 self.with_generic_param_rib(
2584 &generics.params,
2585 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2586 item.id,
2587 LifetimeBinderKind::Item,
2588 generics.span,
2589 |this| visit::walk_item(this, item),
2590 );
2591 }
2592
2593 ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2594 self.with_generic_param_rib(
2595 &generics.params,
2596 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2597 item.id,
2598 LifetimeBinderKind::Function,
2599 generics.span,
2600 |this| visit::walk_item(this, item),
2601 );
2602 self.resolve_define_opaques(define_opaque);
2603 }
2604
2605 ItemKind::Enum(_, ref generics, _)
2606 | ItemKind::Struct(_, ref generics, _)
2607 | ItemKind::Union(_, ref generics, _) => {
2608 self.resolve_adt(item, generics);
2609 }
2610
2611 ItemKind::Impl(Impl {
2612 ref generics,
2613 ref of_trait,
2614 ref self_ty,
2615 items: ref impl_items,
2616 ..
2617 }) => {
2618 self.diag_metadata.current_impl_items = Some(impl_items);
2619 self.resolve_implementation(
2620 &item.attrs,
2621 generics,
2622 of_trait.as_deref(),
2623 self_ty,
2624 item.id,
2625 impl_items,
2626 );
2627 self.diag_metadata.current_impl_items = None;
2628 }
2629
2630 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2631 self.with_generic_param_rib(
2633 &generics.params,
2634 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2635 item.id,
2636 LifetimeBinderKind::Item,
2637 generics.span,
2638 |this| {
2639 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2640 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2641 this.visit_generics(generics);
2642 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2643 this.resolve_trait_items(items);
2644 });
2645 },
2646 );
2647 }
2648
2649 ItemKind::TraitAlias(_, ref generics, ref bounds) => {
2650 self.with_generic_param_rib(
2652 &generics.params,
2653 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2654 item.id,
2655 LifetimeBinderKind::Item,
2656 generics.span,
2657 |this| {
2658 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2659 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2660 this.visit_generics(generics);
2661 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2662 });
2663 },
2664 );
2665 }
2666
2667 ItemKind::Mod(..) => {
2668 let module = self.r.expect_module(self.r.local_def_id(item.id).to_def_id());
2669 let orig_module = replace(&mut self.parent_scope.module, module);
2670 self.with_rib(ValueNS, RibKind::Module(module), |this| {
2671 this.with_rib(TypeNS, RibKind::Module(module), |this| {
2672 if mod_inner_docs {
2673 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2674 }
2675 let old_macro_rules = this.parent_scope.macro_rules;
2676 visit::walk_item(this, item);
2677 if item.attrs.iter().all(|attr| {
2680 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2681 }) {
2682 this.parent_scope.macro_rules = old_macro_rules;
2683 }
2684 })
2685 });
2686 self.parent_scope.module = orig_module;
2687 }
2688
2689 ItemKind::Static(box ast::StaticItem {
2690 ident,
2691 ref ty,
2692 ref expr,
2693 ref define_opaque,
2694 ..
2695 }) => {
2696 self.with_static_rib(def_kind, |this| {
2697 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2698 this.visit_ty(ty);
2699 });
2700 if let Some(expr) = expr {
2701 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Static)));
2704 }
2705 });
2706 self.resolve_define_opaques(define_opaque);
2707 }
2708
2709 ItemKind::Const(box ast::ConstItem {
2710 ident,
2711 ref generics,
2712 ref ty,
2713 ref expr,
2714 ref define_opaque,
2715 ..
2716 }) => {
2717 self.with_generic_param_rib(
2718 &generics.params,
2719 RibKind::Item(
2720 if self.r.tcx.features().generic_const_items() {
2721 HasGenericParams::Yes(generics.span)
2722 } else {
2723 HasGenericParams::No
2724 },
2725 def_kind,
2726 ),
2727 item.id,
2728 LifetimeBinderKind::ConstItem,
2729 generics.span,
2730 |this| {
2731 this.visit_generics(generics);
2732
2733 this.with_lifetime_rib(
2734 LifetimeRibKind::Elided(LifetimeRes::Static),
2735 |this| this.visit_ty(ty),
2736 );
2737
2738 if let Some(expr) = expr {
2739 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Const)));
2740 }
2741 },
2742 );
2743 self.resolve_define_opaques(define_opaque);
2744 }
2745
2746 ItemKind::Use(ref use_tree) => {
2747 let maybe_exported = match use_tree.kind {
2748 UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2749 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2750 };
2751 self.resolve_doc_links(&item.attrs, maybe_exported);
2752
2753 self.future_proof_import(use_tree);
2754 }
2755
2756 ItemKind::MacroDef(_, ref macro_def) => {
2757 if macro_def.macro_rules {
2760 let def_id = self.r.local_def_id(item.id);
2761 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2762 }
2763 }
2764
2765 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2766 visit::walk_item(self, item);
2767 }
2768
2769 ItemKind::Delegation(ref delegation) => {
2770 let span = delegation.path.segments.last().unwrap().ident.span;
2771 self.with_generic_param_rib(
2772 &[],
2773 RibKind::Item(HasGenericParams::Yes(span), def_kind),
2774 item.id,
2775 LifetimeBinderKind::Function,
2776 span,
2777 |this| this.resolve_delegation(delegation),
2778 );
2779 }
2780
2781 ItemKind::ExternCrate(..) => {}
2782
2783 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2784 panic!("unexpanded macro in resolve!")
2785 }
2786 }
2787 }
2788
2789 fn with_generic_param_rib<'c, F>(
2790 &'c mut self,
2791 params: &'c [GenericParam],
2792 kind: RibKind<'ra>,
2793 binder: NodeId,
2794 generics_kind: LifetimeBinderKind,
2795 generics_span: Span,
2796 f: F,
2797 ) where
2798 F: FnOnce(&mut Self),
2799 {
2800 debug!("with_generic_param_rib");
2801 let lifetime_kind =
2802 LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
2803
2804 let mut function_type_rib = Rib::new(kind);
2805 let mut function_value_rib = Rib::new(kind);
2806 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2807
2808 if !params.is_empty() {
2810 let mut seen_bindings = FxHashMap::default();
2811 let mut seen_lifetimes = FxHashSet::default();
2813
2814 for ns in [ValueNS, TypeNS] {
2816 for parent_rib in self.ribs[ns].iter().rev() {
2817 if matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
2820 break;
2821 }
2822
2823 seen_bindings
2824 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2825 }
2826 }
2827
2828 for rib in self.lifetime_ribs.iter().rev() {
2830 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2831 if let LifetimeRibKind::Item = rib.kind {
2832 break;
2833 }
2834 }
2835
2836 for param in params {
2837 let ident = param.ident.normalize_to_macros_2_0();
2838 debug!("with_generic_param_rib: {}", param.id);
2839
2840 if let GenericParamKind::Lifetime = param.kind
2841 && let Some(&original) = seen_lifetimes.get(&ident)
2842 {
2843 diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
2844 self.record_lifetime_param(param.id, LifetimeRes::Error);
2846 continue;
2847 }
2848
2849 match seen_bindings.entry(ident) {
2850 Entry::Occupied(entry) => {
2851 let span = *entry.get();
2852 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
2853 self.report_error(param.ident.span, err);
2854 let rib = match param.kind {
2855 GenericParamKind::Lifetime => {
2856 self.record_lifetime_param(param.id, LifetimeRes::Error);
2858 continue;
2859 }
2860 GenericParamKind::Type { .. } => &mut function_type_rib,
2861 GenericParamKind::Const { .. } => &mut function_value_rib,
2862 };
2863
2864 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
2866 rib.bindings.insert(ident, Res::Err);
2867 continue;
2868 }
2869 Entry::Vacant(entry) => {
2870 entry.insert(param.ident.span);
2871 }
2872 }
2873
2874 if param.ident.name == kw::UnderscoreLifetime {
2875 let is_raw_underscore_lifetime = self
2878 .r
2879 .tcx
2880 .sess
2881 .psess
2882 .raw_identifier_spans
2883 .iter()
2884 .any(|span| span == param.span());
2885
2886 self.r
2887 .dcx()
2888 .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
2889 .emit_unless_delay(is_raw_underscore_lifetime);
2890 self.record_lifetime_param(param.id, LifetimeRes::Error);
2892 continue;
2893 }
2894
2895 if param.ident.name == kw::StaticLifetime {
2896 self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
2897 span: param.ident.span,
2898 lifetime: param.ident,
2899 });
2900 self.record_lifetime_param(param.id, LifetimeRes::Error);
2902 continue;
2903 }
2904
2905 let def_id = self.r.local_def_id(param.id);
2906
2907 let (rib, def_kind) = match param.kind {
2909 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2910 GenericParamKind::Const { .. } => {
2911 (&mut function_value_rib, DefKind::ConstParam)
2912 }
2913 GenericParamKind::Lifetime => {
2914 let res = LifetimeRes::Param { param: def_id, binder };
2915 self.record_lifetime_param(param.id, res);
2916 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2917 continue;
2918 }
2919 };
2920
2921 let res = match kind {
2922 RibKind::Item(..) | RibKind::AssocItem => {
2923 Res::Def(def_kind, def_id.to_def_id())
2924 }
2925 RibKind::Normal => {
2926 if self.r.tcx.features().non_lifetime_binders()
2929 && matches!(param.kind, GenericParamKind::Type { .. })
2930 {
2931 Res::Def(def_kind, def_id.to_def_id())
2932 } else {
2933 Res::Err
2934 }
2935 }
2936 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2937 };
2938 self.r.record_partial_res(param.id, PartialRes::new(res));
2939 rib.bindings.insert(ident, res);
2940 }
2941 }
2942
2943 self.lifetime_ribs.push(function_lifetime_rib);
2944 self.ribs[ValueNS].push(function_value_rib);
2945 self.ribs[TypeNS].push(function_type_rib);
2946
2947 f(self);
2948
2949 self.ribs[TypeNS].pop();
2950 self.ribs[ValueNS].pop();
2951 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2952
2953 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2955 for (_, res) in function_lifetime_rib.bindings.values() {
2956 candidates.retain(|(r, _)| r != res);
2957 }
2958 }
2959
2960 if let LifetimeBinderKind::FnPtrType
2961 | LifetimeBinderKind::WhereBound
2962 | LifetimeBinderKind::Function
2963 | LifetimeBinderKind::ImplBlock = generics_kind
2964 {
2965 self.maybe_report_lifetime_uses(generics_span, params)
2966 }
2967 }
2968
2969 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
2970 self.label_ribs.push(Rib::new(kind));
2971 f(self);
2972 self.label_ribs.pop();
2973 }
2974
2975 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
2976 let kind = RibKind::Item(HasGenericParams::No, def_kind);
2977 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
2978 }
2979
2980 #[instrument(level = "debug", skip(self, f))]
2989 fn with_constant_rib(
2990 &mut self,
2991 is_repeat: IsRepeatExpr,
2992 may_use_generics: ConstantHasGenerics,
2993 item: Option<(Ident, ConstantItemKind)>,
2994 f: impl FnOnce(&mut Self),
2995 ) {
2996 let f = |this: &mut Self| {
2997 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
2998 this.with_rib(
2999 TypeNS,
3000 RibKind::ConstantItem(
3001 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3002 item,
3003 ),
3004 |this| {
3005 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3006 },
3007 )
3008 })
3009 };
3010
3011 if let ConstantHasGenerics::No(cause) = may_use_generics {
3012 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3013 } else {
3014 f(self)
3015 }
3016 }
3017
3018 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3019 let previous_value =
3021 replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3022 let result = f(self);
3023 self.diag_metadata.current_self_type = previous_value;
3024 result
3025 }
3026
3027 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3028 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3029 let result = f(self);
3030 self.diag_metadata.current_self_item = previous_value;
3031 result
3032 }
3033
3034 fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3036 let trait_assoc_items =
3037 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3038
3039 let walk_assoc_item =
3040 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3041 this.with_generic_param_rib(
3042 &generics.params,
3043 RibKind::AssocItem,
3044 item.id,
3045 kind,
3046 generics.span,
3047 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3048 );
3049 };
3050
3051 for item in trait_items {
3052 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3053 match &item.kind {
3054 AssocItemKind::Const(box ast::ConstItem {
3055 generics,
3056 ty,
3057 expr,
3058 define_opaque,
3059 ..
3060 }) => {
3061 self.with_generic_param_rib(
3062 &generics.params,
3063 RibKind::AssocItem,
3064 item.id,
3065 LifetimeBinderKind::ConstItem,
3066 generics.span,
3067 |this| {
3068 this.with_lifetime_rib(
3069 LifetimeRibKind::StaticIfNoLifetimeInScope {
3070 lint_id: item.id,
3071 emit_lint: false,
3072 },
3073 |this| {
3074 this.visit_generics(generics);
3075 this.visit_ty(ty);
3076
3077 if let Some(expr) = expr {
3080 this.resolve_const_body(expr, None);
3086 }
3087 },
3088 )
3089 },
3090 );
3091
3092 self.resolve_define_opaques(define_opaque);
3093 }
3094 AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3095 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3096
3097 self.resolve_define_opaques(define_opaque);
3098 }
3099 AssocItemKind::Delegation(delegation) => {
3100 self.with_generic_param_rib(
3101 &[],
3102 RibKind::AssocItem,
3103 item.id,
3104 LifetimeBinderKind::Function,
3105 delegation.path.segments.last().unwrap().ident.span,
3106 |this| this.resolve_delegation(delegation),
3107 );
3108 }
3109 AssocItemKind::Type(box TyAlias { generics, .. }) => self
3110 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3111 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3112 }),
3113 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3114 panic!("unexpanded macro in resolve!")
3115 }
3116 };
3117 }
3118
3119 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3120 }
3121
3122 fn with_optional_trait_ref<T>(
3124 &mut self,
3125 opt_trait_ref: Option<&TraitRef>,
3126 self_type: &'ast Ty,
3127 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3128 ) -> T {
3129 let mut new_val = None;
3130 let mut new_id = None;
3131 if let Some(trait_ref) = opt_trait_ref {
3132 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3133 self.diag_metadata.currently_processing_impl_trait =
3134 Some((trait_ref.clone(), self_type.clone()));
3135 let res = self.smart_resolve_path_fragment(
3136 &None,
3137 &path,
3138 PathSource::Trait(AliasPossibility::No),
3139 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3140 RecordPartialRes::Yes,
3141 None,
3142 );
3143 self.diag_metadata.currently_processing_impl_trait = None;
3144 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3145 new_id = Some(def_id);
3146 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3147 }
3148 }
3149 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3150 let result = f(self, new_id);
3151 self.current_trait_ref = original_trait_ref;
3152 result
3153 }
3154
3155 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3156 let mut self_type_rib = Rib::new(RibKind::Normal);
3157
3158 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3160 self.ribs[ns].push(self_type_rib);
3161 f(self);
3162 self.ribs[ns].pop();
3163 }
3164
3165 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3166 self.with_self_rib_ns(TypeNS, self_res, f)
3167 }
3168
3169 fn resolve_implementation(
3170 &mut self,
3171 attrs: &[ast::Attribute],
3172 generics: &'ast Generics,
3173 of_trait: Option<&'ast ast::TraitImplHeader>,
3174 self_type: &'ast Ty,
3175 item_id: NodeId,
3176 impl_items: &'ast [Box<AssocItem>],
3177 ) {
3178 debug!("resolve_implementation");
3179 self.with_generic_param_rib(
3181 &generics.params,
3182 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3183 item_id,
3184 LifetimeBinderKind::ImplBlock,
3185 generics.span,
3186 |this| {
3187 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3189 this.with_lifetime_rib(
3190 LifetimeRibKind::AnonymousCreateParameter {
3191 binder: item_id,
3192 report_in_path: true
3193 },
3194 |this| {
3195 this.with_optional_trait_ref(
3197 of_trait.map(|t| &t.trait_ref),
3198 self_type,
3199 |this, trait_id| {
3200 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3201
3202 let item_def_id = this.r.local_def_id(item_id);
3203
3204 if let Some(trait_id) = trait_id {
3206 this.r
3207 .trait_impls
3208 .entry(trait_id)
3209 .or_default()
3210 .push(item_def_id);
3211 }
3212
3213 let item_def_id = item_def_id.to_def_id();
3214 let res = Res::SelfTyAlias {
3215 alias_to: item_def_id,
3216 forbid_generic: false,
3217 is_trait_impl: trait_id.is_some()
3218 };
3219 this.with_self_rib(res, |this| {
3220 if let Some(of_trait) = of_trait {
3221 visit::walk_trait_ref(this, &of_trait.trait_ref);
3223 }
3224 this.visit_ty(self_type);
3226 this.visit_generics(generics);
3228
3229 this.with_current_self_type(self_type, |this| {
3231 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3232 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3233 let mut seen_trait_items = Default::default();
3234 for item in impl_items {
3235 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3236 }
3237 });
3238 });
3239 });
3240 },
3241 )
3242 },
3243 );
3244 });
3245 },
3246 );
3247 }
3248
3249 fn resolve_impl_item(
3250 &mut self,
3251 item: &'ast AssocItem,
3252 seen_trait_items: &mut FxHashMap<DefId, Span>,
3253 trait_id: Option<DefId>,
3254 ) {
3255 use crate::ResolutionError::*;
3256 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3257 match &item.kind {
3258 AssocItemKind::Const(box ast::ConstItem {
3259 ident,
3260 generics,
3261 ty,
3262 expr,
3263 define_opaque,
3264 ..
3265 }) => {
3266 debug!("resolve_implementation AssocItemKind::Const");
3267 self.with_generic_param_rib(
3268 &generics.params,
3269 RibKind::AssocItem,
3270 item.id,
3271 LifetimeBinderKind::ConstItem,
3272 generics.span,
3273 |this| {
3274 this.with_lifetime_rib(
3275 LifetimeRibKind::AnonymousCreateParameter {
3279 binder: item.id,
3280 report_in_path: true,
3281 },
3282 |this| {
3283 this.with_lifetime_rib(
3284 LifetimeRibKind::StaticIfNoLifetimeInScope {
3285 lint_id: item.id,
3286 emit_lint: true,
3288 },
3289 |this| {
3290 this.check_trait_item(
3293 item.id,
3294 *ident,
3295 &item.kind,
3296 ValueNS,
3297 item.span,
3298 seen_trait_items,
3299 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3300 );
3301
3302 this.visit_generics(generics);
3303 this.visit_ty(ty);
3304 if let Some(expr) = expr {
3305 this.resolve_const_body(expr, None);
3311 }
3312 },
3313 )
3314 },
3315 );
3316 },
3317 );
3318 self.resolve_define_opaques(define_opaque);
3319 }
3320 AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3321 debug!("resolve_implementation AssocItemKind::Fn");
3322 self.with_generic_param_rib(
3324 &generics.params,
3325 RibKind::AssocItem,
3326 item.id,
3327 LifetimeBinderKind::Function,
3328 generics.span,
3329 |this| {
3330 this.check_trait_item(
3333 item.id,
3334 *ident,
3335 &item.kind,
3336 ValueNS,
3337 item.span,
3338 seen_trait_items,
3339 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3340 );
3341
3342 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3343 },
3344 );
3345
3346 self.resolve_define_opaques(define_opaque);
3347 }
3348 AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3349 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3350 debug!("resolve_implementation AssocItemKind::Type");
3351 self.with_generic_param_rib(
3353 &generics.params,
3354 RibKind::AssocItem,
3355 item.id,
3356 LifetimeBinderKind::Item,
3357 generics.span,
3358 |this| {
3359 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3360 this.check_trait_item(
3363 item.id,
3364 *ident,
3365 &item.kind,
3366 TypeNS,
3367 item.span,
3368 seen_trait_items,
3369 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3370 );
3371
3372 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3373 });
3374 },
3375 );
3376 self.diag_metadata.in_non_gat_assoc_type = None;
3377 }
3378 AssocItemKind::Delegation(box delegation) => {
3379 debug!("resolve_implementation AssocItemKind::Delegation");
3380 self.with_generic_param_rib(
3381 &[],
3382 RibKind::AssocItem,
3383 item.id,
3384 LifetimeBinderKind::Function,
3385 delegation.path.segments.last().unwrap().ident.span,
3386 |this| {
3387 this.check_trait_item(
3388 item.id,
3389 delegation.ident,
3390 &item.kind,
3391 ValueNS,
3392 item.span,
3393 seen_trait_items,
3394 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3395 );
3396
3397 this.resolve_delegation(delegation)
3398 },
3399 );
3400 }
3401 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3402 panic!("unexpanded macro in resolve!")
3403 }
3404 }
3405 }
3406
3407 fn check_trait_item<F>(
3408 &mut self,
3409 id: NodeId,
3410 mut ident: Ident,
3411 kind: &AssocItemKind,
3412 ns: Namespace,
3413 span: Span,
3414 seen_trait_items: &mut FxHashMap<DefId, Span>,
3415 err: F,
3416 ) where
3417 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3418 {
3419 let Some((module, _)) = self.current_trait_ref else {
3421 return;
3422 };
3423 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3424 let key = BindingKey::new(ident, ns);
3425 let mut binding = self.r.resolution(module, key).and_then(|r| r.best_binding());
3426 debug!(?binding);
3427 if binding.is_none() {
3428 let ns = match ns {
3431 ValueNS => TypeNS,
3432 TypeNS => ValueNS,
3433 _ => ns,
3434 };
3435 let key = BindingKey::new(ident, ns);
3436 binding = self.r.resolution(module, key).and_then(|r| r.best_binding());
3437 debug!(?binding);
3438 }
3439
3440 let feed_visibility = |this: &mut Self, def_id| {
3441 let vis = this.r.tcx.visibility(def_id);
3442 let vis = if vis.is_visible_locally() {
3443 vis.expect_local()
3444 } else {
3445 this.r.dcx().span_delayed_bug(
3446 span,
3447 "error should be emitted when an unexpected trait item is used",
3448 );
3449 Visibility::Public
3450 };
3451 this.r.feed_visibility(this.r.feed(id), vis);
3452 };
3453
3454 let Some(binding) = binding else {
3455 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3457 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3458 let path_names = path_names_to_string(path);
3459 self.report_error(span, err(ident, path_names, candidate));
3460 feed_visibility(self, module.def_id());
3461 return;
3462 };
3463
3464 let res = binding.res();
3465 let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3466 feed_visibility(self, id_in_trait);
3467
3468 match seen_trait_items.entry(id_in_trait) {
3469 Entry::Occupied(entry) => {
3470 self.report_error(
3471 span,
3472 ResolutionError::TraitImplDuplicate {
3473 name: ident,
3474 old_span: *entry.get(),
3475 trait_item_span: binding.span,
3476 },
3477 );
3478 return;
3479 }
3480 Entry::Vacant(entry) => {
3481 entry.insert(span);
3482 }
3483 };
3484
3485 match (def_kind, kind) {
3486 (DefKind::AssocTy, AssocItemKind::Type(..))
3487 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3488 | (DefKind::AssocConst, AssocItemKind::Const(..))
3489 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3490 self.r.record_partial_res(id, PartialRes::new(res));
3491 return;
3492 }
3493 _ => {}
3494 }
3495
3496 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3498 let (code, kind) = match kind {
3499 AssocItemKind::Const(..) => (E0323, "const"),
3500 AssocItemKind::Fn(..) => (E0324, "method"),
3501 AssocItemKind::Type(..) => (E0325, "type"),
3502 AssocItemKind::Delegation(..) => (E0324, "method"),
3503 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3504 span_bug!(span, "unexpanded macro")
3505 }
3506 };
3507 let trait_path = path_names_to_string(path);
3508 self.report_error(
3509 span,
3510 ResolutionError::TraitImplMismatch {
3511 name: ident,
3512 kind,
3513 code,
3514 trait_path,
3515 trait_item_span: binding.span,
3516 },
3517 );
3518 }
3519
3520 fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3521 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3522 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3523 this.visit_expr(expr)
3524 });
3525 })
3526 }
3527
3528 fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3529 self.smart_resolve_path(
3530 delegation.id,
3531 &delegation.qself,
3532 &delegation.path,
3533 PathSource::Delegation,
3534 );
3535 if let Some(qself) = &delegation.qself {
3536 self.visit_ty(&qself.ty);
3537 }
3538 self.visit_path(&delegation.path);
3539 let Some(body) = &delegation.body else { return };
3540 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3541 let span = delegation.path.segments.last().unwrap().ident.span;
3542 let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3543 let res = Res::Local(delegation.id);
3544 this.innermost_rib_bindings(ValueNS).insert(ident, res);
3545 this.visit_block(body);
3546 });
3547 }
3548
3549 fn resolve_params(&mut self, params: &'ast [Param]) {
3550 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3551 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3552 for Param { pat, .. } in params {
3553 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3554 }
3555 this.apply_pattern_bindings(bindings);
3556 });
3557 for Param { ty, .. } in params {
3558 self.visit_ty(ty);
3559 }
3560 }
3561
3562 fn resolve_local(&mut self, local: &'ast Local) {
3563 debug!("resolving local ({:?})", local);
3564 visit_opt!(self, visit_ty, &local.ty);
3566
3567 if let Some((init, els)) = local.kind.init_else_opt() {
3569 self.visit_expr(init);
3570
3571 if let Some(els) = els {
3573 self.visit_block(els);
3574 }
3575 }
3576
3577 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3579 }
3580
3581 fn compute_and_check_binding_map(
3601 &mut self,
3602 pat: &Pat,
3603 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3604 let mut binding_map = FxIndexMap::default();
3605 let mut is_never_pat = false;
3606
3607 pat.walk(&mut |pat| {
3608 match pat.kind {
3609 PatKind::Ident(annotation, ident, ref sub_pat)
3610 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3611 {
3612 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3613 }
3614 PatKind::Or(ref ps) => {
3615 match self.compute_and_check_or_pat_binding_map(ps) {
3618 Ok(bm) => binding_map.extend(bm),
3619 Err(IsNeverPattern) => is_never_pat = true,
3620 }
3621 return false;
3622 }
3623 PatKind::Never => is_never_pat = true,
3624 _ => {}
3625 }
3626
3627 true
3628 });
3629
3630 if is_never_pat {
3631 for (_, binding) in binding_map {
3632 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3633 }
3634 Err(IsNeverPattern)
3635 } else {
3636 Ok(binding_map)
3637 }
3638 }
3639
3640 fn is_base_res_local(&self, nid: NodeId) -> bool {
3641 matches!(
3642 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3643 Some(Res::Local(..))
3644 )
3645 }
3646
3647 fn compute_and_check_or_pat_binding_map(
3667 &mut self,
3668 pats: &[Box<Pat>],
3669 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3670 let mut missing_vars = FxIndexMap::default();
3671 let mut inconsistent_vars = FxIndexMap::default();
3672
3673 let not_never_pats = pats
3675 .iter()
3676 .filter_map(|pat| {
3677 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3678 Some((binding_map, pat))
3679 })
3680 .collect::<Vec<_>>();
3681
3682 for (map_outer, pat_outer) in not_never_pats.iter() {
3684 let inners = not_never_pats
3686 .iter()
3687 .filter(|(_, pat)| pat.id != pat_outer.id)
3688 .flat_map(|(map, _)| map);
3689
3690 for (&name, binding_inner) in inners {
3691 match map_outer.get(&name) {
3692 None => {
3693 let binding_error =
3695 missing_vars.entry(name).or_insert_with(|| BindingError {
3696 name,
3697 origin: BTreeSet::new(),
3698 target: BTreeSet::new(),
3699 could_be_path: name.as_str().starts_with(char::is_uppercase),
3700 });
3701 binding_error.origin.insert(binding_inner.span);
3702 binding_error.target.insert(pat_outer.span);
3703 }
3704 Some(binding_outer) => {
3705 if binding_outer.annotation != binding_inner.annotation {
3706 inconsistent_vars
3708 .entry(name)
3709 .or_insert((binding_inner.span, binding_outer.span));
3710 }
3711 }
3712 }
3713 }
3714 }
3715
3716 for (name, mut v) in missing_vars {
3718 if inconsistent_vars.contains_key(&name) {
3719 v.could_be_path = false;
3720 }
3721 self.report_error(
3722 *v.origin.iter().next().unwrap(),
3723 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3724 );
3725 }
3726
3727 for (name, v) in inconsistent_vars {
3729 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3730 }
3731
3732 if not_never_pats.is_empty() {
3734 Err(IsNeverPattern)
3736 } else {
3737 let mut binding_map = FxIndexMap::default();
3738 for (bm, _) in not_never_pats {
3739 binding_map.extend(bm);
3740 }
3741 Ok(binding_map)
3742 }
3743 }
3744
3745 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3747 let mut is_or_or_never = false;
3748 pat.walk(&mut |pat| match pat.kind {
3749 PatKind::Or(..) | PatKind::Never => {
3750 is_or_or_never = true;
3751 false
3752 }
3753 _ => true,
3754 });
3755 if is_or_or_never {
3756 let _ = self.compute_and_check_binding_map(pat);
3757 }
3758 }
3759
3760 fn resolve_arm(&mut self, arm: &'ast Arm) {
3761 self.with_rib(ValueNS, RibKind::Normal, |this| {
3762 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3763 visit_opt!(this, visit_expr, &arm.guard);
3764 visit_opt!(this, visit_expr, &arm.body);
3765 });
3766 }
3767
3768 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3770 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3771 self.resolve_pattern(pat, pat_src, &mut bindings);
3772 self.apply_pattern_bindings(bindings);
3773 }
3774
3775 fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3777 let rib_bindings = self.innermost_rib_bindings(ValueNS);
3778 let Some((_, pat_bindings)) = pat_bindings.pop() else {
3779 bug!("tried applying nonexistent bindings from pattern");
3780 };
3781
3782 if rib_bindings.is_empty() {
3783 *rib_bindings = pat_bindings;
3786 } else {
3787 rib_bindings.extend(pat_bindings);
3788 }
3789 }
3790
3791 fn resolve_pattern(
3794 &mut self,
3795 pat: &'ast Pat,
3796 pat_src: PatternSource,
3797 bindings: &mut PatternBindings,
3798 ) {
3799 self.visit_pat(pat);
3805 self.resolve_pattern_inner(pat, pat_src, bindings);
3806 self.check_consistent_bindings(pat);
3808 }
3809
3810 #[tracing::instrument(skip(self, bindings), level = "debug")]
3830 fn resolve_pattern_inner(
3831 &mut self,
3832 pat: &'ast Pat,
3833 pat_src: PatternSource,
3834 bindings: &mut PatternBindings,
3835 ) {
3836 pat.walk(&mut |pat| {
3838 match pat.kind {
3839 PatKind::Ident(bmode, ident, ref sub) => {
3840 let has_sub = sub.is_some();
3843 let res = self
3844 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3845 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3846 self.r.record_partial_res(pat.id, PartialRes::new(res));
3847 self.r.record_pat_span(pat.id, pat.span);
3848 }
3849 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3850 self.smart_resolve_path(
3851 pat.id,
3852 qself,
3853 path,
3854 PathSource::TupleStruct(
3855 pat.span,
3856 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3857 ),
3858 );
3859 }
3860 PatKind::Path(ref qself, ref path) => {
3861 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3862 }
3863 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3864 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
3865 self.record_patterns_with_skipped_bindings(pat, rest);
3866 }
3867 PatKind::Or(ref ps) => {
3868 bindings.push((PatBoundCtx::Or, Default::default()));
3872 for p in ps {
3873 bindings.push((PatBoundCtx::Product, Default::default()));
3877 self.resolve_pattern_inner(p, pat_src, bindings);
3878 let collected = bindings.pop().unwrap().1;
3881 bindings.last_mut().unwrap().1.extend(collected);
3882 }
3883 let collected = bindings.pop().unwrap().1;
3887 bindings.last_mut().unwrap().1.extend(collected);
3888
3889 return false;
3891 }
3892 PatKind::Guard(ref subpat, ref guard) => {
3893 bindings.push((PatBoundCtx::Product, Default::default()));
3895 let binding_ctx_stack_len = bindings.len();
3898 self.resolve_pattern_inner(subpat, pat_src, bindings);
3899 assert_eq!(bindings.len(), binding_ctx_stack_len);
3900 let subpat_bindings = bindings.pop().unwrap().1;
3903 self.with_rib(ValueNS, RibKind::Normal, |this| {
3904 *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
3905 this.resolve_expr(guard, None);
3906 });
3907 bindings.last_mut().unwrap().1.extend(subpat_bindings);
3914 return false;
3916 }
3917 _ => {}
3918 }
3919 true
3920 });
3921 }
3922
3923 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
3924 match rest {
3925 ast::PatFieldsRest::Rest | ast::PatFieldsRest::Recovered(_) => {
3926 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
3928 && let Some(res) = partial_res.full_res()
3929 && let Some(def_id) = res.opt_def_id()
3930 {
3931 self.ribs[ValueNS]
3932 .last_mut()
3933 .unwrap()
3934 .patterns_with_skipped_bindings
3935 .entry(def_id)
3936 .or_default()
3937 .push((
3938 pat.span,
3939 match rest {
3940 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
3941 _ => Ok(()),
3942 },
3943 ));
3944 }
3945 }
3946 ast::PatFieldsRest::None => {}
3947 }
3948 }
3949
3950 fn fresh_binding(
3951 &mut self,
3952 ident: Ident,
3953 pat_id: NodeId,
3954 pat_src: PatternSource,
3955 bindings: &mut PatternBindings,
3956 ) -> Res {
3957 let ident = ident.normalize_to_macro_rules();
3961
3962 let already_bound_and = bindings
3964 .iter()
3965 .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
3966 if already_bound_and {
3967 use ResolutionError::*;
3969 let error = match pat_src {
3970 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
3972 _ => IdentifierBoundMoreThanOnceInSamePattern,
3974 };
3975 self.report_error(ident.span, error(ident));
3976 }
3977
3978 let already_bound_or = bindings
3981 .iter()
3982 .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
3983 let res = if let Some(&res) = already_bound_or {
3984 res
3987 } else {
3988 Res::Local(pat_id)
3990 };
3991
3992 bindings.last_mut().unwrap().1.insert(ident, res);
3994 res
3995 }
3996
3997 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
3998 &mut self.ribs[ns].last_mut().unwrap().bindings
3999 }
4000
4001 fn try_resolve_as_non_binding(
4002 &mut self,
4003 pat_src: PatternSource,
4004 ann: BindingMode,
4005 ident: Ident,
4006 has_sub: bool,
4007 ) -> Option<Res> {
4008 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4012
4013 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4014 let (res, binding) = match ls_binding {
4015 LexicalScopeBinding::Item(binding)
4016 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4017 {
4018 self.r.record_use(ident, binding, Used::Other);
4023 return None;
4024 }
4025 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4026 LexicalScopeBinding::Res(res) => (res, None),
4027 };
4028
4029 match res {
4030 Res::SelfCtor(_) | Res::Def(
4032 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4033 _,
4034 ) if is_syntactic_ambiguity => {
4035 if let Some(binding) = binding {
4037 self.r.record_use(ident, binding, Used::Other);
4038 }
4039 Some(res)
4040 }
4041 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4042 let binding = binding.expect("no binding for a ctor or static");
4048 self.report_error(
4049 ident.span,
4050 ResolutionError::BindingShadowsSomethingUnacceptable {
4051 shadowing_binding: pat_src,
4052 name: ident.name,
4053 participle: if binding.is_import() { "imported" } else { "defined" },
4054 article: binding.res().article(),
4055 shadowed_binding: binding.res(),
4056 shadowed_binding_span: binding.span,
4057 },
4058 );
4059 None
4060 }
4061 Res::Def(DefKind::ConstParam, def_id) => {
4062 self.report_error(
4065 ident.span,
4066 ResolutionError::BindingShadowsSomethingUnacceptable {
4067 shadowing_binding: pat_src,
4068 name: ident.name,
4069 participle: "defined",
4070 article: res.article(),
4071 shadowed_binding: res,
4072 shadowed_binding_span: self.r.def_span(def_id),
4073 }
4074 );
4075 None
4076 }
4077 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4078 None
4080 }
4081 Res::SelfCtor(_) => {
4082 self.r.dcx().span_delayed_bug(
4085 ident.span,
4086 "unexpected `SelfCtor` in pattern, expected identifier"
4087 );
4088 None
4089 }
4090 _ => span_bug!(
4091 ident.span,
4092 "unexpected resolution for an identifier in pattern: {:?}",
4093 res,
4094 ),
4095 }
4096 }
4097
4098 fn smart_resolve_path(
4104 &mut self,
4105 id: NodeId,
4106 qself: &Option<Box<QSelf>>,
4107 path: &Path,
4108 source: PathSource<'_, 'ast, 'ra>,
4109 ) {
4110 self.smart_resolve_path_fragment(
4111 qself,
4112 &Segment::from_path(path),
4113 source,
4114 Finalize::new(id, path.span),
4115 RecordPartialRes::Yes,
4116 None,
4117 );
4118 }
4119
4120 #[instrument(level = "debug", skip(self))]
4121 fn smart_resolve_path_fragment(
4122 &mut self,
4123 qself: &Option<Box<QSelf>>,
4124 path: &[Segment],
4125 source: PathSource<'_, 'ast, 'ra>,
4126 finalize: Finalize,
4127 record_partial_res: RecordPartialRes,
4128 parent_qself: Option<&QSelf>,
4129 ) -> PartialRes {
4130 let ns = source.namespace();
4131
4132 let Finalize { node_id, path_span, .. } = finalize;
4133 let report_errors = |this: &mut Self, res: Option<Res>| {
4134 if this.should_report_errs() {
4135 let (err, candidates) = this.smart_resolve_report_errors(
4136 path,
4137 None,
4138 path_span,
4139 source,
4140 res,
4141 parent_qself,
4142 );
4143
4144 let def_id = this.parent_scope.module.nearest_parent_mod();
4145 let instead = res.is_some();
4146 let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4147 && path[0].ident.span.lo() == end.span.lo()
4148 && !matches!(start.kind, ExprKind::Lit(_))
4149 {
4150 let mut sugg = ".";
4151 let mut span = start.span.between(end.span);
4152 if span.lo() + BytePos(2) == span.hi() {
4153 span = span.with_lo(span.lo() + BytePos(1));
4156 sugg = "";
4157 }
4158 Some((
4159 span,
4160 "you might have meant to write `.` instead of `..`",
4161 sugg.to_string(),
4162 Applicability::MaybeIncorrect,
4163 ))
4164 } else if res.is_none()
4165 && let PathSource::Type
4166 | PathSource::Expr(_)
4167 | PathSource::PreciseCapturingArg(..) = source
4168 {
4169 this.suggest_adding_generic_parameter(path, source)
4170 } else {
4171 None
4172 };
4173
4174 let ue = UseError {
4175 err,
4176 candidates,
4177 def_id,
4178 instead,
4179 suggestion,
4180 path: path.into(),
4181 is_call: source.is_call(),
4182 };
4183
4184 this.r.use_injections.push(ue);
4185 }
4186
4187 PartialRes::new(Res::Err)
4188 };
4189
4190 let report_errors_for_call =
4196 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4197 let (following_seg, prefix_path) = match path.split_last() {
4201 Some((last, path)) if !path.is_empty() => (Some(last), path),
4202 _ => return Some(parent_err),
4203 };
4204
4205 let (mut err, candidates) = this.smart_resolve_report_errors(
4206 prefix_path,
4207 following_seg,
4208 path_span,
4209 PathSource::Type,
4210 None,
4211 parent_qself,
4212 );
4213
4214 let failed_to_resolve = match parent_err.node {
4229 ResolutionError::FailedToResolve { .. } => true,
4230 _ => false,
4231 };
4232 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4233
4234 err.messages = take(&mut parent_err.messages);
4236 err.code = take(&mut parent_err.code);
4237 swap(&mut err.span, &mut parent_err.span);
4238 if failed_to_resolve {
4239 err.children = take(&mut parent_err.children);
4240 } else {
4241 err.children.append(&mut parent_err.children);
4242 }
4243 err.sort_span = parent_err.sort_span;
4244 err.is_lint = parent_err.is_lint.clone();
4245
4246 match &mut err.suggestions {
4248 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4249 Suggestions::Enabled(parent_suggestions) => {
4250 typo_suggestions.append(parent_suggestions)
4252 }
4253 Suggestions::Sealed(_) | Suggestions::Disabled => {
4254 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4259 }
4260 },
4261 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4262 }
4263
4264 parent_err.cancel();
4265
4266 let def_id = this.parent_scope.module.nearest_parent_mod();
4267
4268 if this.should_report_errs() {
4269 if candidates.is_empty() {
4270 if path.len() == 2
4271 && let [segment] = prefix_path
4272 {
4273 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4279 } else {
4280 err.emit();
4285 }
4286 } else {
4287 this.r.use_injections.push(UseError {
4289 err,
4290 candidates,
4291 def_id,
4292 instead: false,
4293 suggestion: None,
4294 path: prefix_path.into(),
4295 is_call: source.is_call(),
4296 });
4297 }
4298 } else {
4299 err.cancel();
4300 }
4301
4302 None
4305 };
4306
4307 let partial_res = match self.resolve_qpath_anywhere(
4308 qself,
4309 path,
4310 ns,
4311 source.defer_to_typeck(),
4312 finalize,
4313 source,
4314 ) {
4315 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4316 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4318 && let [Segment { ident, .. }] = path
4319 && items.iter().any(|item| {
4320 if let AssocItemKind::Type(alias) = &item.kind
4321 && alias.ident == *ident
4322 {
4323 true
4324 } else {
4325 false
4326 }
4327 })
4328 {
4329 let mut diag = self.r.tcx.dcx().struct_allow("");
4330 diag.span_suggestion_verbose(
4331 path_span.shrink_to_lo(),
4332 "there is an associated type with the same name",
4333 "Self::",
4334 Applicability::MaybeIncorrect,
4335 );
4336 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4337 }
4338
4339 if source.is_expected(res) || res == Res::Err {
4340 partial_res
4341 } else {
4342 report_errors(self, Some(res))
4343 }
4344 }
4345
4346 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4347 if ns == ValueNS {
4351 let item_name = path.last().unwrap().ident;
4352 let traits = self.traits_in_scope(item_name, ns);
4353 self.r.trait_map.insert(node_id, traits);
4354 }
4355
4356 if PrimTy::from_name(path[0].ident.name).is_some() {
4357 let mut std_path = Vec::with_capacity(1 + path.len());
4358
4359 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4360 std_path.extend(path);
4361 if let PathResult::Module(_) | PathResult::NonModule(_) =
4362 self.resolve_path(&std_path, Some(ns), None, source)
4363 {
4364 let item_span =
4366 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4367
4368 self.r.confused_type_with_std_module.insert(item_span, path_span);
4369 self.r.confused_type_with_std_module.insert(path_span, path_span);
4370 }
4371 }
4372
4373 partial_res
4374 }
4375
4376 Err(err) => {
4377 if let Some(err) = report_errors_for_call(self, err) {
4378 self.report_error(err.span, err.node);
4379 }
4380
4381 PartialRes::new(Res::Err)
4382 }
4383
4384 _ => report_errors(self, None),
4385 };
4386
4387 if record_partial_res == RecordPartialRes::Yes {
4388 self.r.record_partial_res(node_id, partial_res);
4390 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4391 self.lint_unused_qualifications(path, ns, finalize);
4392 }
4393
4394 partial_res
4395 }
4396
4397 fn self_type_is_available(&mut self) -> bool {
4398 let binding = self
4399 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4400 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4401 }
4402
4403 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4404 let ident = Ident::new(kw::SelfLower, self_span);
4405 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4406 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4407 }
4408
4409 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4413 if self.should_report_errs() {
4414 self.r.report_error(span, resolution_error);
4415 }
4416 }
4417
4418 #[inline]
4419 fn should_report_errs(&self) -> bool {
4423 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4424 && !self.r.glob_error.is_some()
4425 }
4426
4427 fn resolve_qpath_anywhere(
4429 &mut self,
4430 qself: &Option<Box<QSelf>>,
4431 path: &[Segment],
4432 primary_ns: Namespace,
4433 defer_to_typeck: bool,
4434 finalize: Finalize,
4435 source: PathSource<'_, 'ast, 'ra>,
4436 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4437 let mut fin_res = None;
4438
4439 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4440 if i == 0 || ns != primary_ns {
4441 match self.resolve_qpath(qself, path, ns, finalize, source)? {
4442 Some(partial_res)
4443 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4444 {
4445 return Ok(Some(partial_res));
4446 }
4447 partial_res => {
4448 if fin_res.is_none() {
4449 fin_res = partial_res;
4450 }
4451 }
4452 }
4453 }
4454 }
4455
4456 assert!(primary_ns != MacroNS);
4457 if qself.is_none()
4458 && let PathResult::NonModule(res) =
4459 self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4460 {
4461 return Ok(Some(res));
4462 }
4463
4464 Ok(fin_res)
4465 }
4466
4467 fn resolve_qpath(
4469 &mut self,
4470 qself: &Option<Box<QSelf>>,
4471 path: &[Segment],
4472 ns: Namespace,
4473 finalize: Finalize,
4474 source: PathSource<'_, 'ast, 'ra>,
4475 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4476 debug!(
4477 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4478 qself, path, ns, finalize,
4479 );
4480
4481 if let Some(qself) = qself {
4482 if qself.position == 0 {
4483 return Ok(Some(PartialRes::with_unresolved_segments(
4487 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4488 path.len(),
4489 )));
4490 }
4491
4492 let num_privacy_errors = self.r.privacy_errors.len();
4493 let trait_res = self.smart_resolve_path_fragment(
4495 &None,
4496 &path[..qself.position],
4497 PathSource::Trait(AliasPossibility::No),
4498 Finalize::new(finalize.node_id, qself.path_span),
4499 RecordPartialRes::No,
4500 Some(&qself),
4501 );
4502
4503 if trait_res.expect_full_res() == Res::Err {
4504 return Ok(Some(trait_res));
4505 }
4506
4507 self.r.privacy_errors.truncate(num_privacy_errors);
4510
4511 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4519 let partial_res = self.smart_resolve_path_fragment(
4520 &None,
4521 &path[..=qself.position],
4522 PathSource::TraitItem(ns, &source),
4523 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4524 RecordPartialRes::No,
4525 Some(&qself),
4526 );
4527
4528 return Ok(Some(PartialRes::with_unresolved_segments(
4532 partial_res.base_res(),
4533 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4534 )));
4535 }
4536
4537 let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4538 PathResult::NonModule(path_res) => path_res,
4539 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4540 PartialRes::new(module.res().unwrap())
4541 }
4542 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4546 PartialRes::new(Res::Err)
4547 }
4548 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4561 if (ns == TypeNS || path.len() > 1)
4562 && PrimTy::from_name(path[0].ident.name).is_some() =>
4563 {
4564 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4565 let tcx = self.r.tcx();
4566
4567 let gate_err_sym_msg = match prim {
4568 PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4569 Some((sym::f16, "the type `f16` is unstable"))
4570 }
4571 PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4572 Some((sym::f128, "the type `f128` is unstable"))
4573 }
4574 _ => None,
4575 };
4576
4577 if let Some((sym, msg)) = gate_err_sym_msg {
4578 let span = path[0].ident.span;
4579 if !span.allows_unstable(sym) {
4580 feature_err(tcx.sess, sym, span, msg).emit();
4581 }
4582 };
4583
4584 if let Some(id) = path[0].id {
4586 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4587 }
4588
4589 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4590 }
4591 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4592 PartialRes::new(module.res().unwrap())
4593 }
4594 PathResult::Failed {
4595 is_error_from_last_segment: false,
4596 span,
4597 label,
4598 suggestion,
4599 module,
4600 segment_name,
4601 error_implied_by_parse_error: _,
4602 } => {
4603 return Err(respan(
4604 span,
4605 ResolutionError::FailedToResolve {
4606 segment: Some(segment_name),
4607 label,
4608 suggestion,
4609 module,
4610 },
4611 ));
4612 }
4613 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4614 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4615 };
4616
4617 Ok(Some(result))
4618 }
4619
4620 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4621 if let Some(label) = label {
4622 if label.ident.as_str().as_bytes()[1] != b'_' {
4623 self.diag_metadata.unused_labels.insert(id, label.ident.span);
4624 }
4625
4626 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4627 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4628 }
4629
4630 self.with_label_rib(RibKind::Normal, |this| {
4631 let ident = label.ident.normalize_to_macro_rules();
4632 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4633 f(this);
4634 });
4635 } else {
4636 f(self);
4637 }
4638 }
4639
4640 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4641 self.with_resolved_label(label, id, |this| this.visit_block(block));
4642 }
4643
4644 fn resolve_block(&mut self, block: &'ast Block) {
4645 debug!("(resolving block) entering block");
4646 let orig_module = self.parent_scope.module;
4648 let anonymous_module = self.r.block_map.get(&block.id).copied();
4649
4650 let mut num_macro_definition_ribs = 0;
4651 if let Some(anonymous_module) = anonymous_module {
4652 debug!("(resolving block) found anonymous module, moving down");
4653 self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4654 self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4655 self.parent_scope.module = anonymous_module;
4656 } else {
4657 self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
4658 }
4659
4660 for stmt in &block.stmts {
4662 if let StmtKind::Item(ref item) = stmt.kind
4663 && let ItemKind::MacroDef(..) = item.kind
4664 {
4665 num_macro_definition_ribs += 1;
4666 let res = self.r.local_def_id(item.id).to_def_id();
4667 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4668 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4669 }
4670
4671 self.visit_stmt(stmt);
4672 }
4673
4674 self.parent_scope.module = orig_module;
4676 for _ in 0..num_macro_definition_ribs {
4677 self.ribs[ValueNS].pop();
4678 self.label_ribs.pop();
4679 }
4680 self.last_block_rib = self.ribs[ValueNS].pop();
4681 if anonymous_module.is_some() {
4682 self.ribs[TypeNS].pop();
4683 }
4684 debug!("(resolving block) leaving block");
4685 }
4686
4687 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4688 debug!(
4689 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4690 constant, anon_const_kind
4691 );
4692
4693 let is_trivial_const_arg = constant
4694 .value
4695 .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4696 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4697 this.resolve_expr(&constant.value, None)
4698 })
4699 }
4700
4701 fn resolve_anon_const_manual(
4708 &mut self,
4709 is_trivial_const_arg: bool,
4710 anon_const_kind: AnonConstKind,
4711 resolve_expr: impl FnOnce(&mut Self),
4712 ) {
4713 let is_repeat_expr = match anon_const_kind {
4714 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4715 _ => IsRepeatExpr::No,
4716 };
4717
4718 let may_use_generics = match anon_const_kind {
4719 AnonConstKind::EnumDiscriminant => {
4720 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4721 }
4722 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4723 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4724 AnonConstKind::ConstArg(_) => {
4725 if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4726 ConstantHasGenerics::Yes
4727 } else {
4728 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4729 }
4730 }
4731 };
4732
4733 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4734 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4735 resolve_expr(this);
4736 });
4737 });
4738 }
4739
4740 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4741 self.resolve_expr(&f.expr, Some(e));
4742 self.visit_ident(&f.ident);
4743 walk_list!(self, visit_attribute, f.attrs.iter());
4744 }
4745
4746 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4747 self.record_candidate_traits_for_expr_if_necessary(expr);
4751
4752 match expr.kind {
4754 ExprKind::Path(ref qself, ref path) => {
4755 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4756 visit::walk_expr(self, expr);
4757 }
4758
4759 ExprKind::Struct(ref se) => {
4760 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
4761 if let Some(qself) = &se.qself {
4765 self.visit_ty(&qself.ty);
4766 }
4767 self.visit_path(&se.path);
4768 walk_list!(self, resolve_expr_field, &se.fields, expr);
4769 match &se.rest {
4770 StructRest::Base(expr) => self.visit_expr(expr),
4771 StructRest::Rest(_span) => {}
4772 StructRest::None => {}
4773 }
4774 }
4775
4776 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4777 match self.resolve_label(label.ident) {
4778 Ok((node_id, _)) => {
4779 self.r.label_res_map.insert(expr.id, node_id);
4781 self.diag_metadata.unused_labels.swap_remove(&node_id);
4782 }
4783 Err(error) => {
4784 self.report_error(label.ident.span, error);
4785 }
4786 }
4787
4788 visit::walk_expr(self, expr);
4790 }
4791
4792 ExprKind::Break(None, Some(ref e)) => {
4793 self.resolve_expr(e, Some(expr));
4796 }
4797
4798 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
4799 self.visit_expr(scrutinee);
4800 self.resolve_pattern_top(pat, PatternSource::Let);
4801 }
4802
4803 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
4804 self.visit_expr(scrutinee);
4805 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4807 self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
4808 for (_, bindings) in &mut bindings {
4813 for (_, binding) in bindings {
4814 *binding = Res::Err;
4815 }
4816 }
4817 self.apply_pattern_bindings(bindings);
4818 }
4819
4820 ExprKind::If(ref cond, ref then, ref opt_else) => {
4821 self.with_rib(ValueNS, RibKind::Normal, |this| {
4822 let old = this.diag_metadata.in_if_condition.replace(cond);
4823 this.visit_expr(cond);
4824 this.diag_metadata.in_if_condition = old;
4825 this.visit_block(then);
4826 });
4827 if let Some(expr) = opt_else {
4828 self.visit_expr(expr);
4829 }
4830 }
4831
4832 ExprKind::Loop(ref block, label, _) => {
4833 self.resolve_labeled_block(label, expr.id, block)
4834 }
4835
4836 ExprKind::While(ref cond, ref block, label) => {
4837 self.with_resolved_label(label, expr.id, |this| {
4838 this.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(block);
4843 })
4844 });
4845 }
4846
4847 ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4848 self.visit_expr(iter);
4849 self.with_rib(ValueNS, RibKind::Normal, |this| {
4850 this.resolve_pattern_top(pat, PatternSource::For);
4851 this.resolve_labeled_block(label, expr.id, body);
4852 });
4853 }
4854
4855 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4856
4857 ExprKind::Field(ref subexpression, _) => {
4859 self.resolve_expr(subexpression, Some(expr));
4860 }
4861 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
4862 self.resolve_expr(receiver, Some(expr));
4863 for arg in args {
4864 self.resolve_expr(arg, None);
4865 }
4866 self.visit_path_segment(seg);
4867 }
4868
4869 ExprKind::Call(ref callee, ref arguments) => {
4870 self.resolve_expr(callee, Some(expr));
4871 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
4872 for (idx, argument) in arguments.iter().enumerate() {
4873 if const_args.contains(&idx) {
4876 let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
4877 self.r.tcx.features().min_generic_const_args(),
4878 );
4879 self.resolve_anon_const_manual(
4880 is_trivial_const_arg,
4881 AnonConstKind::ConstArg(IsRepeatExpr::No),
4882 |this| this.resolve_expr(argument, None),
4883 );
4884 } else {
4885 self.resolve_expr(argument, None);
4886 }
4887 }
4888 }
4889 ExprKind::Type(ref _type_expr, ref _ty) => {
4890 visit::walk_expr(self, expr);
4891 }
4892 ExprKind::Closure(box ast::Closure {
4894 binder: ClosureBinder::For { ref generic_params, span },
4895 ..
4896 }) => {
4897 self.with_generic_param_rib(
4898 generic_params,
4899 RibKind::Normal,
4900 expr.id,
4901 LifetimeBinderKind::Closure,
4902 span,
4903 |this| visit::walk_expr(this, expr),
4904 );
4905 }
4906 ExprKind::Closure(..) => visit::walk_expr(self, expr),
4907 ExprKind::Gen(..) => {
4908 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
4909 }
4910 ExprKind::Repeat(ref elem, ref ct) => {
4911 self.visit_expr(elem);
4912 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
4913 }
4914 ExprKind::ConstBlock(ref ct) => {
4915 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
4916 }
4917 ExprKind::Index(ref elem, ref idx, _) => {
4918 self.resolve_expr(elem, Some(expr));
4919 self.visit_expr(idx);
4920 }
4921 ExprKind::Assign(ref lhs, ref rhs, _) => {
4922 if !self.diag_metadata.is_assign_rhs {
4923 self.diag_metadata.in_assignment = Some(expr);
4924 }
4925 self.visit_expr(lhs);
4926 self.diag_metadata.is_assign_rhs = true;
4927 self.diag_metadata.in_assignment = None;
4928 self.visit_expr(rhs);
4929 self.diag_metadata.is_assign_rhs = false;
4930 }
4931 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
4932 self.diag_metadata.in_range = Some((start, end));
4933 self.resolve_expr(start, Some(expr));
4934 self.resolve_expr(end, Some(expr));
4935 self.diag_metadata.in_range = None;
4936 }
4937 _ => {
4938 visit::walk_expr(self, expr);
4939 }
4940 }
4941 }
4942
4943 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
4944 match expr.kind {
4945 ExprKind::Field(_, ident) => {
4946 let traits = self.traits_in_scope(ident, ValueNS);
4951 self.r.trait_map.insert(expr.id, traits);
4952 }
4953 ExprKind::MethodCall(ref call) => {
4954 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
4955 let traits = self.traits_in_scope(call.seg.ident, ValueNS);
4956 self.r.trait_map.insert(expr.id, traits);
4957 }
4958 _ => {
4959 }
4961 }
4962 }
4963
4964 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
4965 self.r.traits_in_scope(
4966 self.current_trait_ref.as_ref().map(|(module, _)| *module),
4967 &self.parent_scope,
4968 ident.span.ctxt(),
4969 Some((ident.name, ns)),
4970 )
4971 }
4972
4973 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
4974 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
4978 let res = *doc_link_resolutions
4979 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
4980 .or_default()
4981 .entry((Symbol::intern(path_str), ns))
4982 .or_insert_with_key(|(path, ns)| {
4983 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
4984 if let Some(res) = res
4985 && let Some(def_id) = res.opt_def_id()
4986 && self.is_invalid_proc_macro_item_for_doc(def_id)
4987 {
4988 return None;
4991 }
4992 res
4993 });
4994 self.r.doc_link_resolutions = doc_link_resolutions;
4995 res
4996 }
4997
4998 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
4999 if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5000 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5001 {
5002 return false;
5003 }
5004 let Some(local_did) = did.as_local() else { return true };
5005 !self.r.proc_macros.contains(&local_did)
5006 }
5007
5008 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5009 match self.r.tcx.sess.opts.resolve_doc_links {
5010 ResolveDocLinks::None => return,
5011 ResolveDocLinks::ExportedMetadata
5012 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5013 || !maybe_exported.eval(self.r) =>
5014 {
5015 return;
5016 }
5017 ResolveDocLinks::Exported
5018 if !maybe_exported.eval(self.r)
5019 && !rustdoc::has_primitive_or_keyword_docs(attrs) =>
5020 {
5021 return;
5022 }
5023 ResolveDocLinks::ExportedMetadata
5024 | ResolveDocLinks::Exported
5025 | ResolveDocLinks::All => {}
5026 }
5027
5028 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5029 return;
5030 }
5031
5032 let mut need_traits_in_scope = false;
5033 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5034 let mut any_resolved = false;
5036 let mut need_assoc = false;
5037 for ns in [TypeNS, ValueNS, MacroNS] {
5038 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5039 any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5042 } else if ns != MacroNS {
5043 need_assoc = true;
5044 }
5045 }
5046
5047 if need_assoc || !any_resolved {
5049 let mut path = &path_str[..];
5050 while let Some(idx) = path.rfind("::") {
5051 path = &path[..idx];
5052 need_traits_in_scope = true;
5053 for ns in [TypeNS, ValueNS, MacroNS] {
5054 self.resolve_and_cache_rustdoc_path(path, ns);
5055 }
5056 }
5057 }
5058 }
5059
5060 if need_traits_in_scope {
5061 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5063 doc_link_traits_in_scope
5064 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5065 .or_insert_with(|| {
5066 self.r
5067 .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5068 .into_iter()
5069 .filter_map(|tr| {
5070 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5071 return None;
5074 }
5075 Some(tr.def_id)
5076 })
5077 .collect()
5078 });
5079 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5080 }
5081 }
5082
5083 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5084 if let Some(seg) = path.first()
5086 && seg.ident.name == kw::PathRoot
5087 {
5088 return;
5089 }
5090
5091 if finalize.path_span.from_expansion()
5092 || path.iter().any(|seg| seg.ident.span.from_expansion())
5093 {
5094 return;
5095 }
5096
5097 let end_pos =
5098 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5099 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5100 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5109 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5110 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5111 (res == binding.res()).then_some((seg, binding))
5112 });
5113
5114 if let Some((seg, binding)) = unqualified {
5115 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5116 binding,
5117 node_id: finalize.node_id,
5118 path_span: finalize.path_span,
5119 removal_span: path[0].ident.span.until(seg.ident.span),
5120 });
5121 }
5122 }
5123
5124 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5125 if let Some(define_opaque) = define_opaque {
5126 for (id, path) in define_opaque {
5127 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5128 }
5129 }
5130 }
5131}
5132
5133struct ItemInfoCollector<'a, 'ra, 'tcx> {
5136 r: &'a mut Resolver<'ra, 'tcx>,
5137}
5138
5139impl ItemInfoCollector<'_, '_, '_> {
5140 fn collect_fn_info(
5141 &mut self,
5142 header: FnHeader,
5143 decl: &FnDecl,
5144 id: NodeId,
5145 attrs: &[Attribute],
5146 ) {
5147 let sig = DelegationFnSig {
5148 header,
5149 param_count: decl.inputs.len(),
5150 has_self: decl.has_self(),
5151 c_variadic: decl.c_variadic(),
5152 target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5153 };
5154 self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5155 }
5156}
5157
5158impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5159 fn visit_item(&mut self, item: &'ast Item) {
5160 match &item.kind {
5161 ItemKind::TyAlias(box TyAlias { generics, .. })
5162 | ItemKind::Const(box ConstItem { generics, .. })
5163 | ItemKind::Fn(box Fn { generics, .. })
5164 | ItemKind::Enum(_, generics, _)
5165 | ItemKind::Struct(_, generics, _)
5166 | ItemKind::Union(_, generics, _)
5167 | ItemKind::Impl(Impl { generics, .. })
5168 | ItemKind::Trait(box Trait { generics, .. })
5169 | ItemKind::TraitAlias(_, generics, _) => {
5170 if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5171 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5172 }
5173
5174 let def_id = self.r.local_def_id(item.id);
5175 let count = generics
5176 .params
5177 .iter()
5178 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5179 .count();
5180 self.r.item_generics_num_lifetimes.insert(def_id, count);
5181 }
5182
5183 ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5184 for foreign_item in items {
5185 if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5186 let new_header =
5187 FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5188 self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5189 }
5190 }
5191 }
5192
5193 ItemKind::Mod(..)
5194 | ItemKind::Static(..)
5195 | ItemKind::Use(..)
5196 | ItemKind::ExternCrate(..)
5197 | ItemKind::MacroDef(..)
5198 | ItemKind::GlobalAsm(..)
5199 | ItemKind::MacCall(..)
5200 | ItemKind::DelegationMac(..) => {}
5201 ItemKind::Delegation(..) => {
5202 }
5207 }
5208 visit::walk_item(self, item)
5209 }
5210
5211 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5212 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5213 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5214 }
5215 visit::walk_assoc_item(self, item, ctxt);
5216 }
5217}
5218
5219impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5220 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5221 visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5222 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5223 late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5224 visit::walk_crate(&mut late_resolution_visitor, krate);
5225 for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5226 self.lint_buffer.buffer_lint(
5227 lint::builtin::UNUSED_LABELS,
5228 *id,
5229 *span,
5230 BuiltinLintDiag::UnusedLabel,
5231 );
5232 }
5233 }
5234}
5235
5236fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5238 let mut path = expected_path.iter().rev();
5239 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5240 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5241 return false;
5242 }
5243 def_id = parent;
5244 }
5245 true
5246}