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].iter().rev() {
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 if let LifetimeRibKind::Item = rib.kind {
1845 break;
1846 }
1847 }
1848 if lifetimes_in_scope.is_empty() {
1849 self.record_lifetime_res(
1850 lifetime.id,
1851 LifetimeRes::Static { suppress_elision_warning: true },
1853 elision_candidate,
1854 );
1855 return;
1856 } else if emit_lint {
1857 self.r.lint_buffer.buffer_lint(
1858 lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1859 node_id,
1860 lifetime.ident.span,
1861 lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1862 elided,
1863 span: lifetime.ident.span,
1864 lifetimes_in_scope: lifetimes_in_scope.into(),
1865 },
1866 );
1867 }
1868 }
1869 LifetimeRibKind::AnonymousReportError => {
1870 if elided {
1871 let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1872 if let LifetimeRibKind::Generics {
1873 span,
1874 kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1875 ..
1876 } = rib.kind
1877 {
1878 Some(errors::ElidedAnonymousLivetimeReportErrorSuggestion {
1879 lo: span.shrink_to_lo(),
1880 hi: lifetime.ident.span.shrink_to_hi(),
1881 })
1882 } else {
1883 None
1884 }
1885 });
1886 if !self.in_func_body
1889 && let Some((module, _)) = &self.current_trait_ref
1890 && let Some(ty) = &self.diag_metadata.current_self_type
1891 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1892 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1893 {
1894 if def_id_matches_path(
1895 self.r.tcx,
1896 trait_id,
1897 &["core", "iter", "traits", "iterator", "Iterator"],
1898 ) {
1899 self.r.dcx().emit_err(errors::LendingIteratorReportError {
1900 lifetime: lifetime.ident.span,
1901 ty: ty.span,
1902 });
1903 } else {
1904 self.r.dcx().emit_err(errors::AnonymousLivetimeNonGatReportError {
1905 lifetime: lifetime.ident.span,
1906 });
1907 }
1908 } else {
1909 self.r.dcx().emit_err(errors::ElidedAnonymousLivetimeReportError {
1910 span: lifetime.ident.span,
1911 suggestion,
1912 });
1913 }
1914 } else {
1915 self.r.dcx().emit_err(errors::ExplicitAnonymousLivetimeReportError {
1916 span: lifetime.ident.span,
1917 });
1918 };
1919 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1920 return;
1921 }
1922 LifetimeRibKind::Elided(res) => {
1923 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1924 return;
1925 }
1926 LifetimeRibKind::ElisionFailure => {
1927 self.diag_metadata.current_elision_failures.push(missing_lifetime);
1928 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1929 return;
1930 }
1931 LifetimeRibKind::Item => break,
1932 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1933 LifetimeRibKind::ConcreteAnonConst(_) => {
1934 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1936 }
1937 }
1938 }
1939 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1940 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1941 }
1942
1943 #[instrument(level = "debug", skip(self))]
1944 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1945 let id = self.r.next_node_id();
1946 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1947
1948 self.record_lifetime_res(
1949 anchor_id,
1950 LifetimeRes::ElidedAnchor { start: id, end: NodeId::from_u32(id.as_u32() + 1) },
1951 LifetimeElisionCandidate::Ignore,
1952 );
1953 self.resolve_anonymous_lifetime(<, anchor_id, true);
1954 }
1955
1956 #[instrument(level = "debug", skip(self))]
1957 fn create_fresh_lifetime(
1958 &mut self,
1959 ident: Ident,
1960 binder: NodeId,
1961 kind: MissingLifetimeKind,
1962 ) -> LifetimeRes {
1963 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1964 debug!(?ident.span);
1965
1966 let param = self.r.next_node_id();
1968 let res = LifetimeRes::Fresh { param, binder, kind };
1969 self.record_lifetime_param(param, res);
1970
1971 self.r
1973 .extra_lifetime_params_map
1974 .entry(binder)
1975 .or_insert_with(Vec::new)
1976 .push((ident, param, res));
1977 res
1978 }
1979
1980 #[instrument(level = "debug", skip(self))]
1981 fn resolve_elided_lifetimes_in_path(
1982 &mut self,
1983 partial_res: PartialRes,
1984 path: &[Segment],
1985 source: PathSource<'_>,
1986 path_span: Span,
1987 ) {
1988 let proj_start = path.len() - partial_res.unresolved_segments();
1989 for (i, segment) in path.iter().enumerate() {
1990 if segment.has_lifetime_args {
1991 continue;
1992 }
1993 let Some(segment_id) = segment.id else {
1994 continue;
1995 };
1996
1997 let type_def_id = match partial_res.base_res() {
2000 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2001 self.r.tcx.parent(def_id)
2002 }
2003 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2004 self.r.tcx.parent(def_id)
2005 }
2006 Res::Def(DefKind::Struct, def_id)
2007 | Res::Def(DefKind::Union, def_id)
2008 | Res::Def(DefKind::Enum, def_id)
2009 | Res::Def(DefKind::TyAlias, def_id)
2010 | Res::Def(DefKind::Trait, def_id)
2011 if i + 1 == proj_start =>
2012 {
2013 def_id
2014 }
2015 _ => continue,
2016 };
2017
2018 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2019 if expected_lifetimes == 0 {
2020 continue;
2021 }
2022
2023 let node_ids = self.r.next_node_ids(expected_lifetimes);
2024 self.record_lifetime_res(
2025 segment_id,
2026 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2027 LifetimeElisionCandidate::Ignore,
2028 );
2029
2030 let inferred = match source {
2031 PathSource::Trait(..)
2032 | PathSource::TraitItem(..)
2033 | PathSource::Type
2034 | PathSource::PreciseCapturingArg(..)
2035 | PathSource::ReturnTypeNotation => false,
2036 PathSource::Expr(..)
2037 | PathSource::Pat
2038 | PathSource::Struct
2039 | PathSource::TupleStruct(..)
2040 | PathSource::DefineOpaques
2041 | PathSource::Delegation => true,
2042 };
2043 if inferred {
2044 for id in node_ids {
2047 self.record_lifetime_res(
2048 id,
2049 LifetimeRes::Infer,
2050 LifetimeElisionCandidate::Named,
2051 );
2052 }
2053 continue;
2054 }
2055
2056 let elided_lifetime_span = if segment.has_generic_args {
2057 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2059 } else {
2060 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2064 };
2065 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2066
2067 let kind = if segment.has_generic_args {
2068 MissingLifetimeKind::Comma
2069 } else {
2070 MissingLifetimeKind::Brackets
2071 };
2072 let missing_lifetime = MissingLifetime {
2073 id: node_ids.start,
2074 id_for_lint: segment_id,
2075 span: elided_lifetime_span,
2076 kind,
2077 count: expected_lifetimes,
2078 };
2079 let mut should_lint = true;
2080 for rib in self.lifetime_ribs.iter().rev() {
2081 match rib.kind {
2082 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2089 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2090 let sess = self.r.tcx.sess;
2091 let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2092 sess.source_map(),
2093 expected_lifetimes,
2094 path_span,
2095 !segment.has_generic_args,
2096 elided_lifetime_span,
2097 );
2098 self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2099 span: path_span,
2100 subdiag,
2101 });
2102 should_lint = false;
2103
2104 for id in node_ids {
2105 self.record_lifetime_res(
2106 id,
2107 LifetimeRes::Error,
2108 LifetimeElisionCandidate::Named,
2109 );
2110 }
2111 break;
2112 }
2113 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2115 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2117 for id in node_ids {
2118 let res = self.create_fresh_lifetime(ident, binder, kind);
2119 self.record_lifetime_res(
2120 id,
2121 res,
2122 replace(&mut candidate, LifetimeElisionCandidate::Named),
2123 );
2124 }
2125 break;
2126 }
2127 LifetimeRibKind::Elided(res) => {
2128 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2129 for id in node_ids {
2130 self.record_lifetime_res(
2131 id,
2132 res,
2133 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2134 );
2135 }
2136 break;
2137 }
2138 LifetimeRibKind::ElisionFailure => {
2139 self.diag_metadata.current_elision_failures.push(missing_lifetime);
2140 for id in node_ids {
2141 self.record_lifetime_res(
2142 id,
2143 LifetimeRes::Error,
2144 LifetimeElisionCandidate::Ignore,
2145 );
2146 }
2147 break;
2148 }
2149 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2154 for id in node_ids {
2155 self.record_lifetime_res(
2156 id,
2157 LifetimeRes::Error,
2158 LifetimeElisionCandidate::Ignore,
2159 );
2160 }
2161 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2162 break;
2163 }
2164 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2165 LifetimeRibKind::ConcreteAnonConst(_) => {
2166 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2168 }
2169 }
2170 }
2171
2172 if should_lint {
2173 self.r.lint_buffer.buffer_lint(
2174 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2175 segment_id,
2176 elided_lifetime_span,
2177 lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2178 expected_lifetimes,
2179 path_span,
2180 !segment.has_generic_args,
2181 elided_lifetime_span,
2182 ),
2183 );
2184 }
2185 }
2186 }
2187
2188 #[instrument(level = "debug", skip(self))]
2189 fn record_lifetime_res(
2190 &mut self,
2191 id: NodeId,
2192 res: LifetimeRes,
2193 candidate: LifetimeElisionCandidate,
2194 ) {
2195 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2196 panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2197 }
2198
2199 match candidate {
2200 LifetimeElisionCandidate::Missing(missing @ MissingLifetime { .. }) => {
2201 debug_assert_eq!(id, missing.id);
2202 match res {
2203 LifetimeRes::Static { suppress_elision_warning } => {
2204 if !suppress_elision_warning {
2205 self.r.lint_buffer.buffer_lint(
2206 lint::builtin::ELIDED_NAMED_LIFETIMES,
2207 missing.id_for_lint,
2208 missing.span,
2209 BuiltinLintDiag::ElidedNamedLifetimes {
2210 elided: (missing.span, missing.kind),
2211 resolution: lint::ElidedLifetimeResolution::Static,
2212 },
2213 );
2214 }
2215 }
2216 LifetimeRes::Param { param, binder: _ } => {
2217 let tcx = self.r.tcx();
2218 self.r.lint_buffer.buffer_lint(
2219 lint::builtin::ELIDED_NAMED_LIFETIMES,
2220 missing.id_for_lint,
2221 missing.span,
2222 BuiltinLintDiag::ElidedNamedLifetimes {
2223 elided: (missing.span, missing.kind),
2224 resolution: lint::ElidedLifetimeResolution::Param(
2225 tcx.item_name(param.into()),
2226 tcx.source_span(param),
2227 ),
2228 },
2229 );
2230 }
2231 LifetimeRes::Fresh { .. }
2232 | LifetimeRes::Infer
2233 | LifetimeRes::Error
2234 | LifetimeRes::ElidedAnchor { .. } => {}
2235 }
2236 }
2237 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {}
2238 }
2239
2240 match res {
2241 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2242 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2243 candidates.push((res, candidate));
2244 }
2245 }
2246 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2247 }
2248 }
2249
2250 #[instrument(level = "debug", skip(self))]
2251 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2252 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2253 panic!(
2254 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2255 )
2256 }
2257 }
2258
2259 #[instrument(level = "debug", skip(self, inputs))]
2261 fn resolve_fn_signature(
2262 &mut self,
2263 fn_id: NodeId,
2264 has_self: bool,
2265 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2266 output_ty: &'ast FnRetTy,
2267 ) {
2268 let elision_lifetime = self.resolve_fn_params(has_self, inputs);
2270 debug!(?elision_lifetime);
2271
2272 let outer_failures = take(&mut self.diag_metadata.current_elision_failures);
2273 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2274 self.r.lifetime_elision_allowed.insert(fn_id);
2275 LifetimeRibKind::Elided(*res)
2276 } else {
2277 LifetimeRibKind::ElisionFailure
2278 };
2279 self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2280 let elision_failures =
2281 replace(&mut self.diag_metadata.current_elision_failures, outer_failures);
2282 if !elision_failures.is_empty() {
2283 let Err(failure_info) = elision_lifetime else { bug!() };
2284 self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2285 }
2286 }
2287
2288 fn resolve_fn_params(
2292 &mut self,
2293 has_self: bool,
2294 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)>,
2295 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2296 enum Elision {
2297 None,
2299 Self_(LifetimeRes),
2301 Param(LifetimeRes),
2303 Err,
2305 }
2306
2307 let outer_candidates = self.lifetime_elision_candidates.take();
2309
2310 let mut elision_lifetime = Elision::None;
2312 let mut parameter_info = Vec::new();
2314 let mut all_candidates = Vec::new();
2315
2316 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2317 for (index, (pat, ty)) in inputs.enumerate() {
2318 debug!(?pat, ?ty);
2319 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2320 if let Some(pat) = pat {
2321 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2322 }
2323 });
2324
2325 debug_assert_matches!(self.lifetime_elision_candidates, None);
2327 self.lifetime_elision_candidates = Some(Default::default());
2328 self.visit_ty(ty);
2329 let local_candidates = self.lifetime_elision_candidates.take();
2330
2331 if let Some(candidates) = local_candidates {
2332 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2333 let lifetime_count = distinct.len();
2334 if lifetime_count != 0 {
2335 parameter_info.push(ElisionFnParameter {
2336 index,
2337 ident: if let Some(pat) = pat
2338 && let PatKind::Ident(_, ident, _) = pat.kind
2339 {
2340 Some(ident)
2341 } else {
2342 None
2343 },
2344 lifetime_count,
2345 span: ty.span,
2346 });
2347 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2348 match candidate {
2349 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2350 None
2351 }
2352 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2353 }
2354 }));
2355 }
2356 if !distinct.is_empty() {
2357 match elision_lifetime {
2358 Elision::None => {
2360 if let Some(res) = distinct.get_only() {
2361 elision_lifetime = Elision::Param(*res)
2363 } else {
2364 elision_lifetime = Elision::Err;
2366 }
2367 }
2368 Elision::Param(_) => elision_lifetime = Elision::Err,
2370 Elision::Self_(_) | Elision::Err => {}
2372 }
2373 }
2374 }
2375
2376 if index == 0 && has_self {
2378 let self_lifetime = self.find_lifetime_for_self(ty);
2379 elision_lifetime = match self_lifetime {
2380 Set1::One(lifetime) => Elision::Self_(lifetime),
2382 Set1::Many => Elision::Err,
2387 Set1::Empty => Elision::None,
2390 }
2391 }
2392 debug!("(resolving function / closure) recorded parameter");
2393 }
2394
2395 debug_assert_matches!(self.lifetime_elision_candidates, None);
2397 self.lifetime_elision_candidates = outer_candidates;
2398
2399 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2400 return Ok(res);
2401 }
2402
2403 Err((all_candidates, parameter_info))
2405 }
2406
2407 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2409 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2413 r: &'a Resolver<'ra, 'tcx>,
2414 impl_self: Option<Res>,
2415 lifetime: Set1<LifetimeRes>,
2416 }
2417
2418 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2419 fn visit_ty(&mut self, ty: &'ra Ty) {
2420 trace!("FindReferenceVisitor considering ty={:?}", ty);
2421 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2422 let mut visitor =
2424 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2425 visitor.visit_ty(ty);
2426 trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2427 if visitor.self_found {
2428 let lt_id = if let Some(lt) = lt {
2429 lt.id
2430 } else {
2431 let res = self.r.lifetimes_res_map[&ty.id];
2432 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2433 start
2434 };
2435 let lt_res = self.r.lifetimes_res_map[<_id];
2436 trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2437 self.lifetime.insert(lt_res);
2438 }
2439 }
2440 visit::walk_ty(self, ty)
2441 }
2442
2443 fn visit_expr(&mut self, _: &'ra Expr) {}
2446 }
2447
2448 struct SelfVisitor<'a, 'ra, 'tcx> {
2451 r: &'a Resolver<'ra, 'tcx>,
2452 impl_self: Option<Res>,
2453 self_found: bool,
2454 }
2455
2456 impl SelfVisitor<'_, '_, '_> {
2457 fn is_self_ty(&self, ty: &Ty) -> bool {
2459 match ty.kind {
2460 TyKind::ImplicitSelf => true,
2461 TyKind::Path(None, _) => {
2462 let path_res = self.r.partial_res_map[&ty.id].full_res();
2463 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2464 return true;
2465 }
2466 self.impl_self.is_some() && path_res == self.impl_self
2467 }
2468 _ => false,
2469 }
2470 }
2471 }
2472
2473 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2474 fn visit_ty(&mut self, ty: &'ra Ty) {
2475 trace!("SelfVisitor considering ty={:?}", ty);
2476 if self.is_self_ty(ty) {
2477 trace!("SelfVisitor found Self");
2478 self.self_found = true;
2479 }
2480 visit::walk_ty(self, ty)
2481 }
2482
2483 fn visit_expr(&mut self, _: &'ra Expr) {}
2486 }
2487
2488 let impl_self = self
2489 .diag_metadata
2490 .current_self_type
2491 .as_ref()
2492 .and_then(|ty| {
2493 if let TyKind::Path(None, _) = ty.kind {
2494 self.r.partial_res_map.get(&ty.id)
2495 } else {
2496 None
2497 }
2498 })
2499 .and_then(|res| res.full_res())
2500 .filter(|res| {
2501 matches!(
2505 res,
2506 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2507 )
2508 });
2509 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2510 visitor.visit_ty(ty);
2511 trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2512 visitor.lifetime
2513 }
2514
2515 fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2518 let mut suggestion = None;
2519
2520 for i in (0..self.label_ribs.len()).rev() {
2521 let rib = &self.label_ribs[i];
2522
2523 if let RibKind::MacroDefinition(def) = rib.kind
2524 && def == self.r.macro_def(label.span.ctxt())
2527 {
2528 label.span.remove_mark();
2529 }
2530
2531 let ident = label.normalize_to_macro_rules();
2532 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2533 let definition_span = ident.span;
2534 return if self.is_label_valid_from_rib(i) {
2535 Ok((*id, definition_span))
2536 } else {
2537 Err(ResolutionError::UnreachableLabel {
2538 name: label.name,
2539 definition_span,
2540 suggestion,
2541 })
2542 };
2543 }
2544
2545 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2548 }
2549
2550 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2551 }
2552
2553 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2555 let ribs = &self.label_ribs[rib_index + 1..];
2556 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2557 }
2558
2559 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2560 debug!("resolve_adt");
2561 let kind = self.r.local_def_kind(item.id);
2562 self.with_current_self_item(item, |this| {
2563 this.with_generic_param_rib(
2564 &generics.params,
2565 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2566 LifetimeRibKind::Generics {
2567 binder: item.id,
2568 kind: LifetimeBinderKind::Item,
2569 span: generics.span,
2570 },
2571 |this| {
2572 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2573 this.with_self_rib(
2574 Res::SelfTyAlias {
2575 alias_to: item_def_id,
2576 forbid_generic: false,
2577 is_trait_impl: false,
2578 },
2579 |this| {
2580 visit::walk_item(this, item);
2581 },
2582 );
2583 },
2584 );
2585 });
2586 }
2587
2588 fn future_proof_import(&mut self, use_tree: &UseTree) {
2589 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2590 let ident = segment.ident;
2591 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2592 return;
2593 }
2594
2595 let nss = match use_tree.kind {
2596 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2597 _ => &[TypeNS],
2598 };
2599 let report_error = |this: &Self, ns| {
2600 if this.should_report_errs() {
2601 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2602 this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2603 }
2604 };
2605
2606 for &ns in nss {
2607 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2608 Some(LexicalScopeBinding::Res(..)) => {
2609 report_error(self, ns);
2610 }
2611 Some(LexicalScopeBinding::Item(binding)) => {
2612 if let Some(LexicalScopeBinding::Res(..)) =
2613 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2614 {
2615 report_error(self, ns);
2616 }
2617 }
2618 None => {}
2619 }
2620 }
2621 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2622 for (use_tree, _) in items {
2623 self.future_proof_import(use_tree);
2624 }
2625 }
2626 }
2627
2628 fn resolve_item(&mut self, item: &'ast Item) {
2629 let mod_inner_docs =
2630 matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2631 if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2632 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2633 }
2634
2635 let name = item.ident.name;
2636 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
2637
2638 let def_kind = self.r.local_def_kind(item.id);
2639 match item.kind {
2640 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2641 self.with_generic_param_rib(
2642 &generics.params,
2643 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2644 LifetimeRibKind::Generics {
2645 binder: item.id,
2646 kind: LifetimeBinderKind::Item,
2647 span: generics.span,
2648 },
2649 |this| visit::walk_item(this, item),
2650 );
2651 }
2652
2653 ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2654 self.with_generic_param_rib(
2655 &generics.params,
2656 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2657 LifetimeRibKind::Generics {
2658 binder: item.id,
2659 kind: LifetimeBinderKind::Function,
2660 span: generics.span,
2661 },
2662 |this| visit::walk_item(this, item),
2663 );
2664 self.resolve_define_opaques(define_opaque);
2665 }
2666
2667 ItemKind::Enum(_, ref generics)
2668 | ItemKind::Struct(_, ref generics)
2669 | ItemKind::Union(_, ref generics) => {
2670 self.resolve_adt(item, generics);
2671 }
2672
2673 ItemKind::Impl(box Impl {
2674 ref generics,
2675 ref of_trait,
2676 ref self_ty,
2677 items: ref impl_items,
2678 ..
2679 }) => {
2680 self.diag_metadata.current_impl_items = Some(impl_items);
2681 self.resolve_implementation(
2682 &item.attrs,
2683 generics,
2684 of_trait,
2685 self_ty,
2686 item.id,
2687 impl_items,
2688 );
2689 self.diag_metadata.current_impl_items = None;
2690 }
2691
2692 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2693 self.with_generic_param_rib(
2695 &generics.params,
2696 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2697 LifetimeRibKind::Generics {
2698 binder: item.id,
2699 kind: LifetimeBinderKind::Item,
2700 span: generics.span,
2701 },
2702 |this| {
2703 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2704 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2705 this.visit_generics(generics);
2706 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2707 this.resolve_trait_items(items);
2708 });
2709 },
2710 );
2711 }
2712
2713 ItemKind::TraitAlias(ref generics, ref bounds) => {
2714 self.with_generic_param_rib(
2716 &generics.params,
2717 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2718 LifetimeRibKind::Generics {
2719 binder: item.id,
2720 kind: LifetimeBinderKind::Item,
2721 span: generics.span,
2722 },
2723 |this| {
2724 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2725 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2726 this.visit_generics(generics);
2727 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2728 });
2729 },
2730 );
2731 }
2732
2733 ItemKind::Mod(..) => {
2734 self.with_mod_rib(item.id, |this| {
2735 if mod_inner_docs {
2736 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2737 }
2738 let old_macro_rules = this.parent_scope.macro_rules;
2739 visit::walk_item(this, item);
2740 if item.attrs.iter().all(|attr| {
2743 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2744 }) {
2745 this.parent_scope.macro_rules = old_macro_rules;
2746 }
2747 });
2748 }
2749
2750 ItemKind::Static(box ast::StaticItem {
2751 ref ty, ref expr, ref define_opaque, ..
2752 }) => {
2753 self.with_static_rib(def_kind, |this| {
2754 this.with_lifetime_rib(
2755 LifetimeRibKind::Elided(LifetimeRes::Static {
2756 suppress_elision_warning: true,
2757 }),
2758 |this| {
2759 this.visit_ty(ty);
2760 },
2761 );
2762 if let Some(expr) = expr {
2763 this.resolve_const_body(expr, Some((item.ident, ConstantItemKind::Static)));
2766 }
2767 });
2768 self.resolve_define_opaques(define_opaque);
2769 }
2770
2771 ItemKind::Const(box ast::ConstItem {
2772 ref generics,
2773 ref ty,
2774 ref expr,
2775 ref define_opaque,
2776 ..
2777 }) => {
2778 self.with_generic_param_rib(
2779 &generics.params,
2780 RibKind::Item(
2781 if self.r.tcx.features().generic_const_items() {
2782 HasGenericParams::Yes(generics.span)
2783 } else {
2784 HasGenericParams::No
2785 },
2786 def_kind,
2787 ),
2788 LifetimeRibKind::Generics {
2789 binder: item.id,
2790 kind: LifetimeBinderKind::ConstItem,
2791 span: generics.span,
2792 },
2793 |this| {
2794 this.visit_generics(generics);
2795
2796 this.with_lifetime_rib(
2797 LifetimeRibKind::Elided(LifetimeRes::Static {
2798 suppress_elision_warning: true,
2799 }),
2800 |this| this.visit_ty(ty),
2801 );
2802
2803 if let Some(expr) = expr {
2804 this.resolve_const_body(
2805 expr,
2806 Some((item.ident, ConstantItemKind::Const)),
2807 );
2808 }
2809 },
2810 );
2811 self.resolve_define_opaques(define_opaque);
2812 }
2813
2814 ItemKind::Use(ref use_tree) => {
2815 let maybe_exported = match use_tree.kind {
2816 UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2817 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2818 };
2819 self.resolve_doc_links(&item.attrs, maybe_exported);
2820
2821 self.future_proof_import(use_tree);
2822 }
2823
2824 ItemKind::MacroDef(ref macro_def) => {
2825 if macro_def.macro_rules {
2828 let def_id = self.r.local_def_id(item.id);
2829 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2830 }
2831 }
2832
2833 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2834 visit::walk_item(self, item);
2835 }
2836
2837 ItemKind::Delegation(ref delegation) => {
2838 let span = delegation.path.segments.last().unwrap().ident.span;
2839 self.with_generic_param_rib(
2840 &[],
2841 RibKind::Item(HasGenericParams::Yes(span), def_kind),
2842 LifetimeRibKind::Generics {
2843 binder: item.id,
2844 kind: LifetimeBinderKind::Function,
2845 span,
2846 },
2847 |this| this.resolve_delegation(delegation),
2848 );
2849 }
2850
2851 ItemKind::ExternCrate(..) => {}
2852
2853 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2854 panic!("unexpanded macro in resolve!")
2855 }
2856 }
2857 }
2858
2859 fn with_generic_param_rib<'c, F>(
2860 &'c mut self,
2861 params: &'c [GenericParam],
2862 kind: RibKind<'ra>,
2863 lifetime_kind: LifetimeRibKind,
2864 f: F,
2865 ) where
2866 F: FnOnce(&mut Self),
2867 {
2868 debug!("with_generic_param_rib");
2869 let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. } =
2870 lifetime_kind
2871 else {
2872 panic!()
2873 };
2874
2875 let mut function_type_rib = Rib::new(kind);
2876 let mut function_value_rib = Rib::new(kind);
2877 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2878
2879 if !params.is_empty() {
2881 let mut seen_bindings = FxHashMap::default();
2882 let mut seen_lifetimes = FxHashSet::default();
2884
2885 for ns in [ValueNS, TypeNS] {
2887 for parent_rib in self.ribs[ns].iter().rev() {
2888 if matches!(parent_rib.kind, RibKind::Module(..)) {
2891 break;
2892 }
2893
2894 seen_bindings
2895 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2896 }
2897 }
2898
2899 for rib in self.lifetime_ribs.iter().rev() {
2901 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2902 if let LifetimeRibKind::Item = rib.kind {
2903 break;
2904 }
2905 }
2906
2907 for param in params {
2908 let ident = param.ident.normalize_to_macros_2_0();
2909 debug!("with_generic_param_rib: {}", param.id);
2910
2911 if let GenericParamKind::Lifetime = param.kind
2912 && let Some(&original) = seen_lifetimes.get(&ident)
2913 {
2914 diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
2915 self.record_lifetime_param(param.id, LifetimeRes::Error);
2917 continue;
2918 }
2919
2920 match seen_bindings.entry(ident) {
2921 Entry::Occupied(entry) => {
2922 let span = *entry.get();
2923 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
2924 self.report_error(param.ident.span, err);
2925 let rib = match param.kind {
2926 GenericParamKind::Lifetime => {
2927 self.record_lifetime_param(param.id, LifetimeRes::Error);
2929 continue;
2930 }
2931 GenericParamKind::Type { .. } => &mut function_type_rib,
2932 GenericParamKind::Const { .. } => &mut function_value_rib,
2933 };
2934
2935 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
2937 rib.bindings.insert(ident, Res::Err);
2938 continue;
2939 }
2940 Entry::Vacant(entry) => {
2941 entry.insert(param.ident.span);
2942 }
2943 }
2944
2945 if param.ident.name == kw::UnderscoreLifetime {
2946 self.r
2947 .dcx()
2948 .emit_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span });
2949 self.record_lifetime_param(param.id, LifetimeRes::Error);
2951 continue;
2952 }
2953
2954 if param.ident.name == kw::StaticLifetime {
2955 self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
2956 span: param.ident.span,
2957 lifetime: param.ident,
2958 });
2959 self.record_lifetime_param(param.id, LifetimeRes::Error);
2961 continue;
2962 }
2963
2964 let def_id = self.r.local_def_id(param.id);
2965
2966 let (rib, def_kind) = match param.kind {
2968 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2969 GenericParamKind::Const { .. } => {
2970 (&mut function_value_rib, DefKind::ConstParam)
2971 }
2972 GenericParamKind::Lifetime => {
2973 let res = LifetimeRes::Param { param: def_id, binder };
2974 self.record_lifetime_param(param.id, res);
2975 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2976 continue;
2977 }
2978 };
2979
2980 let res = match kind {
2981 RibKind::Item(..) | RibKind::AssocItem => {
2982 Res::Def(def_kind, def_id.to_def_id())
2983 }
2984 RibKind::Normal => {
2985 if self.r.tcx.features().non_lifetime_binders()
2988 && matches!(param.kind, GenericParamKind::Type { .. })
2989 {
2990 Res::Def(def_kind, def_id.to_def_id())
2991 } else {
2992 Res::Err
2993 }
2994 }
2995 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2996 };
2997 self.r.record_partial_res(param.id, PartialRes::new(res));
2998 rib.bindings.insert(ident, res);
2999 }
3000 }
3001
3002 self.lifetime_ribs.push(function_lifetime_rib);
3003 self.ribs[ValueNS].push(function_value_rib);
3004 self.ribs[TypeNS].push(function_type_rib);
3005
3006 f(self);
3007
3008 self.ribs[TypeNS].pop();
3009 self.ribs[ValueNS].pop();
3010 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3011
3012 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3014 for (_, res) in function_lifetime_rib.bindings.values() {
3015 candidates.retain(|(r, _)| r != res);
3016 }
3017 }
3018
3019 if let LifetimeBinderKind::BareFnType
3020 | LifetimeBinderKind::WhereBound
3021 | LifetimeBinderKind::Function
3022 | LifetimeBinderKind::ImplBlock = generics_kind
3023 {
3024 self.maybe_report_lifetime_uses(generics_span, params)
3025 }
3026 }
3027
3028 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3029 self.label_ribs.push(Rib::new(kind));
3030 f(self);
3031 self.label_ribs.pop();
3032 }
3033
3034 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3035 let kind = RibKind::Item(HasGenericParams::No, def_kind);
3036 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3037 }
3038
3039 #[instrument(level = "debug", skip(self, f))]
3048 fn with_constant_rib(
3049 &mut self,
3050 is_repeat: IsRepeatExpr,
3051 may_use_generics: ConstantHasGenerics,
3052 item: Option<(Ident, ConstantItemKind)>,
3053 f: impl FnOnce(&mut Self),
3054 ) {
3055 let f = |this: &mut Self| {
3056 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3057 this.with_rib(
3058 TypeNS,
3059 RibKind::ConstantItem(
3060 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3061 item,
3062 ),
3063 |this| {
3064 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3065 },
3066 )
3067 })
3068 };
3069
3070 if let ConstantHasGenerics::No(cause) = may_use_generics {
3071 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3072 } else {
3073 f(self)
3074 }
3075 }
3076
3077 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3078 let previous_value =
3080 replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3081 let result = f(self);
3082 self.diag_metadata.current_self_type = previous_value;
3083 result
3084 }
3085
3086 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3087 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3088 let result = f(self);
3089 self.diag_metadata.current_self_item = previous_value;
3090 result
3091 }
3092
3093 fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
3095 let trait_assoc_items =
3096 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3097
3098 let walk_assoc_item =
3099 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3100 this.with_generic_param_rib(
3101 &generics.params,
3102 RibKind::AssocItem,
3103 LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind },
3104 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3105 );
3106 };
3107
3108 for item in trait_items {
3109 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3110 match &item.kind {
3111 AssocItemKind::Const(box ast::ConstItem {
3112 generics,
3113 ty,
3114 expr,
3115 define_opaque,
3116 ..
3117 }) => {
3118 self.with_generic_param_rib(
3119 &generics.params,
3120 RibKind::AssocItem,
3121 LifetimeRibKind::Generics {
3122 binder: item.id,
3123 span: generics.span,
3124 kind: LifetimeBinderKind::ConstItem,
3125 },
3126 |this| {
3127 this.with_lifetime_rib(
3128 LifetimeRibKind::StaticIfNoLifetimeInScope {
3129 lint_id: item.id,
3130 emit_lint: false,
3131 },
3132 |this| {
3133 this.visit_generics(generics);
3134 this.visit_ty(ty);
3135
3136 if let Some(expr) = expr {
3139 this.resolve_const_body(expr, None);
3145 }
3146 },
3147 )
3148 },
3149 );
3150
3151 self.resolve_define_opaques(define_opaque);
3152 }
3153 AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3154 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3155
3156 self.resolve_define_opaques(define_opaque);
3157 }
3158 AssocItemKind::Delegation(delegation) => {
3159 self.with_generic_param_rib(
3160 &[],
3161 RibKind::AssocItem,
3162 LifetimeRibKind::Generics {
3163 binder: item.id,
3164 kind: LifetimeBinderKind::Function,
3165 span: delegation.path.segments.last().unwrap().ident.span,
3166 },
3167 |this| this.resolve_delegation(delegation),
3168 );
3169 }
3170 AssocItemKind::Type(box TyAlias { generics, .. }) => self
3171 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3172 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3173 }),
3174 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3175 panic!("unexpanded macro in resolve!")
3176 }
3177 };
3178 }
3179
3180 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3181 }
3182
3183 fn with_optional_trait_ref<T>(
3185 &mut self,
3186 opt_trait_ref: Option<&TraitRef>,
3187 self_type: &'ast Ty,
3188 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3189 ) -> T {
3190 let mut new_val = None;
3191 let mut new_id = None;
3192 if let Some(trait_ref) = opt_trait_ref {
3193 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3194 self.diag_metadata.currently_processing_impl_trait =
3195 Some((trait_ref.clone(), self_type.clone()));
3196 let res = self.smart_resolve_path_fragment(
3197 &None,
3198 &path,
3199 PathSource::Trait(AliasPossibility::No),
3200 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3201 RecordPartialRes::Yes,
3202 None,
3203 );
3204 self.diag_metadata.currently_processing_impl_trait = None;
3205 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3206 new_id = Some(def_id);
3207 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3208 }
3209 }
3210 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3211 let result = f(self, new_id);
3212 self.current_trait_ref = original_trait_ref;
3213 result
3214 }
3215
3216 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3217 let mut self_type_rib = Rib::new(RibKind::Normal);
3218
3219 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3221 self.ribs[ns].push(self_type_rib);
3222 f(self);
3223 self.ribs[ns].pop();
3224 }
3225
3226 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3227 self.with_self_rib_ns(TypeNS, self_res, f)
3228 }
3229
3230 fn resolve_implementation(
3231 &mut self,
3232 attrs: &[ast::Attribute],
3233 generics: &'ast Generics,
3234 opt_trait_reference: &'ast Option<TraitRef>,
3235 self_type: &'ast Ty,
3236 item_id: NodeId,
3237 impl_items: &'ast [P<AssocItem>],
3238 ) {
3239 debug!("resolve_implementation");
3240 self.with_generic_param_rib(
3242 &generics.params,
3243 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3244 LifetimeRibKind::Generics {
3245 span: generics.span,
3246 binder: item_id,
3247 kind: LifetimeBinderKind::ImplBlock,
3248 },
3249 |this| {
3250 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3252 this.with_lifetime_rib(
3253 LifetimeRibKind::AnonymousCreateParameter {
3254 binder: item_id,
3255 report_in_path: true
3256 },
3257 |this| {
3258 this.with_optional_trait_ref(
3260 opt_trait_reference.as_ref(),
3261 self_type,
3262 |this, trait_id| {
3263 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3264
3265 let item_def_id = this.r.local_def_id(item_id);
3266
3267 if let Some(trait_id) = trait_id {
3269 this.r
3270 .trait_impls
3271 .entry(trait_id)
3272 .or_default()
3273 .push(item_def_id);
3274 }
3275
3276 let item_def_id = item_def_id.to_def_id();
3277 let res = Res::SelfTyAlias {
3278 alias_to: item_def_id,
3279 forbid_generic: false,
3280 is_trait_impl: trait_id.is_some()
3281 };
3282 this.with_self_rib(res, |this| {
3283 if let Some(trait_ref) = opt_trait_reference.as_ref() {
3284 visit::walk_trait_ref(this, trait_ref);
3286 }
3287 this.visit_ty(self_type);
3289 this.visit_generics(generics);
3291
3292 this.with_current_self_type(self_type, |this| {
3294 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3295 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3296 let mut seen_trait_items = Default::default();
3297 for item in impl_items {
3298 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3299 }
3300 });
3301 });
3302 });
3303 },
3304 )
3305 },
3306 );
3307 });
3308 },
3309 );
3310 }
3311
3312 fn resolve_impl_item(
3313 &mut self,
3314 item: &'ast AssocItem,
3315 seen_trait_items: &mut FxHashMap<DefId, Span>,
3316 trait_id: Option<DefId>,
3317 ) {
3318 use crate::ResolutionError::*;
3319 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3320 match &item.kind {
3321 AssocItemKind::Const(box ast::ConstItem {
3322 generics, ty, expr, define_opaque, ..
3323 }) => {
3324 debug!("resolve_implementation AssocItemKind::Const");
3325 self.with_generic_param_rib(
3326 &generics.params,
3327 RibKind::AssocItem,
3328 LifetimeRibKind::Generics {
3329 binder: item.id,
3330 span: generics.span,
3331 kind: LifetimeBinderKind::ConstItem,
3332 },
3333 |this| {
3334 this.with_lifetime_rib(
3335 LifetimeRibKind::AnonymousCreateParameter {
3338 binder: item.id,
3339 report_in_path: true,
3340 },
3341 |this| {
3342 this.with_lifetime_rib(
3343 LifetimeRibKind::StaticIfNoLifetimeInScope {
3344 lint_id: item.id,
3345 emit_lint: true,
3347 },
3348 |this| {
3349 this.check_trait_item(
3352 item.id,
3353 item.ident,
3354 &item.kind,
3355 ValueNS,
3356 item.span,
3357 seen_trait_items,
3358 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3359 );
3360
3361 this.visit_generics(generics);
3362 this.visit_ty(ty);
3363 if let Some(expr) = expr {
3364 this.resolve_const_body(expr, None);
3370 }
3371 },
3372 )
3373 },
3374 );
3375 },
3376 );
3377 self.resolve_define_opaques(define_opaque);
3378 }
3379 AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3380 debug!("resolve_implementation AssocItemKind::Fn");
3381 self.with_generic_param_rib(
3383 &generics.params,
3384 RibKind::AssocItem,
3385 LifetimeRibKind::Generics {
3386 binder: item.id,
3387 span: generics.span,
3388 kind: LifetimeBinderKind::Function,
3389 },
3390 |this| {
3391 this.check_trait_item(
3394 item.id,
3395 item.ident,
3396 &item.kind,
3397 ValueNS,
3398 item.span,
3399 seen_trait_items,
3400 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3401 );
3402
3403 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3404 },
3405 );
3406
3407 self.resolve_define_opaques(define_opaque);
3408 }
3409 AssocItemKind::Type(box TyAlias { generics, .. }) => {
3410 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3411 debug!("resolve_implementation AssocItemKind::Type");
3412 self.with_generic_param_rib(
3414 &generics.params,
3415 RibKind::AssocItem,
3416 LifetimeRibKind::Generics {
3417 binder: item.id,
3418 span: generics.span,
3419 kind: LifetimeBinderKind::Item,
3420 },
3421 |this| {
3422 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3423 this.check_trait_item(
3426 item.id,
3427 item.ident,
3428 &item.kind,
3429 TypeNS,
3430 item.span,
3431 seen_trait_items,
3432 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3433 );
3434
3435 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3436 });
3437 },
3438 );
3439 self.diag_metadata.in_non_gat_assoc_type = None;
3440 }
3441 AssocItemKind::Delegation(box delegation) => {
3442 debug!("resolve_implementation AssocItemKind::Delegation");
3443 self.with_generic_param_rib(
3444 &[],
3445 RibKind::AssocItem,
3446 LifetimeRibKind::Generics {
3447 binder: item.id,
3448 kind: LifetimeBinderKind::Function,
3449 span: delegation.path.segments.last().unwrap().ident.span,
3450 },
3451 |this| {
3452 this.check_trait_item(
3453 item.id,
3454 item.ident,
3455 &item.kind,
3456 ValueNS,
3457 item.span,
3458 seen_trait_items,
3459 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3460 );
3461
3462 this.resolve_delegation(delegation)
3463 },
3464 );
3465 }
3466 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3467 panic!("unexpanded macro in resolve!")
3468 }
3469 }
3470 }
3471
3472 fn check_trait_item<F>(
3473 &mut self,
3474 id: NodeId,
3475 mut ident: Ident,
3476 kind: &AssocItemKind,
3477 ns: Namespace,
3478 span: Span,
3479 seen_trait_items: &mut FxHashMap<DefId, Span>,
3480 err: F,
3481 ) where
3482 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3483 {
3484 let Some((module, _)) = self.current_trait_ref else {
3486 return;
3487 };
3488 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3489 let key = BindingKey::new(ident, ns);
3490 let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
3491 debug!(?binding);
3492 if binding.is_none() {
3493 let ns = match ns {
3496 ValueNS => TypeNS,
3497 TypeNS => ValueNS,
3498 _ => ns,
3499 };
3500 let key = BindingKey::new(ident, ns);
3501 binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
3502 debug!(?binding);
3503 }
3504
3505 let feed_visibility = |this: &mut Self, def_id| {
3506 let vis = this.r.tcx.visibility(def_id);
3507 let vis = if vis.is_visible_locally() {
3508 vis.expect_local()
3509 } else {
3510 this.r.dcx().span_delayed_bug(
3511 span,
3512 "error should be emitted when an unexpected trait item is used",
3513 );
3514 rustc_middle::ty::Visibility::Public
3515 };
3516 this.r.feed_visibility(this.r.feed(id), vis);
3517 };
3518
3519 let Some(binding) = binding else {
3520 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3522 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3523 let path_names = path_names_to_string(path);
3524 self.report_error(span, err(ident, path_names, candidate));
3525 feed_visibility(self, module.def_id());
3526 return;
3527 };
3528
3529 let res = binding.res();
3530 let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3531 feed_visibility(self, id_in_trait);
3532
3533 match seen_trait_items.entry(id_in_trait) {
3534 Entry::Occupied(entry) => {
3535 self.report_error(
3536 span,
3537 ResolutionError::TraitImplDuplicate {
3538 name: ident,
3539 old_span: *entry.get(),
3540 trait_item_span: binding.span,
3541 },
3542 );
3543 return;
3544 }
3545 Entry::Vacant(entry) => {
3546 entry.insert(span);
3547 }
3548 };
3549
3550 match (def_kind, kind) {
3551 (DefKind::AssocTy, AssocItemKind::Type(..))
3552 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3553 | (DefKind::AssocConst, AssocItemKind::Const(..))
3554 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3555 self.r.record_partial_res(id, PartialRes::new(res));
3556 return;
3557 }
3558 _ => {}
3559 }
3560
3561 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3563 let (code, kind) = match kind {
3564 AssocItemKind::Const(..) => (E0323, "const"),
3565 AssocItemKind::Fn(..) => (E0324, "method"),
3566 AssocItemKind::Type(..) => (E0325, "type"),
3567 AssocItemKind::Delegation(..) => (E0324, "method"),
3568 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3569 span_bug!(span, "unexpanded macro")
3570 }
3571 };
3572 let trait_path = path_names_to_string(path);
3573 self.report_error(
3574 span,
3575 ResolutionError::TraitImplMismatch {
3576 name: ident,
3577 kind,
3578 code,
3579 trait_path,
3580 trait_item_span: binding.span,
3581 },
3582 );
3583 }
3584
3585 fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3586 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3587 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3588 this.visit_expr(expr)
3589 });
3590 })
3591 }
3592
3593 fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3594 self.smart_resolve_path(
3595 delegation.id,
3596 &delegation.qself,
3597 &delegation.path,
3598 PathSource::Delegation,
3599 );
3600 if let Some(qself) = &delegation.qself {
3601 self.visit_ty(&qself.ty);
3602 }
3603 self.visit_path(&delegation.path, delegation.id);
3604 let Some(body) = &delegation.body else { return };
3605 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3606 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3608
3609 let span = delegation.path.segments.last().unwrap().ident.span;
3610 this.fresh_binding(
3611 Ident::new(kw::SelfLower, span),
3612 delegation.id,
3613 PatternSource::FnParam,
3614 &mut bindings,
3615 );
3616 this.visit_block(body);
3617 });
3618 }
3619
3620 fn resolve_params(&mut self, params: &'ast [Param]) {
3621 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3622 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3623 for Param { pat, .. } in params {
3624 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3625 }
3626 });
3627 for Param { ty, .. } in params {
3628 self.visit_ty(ty);
3629 }
3630 }
3631
3632 fn resolve_local(&mut self, local: &'ast Local) {
3633 debug!("resolving local ({:?})", local);
3634 visit_opt!(self, visit_ty, &local.ty);
3636
3637 if let Some((init, els)) = local.kind.init_else_opt() {
3639 self.visit_expr(init);
3640
3641 if let Some(els) = els {
3643 self.visit_block(els);
3644 }
3645 }
3646
3647 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3649 }
3650
3651 fn compute_and_check_binding_map(
3671 &mut self,
3672 pat: &Pat,
3673 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3674 let mut binding_map = FxIndexMap::default();
3675 let mut is_never_pat = false;
3676
3677 pat.walk(&mut |pat| {
3678 match pat.kind {
3679 PatKind::Ident(annotation, ident, ref sub_pat)
3680 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3681 {
3682 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3683 }
3684 PatKind::Or(ref ps) => {
3685 match self.compute_and_check_or_pat_binding_map(ps) {
3688 Ok(bm) => binding_map.extend(bm),
3689 Err(IsNeverPattern) => is_never_pat = true,
3690 }
3691 return false;
3692 }
3693 PatKind::Never => is_never_pat = true,
3694 _ => {}
3695 }
3696
3697 true
3698 });
3699
3700 if is_never_pat {
3701 for (_, binding) in binding_map {
3702 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3703 }
3704 Err(IsNeverPattern)
3705 } else {
3706 Ok(binding_map)
3707 }
3708 }
3709
3710 fn is_base_res_local(&self, nid: NodeId) -> bool {
3711 matches!(
3712 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3713 Some(Res::Local(..))
3714 )
3715 }
3716
3717 fn compute_and_check_or_pat_binding_map(
3737 &mut self,
3738 pats: &[P<Pat>],
3739 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3740 let mut missing_vars = FxIndexMap::default();
3741 let mut inconsistent_vars = FxIndexMap::default();
3742
3743 let not_never_pats = pats
3745 .iter()
3746 .filter_map(|pat| {
3747 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3748 Some((binding_map, pat))
3749 })
3750 .collect::<Vec<_>>();
3751
3752 for (map_outer, pat_outer) in not_never_pats.iter() {
3754 let inners = not_never_pats
3756 .iter()
3757 .filter(|(_, pat)| pat.id != pat_outer.id)
3758 .flat_map(|(map, _)| map);
3759
3760 for (&name, binding_inner) in inners {
3761 match map_outer.get(&name) {
3762 None => {
3763 let binding_error =
3765 missing_vars.entry(name).or_insert_with(|| BindingError {
3766 name,
3767 origin: BTreeSet::new(),
3768 target: BTreeSet::new(),
3769 could_be_path: name.as_str().starts_with(char::is_uppercase),
3770 });
3771 binding_error.origin.insert(binding_inner.span);
3772 binding_error.target.insert(pat_outer.span);
3773 }
3774 Some(binding_outer) => {
3775 if binding_outer.annotation != binding_inner.annotation {
3776 inconsistent_vars
3778 .entry(name)
3779 .or_insert((binding_inner.span, binding_outer.span));
3780 }
3781 }
3782 }
3783 }
3784 }
3785
3786 for (name, mut v) in missing_vars {
3788 if inconsistent_vars.contains_key(&name) {
3789 v.could_be_path = false;
3790 }
3791 self.report_error(
3792 *v.origin.iter().next().unwrap(),
3793 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3794 );
3795 }
3796
3797 for (name, v) in inconsistent_vars {
3799 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3800 }
3801
3802 if not_never_pats.is_empty() {
3804 Err(IsNeverPattern)
3806 } else {
3807 let mut binding_map = FxIndexMap::default();
3808 for (bm, _) in not_never_pats {
3809 binding_map.extend(bm);
3810 }
3811 Ok(binding_map)
3812 }
3813 }
3814
3815 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3817 let mut is_or_or_never = false;
3818 pat.walk(&mut |pat| match pat.kind {
3819 PatKind::Or(..) | PatKind::Never => {
3820 is_or_or_never = true;
3821 false
3822 }
3823 _ => true,
3824 });
3825 if is_or_or_never {
3826 let _ = self.compute_and_check_binding_map(pat);
3827 }
3828 }
3829
3830 fn resolve_arm(&mut self, arm: &'ast Arm) {
3831 self.with_rib(ValueNS, RibKind::Normal, |this| {
3832 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3833 visit_opt!(this, visit_expr, &arm.guard);
3834 visit_opt!(this, visit_expr, &arm.body);
3835 });
3836 }
3837
3838 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3840 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3841 self.resolve_pattern(pat, pat_src, &mut bindings);
3842 }
3843
3844 fn resolve_pattern(
3845 &mut self,
3846 pat: &'ast Pat,
3847 pat_src: PatternSource,
3848 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3849 ) {
3850 visit::walk_pat(self, pat);
3854 self.resolve_pattern_inner(pat, pat_src, bindings);
3855 self.check_consistent_bindings(pat);
3857 }
3858
3859 #[tracing::instrument(skip(self, bindings), level = "debug")]
3879 fn resolve_pattern_inner(
3880 &mut self,
3881 pat: &Pat,
3882 pat_src: PatternSource,
3883 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3884 ) {
3885 pat.walk(&mut |pat| {
3887 match pat.kind {
3888 PatKind::Ident(bmode, ident, ref sub) => {
3889 let has_sub = sub.is_some();
3892 let res = self
3893 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3894 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3895 self.r.record_partial_res(pat.id, PartialRes::new(res));
3896 self.r.record_pat_span(pat.id, pat.span);
3897 }
3898 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3899 self.smart_resolve_path(
3900 pat.id,
3901 qself,
3902 path,
3903 PathSource::TupleStruct(
3904 pat.span,
3905 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3906 ),
3907 );
3908 }
3909 PatKind::Path(ref qself, ref path) => {
3910 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3911 }
3912 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3913 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3914 self.record_patterns_with_skipped_bindings(pat, rest);
3915 }
3916 PatKind::Or(ref ps) => {
3917 bindings.push((PatBoundCtx::Or, Default::default()));
3921 for p in ps {
3922 bindings.push((PatBoundCtx::Product, Default::default()));
3926 self.resolve_pattern_inner(p, pat_src, bindings);
3927 let collected = bindings.pop().unwrap().1;
3930 bindings.last_mut().unwrap().1.extend(collected);
3931 }
3932 let collected = bindings.pop().unwrap().1;
3936 bindings.last_mut().unwrap().1.extend(collected);
3937
3938 return false;
3940 }
3941 _ => {}
3942 }
3943 true
3944 });
3945 }
3946
3947 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
3948 match rest {
3949 ast::PatFieldsRest::Rest | ast::PatFieldsRest::Recovered(_) => {
3950 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
3952 && let Some(res) = partial_res.full_res()
3953 && let Some(def_id) = res.opt_def_id()
3954 {
3955 self.ribs[ValueNS]
3956 .last_mut()
3957 .unwrap()
3958 .patterns_with_skipped_bindings
3959 .entry(def_id)
3960 .or_default()
3961 .push((
3962 pat.span,
3963 match rest {
3964 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
3965 _ => Ok(()),
3966 },
3967 ));
3968 }
3969 }
3970 ast::PatFieldsRest::None => {}
3971 }
3972 }
3973
3974 fn fresh_binding(
3975 &mut self,
3976 ident: Ident,
3977 pat_id: NodeId,
3978 pat_src: PatternSource,
3979 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3980 ) -> Res {
3981 let ident = ident.normalize_to_macro_rules();
3985
3986 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
3987 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
3989 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
3992
3993 if already_bound_and {
3994 use ResolutionError::*;
3996 let error = match pat_src {
3997 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
3999 _ => IdentifierBoundMoreThanOnceInSamePattern,
4001 };
4002 self.report_error(ident.span, error(ident));
4003 }
4004
4005 let ident_valid = ident.name != kw::Empty;
4007 if ident_valid {
4008 bindings.last_mut().unwrap().1.insert(ident);
4009 }
4010
4011 if already_bound_or {
4012 self.innermost_rib_bindings(ValueNS)[&ident]
4015 } else {
4016 let res = Res::Local(pat_id);
4017 if ident_valid {
4018 self.innermost_rib_bindings(ValueNS).insert(ident, res);
4020 }
4021 res
4022 }
4023 }
4024
4025 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4026 &mut self.ribs[ns].last_mut().unwrap().bindings
4027 }
4028
4029 fn try_resolve_as_non_binding(
4030 &mut self,
4031 pat_src: PatternSource,
4032 ann: BindingMode,
4033 ident: Ident,
4034 has_sub: bool,
4035 ) -> Option<Res> {
4036 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4040
4041 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4042 let (res, binding) = match ls_binding {
4043 LexicalScopeBinding::Item(binding)
4044 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4045 {
4046 self.r.record_use(ident, binding, Used::Other);
4051 return None;
4052 }
4053 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4054 LexicalScopeBinding::Res(res) => (res, None),
4055 };
4056
4057 match res {
4058 Res::SelfCtor(_) | Res::Def(
4060 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4061 _,
4062 ) if is_syntactic_ambiguity => {
4063 if let Some(binding) = binding {
4065 self.r.record_use(ident, binding, Used::Other);
4066 }
4067 Some(res)
4068 }
4069 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4070 let binding = binding.expect("no binding for a ctor or static");
4076 self.report_error(
4077 ident.span,
4078 ResolutionError::BindingShadowsSomethingUnacceptable {
4079 shadowing_binding: pat_src,
4080 name: ident.name,
4081 participle: if binding.is_import() { "imported" } else { "defined" },
4082 article: binding.res().article(),
4083 shadowed_binding: binding.res(),
4084 shadowed_binding_span: binding.span,
4085 },
4086 );
4087 None
4088 }
4089 Res::Def(DefKind::ConstParam, def_id) => {
4090 self.report_error(
4093 ident.span,
4094 ResolutionError::BindingShadowsSomethingUnacceptable {
4095 shadowing_binding: pat_src,
4096 name: ident.name,
4097 participle: "defined",
4098 article: res.article(),
4099 shadowed_binding: res,
4100 shadowed_binding_span: self.r.def_span(def_id),
4101 }
4102 );
4103 None
4104 }
4105 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4106 None
4108 }
4109 Res::SelfCtor(_) => {
4110 self.r.dcx().span_delayed_bug(
4113 ident.span,
4114 "unexpected `SelfCtor` in pattern, expected identifier"
4115 );
4116 None
4117 }
4118 _ => span_bug!(
4119 ident.span,
4120 "unexpected resolution for an identifier in pattern: {:?}",
4121 res,
4122 ),
4123 }
4124 }
4125
4126 fn smart_resolve_path(
4132 &mut self,
4133 id: NodeId,
4134 qself: &Option<P<QSelf>>,
4135 path: &Path,
4136 source: PathSource<'ast>,
4137 ) {
4138 self.smart_resolve_path_fragment(
4139 qself,
4140 &Segment::from_path(path),
4141 source,
4142 Finalize::new(id, path.span),
4143 RecordPartialRes::Yes,
4144 None,
4145 );
4146 }
4147
4148 #[instrument(level = "debug", skip(self))]
4149 fn smart_resolve_path_fragment(
4150 &mut self,
4151 qself: &Option<P<QSelf>>,
4152 path: &[Segment],
4153 source: PathSource<'ast>,
4154 finalize: Finalize,
4155 record_partial_res: RecordPartialRes,
4156 parent_qself: Option<&QSelf>,
4157 ) -> PartialRes {
4158 let ns = source.namespace();
4159
4160 let Finalize { node_id, path_span, .. } = finalize;
4161 let report_errors = |this: &mut Self, res: Option<Res>| {
4162 if this.should_report_errs() {
4163 let (err, candidates) = this.smart_resolve_report_errors(
4164 path,
4165 None,
4166 path_span,
4167 source,
4168 res,
4169 parent_qself,
4170 );
4171
4172 let def_id = this.parent_scope.module.nearest_parent_mod();
4173 let instead = res.is_some();
4174 let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4175 && path[0].ident.span.lo() == end.span.lo()
4176 && !matches!(start.kind, ExprKind::Lit(_))
4177 {
4178 let mut sugg = ".";
4179 let mut span = start.span.between(end.span);
4180 if span.lo() + BytePos(2) == span.hi() {
4181 span = span.with_lo(span.lo() + BytePos(1));
4184 sugg = "";
4185 }
4186 Some((
4187 span,
4188 "you might have meant to write `.` instead of `..`",
4189 sugg.to_string(),
4190 Applicability::MaybeIncorrect,
4191 ))
4192 } else if res.is_none()
4193 && let PathSource::Type
4194 | PathSource::Expr(_)
4195 | PathSource::PreciseCapturingArg(..) = source
4196 {
4197 this.suggest_adding_generic_parameter(path, source)
4198 } else {
4199 None
4200 };
4201
4202 let ue = UseError {
4203 err,
4204 candidates,
4205 def_id,
4206 instead,
4207 suggestion,
4208 path: path.into(),
4209 is_call: source.is_call(),
4210 };
4211
4212 this.r.use_injections.push(ue);
4213 }
4214
4215 PartialRes::new(Res::Err)
4216 };
4217
4218 let report_errors_for_call =
4224 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4225 let (following_seg, prefix_path) = match path.split_last() {
4229 Some((last, path)) if !path.is_empty() => (Some(last), path),
4230 _ => return Some(parent_err),
4231 };
4232
4233 let (mut err, candidates) = this.smart_resolve_report_errors(
4234 prefix_path,
4235 following_seg,
4236 path_span,
4237 PathSource::Type,
4238 None,
4239 parent_qself,
4240 );
4241
4242 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4257
4258 err.messages = take(&mut parent_err.messages);
4260 err.code = take(&mut parent_err.code);
4261 swap(&mut err.span, &mut parent_err.span);
4262 err.children = take(&mut parent_err.children);
4263 err.sort_span = parent_err.sort_span;
4264 err.is_lint = parent_err.is_lint.clone();
4265
4266 match &mut err.suggestions {
4268 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4269 Suggestions::Enabled(parent_suggestions) => {
4270 typo_suggestions.append(parent_suggestions)
4272 }
4273 Suggestions::Sealed(_) | Suggestions::Disabled => {
4274 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4279 }
4280 },
4281 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4282 }
4283
4284 parent_err.cancel();
4285
4286 let def_id = this.parent_scope.module.nearest_parent_mod();
4287
4288 if this.should_report_errs() {
4289 if candidates.is_empty() {
4290 if path.len() == 2
4291 && let [segment] = prefix_path
4292 {
4293 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4299 } else {
4300 err.emit();
4305 }
4306 } else {
4307 this.r.use_injections.push(UseError {
4309 err,
4310 candidates,
4311 def_id,
4312 instead: false,
4313 suggestion: None,
4314 path: prefix_path.into(),
4315 is_call: source.is_call(),
4316 });
4317 }
4318 } else {
4319 err.cancel();
4320 }
4321
4322 None
4325 };
4326
4327 let partial_res = match self.resolve_qpath_anywhere(
4328 qself,
4329 path,
4330 ns,
4331 path_span,
4332 source.defer_to_typeck(),
4333 finalize,
4334 ) {
4335 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4336 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4338 && let [Segment { ident, .. }] = path
4339 && items.iter().any(|item| {
4340 item.ident == *ident && matches!(item.kind, AssocItemKind::Type(_))
4341 })
4342 {
4343 let mut diag = self.r.tcx.dcx().struct_allow("");
4344 diag.span_suggestion_verbose(
4345 path_span.shrink_to_lo(),
4346 "there is an associated type with the same name",
4347 "Self::",
4348 Applicability::MaybeIncorrect,
4349 );
4350 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4351 }
4352
4353 if source.is_expected(res) || res == Res::Err {
4354 partial_res
4355 } else {
4356 report_errors(self, Some(res))
4357 }
4358 }
4359
4360 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4361 if ns == ValueNS {
4365 let item_name = path.last().unwrap().ident;
4366 let traits = self.traits_in_scope(item_name, ns);
4367 self.r.trait_map.insert(node_id, traits);
4368 }
4369
4370 if PrimTy::from_name(path[0].ident.name).is_some() {
4371 let mut std_path = Vec::with_capacity(1 + path.len());
4372
4373 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4374 std_path.extend(path);
4375 if let PathResult::Module(_) | PathResult::NonModule(_) =
4376 self.resolve_path(&std_path, Some(ns), None)
4377 {
4378 let item_span =
4380 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4381
4382 self.r.confused_type_with_std_module.insert(item_span, path_span);
4383 self.r.confused_type_with_std_module.insert(path_span, path_span);
4384 }
4385 }
4386
4387 partial_res
4388 }
4389
4390 Err(err) => {
4391 if let Some(err) = report_errors_for_call(self, err) {
4392 self.report_error(err.span, err.node);
4393 }
4394
4395 PartialRes::new(Res::Err)
4396 }
4397
4398 _ => report_errors(self, None),
4399 };
4400
4401 if record_partial_res == RecordPartialRes::Yes {
4402 self.r.record_partial_res(node_id, partial_res);
4404 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4405 self.lint_unused_qualifications(path, ns, finalize);
4406 }
4407
4408 partial_res
4409 }
4410
4411 fn self_type_is_available(&mut self) -> bool {
4412 let binding = self
4413 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4414 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4415 }
4416
4417 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4418 let ident = Ident::new(kw::SelfLower, self_span);
4419 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4420 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4421 }
4422
4423 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4427 if self.should_report_errs() {
4428 self.r.report_error(span, resolution_error);
4429 }
4430 }
4431
4432 #[inline]
4433 fn should_report_errs(&self) -> bool {
4437 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4438 && !self.r.glob_error.is_some()
4439 }
4440
4441 fn resolve_qpath_anywhere(
4443 &mut self,
4444 qself: &Option<P<QSelf>>,
4445 path: &[Segment],
4446 primary_ns: Namespace,
4447 span: Span,
4448 defer_to_typeck: bool,
4449 finalize: Finalize,
4450 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4451 let mut fin_res = None;
4452
4453 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4454 if i == 0 || ns != primary_ns {
4455 match self.resolve_qpath(qself, path, ns, finalize)? {
4456 Some(partial_res)
4457 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4458 {
4459 return Ok(Some(partial_res));
4460 }
4461 partial_res => {
4462 if fin_res.is_none() {
4463 fin_res = partial_res;
4464 }
4465 }
4466 }
4467 }
4468 }
4469
4470 assert!(primary_ns != MacroNS);
4471
4472 if qself.is_none() {
4473 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
4474 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
4475 if let Ok((_, res)) =
4476 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false, None)
4477 {
4478 return Ok(Some(PartialRes::new(res)));
4479 }
4480 }
4481
4482 Ok(fin_res)
4483 }
4484
4485 fn resolve_qpath(
4487 &mut self,
4488 qself: &Option<P<QSelf>>,
4489 path: &[Segment],
4490 ns: Namespace,
4491 finalize: Finalize,
4492 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4493 debug!(
4494 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4495 qself, path, ns, finalize,
4496 );
4497
4498 if let Some(qself) = qself {
4499 if qself.position == 0 {
4500 return Ok(Some(PartialRes::with_unresolved_segments(
4504 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4505 path.len(),
4506 )));
4507 }
4508
4509 let num_privacy_errors = self.r.privacy_errors.len();
4510 let trait_res = self.smart_resolve_path_fragment(
4512 &None,
4513 &path[..qself.position],
4514 PathSource::Trait(AliasPossibility::No),
4515 Finalize::new(finalize.node_id, qself.path_span),
4516 RecordPartialRes::No,
4517 Some(&qself),
4518 );
4519
4520 if trait_res.expect_full_res() == Res::Err {
4521 return Ok(Some(trait_res));
4522 }
4523
4524 self.r.privacy_errors.truncate(num_privacy_errors);
4527
4528 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4536 let partial_res = self.smart_resolve_path_fragment(
4537 &None,
4538 &path[..=qself.position],
4539 PathSource::TraitItem(ns),
4540 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4541 RecordPartialRes::No,
4542 Some(&qself),
4543 );
4544
4545 return Ok(Some(PartialRes::with_unresolved_segments(
4549 partial_res.base_res(),
4550 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4551 )));
4552 }
4553
4554 let result = match self.resolve_path(path, Some(ns), Some(finalize)) {
4555 PathResult::NonModule(path_res) => path_res,
4556 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4557 PartialRes::new(module.res().unwrap())
4558 }
4559 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4563 PartialRes::new(Res::Err)
4564 }
4565 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4578 if (ns == TypeNS || path.len() > 1)
4579 && PrimTy::from_name(path[0].ident.name).is_some() =>
4580 {
4581 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4582 let tcx = self.r.tcx();
4583
4584 let gate_err_sym_msg = match prim {
4585 PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4586 Some((sym::f16, "the type `f16` is unstable"))
4587 }
4588 PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4589 Some((sym::f128, "the type `f128` is unstable"))
4590 }
4591 _ => None,
4592 };
4593
4594 if let Some((sym, msg)) = gate_err_sym_msg {
4595 let span = path[0].ident.span;
4596 if !span.allows_unstable(sym) {
4597 feature_err(tcx.sess, sym, span, msg).emit();
4598 }
4599 };
4600
4601 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4602 }
4603 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4604 PartialRes::new(module.res().unwrap())
4605 }
4606 PathResult::Failed {
4607 is_error_from_last_segment: false,
4608 span,
4609 label,
4610 suggestion,
4611 module,
4612 segment_name,
4613 error_implied_by_parse_error: _,
4614 } => {
4615 return Err(respan(
4616 span,
4617 ResolutionError::FailedToResolve {
4618 segment: Some(segment_name),
4619 label,
4620 suggestion,
4621 module,
4622 },
4623 ));
4624 }
4625 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4626 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4627 };
4628
4629 Ok(Some(result))
4630 }
4631
4632 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4633 if let Some(label) = label {
4634 if label.ident.as_str().as_bytes()[1] != b'_' {
4635 self.diag_metadata.unused_labels.insert(id, label.ident.span);
4636 }
4637
4638 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4639 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4640 }
4641
4642 self.with_label_rib(RibKind::Normal, |this| {
4643 let ident = label.ident.normalize_to_macro_rules();
4644 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4645 f(this);
4646 });
4647 } else {
4648 f(self);
4649 }
4650 }
4651
4652 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4653 self.with_resolved_label(label, id, |this| this.visit_block(block));
4654 }
4655
4656 fn resolve_block(&mut self, block: &'ast Block) {
4657 debug!("(resolving block) entering block");
4658 let orig_module = self.parent_scope.module;
4660 let anonymous_module = self.r.block_map.get(&block.id).cloned(); let mut num_macro_definition_ribs = 0;
4663 if let Some(anonymous_module) = anonymous_module {
4664 debug!("(resolving block) found anonymous module, moving down");
4665 self.ribs[ValueNS].push(Rib::new(RibKind::Module(anonymous_module)));
4666 self.ribs[TypeNS].push(Rib::new(RibKind::Module(anonymous_module)));
4667 self.parent_scope.module = anonymous_module;
4668 } else {
4669 self.ribs[ValueNS].push(Rib::new(RibKind::Normal));
4670 }
4671
4672 for stmt in &block.stmts {
4674 if let StmtKind::Item(ref item) = stmt.kind
4675 && let ItemKind::MacroDef(..) = item.kind
4676 {
4677 num_macro_definition_ribs += 1;
4678 let res = self.r.local_def_id(item.id).to_def_id();
4679 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4680 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4681 }
4682
4683 self.visit_stmt(stmt);
4684 }
4685
4686 self.parent_scope.module = orig_module;
4688 for _ in 0..num_macro_definition_ribs {
4689 self.ribs[ValueNS].pop();
4690 self.label_ribs.pop();
4691 }
4692 self.last_block_rib = self.ribs[ValueNS].pop();
4693 if anonymous_module.is_some() {
4694 self.ribs[TypeNS].pop();
4695 }
4696 debug!("(resolving block) leaving block");
4697 }
4698
4699 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4700 debug!(
4701 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4702 constant, anon_const_kind
4703 );
4704
4705 let is_trivial_const_arg = constant
4706 .value
4707 .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4708 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4709 this.resolve_expr(&constant.value, None)
4710 })
4711 }
4712
4713 fn resolve_anon_const_manual(
4720 &mut self,
4721 is_trivial_const_arg: bool,
4722 anon_const_kind: AnonConstKind,
4723 resolve_expr: impl FnOnce(&mut Self),
4724 ) {
4725 let is_repeat_expr = match anon_const_kind {
4726 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4727 _ => IsRepeatExpr::No,
4728 };
4729
4730 let may_use_generics = match anon_const_kind {
4731 AnonConstKind::EnumDiscriminant => {
4732 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4733 }
4734 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4735 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4736 AnonConstKind::ConstArg(_) => {
4737 if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4738 ConstantHasGenerics::Yes
4739 } else {
4740 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4741 }
4742 }
4743 };
4744
4745 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4746 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4747 resolve_expr(this);
4748 });
4749 });
4750 }
4751
4752 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4753 self.resolve_expr(&f.expr, Some(e));
4754 self.visit_ident(&f.ident);
4755 walk_list!(self, visit_attribute, f.attrs.iter());
4756 }
4757
4758 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4759 self.record_candidate_traits_for_expr_if_necessary(expr);
4763
4764 match expr.kind {
4766 ExprKind::Path(ref qself, ref path) => {
4767 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4768 visit::walk_expr(self, expr);
4769 }
4770
4771 ExprKind::Struct(ref se) => {
4772 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct);
4773 if let Some(qself) = &se.qself {
4777 self.visit_ty(&qself.ty);
4778 }
4779 self.visit_path(&se.path, expr.id);
4780 walk_list!(self, resolve_expr_field, &se.fields, expr);
4781 match &se.rest {
4782 StructRest::Base(expr) => self.visit_expr(expr),
4783 StructRest::Rest(_span) => {}
4784 StructRest::None => {}
4785 }
4786 }
4787
4788 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4789 match self.resolve_label(label.ident) {
4790 Ok((node_id, _)) => {
4791 self.r.label_res_map.insert(expr.id, node_id);
4793 self.diag_metadata.unused_labels.swap_remove(&node_id);
4794 }
4795 Err(error) => {
4796 self.report_error(label.ident.span, error);
4797 }
4798 }
4799
4800 visit::walk_expr(self, expr);
4802 }
4803
4804 ExprKind::Break(None, Some(ref e)) => {
4805 self.resolve_expr(e, Some(expr));
4808 }
4809
4810 ExprKind::Let(ref pat, ref scrutinee, _, _) => {
4811 self.visit_expr(scrutinee);
4812 self.resolve_pattern_top(pat, PatternSource::Let);
4813 }
4814
4815 ExprKind::If(ref cond, ref then, ref opt_else) => {
4816 self.with_rib(ValueNS, RibKind::Normal, |this| {
4817 let old = this.diag_metadata.in_if_condition.replace(cond);
4818 this.visit_expr(cond);
4819 this.diag_metadata.in_if_condition = old;
4820 this.visit_block(then);
4821 });
4822 if let Some(expr) = opt_else {
4823 self.visit_expr(expr);
4824 }
4825 }
4826
4827 ExprKind::Loop(ref block, label, _) => {
4828 self.resolve_labeled_block(label, expr.id, block)
4829 }
4830
4831 ExprKind::While(ref cond, ref block, label) => {
4832 self.with_resolved_label(label, expr.id, |this| {
4833 this.with_rib(ValueNS, RibKind::Normal, |this| {
4834 let old = this.diag_metadata.in_if_condition.replace(cond);
4835 this.visit_expr(cond);
4836 this.diag_metadata.in_if_condition = old;
4837 this.visit_block(block);
4838 })
4839 });
4840 }
4841
4842 ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4843 self.visit_expr(iter);
4844 self.with_rib(ValueNS, RibKind::Normal, |this| {
4845 this.resolve_pattern_top(pat, PatternSource::For);
4846 this.resolve_labeled_block(label, expr.id, body);
4847 });
4848 }
4849
4850 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4851
4852 ExprKind::Field(ref subexpression, _) => {
4854 self.resolve_expr(subexpression, Some(expr));
4855 }
4856 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
4857 self.resolve_expr(receiver, Some(expr));
4858 for arg in args {
4859 self.resolve_expr(arg, None);
4860 }
4861 self.visit_path_segment(seg);
4862 }
4863
4864 ExprKind::Call(ref callee, ref arguments) => {
4865 self.resolve_expr(callee, Some(expr));
4866 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
4867 for (idx, argument) in arguments.iter().enumerate() {
4868 if const_args.contains(&idx) {
4871 let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
4872 self.r.tcx.features().min_generic_const_args(),
4873 );
4874 self.resolve_anon_const_manual(
4875 is_trivial_const_arg,
4876 AnonConstKind::ConstArg(IsRepeatExpr::No),
4877 |this| this.resolve_expr(argument, None),
4878 );
4879 } else {
4880 self.resolve_expr(argument, None);
4881 }
4882 }
4883 }
4884 ExprKind::Type(ref _type_expr, ref _ty) => {
4885 visit::walk_expr(self, expr);
4886 }
4887 ExprKind::Closure(box ast::Closure {
4889 binder: ClosureBinder::For { ref generic_params, span },
4890 ..
4891 }) => {
4892 self.with_generic_param_rib(
4893 generic_params,
4894 RibKind::Normal,
4895 LifetimeRibKind::Generics {
4896 binder: expr.id,
4897 kind: LifetimeBinderKind::Closure,
4898 span,
4899 },
4900 |this| visit::walk_expr(this, expr),
4901 );
4902 }
4903 ExprKind::Closure(..) => visit::walk_expr(self, expr),
4904 ExprKind::Gen(..) => {
4905 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
4906 }
4907 ExprKind::Repeat(ref elem, ref ct) => {
4908 self.visit_expr(elem);
4909 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
4910 }
4911 ExprKind::ConstBlock(ref ct) => {
4912 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
4913 }
4914 ExprKind::Index(ref elem, ref idx, _) => {
4915 self.resolve_expr(elem, Some(expr));
4916 self.visit_expr(idx);
4917 }
4918 ExprKind::Assign(ref lhs, ref rhs, _) => {
4919 if !self.diag_metadata.is_assign_rhs {
4920 self.diag_metadata.in_assignment = Some(expr);
4921 }
4922 self.visit_expr(lhs);
4923 self.diag_metadata.is_assign_rhs = true;
4924 self.diag_metadata.in_assignment = None;
4925 self.visit_expr(rhs);
4926 self.diag_metadata.is_assign_rhs = false;
4927 }
4928 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
4929 self.diag_metadata.in_range = Some((start, end));
4930 self.resolve_expr(start, Some(expr));
4931 self.resolve_expr(end, Some(expr));
4932 self.diag_metadata.in_range = None;
4933 }
4934 _ => {
4935 visit::walk_expr(self, expr);
4936 }
4937 }
4938 }
4939
4940 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
4941 match expr.kind {
4942 ExprKind::Field(_, ident) => {
4943 let traits = self.traits_in_scope(ident, ValueNS);
4948 self.r.trait_map.insert(expr.id, traits);
4949 }
4950 ExprKind::MethodCall(ref call) => {
4951 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
4952 let traits = self.traits_in_scope(call.seg.ident, ValueNS);
4953 self.r.trait_map.insert(expr.id, traits);
4954 }
4955 _ => {
4956 }
4958 }
4959 }
4960
4961 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
4962 self.r.traits_in_scope(
4963 self.current_trait_ref.as_ref().map(|(module, _)| *module),
4964 &self.parent_scope,
4965 ident.span.ctxt(),
4966 Some((ident.name, ns)),
4967 )
4968 }
4969
4970 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
4971 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
4975 let res = *doc_link_resolutions
4976 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
4977 .or_default()
4978 .entry((Symbol::intern(path_str), ns))
4979 .or_insert_with_key(|(path, ns)| {
4980 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
4981 if let Some(res) = res
4982 && let Some(def_id) = res.opt_def_id()
4983 && self.is_invalid_proc_macro_item_for_doc(def_id)
4984 {
4985 return None;
4988 }
4989 res
4990 });
4991 self.r.doc_link_resolutions = doc_link_resolutions;
4992 res
4993 }
4994
4995 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
4996 if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
4997 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
4998 {
4999 return false;
5000 }
5001 let Some(local_did) = did.as_local() else { return true };
5002 let Some(node_id) = self.r.def_id_to_node_id.get(local_did) else { return true };
5003 !self.r.proc_macros.contains(node_id)
5004 }
5005
5006 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5007 match self.r.tcx.sess.opts.resolve_doc_links {
5008 ResolveDocLinks::None => return,
5009 ResolveDocLinks::ExportedMetadata
5010 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5011 || !maybe_exported.eval(self.r) =>
5012 {
5013 return;
5014 }
5015 ResolveDocLinks::Exported
5016 if !maybe_exported.eval(self.r)
5017 && !rustdoc::has_primitive_or_keyword_docs(attrs) =>
5018 {
5019 return;
5020 }
5021 ResolveDocLinks::ExportedMetadata
5022 | ResolveDocLinks::Exported
5023 | ResolveDocLinks::All => {}
5024 }
5025
5026 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5027 return;
5028 }
5029
5030 let mut need_traits_in_scope = false;
5031 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5032 let mut any_resolved = false;
5034 let mut need_assoc = false;
5035 for ns in [TypeNS, ValueNS, MacroNS] {
5036 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5037 any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5040 } else if ns != MacroNS {
5041 need_assoc = true;
5042 }
5043 }
5044
5045 if need_assoc || !any_resolved {
5047 let mut path = &path_str[..];
5048 while let Some(idx) = path.rfind("::") {
5049 path = &path[..idx];
5050 need_traits_in_scope = true;
5051 for ns in [TypeNS, ValueNS, MacroNS] {
5052 self.resolve_and_cache_rustdoc_path(path, ns);
5053 }
5054 }
5055 }
5056 }
5057
5058 if need_traits_in_scope {
5059 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5061 doc_link_traits_in_scope
5062 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5063 .or_insert_with(|| {
5064 self.r
5065 .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5066 .into_iter()
5067 .filter_map(|tr| {
5068 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5069 return None;
5072 }
5073 Some(tr.def_id)
5074 })
5075 .collect()
5076 });
5077 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5078 }
5079 }
5080
5081 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5082 if let Some(seg) = path.first()
5084 && seg.ident.name == kw::PathRoot
5085 {
5086 return;
5087 }
5088
5089 if finalize.path_span.from_expansion()
5090 || path.iter().any(|seg| seg.ident.span.from_expansion())
5091 {
5092 return;
5093 }
5094
5095 let end_pos =
5096 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5097 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5098 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5107 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5108 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5109 (res == binding.res()).then_some((seg, binding))
5110 });
5111
5112 if let Some((seg, binding)) = unqualified {
5113 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5114 binding,
5115 node_id: finalize.node_id,
5116 path_span: finalize.path_span,
5117 removal_span: path[0].ident.span.until(seg.ident.span),
5118 });
5119 }
5120 }
5121
5122 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5123 if let Some(define_opaque) = define_opaque {
5124 for (id, path) in define_opaque {
5125 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5126 }
5127 }
5128 }
5129}
5130
5131struct ItemInfoCollector<'a, 'ra, 'tcx> {
5134 r: &'a mut Resolver<'ra, 'tcx>,
5135}
5136
5137impl ItemInfoCollector<'_, '_, '_> {
5138 fn collect_fn_info(
5139 &mut self,
5140 header: FnHeader,
5141 decl: &FnDecl,
5142 id: NodeId,
5143 attrs: &[Attribute],
5144 ) {
5145 let sig = DelegationFnSig {
5146 header,
5147 param_count: decl.inputs.len(),
5148 has_self: decl.has_self(),
5149 c_variadic: decl.c_variadic(),
5150 target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5151 };
5152 self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5153 }
5154}
5155
5156impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5157 fn visit_item(&mut self, item: &'ast Item) {
5158 match &item.kind {
5159 ItemKind::TyAlias(box TyAlias { generics, .. })
5160 | ItemKind::Const(box ConstItem { generics, .. })
5161 | ItemKind::Fn(box Fn { generics, .. })
5162 | ItemKind::Enum(_, generics)
5163 | ItemKind::Struct(_, generics)
5164 | ItemKind::Union(_, generics)
5165 | ItemKind::Impl(box Impl { generics, .. })
5166 | ItemKind::Trait(box Trait { generics, .. })
5167 | ItemKind::TraitAlias(generics, _) => {
5168 if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5169 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5170 }
5171
5172 let def_id = self.r.local_def_id(item.id);
5173 let count = generics
5174 .params
5175 .iter()
5176 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5177 .count();
5178 self.r.item_generics_num_lifetimes.insert(def_id, count);
5179 }
5180
5181 ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5182 for foreign_item in items {
5183 if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5184 let new_header =
5185 FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5186 self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5187 }
5188 }
5189 }
5190
5191 ItemKind::Mod(..)
5192 | ItemKind::Static(..)
5193 | ItemKind::Use(..)
5194 | ItemKind::ExternCrate(..)
5195 | ItemKind::MacroDef(..)
5196 | ItemKind::GlobalAsm(..)
5197 | ItemKind::MacCall(..)
5198 | ItemKind::DelegationMac(..) => {}
5199 ItemKind::Delegation(..) => {
5200 }
5205 }
5206 visit::walk_item(self, item)
5207 }
5208
5209 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5210 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5211 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5212 }
5213 visit::walk_assoc_item(self, item, ctxt);
5214 }
5215}
5216
5217impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5218 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5219 visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5220 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5221 late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5222 visit::walk_crate(&mut late_resolution_visitor, krate);
5223 for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5224 self.lint_buffer.buffer_lint(
5225 lint::builtin::UNUSED_LABELS,
5226 *id,
5227 *span,
5228 BuiltinLintDiag::UnusedLabel,
5229 );
5230 }
5231 }
5232}
5233
5234fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5236 let mut path = expected_path.iter().rev();
5237 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5238 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5239 return false;
5240 }
5241 def_id = parent;
5242 }
5243 true
5244}