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