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