1use std::assert_matches::debug_assert_matches;
10use std::borrow::Cow;
11use std::collections::hash_map::Entry;
12use std::mem::{replace, swap, take};
13
14use rustc_ast::visit::{
15 AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,
16};
17use rustc_ast::*;
18use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
19use rustc_data_structures::unord::{UnordMap, UnordSet};
20use rustc_errors::codes::*;
21use rustc_errors::{
22 Applicability, DiagArgValue, ErrorGuaranteed, IntoDiagArg, StashKey, Suggestions,
23};
24use rustc_hir::def::Namespace::{self, *};
25use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS};
26use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId};
27use rustc_hir::{MissingLifetimeKind, PrimTy, TraitCandidate};
28use rustc_middle::middle::resolve_bound_vars::Set1;
29use rustc_middle::ty::{DelegationFnSig, Visibility};
30use rustc_middle::{bug, span_bug};
31use rustc_session::config::{CrateType, ResolveDocLinks};
32use rustc_session::lint;
33use rustc_session::parse::feature_err;
34use rustc_span::source_map::{Spanned, respan};
35use rustc_span::{BytePos, Ident, Span, Symbol, SyntaxContext, kw, sym};
36use smallvec::{SmallVec, smallvec};
37use thin_vec::ThinVec;
38use tracing::{debug, instrument, trace};
39
40use crate::{
41 BindingError, BindingKey, Finalize, LexicalScopeBinding, Module, ModuleOrUniformRoot,
42 NameBinding, ParentScope, PathResult, ResolutionError, Resolver, Segment, TyCtxt, UseError,
43 Used, errors, path_names_to_string, rustdoc,
44};
45
46mod diagnostics;
47
48type Res = def::Res<NodeId>;
49
50use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
51
52#[derive(Copy, Clone, Debug)]
53struct BindingInfo {
54 span: Span,
55 annotation: BindingMode,
56}
57
58#[derive(Copy, Clone, PartialEq, Eq, Debug)]
59pub(crate) enum PatternSource {
60 Match,
61 Let,
62 For,
63 FnParam,
64}
65
66#[derive(Copy, Clone, Debug, PartialEq, Eq)]
67enum IsRepeatExpr {
68 No,
69 Yes,
70}
71
72struct IsNeverPattern;
73
74#[derive(Copy, Clone, Debug, PartialEq, Eq)]
77enum AnonConstKind {
78 EnumDiscriminant,
79 FieldDefaultValue,
80 InlineConst,
81 ConstArg(IsRepeatExpr),
82}
83
84impl PatternSource {
85 fn descr(self) -> &'static str {
86 match self {
87 PatternSource::Match => "match binding",
88 PatternSource::Let => "let binding",
89 PatternSource::For => "for binding",
90 PatternSource::FnParam => "function parameter",
91 }
92 }
93}
94
95impl IntoDiagArg for PatternSource {
96 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
97 DiagArgValue::Str(Cow::Borrowed(self.descr()))
98 }
99}
100
101#[derive(PartialEq)]
105enum PatBoundCtx {
106 Product,
108 Or,
110}
111
112type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;
124
125#[derive(Copy, Clone, Debug)]
127pub(crate) enum HasGenericParams {
128 Yes(Span),
129 No,
130}
131
132#[derive(Copy, Clone, Debug, Eq, PartialEq)]
134pub(crate) enum ConstantHasGenerics {
135 Yes,
136 No(NoConstantGenericsReason),
137}
138
139impl ConstantHasGenerics {
140 fn force_yes_if(self, b: bool) -> Self {
141 if b { Self::Yes } else { self }
142 }
143}
144
145#[derive(Copy, Clone, Debug, Eq, PartialEq)]
147pub(crate) enum NoConstantGenericsReason {
148 NonTrivialConstArg,
155 IsEnumDiscriminant,
164}
165
166#[derive(Copy, Clone, Debug, Eq, PartialEq)]
167pub(crate) enum ConstantItemKind {
168 Const,
169 Static,
170}
171
172impl ConstantItemKind {
173 pub(crate) fn as_str(&self) -> &'static str {
174 match self {
175 Self::Const => "const",
176 Self::Static => "static",
177 }
178 }
179}
180
181#[derive(Debug, Copy, Clone, PartialEq, Eq)]
182enum RecordPartialRes {
183 Yes,
184 No,
185}
186
187#[derive(Copy, Clone, Debug)]
190pub(crate) enum RibKind<'ra> {
191 Normal,
193
194 Block(Option<Module<'ra>>),
200
201 AssocItem,
206
207 FnOrCoroutine,
209
210 Item(HasGenericParams, DefKind),
212
213 ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
218
219 Module(Module<'ra>),
221
222 MacroDefinition(DefId),
224
225 ForwardGenericParamBan(ForwardGenericParamBanReason),
229
230 ConstParamTy,
233
234 InlineAsmSym,
237}
238
239#[derive(Copy, Clone, PartialEq, Eq, Debug)]
240pub(crate) enum ForwardGenericParamBanReason {
241 Default,
242 ConstParamTy,
243}
244
245impl RibKind<'_> {
246 pub(crate) fn contains_params(&self) -> bool {
249 match self {
250 RibKind::Normal
251 | RibKind::Block(..)
252 | RibKind::FnOrCoroutine
253 | RibKind::ConstantItem(..)
254 | RibKind::Module(_)
255 | RibKind::MacroDefinition(_)
256 | RibKind::InlineAsmSym => false,
257 RibKind::ConstParamTy
258 | RibKind::AssocItem
259 | RibKind::Item(..)
260 | RibKind::ForwardGenericParamBan(_) => true,
261 }
262 }
263
264 fn is_label_barrier(self) -> bool {
266 match self {
267 RibKind::Normal | RibKind::MacroDefinition(..) => false,
268 RibKind::FnOrCoroutine | RibKind::ConstantItem(..) => true,
269 kind => bug!("unexpected rib kind: {kind:?}"),
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 visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1531 let mut forward_ty_ban_rib =
1537 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1538 let mut forward_const_ban_rib =
1539 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1540 for param in params.iter() {
1541 match param.kind {
1542 GenericParamKind::Type { .. } => {
1543 forward_ty_ban_rib
1544 .bindings
1545 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1546 }
1547 GenericParamKind::Const { .. } => {
1548 forward_const_ban_rib
1549 .bindings
1550 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1551 }
1552 GenericParamKind::Lifetime => {}
1553 }
1554 }
1555
1556 if add_self_upper {
1566 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1568 }
1569
1570 let mut forward_ty_ban_rib_const_param_ty = Rib {
1573 bindings: forward_ty_ban_rib.bindings.clone(),
1574 patterns_with_skipped_bindings: Default::default(),
1575 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1576 };
1577 let mut forward_const_ban_rib_const_param_ty = Rib {
1578 bindings: forward_const_ban_rib.bindings.clone(),
1579 patterns_with_skipped_bindings: Default::default(),
1580 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1581 };
1582 if !self.r.tcx.features().generic_const_parameter_types() {
1585 forward_ty_ban_rib_const_param_ty.bindings.clear();
1586 forward_const_ban_rib_const_param_ty.bindings.clear();
1587 }
1588
1589 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1590 for param in params {
1591 match param.kind {
1592 GenericParamKind::Lifetime => {
1593 for bound in ¶m.bounds {
1594 this.visit_param_bound(bound, BoundKind::Bound);
1595 }
1596 }
1597 GenericParamKind::Type { ref default } => {
1598 for bound in ¶m.bounds {
1599 this.visit_param_bound(bound, BoundKind::Bound);
1600 }
1601
1602 if let Some(ty) = default {
1603 this.ribs[TypeNS].push(forward_ty_ban_rib);
1604 this.ribs[ValueNS].push(forward_const_ban_rib);
1605 this.visit_ty(ty);
1606 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1607 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1608 }
1609
1610 let i = &Ident::with_dummy_span(param.ident.name);
1612 forward_ty_ban_rib.bindings.swap_remove(i);
1613 forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1614 }
1615 GenericParamKind::Const { ref ty, span: _, ref default } => {
1616 assert!(param.bounds.is_empty());
1618
1619 this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1620 this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1621 if this.r.tcx.features().generic_const_parameter_types() {
1622 this.visit_ty(ty)
1623 } else {
1624 this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1625 this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1626 this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1627 this.visit_ty(ty)
1628 });
1629 this.ribs[TypeNS].pop().unwrap();
1630 this.ribs[ValueNS].pop().unwrap();
1631 }
1632 forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1633 forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1634
1635 if let Some(expr) = default {
1636 this.ribs[TypeNS].push(forward_ty_ban_rib);
1637 this.ribs[ValueNS].push(forward_const_ban_rib);
1638 this.resolve_anon_const(
1639 expr,
1640 AnonConstKind::ConstArg(IsRepeatExpr::No),
1641 );
1642 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1643 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1644 }
1645
1646 let i = &Ident::with_dummy_span(param.ident.name);
1648 forward_const_ban_rib.bindings.swap_remove(i);
1649 forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1650 }
1651 }
1652 }
1653 })
1654 }
1655
1656 #[instrument(level = "debug", skip(self, work))]
1657 fn with_lifetime_rib<T>(
1658 &mut self,
1659 kind: LifetimeRibKind,
1660 work: impl FnOnce(&mut Self) -> T,
1661 ) -> T {
1662 self.lifetime_ribs.push(LifetimeRib::new(kind));
1663 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1664 let ret = work(self);
1665 self.lifetime_elision_candidates = outer_elision_candidates;
1666 self.lifetime_ribs.pop();
1667 ret
1668 }
1669
1670 #[instrument(level = "debug", skip(self))]
1671 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1672 let ident = lifetime.ident;
1673
1674 if ident.name == kw::StaticLifetime {
1675 self.record_lifetime_res(
1676 lifetime.id,
1677 LifetimeRes::Static,
1678 LifetimeElisionCandidate::Named,
1679 );
1680 return;
1681 }
1682
1683 if ident.name == kw::UnderscoreLifetime {
1684 return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1685 }
1686
1687 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1688 while let Some(rib) = lifetime_rib_iter.next() {
1689 let normalized_ident = ident.normalize_to_macros_2_0();
1690 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1691 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1692
1693 if let LifetimeRes::Param { param, binder } = res {
1694 match self.lifetime_uses.entry(param) {
1695 Entry::Vacant(v) => {
1696 debug!("First use of {:?} at {:?}", res, ident.span);
1697 let use_set = self
1698 .lifetime_ribs
1699 .iter()
1700 .rev()
1701 .find_map(|rib| match rib.kind {
1702 LifetimeRibKind::Item
1705 | LifetimeRibKind::AnonymousReportError
1706 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1707 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1708 LifetimeRibKind::AnonymousCreateParameter {
1711 binder: anon_binder,
1712 ..
1713 } => Some(if binder == anon_binder {
1714 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1715 } else {
1716 LifetimeUseSet::Many
1717 }),
1718 LifetimeRibKind::Elided(r) => Some(if res == r {
1721 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1722 } else {
1723 LifetimeUseSet::Many
1724 }),
1725 LifetimeRibKind::Generics { .. }
1726 | LifetimeRibKind::ConstParamTy => None,
1727 LifetimeRibKind::ConcreteAnonConst(_) => {
1728 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1729 }
1730 })
1731 .unwrap_or(LifetimeUseSet::Many);
1732 debug!(?use_ctxt, ?use_set);
1733 v.insert(use_set);
1734 }
1735 Entry::Occupied(mut o) => {
1736 debug!("Many uses of {:?} at {:?}", res, ident.span);
1737 *o.get_mut() = LifetimeUseSet::Many;
1738 }
1739 }
1740 }
1741 return;
1742 }
1743
1744 match rib.kind {
1745 LifetimeRibKind::Item => break,
1746 LifetimeRibKind::ConstParamTy => {
1747 self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1748 self.record_lifetime_res(
1749 lifetime.id,
1750 LifetimeRes::Error,
1751 LifetimeElisionCandidate::Ignore,
1752 );
1753 return;
1754 }
1755 LifetimeRibKind::ConcreteAnonConst(cause) => {
1756 self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1757 self.record_lifetime_res(
1758 lifetime.id,
1759 LifetimeRes::Error,
1760 LifetimeElisionCandidate::Ignore,
1761 );
1762 return;
1763 }
1764 LifetimeRibKind::AnonymousCreateParameter { .. }
1765 | LifetimeRibKind::Elided(_)
1766 | LifetimeRibKind::Generics { .. }
1767 | LifetimeRibKind::ElisionFailure
1768 | LifetimeRibKind::AnonymousReportError
1769 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1770 }
1771 }
1772
1773 let normalized_ident = ident.normalize_to_macros_2_0();
1774 let outer_res = lifetime_rib_iter
1775 .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1776
1777 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1778 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1779 }
1780
1781 #[instrument(level = "debug", skip(self))]
1782 fn resolve_anonymous_lifetime(
1783 &mut self,
1784 lifetime: &Lifetime,
1785 id_for_lint: NodeId,
1786 elided: bool,
1787 ) {
1788 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1789
1790 let kind =
1791 if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1792 let missing_lifetime = MissingLifetime {
1793 id: lifetime.id,
1794 span: lifetime.ident.span,
1795 kind,
1796 count: 1,
1797 id_for_lint,
1798 };
1799 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1800 for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1801 debug!(?rib.kind);
1802 match rib.kind {
1803 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1804 let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1805 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1806 return;
1807 }
1808 LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1809 let mut lifetimes_in_scope = vec![];
1810 for rib in self.lifetime_ribs[..i].iter().rev() {
1811 lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1812 if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1814 && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1815 {
1816 lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1817 }
1818 if let LifetimeRibKind::Item = rib.kind {
1819 break;
1820 }
1821 }
1822 if lifetimes_in_scope.is_empty() {
1823 self.record_lifetime_res(
1824 lifetime.id,
1825 LifetimeRes::Static,
1826 elision_candidate,
1827 );
1828 return;
1829 } else if emit_lint {
1830 self.r.lint_buffer.buffer_lint(
1831 lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1832 node_id,
1833 lifetime.ident.span,
1834 lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1835 elided,
1836 span: lifetime.ident.span,
1837 lifetimes_in_scope: lifetimes_in_scope.into(),
1838 },
1839 );
1840 }
1841 }
1842 LifetimeRibKind::AnonymousReportError => {
1843 if elided {
1844 let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1845 if let LifetimeRibKind::Generics {
1846 span,
1847 kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1848 ..
1849 } = rib.kind
1850 {
1851 Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
1852 lo: span.shrink_to_lo(),
1853 hi: lifetime.ident.span.shrink_to_hi(),
1854 })
1855 } else {
1856 None
1857 }
1858 });
1859 if !self.in_func_body
1862 && let Some((module, _)) = &self.current_trait_ref
1863 && let Some(ty) = &self.diag_metadata.current_self_type
1864 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1865 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1866 {
1867 if def_id_matches_path(
1868 self.r.tcx,
1869 trait_id,
1870 &["core", "iter", "traits", "iterator", "Iterator"],
1871 ) {
1872 self.r.dcx().emit_err(errors::LendingIteratorReportError {
1873 lifetime: lifetime.ident.span,
1874 ty: ty.span,
1875 });
1876 } else {
1877 self.r.dcx().emit_err(errors::AnonymousLifetimeNonGatReportError {
1878 lifetime: lifetime.ident.span,
1879 });
1880 }
1881 } else {
1882 self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
1883 span: lifetime.ident.span,
1884 suggestion,
1885 });
1886 }
1887 } else {
1888 self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
1889 span: lifetime.ident.span,
1890 });
1891 };
1892 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1893 return;
1894 }
1895 LifetimeRibKind::Elided(res) => {
1896 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1897 return;
1898 }
1899 LifetimeRibKind::ElisionFailure => {
1900 self.diag_metadata.current_elision_failures.push(missing_lifetime);
1901 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1902 return;
1903 }
1904 LifetimeRibKind::Item => break,
1905 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1906 LifetimeRibKind::ConcreteAnonConst(_) => {
1907 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1909 }
1910 }
1911 }
1912 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1913 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1914 }
1915
1916 #[instrument(level = "debug", skip(self))]
1917 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1918 let id = self.r.next_node_id();
1919 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1920
1921 self.record_lifetime_res(
1922 anchor_id,
1923 LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
1924 LifetimeElisionCandidate::Ignore,
1925 );
1926 self.resolve_anonymous_lifetime(<, anchor_id, true);
1927 }
1928
1929 #[instrument(level = "debug", skip(self))]
1930 fn create_fresh_lifetime(
1931 &mut self,
1932 ident: Ident,
1933 binder: NodeId,
1934 kind: MissingLifetimeKind,
1935 ) -> LifetimeRes {
1936 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1937 debug!(?ident.span);
1938
1939 let param = self.r.next_node_id();
1941 let res = LifetimeRes::Fresh { param, binder, kind };
1942 self.record_lifetime_param(param, res);
1943
1944 self.r
1946 .extra_lifetime_params_map
1947 .entry(binder)
1948 .or_insert_with(Vec::new)
1949 .push((ident, param, res));
1950 res
1951 }
1952
1953 #[instrument(level = "debug", skip(self))]
1954 fn resolve_elided_lifetimes_in_path(
1955 &mut self,
1956 partial_res: PartialRes,
1957 path: &[Segment],
1958 source: PathSource<'_, 'ast, 'ra>,
1959 path_span: Span,
1960 ) {
1961 let proj_start = path.len() - partial_res.unresolved_segments();
1962 for (i, segment) in path.iter().enumerate() {
1963 if segment.has_lifetime_args {
1964 continue;
1965 }
1966 let Some(segment_id) = segment.id else {
1967 continue;
1968 };
1969
1970 let type_def_id = match partial_res.base_res() {
1973 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1974 self.r.tcx.parent(def_id)
1975 }
1976 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1977 self.r.tcx.parent(def_id)
1978 }
1979 Res::Def(DefKind::Struct, def_id)
1980 | Res::Def(DefKind::Union, def_id)
1981 | Res::Def(DefKind::Enum, def_id)
1982 | Res::Def(DefKind::TyAlias, def_id)
1983 | Res::Def(DefKind::Trait, def_id)
1984 if i + 1 == proj_start =>
1985 {
1986 def_id
1987 }
1988 _ => continue,
1989 };
1990
1991 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
1992 if expected_lifetimes == 0 {
1993 continue;
1994 }
1995
1996 let node_ids = self.r.next_node_ids(expected_lifetimes);
1997 self.record_lifetime_res(
1998 segment_id,
1999 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2000 LifetimeElisionCandidate::Ignore,
2001 );
2002
2003 let inferred = match source {
2004 PathSource::Trait(..)
2005 | PathSource::TraitItem(..)
2006 | PathSource::Type
2007 | PathSource::PreciseCapturingArg(..)
2008 | PathSource::ReturnTypeNotation => false,
2009 PathSource::Expr(..)
2010 | PathSource::Pat
2011 | PathSource::Struct(_)
2012 | PathSource::TupleStruct(..)
2013 | PathSource::DefineOpaques
2014 | PathSource::Delegation => true,
2015 };
2016 if inferred {
2017 for id in node_ids {
2020 self.record_lifetime_res(
2021 id,
2022 LifetimeRes::Infer,
2023 LifetimeElisionCandidate::Named,
2024 );
2025 }
2026 continue;
2027 }
2028
2029 let elided_lifetime_span = if segment.has_generic_args {
2030 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2032 } else {
2033 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2037 };
2038 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2039
2040 let kind = if segment.has_generic_args {
2041 MissingLifetimeKind::Comma
2042 } else {
2043 MissingLifetimeKind::Brackets
2044 };
2045 let missing_lifetime = MissingLifetime {
2046 id: node_ids.start,
2047 id_for_lint: segment_id,
2048 span: elided_lifetime_span,
2049 kind,
2050 count: expected_lifetimes,
2051 };
2052 let mut should_lint = true;
2053 for rib in self.lifetime_ribs.iter().rev() {
2054 match rib.kind {
2055 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2062 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2063 let sess = self.r.tcx.sess;
2064 let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2065 sess.source_map(),
2066 expected_lifetimes,
2067 path_span,
2068 !segment.has_generic_args,
2069 elided_lifetime_span,
2070 );
2071 self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2072 span: path_span,
2073 subdiag,
2074 });
2075 should_lint = false;
2076
2077 for id in node_ids {
2078 self.record_lifetime_res(
2079 id,
2080 LifetimeRes::Error,
2081 LifetimeElisionCandidate::Named,
2082 );
2083 }
2084 break;
2085 }
2086 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2088 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2090 for id in node_ids {
2091 let res = self.create_fresh_lifetime(ident, binder, kind);
2092 self.record_lifetime_res(
2093 id,
2094 res,
2095 replace(&mut candidate, LifetimeElisionCandidate::Named),
2096 );
2097 }
2098 break;
2099 }
2100 LifetimeRibKind::Elided(res) => {
2101 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2102 for id in node_ids {
2103 self.record_lifetime_res(
2104 id,
2105 res,
2106 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2107 );
2108 }
2109 break;
2110 }
2111 LifetimeRibKind::ElisionFailure => {
2112 self.diag_metadata.current_elision_failures.push(missing_lifetime);
2113 for id in node_ids {
2114 self.record_lifetime_res(
2115 id,
2116 LifetimeRes::Error,
2117 LifetimeElisionCandidate::Ignore,
2118 );
2119 }
2120 break;
2121 }
2122 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2127 for id in node_ids {
2128 self.record_lifetime_res(
2129 id,
2130 LifetimeRes::Error,
2131 LifetimeElisionCandidate::Ignore,
2132 );
2133 }
2134 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2135 break;
2136 }
2137 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2138 LifetimeRibKind::ConcreteAnonConst(_) => {
2139 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2141 }
2142 }
2143 }
2144
2145 if should_lint {
2146 self.r.lint_buffer.buffer_lint(
2147 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2148 segment_id,
2149 elided_lifetime_span,
2150 lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2151 expected_lifetimes,
2152 path_span,
2153 !segment.has_generic_args,
2154 elided_lifetime_span,
2155 ),
2156 );
2157 }
2158 }
2159 }
2160
2161 #[instrument(level = "debug", skip(self))]
2162 fn record_lifetime_res(
2163 &mut self,
2164 id: NodeId,
2165 res: LifetimeRes,
2166 candidate: LifetimeElisionCandidate,
2167 ) {
2168 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2169 panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2170 }
2171
2172 match res {
2173 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2174 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2175 candidates.push((res, candidate));
2176 }
2177 }
2178 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2179 }
2180 }
2181
2182 #[instrument(level = "debug", skip(self))]
2183 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2184 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2185 panic!(
2186 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2187 )
2188 }
2189 }
2190
2191 #[instrument(level = "debug", skip(self, inputs))]
2193 fn resolve_fn_signature(
2194 &mut self,
2195 fn_id: NodeId,
2196 has_self: bool,
2197 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2198 output_ty: &'ast FnRetTy,
2199 report_elided_lifetimes_in_path: bool,
2200 ) {
2201 let rib = LifetimeRibKind::AnonymousCreateParameter {
2202 binder: fn_id,
2203 report_in_path: report_elided_lifetimes_in_path,
2204 };
2205 self.with_lifetime_rib(rib, |this| {
2206 let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2208 debug!(?elision_lifetime);
2209
2210 let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2211 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2212 this.r.lifetime_elision_allowed.insert(fn_id);
2213 LifetimeRibKind::Elided(*res)
2214 } else {
2215 LifetimeRibKind::ElisionFailure
2216 };
2217 this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2218 let elision_failures =
2219 replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2220 if !elision_failures.is_empty() {
2221 let Err(failure_info) = elision_lifetime else { bug!() };
2222 this.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2223 }
2224 });
2225 }
2226
2227 fn resolve_fn_params(
2231 &mut self,
2232 has_self: bool,
2233 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2234 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2235 enum Elision {
2236 None,
2238 Self_(LifetimeRes),
2240 Param(LifetimeRes),
2242 Err,
2244 }
2245
2246 let outer_candidates = self.lifetime_elision_candidates.take();
2248
2249 let mut elision_lifetime = Elision::None;
2251 let mut parameter_info = Vec::new();
2253 let mut all_candidates = Vec::new();
2254
2255 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2257 for (pat, _) in inputs.clone() {
2258 debug!("resolving bindings in pat = {pat:?}");
2259 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2260 if let Some(pat) = pat {
2261 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2262 }
2263 });
2264 }
2265 self.apply_pattern_bindings(bindings);
2266
2267 for (index, (pat, ty)) in inputs.enumerate() {
2268 debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2269 debug_assert_matches!(self.lifetime_elision_candidates, None);
2271 self.lifetime_elision_candidates = Some(Default::default());
2272 self.visit_ty(ty);
2273 let local_candidates = self.lifetime_elision_candidates.take();
2274
2275 if let Some(candidates) = local_candidates {
2276 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2277 let lifetime_count = distinct.len();
2278 if lifetime_count != 0 {
2279 parameter_info.push(ElisionFnParameter {
2280 index,
2281 ident: if let Some(pat) = pat
2282 && let PatKind::Ident(_, ident, _) = pat.kind
2283 {
2284 Some(ident)
2285 } else {
2286 None
2287 },
2288 lifetime_count,
2289 span: ty.span,
2290 });
2291 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2292 match candidate {
2293 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2294 None
2295 }
2296 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2297 }
2298 }));
2299 }
2300 if !distinct.is_empty() {
2301 match elision_lifetime {
2302 Elision::None => {
2304 if let Some(res) = distinct.get_only() {
2305 elision_lifetime = Elision::Param(*res)
2307 } else {
2308 elision_lifetime = Elision::Err;
2310 }
2311 }
2312 Elision::Param(_) => elision_lifetime = Elision::Err,
2314 Elision::Self_(_) | Elision::Err => {}
2316 }
2317 }
2318 }
2319
2320 if index == 0 && has_self {
2322 let self_lifetime = self.find_lifetime_for_self(ty);
2323 elision_lifetime = match self_lifetime {
2324 Set1::One(lifetime) => Elision::Self_(lifetime),
2326 Set1::Many => Elision::Err,
2331 Set1::Empty => Elision::None,
2334 }
2335 }
2336 debug!("(resolving function / closure) recorded parameter");
2337 }
2338
2339 debug_assert_matches!(self.lifetime_elision_candidates, None);
2341 self.lifetime_elision_candidates = outer_candidates;
2342
2343 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2344 return Ok(res);
2345 }
2346
2347 Err((all_candidates, parameter_info))
2349 }
2350
2351 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2353 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2357 r: &'a Resolver<'ra, 'tcx>,
2358 impl_self: Option<Res>,
2359 lifetime: Set1<LifetimeRes>,
2360 }
2361
2362 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2363 fn visit_ty(&mut self, ty: &'ra Ty) {
2364 trace!("FindReferenceVisitor considering ty={:?}", ty);
2365 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2366 let mut visitor =
2368 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2369 visitor.visit_ty(ty);
2370 trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2371 if visitor.self_found {
2372 let lt_id = if let Some(lt) = lt {
2373 lt.id
2374 } else {
2375 let res = self.r.lifetimes_res_map[&ty.id];
2376 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2377 start
2378 };
2379 let lt_res = self.r.lifetimes_res_map[<_id];
2380 trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2381 self.lifetime.insert(lt_res);
2382 }
2383 }
2384 visit::walk_ty(self, ty)
2385 }
2386
2387 fn visit_expr(&mut self, _: &'ra Expr) {}
2390 }
2391
2392 struct SelfVisitor<'a, 'ra, 'tcx> {
2395 r: &'a Resolver<'ra, 'tcx>,
2396 impl_self: Option<Res>,
2397 self_found: bool,
2398 }
2399
2400 impl SelfVisitor<'_, '_, '_> {
2401 fn is_self_ty(&self, ty: &Ty) -> bool {
2403 match ty.kind {
2404 TyKind::ImplicitSelf => true,
2405 TyKind::Path(None, _) => {
2406 let path_res = self.r.partial_res_map[&ty.id].full_res();
2407 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2408 return true;
2409 }
2410 self.impl_self.is_some() && path_res == self.impl_self
2411 }
2412 _ => false,
2413 }
2414 }
2415 }
2416
2417 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2418 fn visit_ty(&mut self, ty: &'ra Ty) {
2419 trace!("SelfVisitor considering ty={:?}", ty);
2420 if self.is_self_ty(ty) {
2421 trace!("SelfVisitor found Self");
2422 self.self_found = true;
2423 }
2424 visit::walk_ty(self, ty)
2425 }
2426
2427 fn visit_expr(&mut self, _: &'ra Expr) {}
2430 }
2431
2432 let impl_self = self
2433 .diag_metadata
2434 .current_self_type
2435 .as_ref()
2436 .and_then(|ty| {
2437 if let TyKind::Path(None, _) = ty.kind {
2438 self.r.partial_res_map.get(&ty.id)
2439 } else {
2440 None
2441 }
2442 })
2443 .and_then(|res| res.full_res())
2444 .filter(|res| {
2445 matches!(
2449 res,
2450 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2451 )
2452 });
2453 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2454 visitor.visit_ty(ty);
2455 trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2456 visitor.lifetime
2457 }
2458
2459 fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2462 let mut suggestion = None;
2463
2464 for i in (0..self.label_ribs.len()).rev() {
2465 let rib = &self.label_ribs[i];
2466
2467 if let RibKind::MacroDefinition(def) = rib.kind
2468 && def == self.r.macro_def(label.span.ctxt())
2471 {
2472 label.span.remove_mark();
2473 }
2474
2475 let ident = label.normalize_to_macro_rules();
2476 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2477 let definition_span = ident.span;
2478 return if self.is_label_valid_from_rib(i) {
2479 Ok((*id, definition_span))
2480 } else {
2481 Err(ResolutionError::UnreachableLabel {
2482 name: label.name,
2483 definition_span,
2484 suggestion,
2485 })
2486 };
2487 }
2488
2489 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2492 }
2493
2494 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2495 }
2496
2497 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2499 let ribs = &self.label_ribs[rib_index + 1..];
2500 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2501 }
2502
2503 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2504 debug!("resolve_adt");
2505 let kind = self.r.local_def_kind(item.id);
2506 self.with_current_self_item(item, |this| {
2507 this.with_generic_param_rib(
2508 &generics.params,
2509 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2510 item.id,
2511 LifetimeBinderKind::Item,
2512 generics.span,
2513 |this| {
2514 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2515 this.with_self_rib(
2516 Res::SelfTyAlias {
2517 alias_to: item_def_id,
2518 forbid_generic: false,
2519 is_trait_impl: false,
2520 },
2521 |this| {
2522 visit::walk_item(this, item);
2523 },
2524 );
2525 },
2526 );
2527 });
2528 }
2529
2530 fn future_proof_import(&mut self, use_tree: &UseTree) {
2531 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2532 let ident = segment.ident;
2533 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2534 return;
2535 }
2536
2537 let nss = match use_tree.kind {
2538 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2539 _ => &[TypeNS],
2540 };
2541 let report_error = |this: &Self, ns| {
2542 if this.should_report_errs() {
2543 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2544 this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2545 }
2546 };
2547
2548 for &ns in nss {
2549 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2550 Some(LexicalScopeBinding::Res(..)) => {
2551 report_error(self, ns);
2552 }
2553 Some(LexicalScopeBinding::Item(binding)) => {
2554 if let Some(LexicalScopeBinding::Res(..)) =
2555 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2556 {
2557 report_error(self, ns);
2558 }
2559 }
2560 None => {}
2561 }
2562 }
2563 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2564 for (use_tree, _) in items {
2565 self.future_proof_import(use_tree);
2566 }
2567 }
2568 }
2569
2570 fn resolve_item(&mut self, item: &'ast Item) {
2571 let mod_inner_docs =
2572 matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2573 if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2574 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2575 }
2576
2577 debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2578
2579 let def_kind = self.r.local_def_kind(item.id);
2580 match item.kind {
2581 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2582 self.with_generic_param_rib(
2583 &generics.params,
2584 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2585 item.id,
2586 LifetimeBinderKind::Item,
2587 generics.span,
2588 |this| visit::walk_item(this, item),
2589 );
2590 }
2591
2592 ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2593 self.with_generic_param_rib(
2594 &generics.params,
2595 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2596 item.id,
2597 LifetimeBinderKind::Function,
2598 generics.span,
2599 |this| visit::walk_item(this, item),
2600 );
2601 self.resolve_define_opaques(define_opaque);
2602 }
2603
2604 ItemKind::Enum(_, ref generics, _)
2605 | ItemKind::Struct(_, ref generics, _)
2606 | ItemKind::Union(_, ref generics, _) => {
2607 self.resolve_adt(item, generics);
2608 }
2609
2610 ItemKind::Impl(Impl {
2611 ref generics,
2612 ref of_trait,
2613 ref self_ty,
2614 items: ref impl_items,
2615 ..
2616 }) => {
2617 self.diag_metadata.current_impl_items = Some(impl_items);
2618 self.resolve_implementation(
2619 &item.attrs,
2620 generics,
2621 of_trait.as_deref(),
2622 self_ty,
2623 item.id,
2624 impl_items,
2625 );
2626 self.diag_metadata.current_impl_items = None;
2627 }
2628
2629 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2630 self.with_generic_param_rib(
2632 &generics.params,
2633 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2634 item.id,
2635 LifetimeBinderKind::Item,
2636 generics.span,
2637 |this| {
2638 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2639 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2640 this.visit_generics(generics);
2641 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2642 this.resolve_trait_items(items);
2643 });
2644 },
2645 );
2646 }
2647
2648 ItemKind::TraitAlias(_, ref generics, ref bounds) => {
2649 self.with_generic_param_rib(
2651 &generics.params,
2652 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2653 item.id,
2654 LifetimeBinderKind::Item,
2655 generics.span,
2656 |this| {
2657 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2658 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2659 this.visit_generics(generics);
2660 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2661 });
2662 },
2663 );
2664 }
2665
2666 ItemKind::Mod(..) => {
2667 let module = self.r.expect_module(self.r.local_def_id(item.id).to_def_id());
2668 let orig_module = replace(&mut self.parent_scope.module, module);
2669 self.with_rib(ValueNS, RibKind::Module(module), |this| {
2670 this.with_rib(TypeNS, RibKind::Module(module), |this| {
2671 if mod_inner_docs {
2672 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2673 }
2674 let old_macro_rules = this.parent_scope.macro_rules;
2675 visit::walk_item(this, item);
2676 if item.attrs.iter().all(|attr| {
2679 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2680 }) {
2681 this.parent_scope.macro_rules = old_macro_rules;
2682 }
2683 })
2684 });
2685 self.parent_scope.module = orig_module;
2686 }
2687
2688 ItemKind::Static(box ast::StaticItem {
2689 ident,
2690 ref ty,
2691 ref expr,
2692 ref define_opaque,
2693 ..
2694 }) => {
2695 self.with_static_rib(def_kind, |this| {
2696 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2697 this.visit_ty(ty);
2698 });
2699 if let Some(expr) = expr {
2700 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Static)));
2703 }
2704 });
2705 self.resolve_define_opaques(define_opaque);
2706 }
2707
2708 ItemKind::Const(box ast::ConstItem {
2709 ident,
2710 ref generics,
2711 ref ty,
2712 ref expr,
2713 ref define_opaque,
2714 ..
2715 }) => {
2716 self.with_generic_param_rib(
2717 &generics.params,
2718 RibKind::Item(
2719 if self.r.tcx.features().generic_const_items() {
2720 HasGenericParams::Yes(generics.span)
2721 } else {
2722 HasGenericParams::No
2723 },
2724 def_kind,
2725 ),
2726 item.id,
2727 LifetimeBinderKind::ConstItem,
2728 generics.span,
2729 |this| {
2730 this.visit_generics(generics);
2731
2732 this.with_lifetime_rib(
2733 LifetimeRibKind::Elided(LifetimeRes::Static),
2734 |this| this.visit_ty(ty),
2735 );
2736
2737 if let Some(expr) = expr {
2738 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Const)));
2739 }
2740 },
2741 );
2742 self.resolve_define_opaques(define_opaque);
2743 }
2744
2745 ItemKind::Use(ref use_tree) => {
2746 let maybe_exported = match use_tree.kind {
2747 UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2748 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2749 };
2750 self.resolve_doc_links(&item.attrs, maybe_exported);
2751
2752 self.future_proof_import(use_tree);
2753 }
2754
2755 ItemKind::MacroDef(_, ref macro_def) => {
2756 if macro_def.macro_rules {
2759 let def_id = self.r.local_def_id(item.id);
2760 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2761 }
2762 }
2763
2764 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2765 visit::walk_item(self, item);
2766 }
2767
2768 ItemKind::Delegation(ref delegation) => {
2769 let span = delegation.path.segments.last().unwrap().ident.span;
2770 self.with_generic_param_rib(
2771 &[],
2772 RibKind::Item(HasGenericParams::Yes(span), def_kind),
2773 item.id,
2774 LifetimeBinderKind::Function,
2775 span,
2776 |this| this.resolve_delegation(delegation),
2777 );
2778 }
2779
2780 ItemKind::ExternCrate(..) => {}
2781
2782 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2783 panic!("unexpanded macro in resolve!")
2784 }
2785 }
2786 }
2787
2788 fn with_generic_param_rib<'c, F>(
2789 &'c mut self,
2790 params: &'c [GenericParam],
2791 kind: RibKind<'ra>,
2792 binder: NodeId,
2793 generics_kind: LifetimeBinderKind,
2794 generics_span: Span,
2795 f: F,
2796 ) where
2797 F: FnOnce(&mut Self),
2798 {
2799 debug!("with_generic_param_rib");
2800 let lifetime_kind =
2801 LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
2802
2803 let mut function_type_rib = Rib::new(kind);
2804 let mut function_value_rib = Rib::new(kind);
2805 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2806
2807 if !params.is_empty() {
2809 let mut seen_bindings = FxHashMap::default();
2810 let mut seen_lifetimes = FxHashSet::default();
2812
2813 for ns in [ValueNS, TypeNS] {
2815 for parent_rib in self.ribs[ns].iter().rev() {
2816 if matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
2819 break;
2820 }
2821
2822 seen_bindings
2823 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2824 }
2825 }
2826
2827 for rib in self.lifetime_ribs.iter().rev() {
2829 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2830 if let LifetimeRibKind::Item = rib.kind {
2831 break;
2832 }
2833 }
2834
2835 for param in params {
2836 let ident = param.ident.normalize_to_macros_2_0();
2837 debug!("with_generic_param_rib: {}", param.id);
2838
2839 if let GenericParamKind::Lifetime = param.kind
2840 && let Some(&original) = seen_lifetimes.get(&ident)
2841 {
2842 diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
2843 self.record_lifetime_param(param.id, LifetimeRes::Error);
2845 continue;
2846 }
2847
2848 match seen_bindings.entry(ident) {
2849 Entry::Occupied(entry) => {
2850 let span = *entry.get();
2851 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
2852 self.report_error(param.ident.span, err);
2853 let rib = match param.kind {
2854 GenericParamKind::Lifetime => {
2855 self.record_lifetime_param(param.id, LifetimeRes::Error);
2857 continue;
2858 }
2859 GenericParamKind::Type { .. } => &mut function_type_rib,
2860 GenericParamKind::Const { .. } => &mut function_value_rib,
2861 };
2862
2863 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
2865 rib.bindings.insert(ident, Res::Err);
2866 continue;
2867 }
2868 Entry::Vacant(entry) => {
2869 entry.insert(param.ident.span);
2870 }
2871 }
2872
2873 if param.ident.name == kw::UnderscoreLifetime {
2874 let is_raw_underscore_lifetime = self
2877 .r
2878 .tcx
2879 .sess
2880 .psess
2881 .raw_identifier_spans
2882 .iter()
2883 .any(|span| span == param.span());
2884
2885 self.r
2886 .dcx()
2887 .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
2888 .emit_unless_delay(is_raw_underscore_lifetime);
2889 self.record_lifetime_param(param.id, LifetimeRes::Error);
2891 continue;
2892 }
2893
2894 if param.ident.name == kw::StaticLifetime {
2895 self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
2896 span: param.ident.span,
2897 lifetime: param.ident,
2898 });
2899 self.record_lifetime_param(param.id, LifetimeRes::Error);
2901 continue;
2902 }
2903
2904 let def_id = self.r.local_def_id(param.id);
2905
2906 let (rib, def_kind) = match param.kind {
2908 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2909 GenericParamKind::Const { .. } => {
2910 (&mut function_value_rib, DefKind::ConstParam)
2911 }
2912 GenericParamKind::Lifetime => {
2913 let res = LifetimeRes::Param { param: def_id, binder };
2914 self.record_lifetime_param(param.id, res);
2915 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2916 continue;
2917 }
2918 };
2919
2920 let res = match kind {
2921 RibKind::Item(..) | RibKind::AssocItem => {
2922 Res::Def(def_kind, def_id.to_def_id())
2923 }
2924 RibKind::Normal => {
2925 if self.r.tcx.features().non_lifetime_binders()
2928 && matches!(param.kind, GenericParamKind::Type { .. })
2929 {
2930 Res::Def(def_kind, def_id.to_def_id())
2931 } else {
2932 Res::Err
2933 }
2934 }
2935 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2936 };
2937 self.r.record_partial_res(param.id, PartialRes::new(res));
2938 rib.bindings.insert(ident, res);
2939 }
2940 }
2941
2942 self.lifetime_ribs.push(function_lifetime_rib);
2943 self.ribs[ValueNS].push(function_value_rib);
2944 self.ribs[TypeNS].push(function_type_rib);
2945
2946 f(self);
2947
2948 self.ribs[TypeNS].pop();
2949 self.ribs[ValueNS].pop();
2950 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2951
2952 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2954 for (_, res) in function_lifetime_rib.bindings.values() {
2955 candidates.retain(|(r, _)| r != res);
2956 }
2957 }
2958
2959 if let LifetimeBinderKind::FnPtrType
2960 | LifetimeBinderKind::WhereBound
2961 | LifetimeBinderKind::Function
2962 | LifetimeBinderKind::ImplBlock = generics_kind
2963 {
2964 self.maybe_report_lifetime_uses(generics_span, params)
2965 }
2966 }
2967
2968 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
2969 self.label_ribs.push(Rib::new(kind));
2970 f(self);
2971 self.label_ribs.pop();
2972 }
2973
2974 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
2975 let kind = RibKind::Item(HasGenericParams::No, def_kind);
2976 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
2977 }
2978
2979 #[instrument(level = "debug", skip(self, f))]
2988 fn with_constant_rib(
2989 &mut self,
2990 is_repeat: IsRepeatExpr,
2991 may_use_generics: ConstantHasGenerics,
2992 item: Option<(Ident, ConstantItemKind)>,
2993 f: impl FnOnce(&mut Self),
2994 ) {
2995 let f = |this: &mut Self| {
2996 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
2997 this.with_rib(
2998 TypeNS,
2999 RibKind::ConstantItem(
3000 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3001 item,
3002 ),
3003 |this| {
3004 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3005 },
3006 )
3007 })
3008 };
3009
3010 if let ConstantHasGenerics::No(cause) = may_use_generics {
3011 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3012 } else {
3013 f(self)
3014 }
3015 }
3016
3017 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3018 let previous_value =
3020 replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3021 let result = f(self);
3022 self.diag_metadata.current_self_type = previous_value;
3023 result
3024 }
3025
3026 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3027 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3028 let result = f(self);
3029 self.diag_metadata.current_self_item = previous_value;
3030 result
3031 }
3032
3033 fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3035 let trait_assoc_items =
3036 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3037
3038 let walk_assoc_item =
3039 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3040 this.with_generic_param_rib(
3041 &generics.params,
3042 RibKind::AssocItem,
3043 item.id,
3044 kind,
3045 generics.span,
3046 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3047 );
3048 };
3049
3050 for item in trait_items {
3051 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3052 match &item.kind {
3053 AssocItemKind::Const(box ast::ConstItem {
3054 generics,
3055 ty,
3056 expr,
3057 define_opaque,
3058 ..
3059 }) => {
3060 self.with_generic_param_rib(
3061 &generics.params,
3062 RibKind::AssocItem,
3063 item.id,
3064 LifetimeBinderKind::ConstItem,
3065 generics.span,
3066 |this| {
3067 this.with_lifetime_rib(
3068 LifetimeRibKind::StaticIfNoLifetimeInScope {
3069 lint_id: item.id,
3070 emit_lint: false,
3071 },
3072 |this| {
3073 this.visit_generics(generics);
3074 this.visit_ty(ty);
3075
3076 if let Some(expr) = expr {
3079 this.resolve_const_body(expr, None);
3085 }
3086 },
3087 )
3088 },
3089 );
3090
3091 self.resolve_define_opaques(define_opaque);
3092 }
3093 AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3094 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3095
3096 self.resolve_define_opaques(define_opaque);
3097 }
3098 AssocItemKind::Delegation(delegation) => {
3099 self.with_generic_param_rib(
3100 &[],
3101 RibKind::AssocItem,
3102 item.id,
3103 LifetimeBinderKind::Function,
3104 delegation.path.segments.last().unwrap().ident.span,
3105 |this| this.resolve_delegation(delegation),
3106 );
3107 }
3108 AssocItemKind::Type(box TyAlias { generics, .. }) => self
3109 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3110 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3111 }),
3112 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3113 panic!("unexpanded macro in resolve!")
3114 }
3115 };
3116 }
3117
3118 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3119 }
3120
3121 fn with_optional_trait_ref<T>(
3123 &mut self,
3124 opt_trait_ref: Option<&TraitRef>,
3125 self_type: &'ast Ty,
3126 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3127 ) -> T {
3128 let mut new_val = None;
3129 let mut new_id = None;
3130 if let Some(trait_ref) = opt_trait_ref {
3131 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3132 self.diag_metadata.currently_processing_impl_trait =
3133 Some((trait_ref.clone(), self_type.clone()));
3134 let res = self.smart_resolve_path_fragment(
3135 &None,
3136 &path,
3137 PathSource::Trait(AliasPossibility::No),
3138 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3139 RecordPartialRes::Yes,
3140 None,
3141 );
3142 self.diag_metadata.currently_processing_impl_trait = None;
3143 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3144 new_id = Some(def_id);
3145 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3146 }
3147 }
3148 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3149 let result = f(self, new_id);
3150 self.current_trait_ref = original_trait_ref;
3151 result
3152 }
3153
3154 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3155 let mut self_type_rib = Rib::new(RibKind::Normal);
3156
3157 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3159 self.ribs[ns].push(self_type_rib);
3160 f(self);
3161 self.ribs[ns].pop();
3162 }
3163
3164 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3165 self.with_self_rib_ns(TypeNS, self_res, f)
3166 }
3167
3168 fn resolve_implementation(
3169 &mut self,
3170 attrs: &[ast::Attribute],
3171 generics: &'ast Generics,
3172 of_trait: Option<&'ast ast::TraitImplHeader>,
3173 self_type: &'ast Ty,
3174 item_id: NodeId,
3175 impl_items: &'ast [Box<AssocItem>],
3176 ) {
3177 debug!("resolve_implementation");
3178 self.with_generic_param_rib(
3180 &generics.params,
3181 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3182 item_id,
3183 LifetimeBinderKind::ImplBlock,
3184 generics.span,
3185 |this| {
3186 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3188 this.with_lifetime_rib(
3189 LifetimeRibKind::AnonymousCreateParameter {
3190 binder: item_id,
3191 report_in_path: true
3192 },
3193 |this| {
3194 this.with_optional_trait_ref(
3196 of_trait.map(|t| &t.trait_ref),
3197 self_type,
3198 |this, trait_id| {
3199 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3200
3201 let item_def_id = this.r.local_def_id(item_id);
3202
3203 if let Some(trait_id) = trait_id {
3205 this.r
3206 .trait_impls
3207 .entry(trait_id)
3208 .or_default()
3209 .push(item_def_id);
3210 }
3211
3212 let item_def_id = item_def_id.to_def_id();
3213 let res = Res::SelfTyAlias {
3214 alias_to: item_def_id,
3215 forbid_generic: false,
3216 is_trait_impl: trait_id.is_some()
3217 };
3218 this.with_self_rib(res, |this| {
3219 if let Some(of_trait) = of_trait {
3220 visit::walk_trait_ref(this, &of_trait.trait_ref);
3222 }
3223 this.visit_ty(self_type);
3225 this.visit_generics(generics);
3227
3228 this.with_current_self_type(self_type, |this| {
3230 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3231 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3232 let mut seen_trait_items = Default::default();
3233 for item in impl_items {
3234 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3235 }
3236 });
3237 });
3238 });
3239 },
3240 )
3241 },
3242 );
3243 });
3244 },
3245 );
3246 }
3247
3248 fn resolve_impl_item(
3249 &mut self,
3250 item: &'ast AssocItem,
3251 seen_trait_items: &mut FxHashMap<DefId, Span>,
3252 trait_id: Option<DefId>,
3253 ) {
3254 use crate::ResolutionError::*;
3255 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3256 match &item.kind {
3257 AssocItemKind::Const(box ast::ConstItem {
3258 ident,
3259 generics,
3260 ty,
3261 expr,
3262 define_opaque,
3263 ..
3264 }) => {
3265 debug!("resolve_implementation AssocItemKind::Const");
3266 self.with_generic_param_rib(
3267 &generics.params,
3268 RibKind::AssocItem,
3269 item.id,
3270 LifetimeBinderKind::ConstItem,
3271 generics.span,
3272 |this| {
3273 this.with_lifetime_rib(
3274 LifetimeRibKind::AnonymousCreateParameter {
3278 binder: item.id,
3279 report_in_path: true,
3280 },
3281 |this| {
3282 this.with_lifetime_rib(
3283 LifetimeRibKind::StaticIfNoLifetimeInScope {
3284 lint_id: item.id,
3285 emit_lint: true,
3287 },
3288 |this| {
3289 this.check_trait_item(
3292 item.id,
3293 *ident,
3294 &item.kind,
3295 ValueNS,
3296 item.span,
3297 seen_trait_items,
3298 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3299 );
3300
3301 this.visit_generics(generics);
3302 this.visit_ty(ty);
3303 if let Some(expr) = expr {
3304 this.resolve_const_body(expr, None);
3310 }
3311 },
3312 )
3313 },
3314 );
3315 },
3316 );
3317 self.resolve_define_opaques(define_opaque);
3318 }
3319 AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3320 debug!("resolve_implementation AssocItemKind::Fn");
3321 self.with_generic_param_rib(
3323 &generics.params,
3324 RibKind::AssocItem,
3325 item.id,
3326 LifetimeBinderKind::Function,
3327 generics.span,
3328 |this| {
3329 this.check_trait_item(
3332 item.id,
3333 *ident,
3334 &item.kind,
3335 ValueNS,
3336 item.span,
3337 seen_trait_items,
3338 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3339 );
3340
3341 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3342 },
3343 );
3344
3345 self.resolve_define_opaques(define_opaque);
3346 }
3347 AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3348 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3349 debug!("resolve_implementation AssocItemKind::Type");
3350 self.with_generic_param_rib(
3352 &generics.params,
3353 RibKind::AssocItem,
3354 item.id,
3355 LifetimeBinderKind::Item,
3356 generics.span,
3357 |this| {
3358 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3359 this.check_trait_item(
3362 item.id,
3363 *ident,
3364 &item.kind,
3365 TypeNS,
3366 item.span,
3367 seen_trait_items,
3368 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3369 );
3370
3371 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3372 });
3373 },
3374 );
3375 self.diag_metadata.in_non_gat_assoc_type = None;
3376 }
3377 AssocItemKind::Delegation(box delegation) => {
3378 debug!("resolve_implementation AssocItemKind::Delegation");
3379 self.with_generic_param_rib(
3380 &[],
3381 RibKind::AssocItem,
3382 item.id,
3383 LifetimeBinderKind::Function,
3384 delegation.path.segments.last().unwrap().ident.span,
3385 |this| {
3386 this.check_trait_item(
3387 item.id,
3388 delegation.ident,
3389 &item.kind,
3390 ValueNS,
3391 item.span,
3392 seen_trait_items,
3393 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3394 );
3395
3396 this.resolve_delegation(delegation)
3397 },
3398 );
3399 }
3400 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3401 panic!("unexpanded macro in resolve!")
3402 }
3403 }
3404 }
3405
3406 fn check_trait_item<F>(
3407 &mut self,
3408 id: NodeId,
3409 mut ident: Ident,
3410 kind: &AssocItemKind,
3411 ns: Namespace,
3412 span: Span,
3413 seen_trait_items: &mut FxHashMap<DefId, Span>,
3414 err: F,
3415 ) where
3416 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3417 {
3418 let Some((module, _)) = self.current_trait_ref else {
3420 return;
3421 };
3422 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3423 let key = BindingKey::new(ident, ns);
3424 let mut binding = self.r.resolution(module, key).and_then(|r| r.best_binding());
3425 debug!(?binding);
3426 if binding.is_none() {
3427 let ns = match ns {
3430 ValueNS => TypeNS,
3431 TypeNS => ValueNS,
3432 _ => ns,
3433 };
3434 let key = BindingKey::new(ident, ns);
3435 binding = self.r.resolution(module, key).and_then(|r| r.best_binding());
3436 debug!(?binding);
3437 }
3438
3439 let feed_visibility = |this: &mut Self, def_id| {
3440 let vis = this.r.tcx.visibility(def_id);
3441 let vis = if vis.is_visible_locally() {
3442 vis.expect_local()
3443 } else {
3444 this.r.dcx().span_delayed_bug(
3445 span,
3446 "error should be emitted when an unexpected trait item is used",
3447 );
3448 Visibility::Public
3449 };
3450 this.r.feed_visibility(this.r.feed(id), vis);
3451 };
3452
3453 let Some(binding) = binding else {
3454 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3456 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3457 let path_names = path_names_to_string(path);
3458 self.report_error(span, err(ident, path_names, candidate));
3459 feed_visibility(self, module.def_id());
3460 return;
3461 };
3462
3463 let res = binding.res();
3464 let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3465 feed_visibility(self, id_in_trait);
3466
3467 match seen_trait_items.entry(id_in_trait) {
3468 Entry::Occupied(entry) => {
3469 self.report_error(
3470 span,
3471 ResolutionError::TraitImplDuplicate {
3472 name: ident,
3473 old_span: *entry.get(),
3474 trait_item_span: binding.span,
3475 },
3476 );
3477 return;
3478 }
3479 Entry::Vacant(entry) => {
3480 entry.insert(span);
3481 }
3482 };
3483
3484 match (def_kind, kind) {
3485 (DefKind::AssocTy, AssocItemKind::Type(..))
3486 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3487 | (DefKind::AssocConst, AssocItemKind::Const(..))
3488 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3489 self.r.record_partial_res(id, PartialRes::new(res));
3490 return;
3491 }
3492 _ => {}
3493 }
3494
3495 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3497 let (code, kind) = match kind {
3498 AssocItemKind::Const(..) => (E0323, "const"),
3499 AssocItemKind::Fn(..) => (E0324, "method"),
3500 AssocItemKind::Type(..) => (E0325, "type"),
3501 AssocItemKind::Delegation(..) => (E0324, "method"),
3502 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3503 span_bug!(span, "unexpanded macro")
3504 }
3505 };
3506 let trait_path = path_names_to_string(path);
3507 self.report_error(
3508 span,
3509 ResolutionError::TraitImplMismatch {
3510 name: ident,
3511 kind,
3512 code,
3513 trait_path,
3514 trait_item_span: binding.span,
3515 },
3516 );
3517 }
3518
3519 fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3520 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3521 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3522 this.visit_expr(expr)
3523 });
3524 })
3525 }
3526
3527 fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3528 self.smart_resolve_path(
3529 delegation.id,
3530 &delegation.qself,
3531 &delegation.path,
3532 PathSource::Delegation,
3533 );
3534 if let Some(qself) = &delegation.qself {
3535 self.visit_ty(&qself.ty);
3536 }
3537 self.visit_path(&delegation.path);
3538 let Some(body) = &delegation.body else { return };
3539 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3540 let span = delegation.path.segments.last().unwrap().ident.span;
3541 let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3542 let res = Res::Local(delegation.id);
3543 this.innermost_rib_bindings(ValueNS).insert(ident, res);
3544 this.visit_block(body);
3545 });
3546 }
3547
3548 fn resolve_params(&mut self, params: &'ast [Param]) {
3549 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3550 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3551 for Param { pat, .. } in params {
3552 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3553 }
3554 this.apply_pattern_bindings(bindings);
3555 });
3556 for Param { ty, .. } in params {
3557 self.visit_ty(ty);
3558 }
3559 }
3560
3561 fn resolve_local(&mut self, local: &'ast Local) {
3562 debug!("resolving local ({:?})", local);
3563 visit_opt!(self, visit_ty, &local.ty);
3565
3566 if let Some((init, els)) = local.kind.init_else_opt() {
3568 self.visit_expr(init);
3569
3570 if let Some(els) = els {
3572 self.visit_block(els);
3573 }
3574 }
3575
3576 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3578 }
3579
3580 fn compute_and_check_binding_map(
3600 &mut self,
3601 pat: &Pat,
3602 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3603 let mut binding_map = FxIndexMap::default();
3604 let mut is_never_pat = false;
3605
3606 pat.walk(&mut |pat| {
3607 match pat.kind {
3608 PatKind::Ident(annotation, ident, ref sub_pat)
3609 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3610 {
3611 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3612 }
3613 PatKind::Or(ref ps) => {
3614 match self.compute_and_check_or_pat_binding_map(ps) {
3617 Ok(bm) => binding_map.extend(bm),
3618 Err(IsNeverPattern) => is_never_pat = true,
3619 }
3620 return false;
3621 }
3622 PatKind::Never => is_never_pat = true,
3623 _ => {}
3624 }
3625
3626 true
3627 });
3628
3629 if is_never_pat {
3630 for (_, binding) in binding_map {
3631 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3632 }
3633 Err(IsNeverPattern)
3634 } else {
3635 Ok(binding_map)
3636 }
3637 }
3638
3639 fn is_base_res_local(&self, nid: NodeId) -> bool {
3640 matches!(
3641 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3642 Some(Res::Local(..))
3643 )
3644 }
3645
3646 fn compute_and_check_or_pat_binding_map(
3666 &mut self,
3667 pats: &[Box<Pat>],
3668 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3669 let mut missing_vars = FxIndexMap::default();
3670 let mut inconsistent_vars = FxIndexMap::default();
3671
3672 let not_never_pats = pats
3674 .iter()
3675 .filter_map(|pat| {
3676 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3677 Some((binding_map, pat))
3678 })
3679 .collect::<Vec<_>>();
3680
3681 for (map_outer, pat_outer) in not_never_pats.iter() {
3683 let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
3685
3686 for (map, pat) in inners {
3687 for (&name, binding_inner) in map {
3688 match map_outer.get(&name) {
3689 None => {
3690 let binding_error =
3692 missing_vars.entry(name).or_insert_with(|| BindingError {
3693 name,
3694 origin: Default::default(),
3695 target: Default::default(),
3696 could_be_path: name.as_str().starts_with(char::is_uppercase),
3697 });
3698 binding_error.origin.push((binding_inner.span, (***pat).clone()));
3699 binding_error.target.push((***pat_outer).clone());
3700 }
3701 Some(binding_outer) => {
3702 if binding_outer.annotation != binding_inner.annotation {
3703 inconsistent_vars
3705 .entry(name)
3706 .or_insert((binding_inner.span, binding_outer.span));
3707 }
3708 }
3709 }
3710 }
3711 }
3712 }
3713
3714 for (name, mut v) in missing_vars {
3716 if inconsistent_vars.contains_key(&name) {
3717 v.could_be_path = false;
3718 }
3719 self.report_error(
3720 v.origin.iter().next().unwrap().0,
3721 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3722 );
3723 }
3724
3725 for (name, v) in inconsistent_vars {
3727 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3728 }
3729
3730 if not_never_pats.is_empty() {
3732 Err(IsNeverPattern)
3734 } else {
3735 let mut binding_map = FxIndexMap::default();
3736 for (bm, _) in not_never_pats {
3737 binding_map.extend(bm);
3738 }
3739 Ok(binding_map)
3740 }
3741 }
3742
3743 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3745 let mut is_or_or_never = false;
3746 pat.walk(&mut |pat| match pat.kind {
3747 PatKind::Or(..) | PatKind::Never => {
3748 is_or_or_never = true;
3749 false
3750 }
3751 _ => true,
3752 });
3753 if is_or_or_never {
3754 let _ = self.compute_and_check_binding_map(pat);
3755 }
3756 }
3757
3758 fn resolve_arm(&mut self, arm: &'ast Arm) {
3759 self.with_rib(ValueNS, RibKind::Normal, |this| {
3760 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3761 visit_opt!(this, visit_expr, &arm.guard);
3762 visit_opt!(this, visit_expr, &arm.body);
3763 });
3764 }
3765
3766 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3768 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3769 self.resolve_pattern(pat, pat_src, &mut bindings);
3770 self.apply_pattern_bindings(bindings);
3771 }
3772
3773 fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3775 let rib_bindings = self.innermost_rib_bindings(ValueNS);
3776 let Some((_, pat_bindings)) = pat_bindings.pop() else {
3777 bug!("tried applying nonexistent bindings from pattern");
3778 };
3779
3780 if rib_bindings.is_empty() {
3781 *rib_bindings = pat_bindings;
3784 } else {
3785 rib_bindings.extend(pat_bindings);
3786 }
3787 }
3788
3789 fn resolve_pattern(
3792 &mut self,
3793 pat: &'ast Pat,
3794 pat_src: PatternSource,
3795 bindings: &mut PatternBindings,
3796 ) {
3797 self.visit_pat(pat);
3803 self.resolve_pattern_inner(pat, pat_src, bindings);
3804 self.check_consistent_bindings(pat);
3806 }
3807
3808 #[tracing::instrument(skip(self, bindings), level = "debug")]
3828 fn resolve_pattern_inner(
3829 &mut self,
3830 pat: &'ast Pat,
3831 pat_src: PatternSource,
3832 bindings: &mut PatternBindings,
3833 ) {
3834 pat.walk(&mut |pat| {
3836 match pat.kind {
3837 PatKind::Ident(bmode, ident, ref sub) => {
3838 let has_sub = sub.is_some();
3841 let res = self
3842 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3843 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3844 self.r.record_partial_res(pat.id, PartialRes::new(res));
3845 self.r.record_pat_span(pat.id, pat.span);
3846 }
3847 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3848 self.smart_resolve_path(
3849 pat.id,
3850 qself,
3851 path,
3852 PathSource::TupleStruct(
3853 pat.span,
3854 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3855 ),
3856 );
3857 }
3858 PatKind::Path(ref qself, ref path) => {
3859 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3860 }
3861 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3862 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
3863 self.record_patterns_with_skipped_bindings(pat, rest);
3864 }
3865 PatKind::Or(ref ps) => {
3866 bindings.push((PatBoundCtx::Or, Default::default()));
3870 for p in ps {
3871 bindings.push((PatBoundCtx::Product, Default::default()));
3875 self.resolve_pattern_inner(p, pat_src, bindings);
3876 let collected = bindings.pop().unwrap().1;
3879 bindings.last_mut().unwrap().1.extend(collected);
3880 }
3881 let collected = bindings.pop().unwrap().1;
3885 bindings.last_mut().unwrap().1.extend(collected);
3886
3887 return false;
3889 }
3890 PatKind::Guard(ref subpat, ref guard) => {
3891 bindings.push((PatBoundCtx::Product, Default::default()));
3893 let binding_ctx_stack_len = bindings.len();
3896 self.resolve_pattern_inner(subpat, pat_src, bindings);
3897 assert_eq!(bindings.len(), binding_ctx_stack_len);
3898 let subpat_bindings = bindings.pop().unwrap().1;
3901 self.with_rib(ValueNS, RibKind::Normal, |this| {
3902 *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
3903 this.resolve_expr(guard, None);
3904 });
3905 bindings.last_mut().unwrap().1.extend(subpat_bindings);
3912 return false;
3914 }
3915 _ => {}
3916 }
3917 true
3918 });
3919 }
3920
3921 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
3922 match rest {
3923 ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
3924 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
3926 && let Some(res) = partial_res.full_res()
3927 && let Some(def_id) = res.opt_def_id()
3928 {
3929 self.ribs[ValueNS]
3930 .last_mut()
3931 .unwrap()
3932 .patterns_with_skipped_bindings
3933 .entry(def_id)
3934 .or_default()
3935 .push((
3936 pat.span,
3937 match rest {
3938 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
3939 _ => Ok(()),
3940 },
3941 ));
3942 }
3943 }
3944 ast::PatFieldsRest::None => {}
3945 }
3946 }
3947
3948 fn fresh_binding(
3949 &mut self,
3950 ident: Ident,
3951 pat_id: NodeId,
3952 pat_src: PatternSource,
3953 bindings: &mut PatternBindings,
3954 ) -> Res {
3955 let ident = ident.normalize_to_macro_rules();
3959
3960 let already_bound_and = bindings
3962 .iter()
3963 .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
3964 if already_bound_and {
3965 use ResolutionError::*;
3967 let error = match pat_src {
3968 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
3970 _ => IdentifierBoundMoreThanOnceInSamePattern,
3972 };
3973 self.report_error(ident.span, error(ident));
3974 }
3975
3976 let already_bound_or = bindings
3979 .iter()
3980 .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
3981 let res = if let Some(&res) = already_bound_or {
3982 res
3985 } else {
3986 Res::Local(pat_id)
3988 };
3989
3990 bindings.last_mut().unwrap().1.insert(ident, res);
3992 res
3993 }
3994
3995 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
3996 &mut self.ribs[ns].last_mut().unwrap().bindings
3997 }
3998
3999 fn try_resolve_as_non_binding(
4000 &mut self,
4001 pat_src: PatternSource,
4002 ann: BindingMode,
4003 ident: Ident,
4004 has_sub: bool,
4005 ) -> Option<Res> {
4006 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4010
4011 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4012 let (res, binding) = match ls_binding {
4013 LexicalScopeBinding::Item(binding)
4014 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4015 {
4016 self.r.record_use(ident, binding, Used::Other);
4021 return None;
4022 }
4023 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4024 LexicalScopeBinding::Res(res) => (res, None),
4025 };
4026
4027 match res {
4028 Res::SelfCtor(_) | Res::Def(
4030 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4031 _,
4032 ) if is_syntactic_ambiguity => {
4033 if let Some(binding) = binding {
4035 self.r.record_use(ident, binding, Used::Other);
4036 }
4037 Some(res)
4038 }
4039 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4040 let binding = binding.expect("no binding for a ctor or static");
4046 self.report_error(
4047 ident.span,
4048 ResolutionError::BindingShadowsSomethingUnacceptable {
4049 shadowing_binding: pat_src,
4050 name: ident.name,
4051 participle: if binding.is_import() { "imported" } else { "defined" },
4052 article: binding.res().article(),
4053 shadowed_binding: binding.res(),
4054 shadowed_binding_span: binding.span,
4055 },
4056 );
4057 None
4058 }
4059 Res::Def(DefKind::ConstParam, def_id) => {
4060 self.report_error(
4063 ident.span,
4064 ResolutionError::BindingShadowsSomethingUnacceptable {
4065 shadowing_binding: pat_src,
4066 name: ident.name,
4067 participle: "defined",
4068 article: res.article(),
4069 shadowed_binding: res,
4070 shadowed_binding_span: self.r.def_span(def_id),
4071 }
4072 );
4073 None
4074 }
4075 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4076 None
4078 }
4079 Res::SelfCtor(_) => {
4080 self.r.dcx().span_delayed_bug(
4083 ident.span,
4084 "unexpected `SelfCtor` in pattern, expected identifier"
4085 );
4086 None
4087 }
4088 _ => span_bug!(
4089 ident.span,
4090 "unexpected resolution for an identifier in pattern: {:?}",
4091 res,
4092 ),
4093 }
4094 }
4095
4096 fn smart_resolve_path(
4102 &mut self,
4103 id: NodeId,
4104 qself: &Option<Box<QSelf>>,
4105 path: &Path,
4106 source: PathSource<'_, 'ast, 'ra>,
4107 ) {
4108 self.smart_resolve_path_fragment(
4109 qself,
4110 &Segment::from_path(path),
4111 source,
4112 Finalize::new(id, path.span),
4113 RecordPartialRes::Yes,
4114 None,
4115 );
4116 }
4117
4118 #[instrument(level = "debug", skip(self))]
4119 fn smart_resolve_path_fragment(
4120 &mut self,
4121 qself: &Option<Box<QSelf>>,
4122 path: &[Segment],
4123 source: PathSource<'_, 'ast, 'ra>,
4124 finalize: Finalize,
4125 record_partial_res: RecordPartialRes,
4126 parent_qself: Option<&QSelf>,
4127 ) -> PartialRes {
4128 let ns = source.namespace();
4129
4130 let Finalize { node_id, path_span, .. } = finalize;
4131 let report_errors = |this: &mut Self, res: Option<Res>| {
4132 if this.should_report_errs() {
4133 let (err, candidates) = this.smart_resolve_report_errors(
4134 path,
4135 None,
4136 path_span,
4137 source,
4138 res,
4139 parent_qself,
4140 );
4141
4142 let def_id = this.parent_scope.module.nearest_parent_mod();
4143 let instead = res.is_some();
4144 let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4145 && path[0].ident.span.lo() == end.span.lo()
4146 && !matches!(start.kind, ExprKind::Lit(_))
4147 {
4148 let mut sugg = ".";
4149 let mut span = start.span.between(end.span);
4150 if span.lo() + BytePos(2) == span.hi() {
4151 span = span.with_lo(span.lo() + BytePos(1));
4154 sugg = "";
4155 }
4156 Some((
4157 span,
4158 "you might have meant to write `.` instead of `..`",
4159 sugg.to_string(),
4160 Applicability::MaybeIncorrect,
4161 ))
4162 } else if res.is_none()
4163 && let PathSource::Type
4164 | PathSource::Expr(_)
4165 | PathSource::PreciseCapturingArg(..) = source
4166 {
4167 this.suggest_adding_generic_parameter(path, source)
4168 } else {
4169 None
4170 };
4171
4172 let ue = UseError {
4173 err,
4174 candidates,
4175 def_id,
4176 instead,
4177 suggestion,
4178 path: path.into(),
4179 is_call: source.is_call(),
4180 };
4181
4182 this.r.use_injections.push(ue);
4183 }
4184
4185 PartialRes::new(Res::Err)
4186 };
4187
4188 let report_errors_for_call =
4194 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4195 let (following_seg, prefix_path) = match path.split_last() {
4199 Some((last, path)) if !path.is_empty() => (Some(last), path),
4200 _ => return Some(parent_err),
4201 };
4202
4203 let (mut err, candidates) = this.smart_resolve_report_errors(
4204 prefix_path,
4205 following_seg,
4206 path_span,
4207 PathSource::Type,
4208 None,
4209 parent_qself,
4210 );
4211
4212 let failed_to_resolve = match parent_err.node {
4227 ResolutionError::FailedToResolve { .. } => true,
4228 _ => false,
4229 };
4230 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4231
4232 err.messages = take(&mut parent_err.messages);
4234 err.code = take(&mut parent_err.code);
4235 swap(&mut err.span, &mut parent_err.span);
4236 if failed_to_resolve {
4237 err.children = take(&mut parent_err.children);
4238 } else {
4239 err.children.append(&mut parent_err.children);
4240 }
4241 err.sort_span = parent_err.sort_span;
4242 err.is_lint = parent_err.is_lint.clone();
4243
4244 match &mut err.suggestions {
4246 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4247 Suggestions::Enabled(parent_suggestions) => {
4248 typo_suggestions.append(parent_suggestions)
4250 }
4251 Suggestions::Sealed(_) | Suggestions::Disabled => {
4252 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4257 }
4258 },
4259 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4260 }
4261
4262 parent_err.cancel();
4263
4264 let def_id = this.parent_scope.module.nearest_parent_mod();
4265
4266 if this.should_report_errs() {
4267 if candidates.is_empty() {
4268 if path.len() == 2
4269 && let [segment] = prefix_path
4270 {
4271 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4277 } else {
4278 err.emit();
4283 }
4284 } else {
4285 this.r.use_injections.push(UseError {
4287 err,
4288 candidates,
4289 def_id,
4290 instead: false,
4291 suggestion: None,
4292 path: prefix_path.into(),
4293 is_call: source.is_call(),
4294 });
4295 }
4296 } else {
4297 err.cancel();
4298 }
4299
4300 None
4303 };
4304
4305 let partial_res = match self.resolve_qpath_anywhere(
4306 qself,
4307 path,
4308 ns,
4309 source.defer_to_typeck(),
4310 finalize,
4311 source,
4312 ) {
4313 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4314 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4316 && let [Segment { ident, .. }] = path
4317 && items.iter().any(|item| {
4318 if let AssocItemKind::Type(alias) = &item.kind
4319 && alias.ident == *ident
4320 {
4321 true
4322 } else {
4323 false
4324 }
4325 })
4326 {
4327 let mut diag = self.r.tcx.dcx().struct_allow("");
4328 diag.span_suggestion_verbose(
4329 path_span.shrink_to_lo(),
4330 "there is an associated type with the same name",
4331 "Self::",
4332 Applicability::MaybeIncorrect,
4333 );
4334 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4335 }
4336
4337 if source.is_expected(res) || res == Res::Err {
4338 partial_res
4339 } else {
4340 report_errors(self, Some(res))
4341 }
4342 }
4343
4344 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4345 if ns == ValueNS {
4349 let item_name = path.last().unwrap().ident;
4350 let traits = self.traits_in_scope(item_name, ns);
4351 self.r.trait_map.insert(node_id, traits);
4352 }
4353
4354 if PrimTy::from_name(path[0].ident.name).is_some() {
4355 let mut std_path = Vec::with_capacity(1 + path.len());
4356
4357 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4358 std_path.extend(path);
4359 if let PathResult::Module(_) | PathResult::NonModule(_) =
4360 self.resolve_path(&std_path, Some(ns), None, source)
4361 {
4362 let item_span =
4364 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4365
4366 self.r.confused_type_with_std_module.insert(item_span, path_span);
4367 self.r.confused_type_with_std_module.insert(path_span, path_span);
4368 }
4369 }
4370
4371 partial_res
4372 }
4373
4374 Err(err) => {
4375 if let Some(err) = report_errors_for_call(self, err) {
4376 self.report_error(err.span, err.node);
4377 }
4378
4379 PartialRes::new(Res::Err)
4380 }
4381
4382 _ => report_errors(self, None),
4383 };
4384
4385 if record_partial_res == RecordPartialRes::Yes {
4386 self.r.record_partial_res(node_id, partial_res);
4388 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4389 self.lint_unused_qualifications(path, ns, finalize);
4390 }
4391
4392 partial_res
4393 }
4394
4395 fn self_type_is_available(&mut self) -> bool {
4396 let binding = self
4397 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4398 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4399 }
4400
4401 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4402 let ident = Ident::new(kw::SelfLower, self_span);
4403 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4404 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4405 }
4406
4407 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4411 if self.should_report_errs() {
4412 self.r.report_error(span, resolution_error);
4413 }
4414 }
4415
4416 #[inline]
4417 fn should_report_errs(&self) -> bool {
4421 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4422 && !self.r.glob_error.is_some()
4423 }
4424
4425 fn resolve_qpath_anywhere(
4427 &mut self,
4428 qself: &Option<Box<QSelf>>,
4429 path: &[Segment],
4430 primary_ns: Namespace,
4431 defer_to_typeck: bool,
4432 finalize: Finalize,
4433 source: PathSource<'_, 'ast, 'ra>,
4434 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4435 let mut fin_res = None;
4436
4437 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4438 if i == 0 || ns != primary_ns {
4439 match self.resolve_qpath(qself, path, ns, finalize, source)? {
4440 Some(partial_res)
4441 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4442 {
4443 return Ok(Some(partial_res));
4444 }
4445 partial_res => {
4446 if fin_res.is_none() {
4447 fin_res = partial_res;
4448 }
4449 }
4450 }
4451 }
4452 }
4453
4454 assert!(primary_ns != MacroNS);
4455 if qself.is_none()
4456 && let PathResult::NonModule(res) =
4457 self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4458 {
4459 return Ok(Some(res));
4460 }
4461
4462 Ok(fin_res)
4463 }
4464
4465 fn resolve_qpath(
4467 &mut self,
4468 qself: &Option<Box<QSelf>>,
4469 path: &[Segment],
4470 ns: Namespace,
4471 finalize: Finalize,
4472 source: PathSource<'_, 'ast, 'ra>,
4473 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4474 debug!(
4475 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4476 qself, path, ns, finalize,
4477 );
4478
4479 if let Some(qself) = qself {
4480 if qself.position == 0 {
4481 return Ok(Some(PartialRes::with_unresolved_segments(
4485 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4486 path.len(),
4487 )));
4488 }
4489
4490 let num_privacy_errors = self.r.privacy_errors.len();
4491 let trait_res = self.smart_resolve_path_fragment(
4493 &None,
4494 &path[..qself.position],
4495 PathSource::Trait(AliasPossibility::No),
4496 Finalize::new(finalize.node_id, qself.path_span),
4497 RecordPartialRes::No,
4498 Some(&qself),
4499 );
4500
4501 if trait_res.expect_full_res() == Res::Err {
4502 return Ok(Some(trait_res));
4503 }
4504
4505 self.r.privacy_errors.truncate(num_privacy_errors);
4508
4509 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4517 let partial_res = self.smart_resolve_path_fragment(
4518 &None,
4519 &path[..=qself.position],
4520 PathSource::TraitItem(ns, &source),
4521 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4522 RecordPartialRes::No,
4523 Some(&qself),
4524 );
4525
4526 return Ok(Some(PartialRes::with_unresolved_segments(
4530 partial_res.base_res(),
4531 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4532 )));
4533 }
4534
4535 let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4536 PathResult::NonModule(path_res) => path_res,
4537 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4538 PartialRes::new(module.res().unwrap())
4539 }
4540 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4544 PartialRes::new(Res::Err)
4545 }
4546 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4559 if (ns == TypeNS || path.len() > 1)
4560 && PrimTy::from_name(path[0].ident.name).is_some() =>
4561 {
4562 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4563 let tcx = self.r.tcx();
4564
4565 let gate_err_sym_msg = match prim {
4566 PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4567 Some((sym::f16, "the type `f16` is unstable"))
4568 }
4569 PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4570 Some((sym::f128, "the type `f128` is unstable"))
4571 }
4572 _ => None,
4573 };
4574
4575 if let Some((sym, msg)) = gate_err_sym_msg {
4576 let span = path[0].ident.span;
4577 if !span.allows_unstable(sym) {
4578 feature_err(tcx.sess, sym, span, msg).emit();
4579 }
4580 };
4581
4582 if let Some(id) = path[0].id {
4584 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4585 }
4586
4587 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4588 }
4589 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4590 PartialRes::new(module.res().unwrap())
4591 }
4592 PathResult::Failed {
4593 is_error_from_last_segment: false,
4594 span,
4595 label,
4596 suggestion,
4597 module,
4598 segment_name,
4599 error_implied_by_parse_error: _,
4600 } => {
4601 return Err(respan(
4602 span,
4603 ResolutionError::FailedToResolve {
4604 segment: Some(segment_name),
4605 label,
4606 suggestion,
4607 module,
4608 },
4609 ));
4610 }
4611 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4612 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4613 };
4614
4615 Ok(Some(result))
4616 }
4617
4618 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4619 if let Some(label) = label {
4620 if label.ident.as_str().as_bytes()[1] != b'_' {
4621 self.diag_metadata.unused_labels.insert(id, label.ident.span);
4622 }
4623
4624 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4625 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4626 }
4627
4628 self.with_label_rib(RibKind::Normal, |this| {
4629 let ident = label.ident.normalize_to_macro_rules();
4630 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4631 f(this);
4632 });
4633 } else {
4634 f(self);
4635 }
4636 }
4637
4638 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4639 self.with_resolved_label(label, id, |this| this.visit_block(block));
4640 }
4641
4642 fn resolve_block(&mut self, block: &'ast Block) {
4643 debug!("(resolving block) entering block");
4644 let orig_module = self.parent_scope.module;
4646 let anonymous_module = self.r.block_map.get(&block.id).copied();
4647
4648 let mut num_macro_definition_ribs = 0;
4649 if let Some(anonymous_module) = anonymous_module {
4650 debug!("(resolving block) found anonymous module, moving down");
4651 self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4652 self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4653 self.parent_scope.module = anonymous_module;
4654 } else {
4655 self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
4656 }
4657
4658 for stmt in &block.stmts {
4660 if let StmtKind::Item(ref item) = stmt.kind
4661 && let ItemKind::MacroDef(..) = item.kind
4662 {
4663 num_macro_definition_ribs += 1;
4664 let res = self.r.local_def_id(item.id).to_def_id();
4665 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4666 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4667 }
4668
4669 self.visit_stmt(stmt);
4670 }
4671
4672 self.parent_scope.module = orig_module;
4674 for _ in 0..num_macro_definition_ribs {
4675 self.ribs[ValueNS].pop();
4676 self.label_ribs.pop();
4677 }
4678 self.last_block_rib = self.ribs[ValueNS].pop();
4679 if anonymous_module.is_some() {
4680 self.ribs[TypeNS].pop();
4681 }
4682 debug!("(resolving block) leaving block");
4683 }
4684
4685 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4686 debug!(
4687 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4688 constant, anon_const_kind
4689 );
4690
4691 let is_trivial_const_arg = constant
4692 .value
4693 .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4694 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4695 this.resolve_expr(&constant.value, None)
4696 })
4697 }
4698
4699 fn resolve_anon_const_manual(
4706 &mut self,
4707 is_trivial_const_arg: bool,
4708 anon_const_kind: AnonConstKind,
4709 resolve_expr: impl FnOnce(&mut Self),
4710 ) {
4711 let is_repeat_expr = match anon_const_kind {
4712 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4713 _ => IsRepeatExpr::No,
4714 };
4715
4716 let may_use_generics = match anon_const_kind {
4717 AnonConstKind::EnumDiscriminant => {
4718 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4719 }
4720 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4721 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4722 AnonConstKind::ConstArg(_) => {
4723 if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4724 ConstantHasGenerics::Yes
4725 } else {
4726 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4727 }
4728 }
4729 };
4730
4731 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4732 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4733 resolve_expr(this);
4734 });
4735 });
4736 }
4737
4738 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4739 self.resolve_expr(&f.expr, Some(e));
4740 self.visit_ident(&f.ident);
4741 walk_list!(self, visit_attribute, f.attrs.iter());
4742 }
4743
4744 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4745 self.record_candidate_traits_for_expr_if_necessary(expr);
4749
4750 match expr.kind {
4752 ExprKind::Path(ref qself, ref path) => {
4753 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4754 visit::walk_expr(self, expr);
4755 }
4756
4757 ExprKind::Struct(ref se) => {
4758 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
4759 if let Some(qself) = &se.qself {
4763 self.visit_ty(&qself.ty);
4764 }
4765 self.visit_path(&se.path);
4766 walk_list!(self, resolve_expr_field, &se.fields, expr);
4767 match &se.rest {
4768 StructRest::Base(expr) => self.visit_expr(expr),
4769 StructRest::Rest(_span) => {}
4770 StructRest::None => {}
4771 }
4772 }
4773
4774 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4775 match self.resolve_label(label.ident) {
4776 Ok((node_id, _)) => {
4777 self.r.label_res_map.insert(expr.id, node_id);
4779 self.diag_metadata.unused_labels.swap_remove(&node_id);
4780 }
4781 Err(error) => {
4782 self.report_error(label.ident.span, error);
4783 }
4784 }
4785
4786 visit::walk_expr(self, expr);
4788 }
4789
4790 ExprKind::Break(None, Some(ref e)) => {
4791 self.resolve_expr(e, Some(expr));
4794 }
4795
4796 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
4797 self.visit_expr(scrutinee);
4798 self.resolve_pattern_top(pat, PatternSource::Let);
4799 }
4800
4801 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
4802 self.visit_expr(scrutinee);
4803 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4805 self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
4806 for (_, bindings) in &mut bindings {
4811 for (_, binding) in bindings {
4812 *binding = Res::Err;
4813 }
4814 }
4815 self.apply_pattern_bindings(bindings);
4816 }
4817
4818 ExprKind::If(ref cond, ref then, ref opt_else) => {
4819 self.with_rib(ValueNS, RibKind::Normal, |this| {
4820 let old = this.diag_metadata.in_if_condition.replace(cond);
4821 this.visit_expr(cond);
4822 this.diag_metadata.in_if_condition = old;
4823 this.visit_block(then);
4824 });
4825 if let Some(expr) = opt_else {
4826 self.visit_expr(expr);
4827 }
4828 }
4829
4830 ExprKind::Loop(ref block, label, _) => {
4831 self.resolve_labeled_block(label, expr.id, block)
4832 }
4833
4834 ExprKind::While(ref cond, ref block, label) => {
4835 self.with_resolved_label(label, expr.id, |this| {
4836 this.with_rib(ValueNS, RibKind::Normal, |this| {
4837 let old = this.diag_metadata.in_if_condition.replace(cond);
4838 this.visit_expr(cond);
4839 this.diag_metadata.in_if_condition = old;
4840 this.visit_block(block);
4841 })
4842 });
4843 }
4844
4845 ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4846 self.visit_expr(iter);
4847 self.with_rib(ValueNS, RibKind::Normal, |this| {
4848 this.resolve_pattern_top(pat, PatternSource::For);
4849 this.resolve_labeled_block(label, expr.id, body);
4850 });
4851 }
4852
4853 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4854
4855 ExprKind::Field(ref subexpression, _) => {
4857 self.resolve_expr(subexpression, Some(expr));
4858 }
4859 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
4860 self.resolve_expr(receiver, Some(expr));
4861 for arg in args {
4862 self.resolve_expr(arg, None);
4863 }
4864 self.visit_path_segment(seg);
4865 }
4866
4867 ExprKind::Call(ref callee, ref arguments) => {
4868 self.resolve_expr(callee, Some(expr));
4869 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
4870 for (idx, argument) in arguments.iter().enumerate() {
4871 if const_args.contains(&idx) {
4874 let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
4875 self.r.tcx.features().min_generic_const_args(),
4876 );
4877 self.resolve_anon_const_manual(
4878 is_trivial_const_arg,
4879 AnonConstKind::ConstArg(IsRepeatExpr::No),
4880 |this| this.resolve_expr(argument, None),
4881 );
4882 } else {
4883 self.resolve_expr(argument, None);
4884 }
4885 }
4886 }
4887 ExprKind::Type(ref _type_expr, ref _ty) => {
4888 visit::walk_expr(self, expr);
4889 }
4890 ExprKind::Closure(box ast::Closure {
4892 binder: ClosureBinder::For { ref generic_params, span },
4893 ..
4894 }) => {
4895 self.with_generic_param_rib(
4896 generic_params,
4897 RibKind::Normal,
4898 expr.id,
4899 LifetimeBinderKind::Closure,
4900 span,
4901 |this| visit::walk_expr(this, expr),
4902 );
4903 }
4904 ExprKind::Closure(..) => visit::walk_expr(self, expr),
4905 ExprKind::Gen(..) => {
4906 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
4907 }
4908 ExprKind::Repeat(ref elem, ref ct) => {
4909 self.visit_expr(elem);
4910 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
4911 }
4912 ExprKind::ConstBlock(ref ct) => {
4913 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
4914 }
4915 ExprKind::Index(ref elem, ref idx, _) => {
4916 self.resolve_expr(elem, Some(expr));
4917 self.visit_expr(idx);
4918 }
4919 ExprKind::Assign(ref lhs, ref rhs, _) => {
4920 if !self.diag_metadata.is_assign_rhs {
4921 self.diag_metadata.in_assignment = Some(expr);
4922 }
4923 self.visit_expr(lhs);
4924 self.diag_metadata.is_assign_rhs = true;
4925 self.diag_metadata.in_assignment = None;
4926 self.visit_expr(rhs);
4927 self.diag_metadata.is_assign_rhs = false;
4928 }
4929 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
4930 self.diag_metadata.in_range = Some((start, end));
4931 self.resolve_expr(start, Some(expr));
4932 self.resolve_expr(end, Some(expr));
4933 self.diag_metadata.in_range = None;
4934 }
4935 _ => {
4936 visit::walk_expr(self, expr);
4937 }
4938 }
4939 }
4940
4941 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
4942 match expr.kind {
4943 ExprKind::Field(_, ident) => {
4944 let traits = self.traits_in_scope(ident, ValueNS);
4949 self.r.trait_map.insert(expr.id, traits);
4950 }
4951 ExprKind::MethodCall(ref call) => {
4952 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
4953 let traits = self.traits_in_scope(call.seg.ident, ValueNS);
4954 self.r.trait_map.insert(expr.id, traits);
4955 }
4956 _ => {
4957 }
4959 }
4960 }
4961
4962 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
4963 self.r.traits_in_scope(
4964 self.current_trait_ref.as_ref().map(|(module, _)| *module),
4965 &self.parent_scope,
4966 ident.span.ctxt(),
4967 Some((ident.name, ns)),
4968 )
4969 }
4970
4971 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
4972 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
4976 let res = *doc_link_resolutions
4977 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
4978 .or_default()
4979 .entry((Symbol::intern(path_str), ns))
4980 .or_insert_with_key(|(path, ns)| {
4981 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
4982 if let Some(res) = res
4983 && let Some(def_id) = res.opt_def_id()
4984 && self.is_invalid_proc_macro_item_for_doc(def_id)
4985 {
4986 return None;
4989 }
4990 res
4991 });
4992 self.r.doc_link_resolutions = doc_link_resolutions;
4993 res
4994 }
4995
4996 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
4997 if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
4998 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
4999 {
5000 return false;
5001 }
5002 let Some(local_did) = did.as_local() else { return true };
5003 !self.r.proc_macros.contains(&local_did)
5004 }
5005
5006 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5007 match self.r.tcx.sess.opts.resolve_doc_links {
5008 ResolveDocLinks::None => return,
5009 ResolveDocLinks::ExportedMetadata
5010 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5011 || !maybe_exported.eval(self.r) =>
5012 {
5013 return;
5014 }
5015 ResolveDocLinks::Exported
5016 if !maybe_exported.eval(self.r)
5017 && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5018 {
5019 return;
5020 }
5021 ResolveDocLinks::ExportedMetadata
5022 | ResolveDocLinks::Exported
5023 | ResolveDocLinks::All => {}
5024 }
5025
5026 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5027 return;
5028 }
5029
5030 let mut need_traits_in_scope = false;
5031 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5032 let mut any_resolved = false;
5034 let mut need_assoc = false;
5035 for ns in [TypeNS, ValueNS, MacroNS] {
5036 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5037 any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5040 } else if ns != MacroNS {
5041 need_assoc = true;
5042 }
5043 }
5044
5045 if need_assoc || !any_resolved {
5047 let mut path = &path_str[..];
5048 while let Some(idx) = path.rfind("::") {
5049 path = &path[..idx];
5050 need_traits_in_scope = true;
5051 for ns in [TypeNS, ValueNS, MacroNS] {
5052 self.resolve_and_cache_rustdoc_path(path, ns);
5053 }
5054 }
5055 }
5056 }
5057
5058 if need_traits_in_scope {
5059 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5061 doc_link_traits_in_scope
5062 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5063 .or_insert_with(|| {
5064 self.r
5065 .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5066 .into_iter()
5067 .filter_map(|tr| {
5068 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5069 return None;
5072 }
5073 Some(tr.def_id)
5074 })
5075 .collect()
5076 });
5077 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5078 }
5079 }
5080
5081 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5082 if let Some(seg) = path.first()
5084 && seg.ident.name == kw::PathRoot
5085 {
5086 return;
5087 }
5088
5089 if finalize.path_span.from_expansion()
5090 || path.iter().any(|seg| seg.ident.span.from_expansion())
5091 {
5092 return;
5093 }
5094
5095 let end_pos =
5096 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5097 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5098 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5107 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5108 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5109 (res == binding.res()).then_some((seg, binding))
5110 });
5111
5112 if let Some((seg, binding)) = unqualified {
5113 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5114 binding,
5115 node_id: finalize.node_id,
5116 path_span: finalize.path_span,
5117 removal_span: path[0].ident.span.until(seg.ident.span),
5118 });
5119 }
5120 }
5121
5122 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5123 if let Some(define_opaque) = define_opaque {
5124 for (id, path) in define_opaque {
5125 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5126 }
5127 }
5128 }
5129}
5130
5131struct ItemInfoCollector<'a, 'ra, 'tcx> {
5134 r: &'a mut Resolver<'ra, 'tcx>,
5135}
5136
5137impl ItemInfoCollector<'_, '_, '_> {
5138 fn collect_fn_info(
5139 &mut self,
5140 header: FnHeader,
5141 decl: &FnDecl,
5142 id: NodeId,
5143 attrs: &[Attribute],
5144 ) {
5145 let sig = DelegationFnSig {
5146 header,
5147 param_count: decl.inputs.len(),
5148 has_self: decl.has_self(),
5149 c_variadic: decl.c_variadic(),
5150 target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5151 };
5152 self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5153 }
5154}
5155
5156impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5157 fn visit_item(&mut self, item: &'ast Item) {
5158 match &item.kind {
5159 ItemKind::TyAlias(box TyAlias { generics, .. })
5160 | ItemKind::Const(box ConstItem { generics, .. })
5161 | ItemKind::Fn(box Fn { generics, .. })
5162 | ItemKind::Enum(_, generics, _)
5163 | ItemKind::Struct(_, generics, _)
5164 | ItemKind::Union(_, generics, _)
5165 | ItemKind::Impl(Impl { generics, .. })
5166 | ItemKind::Trait(box Trait { generics, .. })
5167 | ItemKind::TraitAlias(_, generics, _) => {
5168 if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5169 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5170 }
5171
5172 let def_id = self.r.local_def_id(item.id);
5173 let count = generics
5174 .params
5175 .iter()
5176 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5177 .count();
5178 self.r.item_generics_num_lifetimes.insert(def_id, count);
5179 }
5180
5181 ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5182 for foreign_item in items {
5183 if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5184 let new_header =
5185 FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5186 self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5187 }
5188 }
5189 }
5190
5191 ItemKind::Mod(..)
5192 | ItemKind::Static(..)
5193 | ItemKind::Use(..)
5194 | ItemKind::ExternCrate(..)
5195 | ItemKind::MacroDef(..)
5196 | ItemKind::GlobalAsm(..)
5197 | ItemKind::MacCall(..)
5198 | ItemKind::DelegationMac(..) => {}
5199 ItemKind::Delegation(..) => {
5200 }
5205 }
5206 visit::walk_item(self, item)
5207 }
5208
5209 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5210 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5211 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5212 }
5213 visit::walk_assoc_item(self, item, ctxt);
5214 }
5215}
5216
5217impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5218 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5219 visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5220 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5221 late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5222 visit::walk_crate(&mut late_resolution_visitor, krate);
5223 for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5224 self.lint_buffer.buffer_lint(
5225 lint::builtin::UNUSED_LABELS,
5226 *id,
5227 *span,
5228 errors::UnusedLabel,
5229 );
5230 }
5231 }
5232}
5233
5234fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5236 let mut path = expected_path.iter().rev();
5237 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5238 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5239 return false;
5240 }
5241 def_id = parent;
5242 }
5243 true
5244}