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::Or(patterns) => {
962 for pat in patterns {
963 self.visit_ty_pat(pat)
964 }
965 }
966 TyPatKind::Err(_) => {}
967 }
968 }
969
970 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
971 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
972 self.with_generic_param_rib(
973 &tref.bound_generic_params,
974 RibKind::Normal,
975 LifetimeRibKind::Generics {
976 binder: tref.trait_ref.ref_id,
977 kind: LifetimeBinderKind::PolyTrait,
978 span,
979 },
980 |this| {
981 this.visit_generic_params(&tref.bound_generic_params, false);
982 this.smart_resolve_path(
983 tref.trait_ref.ref_id,
984 &None,
985 &tref.trait_ref.path,
986 PathSource::Trait(AliasPossibility::Maybe),
987 );
988 this.visit_trait_ref(&tref.trait_ref);
989 },
990 );
991 }
992 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
993 self.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
994 let def_kind = self.r.local_def_kind(foreign_item.id);
995 match foreign_item.kind {
996 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
997 self.with_generic_param_rib(
998 &generics.params,
999 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1000 LifetimeRibKind::Generics {
1001 binder: foreign_item.id,
1002 kind: LifetimeBinderKind::Item,
1003 span: generics.span,
1004 },
1005 |this| visit::walk_item(this, foreign_item),
1006 );
1007 }
1008 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
1009 self.with_generic_param_rib(
1010 &generics.params,
1011 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1012 LifetimeRibKind::Generics {
1013 binder: foreign_item.id,
1014 kind: LifetimeBinderKind::Function,
1015 span: generics.span,
1016 },
1017 |this| visit::walk_item(this, foreign_item),
1018 );
1019 }
1020 ForeignItemKind::Static(..) => {
1021 self.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1022 }
1023 ForeignItemKind::MacCall(..) => {
1024 panic!("unexpanded macro in resolve!")
1025 }
1026 }
1027 }
1028 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
1029 let previous_value = self.diag_metadata.current_function;
1030 match fn_kind {
1031 FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1034 | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1035 self.visit_fn_header(&sig.header);
1036 self.visit_ident(ident);
1037 self.visit_generics(generics);
1038 self.with_lifetime_rib(
1039 LifetimeRibKind::AnonymousCreateParameter {
1040 binder: fn_id,
1041 report_in_path: false,
1042 },
1043 |this| {
1044 this.resolve_fn_signature(
1045 fn_id,
1046 sig.decl.has_self(),
1047 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1048 &sig.decl.output,
1049 );
1050 },
1051 );
1052 return;
1053 }
1054 FnKind::Fn(..) => {
1055 self.diag_metadata.current_function = Some((fn_kind, sp));
1056 }
1057 FnKind::Closure(..) => {}
1059 };
1060 debug!("(resolving function) entering function");
1061
1062 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1064 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1066 match fn_kind {
1067 FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1068 this.visit_generics(generics);
1069
1070 let declaration = &sig.decl;
1071 let coro_node_id = sig
1072 .header
1073 .coroutine_kind
1074 .map(|coroutine_kind| coroutine_kind.return_id());
1075
1076 this.with_lifetime_rib(
1077 LifetimeRibKind::AnonymousCreateParameter {
1078 binder: fn_id,
1079 report_in_path: coro_node_id.is_some(),
1080 },
1081 |this| {
1082 this.resolve_fn_signature(
1083 fn_id,
1084 declaration.has_self(),
1085 declaration
1086 .inputs
1087 .iter()
1088 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1089 &declaration.output,
1090 );
1091 },
1092 );
1093
1094 if let Some(contract) = contract {
1095 this.visit_contract(contract);
1096 }
1097
1098 if let Some(body) = body {
1099 let previous_state = replace(&mut this.in_func_body, true);
1102 this.last_block_rib = None;
1104 this.with_lifetime_rib(
1106 LifetimeRibKind::Elided(LifetimeRes::Infer),
1107 |this| this.visit_block(body),
1108 );
1109
1110 debug!("(resolving function) leaving function");
1111 this.in_func_body = previous_state;
1112 }
1113 }
1114 FnKind::Closure(binder, _, declaration, body) => {
1115 this.visit_closure_binder(binder);
1116
1117 this.with_lifetime_rib(
1118 match binder {
1119 ClosureBinder::NotPresent => {
1121 LifetimeRibKind::AnonymousCreateParameter {
1122 binder: fn_id,
1123 report_in_path: false,
1124 }
1125 }
1126 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1127 },
1128 |this| this.resolve_params(&declaration.inputs),
1130 );
1131 this.with_lifetime_rib(
1132 match binder {
1133 ClosureBinder::NotPresent => {
1134 LifetimeRibKind::Elided(LifetimeRes::Infer)
1135 }
1136 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1137 },
1138 |this| visit::walk_fn_ret_ty(this, &declaration.output),
1139 );
1140
1141 let previous_state = replace(&mut this.in_func_body, true);
1144 this.with_lifetime_rib(
1146 LifetimeRibKind::Elided(LifetimeRes::Infer),
1147 |this| this.visit_expr(body),
1148 );
1149
1150 debug!("(resolving function) leaving function");
1151 this.in_func_body = previous_state;
1152 }
1153 }
1154 })
1155 });
1156 self.diag_metadata.current_function = previous_value;
1157 }
1158
1159 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1160 self.resolve_lifetime(lifetime, use_ctxt)
1161 }
1162
1163 fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1164 match arg {
1165 PreciseCapturingArg::Lifetime(_) => {}
1168
1169 PreciseCapturingArg::Arg(path, id) => {
1170 let mut check_ns = |ns| {
1177 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1178 };
1179 if !check_ns(TypeNS) && check_ns(ValueNS) {
1181 self.smart_resolve_path(
1182 *id,
1183 &None,
1184 path,
1185 PathSource::PreciseCapturingArg(ValueNS),
1186 );
1187 } else {
1188 self.smart_resolve_path(
1189 *id,
1190 &None,
1191 path,
1192 PathSource::PreciseCapturingArg(TypeNS),
1193 );
1194 }
1195 }
1196 }
1197
1198 visit::walk_precise_capturing_arg(self, arg)
1199 }
1200
1201 fn visit_generics(&mut self, generics: &'ast Generics) {
1202 self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1203 for p in &generics.where_clause.predicates {
1204 self.visit_where_predicate(p);
1205 }
1206 }
1207
1208 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1209 match b {
1210 ClosureBinder::NotPresent => {}
1211 ClosureBinder::For { generic_params, .. } => {
1212 self.visit_generic_params(
1213 generic_params,
1214 self.diag_metadata.current_self_item.is_some(),
1215 );
1216 }
1217 }
1218 }
1219
1220 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1221 debug!("visit_generic_arg({:?})", arg);
1222 let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1223 match arg {
1224 GenericArg::Type(ty) => {
1225 if let TyKind::Path(None, ref path) = ty.kind
1231 && path.is_potential_trivial_const_arg(false)
1234 {
1235 let mut check_ns = |ns| {
1236 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1237 .is_some()
1238 };
1239 if !check_ns(TypeNS) && check_ns(ValueNS) {
1240 self.resolve_anon_const_manual(
1241 true,
1242 AnonConstKind::ConstArg(IsRepeatExpr::No),
1243 |this| {
1244 this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1245 this.visit_path(path, ty.id);
1246 },
1247 );
1248
1249 self.diag_metadata.currently_processing_generic_args = prev;
1250 return;
1251 }
1252 }
1253
1254 self.visit_ty(ty);
1255 }
1256 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1257 GenericArg::Const(ct) => {
1258 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1259 }
1260 }
1261 self.diag_metadata.currently_processing_generic_args = prev;
1262 }
1263
1264 fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1265 self.visit_ident(&constraint.ident);
1266 if let Some(ref gen_args) = constraint.gen_args {
1267 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1269 this.visit_generic_args(gen_args)
1270 });
1271 }
1272 match constraint.kind {
1273 AssocItemConstraintKind::Equality { ref term } => match term {
1274 Term::Ty(ty) => self.visit_ty(ty),
1275 Term::Const(c) => {
1276 self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1277 }
1278 },
1279 AssocItemConstraintKind::Bound { ref bounds } => {
1280 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1281 }
1282 }
1283 }
1284
1285 fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1286 let Some(ref args) = path_segment.args else {
1287 return;
1288 };
1289
1290 match &**args {
1291 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1292 GenericArgs::Parenthesized(p_args) => {
1293 for rib in self.lifetime_ribs.iter().rev() {
1295 match rib.kind {
1296 LifetimeRibKind::Generics {
1299 binder,
1300 kind: LifetimeBinderKind::PolyTrait,
1301 ..
1302 } => {
1303 self.with_lifetime_rib(
1304 LifetimeRibKind::AnonymousCreateParameter {
1305 binder,
1306 report_in_path: false,
1307 },
1308 |this| {
1309 this.resolve_fn_signature(
1310 binder,
1311 false,
1312 p_args.inputs.iter().map(|ty| (None, &**ty)),
1313 &p_args.output,
1314 )
1315 },
1316 );
1317 break;
1318 }
1319 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1322 visit::walk_generic_args(self, args);
1323 break;
1324 }
1325 LifetimeRibKind::AnonymousCreateParameter { .. }
1326 | LifetimeRibKind::AnonymousReportError
1327 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1328 | LifetimeRibKind::Elided(_)
1329 | LifetimeRibKind::ElisionFailure
1330 | LifetimeRibKind::ConcreteAnonConst(_)
1331 | LifetimeRibKind::ConstParamTy => {}
1332 }
1333 }
1334 }
1335 GenericArgs::ParenthesizedElided(_) => {}
1336 }
1337 }
1338
1339 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1340 debug!("visit_where_predicate {:?}", p);
1341 let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1342 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1343 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1344 bounded_ty,
1345 bounds,
1346 bound_generic_params,
1347 ..
1348 }) = &p.kind
1349 {
1350 let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1351 this.with_generic_param_rib(
1352 bound_generic_params,
1353 RibKind::Normal,
1354 LifetimeRibKind::Generics {
1355 binder: bounded_ty.id,
1356 kind: LifetimeBinderKind::WhereBound,
1357 span,
1358 },
1359 |this| {
1360 this.visit_generic_params(bound_generic_params, false);
1361 this.visit_ty(bounded_ty);
1362 for bound in bounds {
1363 this.visit_param_bound(bound, BoundKind::Bound)
1364 }
1365 },
1366 );
1367 } else {
1368 visit::walk_where_predicate(this, p);
1369 }
1370 });
1371 self.diag_metadata.current_where_predicate = previous_value;
1372 }
1373
1374 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1375 for (op, _) in &asm.operands {
1376 match op {
1377 InlineAsmOperand::In { expr, .. }
1378 | InlineAsmOperand::Out { expr: Some(expr), .. }
1379 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1380 InlineAsmOperand::Out { expr: None, .. } => {}
1381 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1382 self.visit_expr(in_expr);
1383 if let Some(out_expr) = out_expr {
1384 self.visit_expr(out_expr);
1385 }
1386 }
1387 InlineAsmOperand::Const { anon_const, .. } => {
1388 self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1391 }
1392 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1393 InlineAsmOperand::Label { block } => self.visit_block(block),
1394 }
1395 }
1396 }
1397
1398 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1399 self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1401 this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1402 this.with_label_rib(RibKind::InlineAsmSym, |this| {
1403 this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1404 visit::walk_inline_asm_sym(this, sym);
1405 });
1406 })
1407 });
1408 }
1409
1410 fn visit_variant(&mut self, v: &'ast Variant) {
1411 self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1412 visit::walk_variant(self, v)
1413 }
1414
1415 fn visit_variant_discr(&mut self, discr: &'ast AnonConst) {
1416 self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1417 }
1418
1419 fn visit_field_def(&mut self, f: &'ast FieldDef) {
1420 self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1421 let FieldDef {
1422 attrs,
1423 id: _,
1424 span: _,
1425 vis,
1426 ident,
1427 ty,
1428 is_placeholder: _,
1429 default,
1430 safety: _,
1431 } = f;
1432 walk_list!(self, visit_attribute, attrs);
1433 try_visit!(self.visit_vis(vis));
1434 visit_opt!(self, visit_ident, ident);
1435 try_visit!(self.visit_ty(ty));
1436 if let Some(v) = &default {
1437 self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1438 }
1439 }
1440}
1441
1442impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1443 fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1444 let graph_root = resolver.graph_root;
1447 let parent_scope = ParentScope::module(graph_root, resolver);
1448 let start_rib_kind = RibKind::Module(graph_root);
1449 LateResolutionVisitor {
1450 r: resolver,
1451 parent_scope,
1452 ribs: PerNS {
1453 value_ns: vec![Rib::new(start_rib_kind)],
1454 type_ns: vec![Rib::new(start_rib_kind)],
1455 macro_ns: vec![Rib::new(start_rib_kind)],
1456 },
1457 last_block_rib: None,
1458 label_ribs: Vec::new(),
1459 lifetime_ribs: Vec::new(),
1460 lifetime_elision_candidates: None,
1461 current_trait_ref: None,
1462 diag_metadata: Default::default(),
1463 in_func_body: false,
1465 lifetime_uses: Default::default(),
1466 }
1467 }
1468
1469 fn maybe_resolve_ident_in_lexical_scope(
1470 &mut self,
1471 ident: Ident,
1472 ns: Namespace,
1473 ) -> Option<LexicalScopeBinding<'ra>> {
1474 self.r.resolve_ident_in_lexical_scope(
1475 ident,
1476 ns,
1477 &self.parent_scope,
1478 None,
1479 &self.ribs[ns],
1480 None,
1481 )
1482 }
1483
1484 fn resolve_ident_in_lexical_scope(
1485 &mut self,
1486 ident: Ident,
1487 ns: Namespace,
1488 finalize: Option<Finalize>,
1489 ignore_binding: Option<NameBinding<'ra>>,
1490 ) -> Option<LexicalScopeBinding<'ra>> {
1491 self.r.resolve_ident_in_lexical_scope(
1492 ident,
1493 ns,
1494 &self.parent_scope,
1495 finalize,
1496 &self.ribs[ns],
1497 ignore_binding,
1498 )
1499 }
1500
1501 fn resolve_path(
1502 &mut self,
1503 path: &[Segment],
1504 opt_ns: Option<Namespace>, finalize: Option<Finalize>,
1506 ) -> PathResult<'ra> {
1507 self.r.resolve_path_with_ribs(
1508 path,
1509 opt_ns,
1510 &self.parent_scope,
1511 finalize,
1512 Some(&self.ribs),
1513 None,
1514 None,
1515 )
1516 }
1517
1518 fn with_rib<T>(
1538 &mut self,
1539 ns: Namespace,
1540 kind: RibKind<'ra>,
1541 work: impl FnOnce(&mut Self) -> T,
1542 ) -> T {
1543 self.ribs[ns].push(Rib::new(kind));
1544 let ret = work(self);
1545 self.ribs[ns].pop();
1546 ret
1547 }
1548
1549 fn with_mod_rib<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1550 let module = self.r.expect_module(self.r.local_def_id(id).to_def_id());
1551 let orig_module = replace(&mut self.parent_scope.module, module);
1553 self.with_rib(ValueNS, RibKind::Module(module), |this| {
1554 this.with_rib(TypeNS, RibKind::Module(module), |this| {
1555 let ret = f(this);
1556 this.parent_scope.module = orig_module;
1557 ret
1558 })
1559 })
1560 }
1561
1562 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1563 let mut forward_ty_ban_rib =
1569 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1570 let mut forward_const_ban_rib =
1571 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1572 for param in params.iter() {
1573 match param.kind {
1574 GenericParamKind::Type { .. } => {
1575 forward_ty_ban_rib
1576 .bindings
1577 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1578 }
1579 GenericParamKind::Const { .. } => {
1580 forward_const_ban_rib
1581 .bindings
1582 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1583 }
1584 GenericParamKind::Lifetime => {}
1585 }
1586 }
1587
1588 if add_self_upper {
1598 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1600 }
1601
1602 let mut forward_ty_ban_rib_const_param_ty = Rib {
1605 bindings: forward_ty_ban_rib.bindings.clone(),
1606 patterns_with_skipped_bindings: Default::default(),
1607 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1608 };
1609 let mut forward_const_ban_rib_const_param_ty = Rib {
1610 bindings: forward_const_ban_rib.bindings.clone(),
1611 patterns_with_skipped_bindings: Default::default(),
1612 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1613 };
1614 if !self.r.tcx.features().generic_const_parameter_types() {
1617 forward_ty_ban_rib_const_param_ty.bindings.clear();
1618 forward_const_ban_rib_const_param_ty.bindings.clear();
1619 }
1620
1621 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1622 for param in params {
1623 match param.kind {
1624 GenericParamKind::Lifetime => {
1625 for bound in ¶m.bounds {
1626 this.visit_param_bound(bound, BoundKind::Bound);
1627 }
1628 }
1629 GenericParamKind::Type { ref default } => {
1630 for bound in ¶m.bounds {
1631 this.visit_param_bound(bound, BoundKind::Bound);
1632 }
1633
1634 if let Some(ty) = default {
1635 this.ribs[TypeNS].push(forward_ty_ban_rib);
1636 this.ribs[ValueNS].push(forward_const_ban_rib);
1637 this.visit_ty(ty);
1638 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1639 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1640 }
1641
1642 let i = &Ident::with_dummy_span(param.ident.name);
1644 forward_ty_ban_rib.bindings.swap_remove(i);
1645 forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1646 }
1647 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1648 assert!(param.bounds.is_empty());
1650
1651 this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1652 this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1653 if this.r.tcx.features().generic_const_parameter_types() {
1654 this.visit_ty(ty)
1655 } else {
1656 this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1657 this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1658 this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1659 this.visit_ty(ty)
1660 });
1661 this.ribs[TypeNS].pop().unwrap();
1662 this.ribs[ValueNS].pop().unwrap();
1663 }
1664 forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1665 forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1666
1667 if let Some(expr) = default {
1668 this.ribs[TypeNS].push(forward_ty_ban_rib);
1669 this.ribs[ValueNS].push(forward_const_ban_rib);
1670 this.resolve_anon_const(
1671 expr,
1672 AnonConstKind::ConstArg(IsRepeatExpr::No),
1673 );
1674 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1675 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1676 }
1677
1678 let i = &Ident::with_dummy_span(param.ident.name);
1680 forward_const_ban_rib.bindings.swap_remove(i);
1681 forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1682 }
1683 }
1684 }
1685 })
1686 }
1687
1688 #[instrument(level = "debug", skip(self, work))]
1689 fn with_lifetime_rib<T>(
1690 &mut self,
1691 kind: LifetimeRibKind,
1692 work: impl FnOnce(&mut Self) -> T,
1693 ) -> T {
1694 self.lifetime_ribs.push(LifetimeRib::new(kind));
1695 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1696 let ret = work(self);
1697 self.lifetime_elision_candidates = outer_elision_candidates;
1698 self.lifetime_ribs.pop();
1699 ret
1700 }
1701
1702 #[instrument(level = "debug", skip(self))]
1703 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1704 let ident = lifetime.ident;
1705
1706 if ident.name == kw::StaticLifetime {
1707 self.record_lifetime_res(
1708 lifetime.id,
1709 LifetimeRes::Static { suppress_elision_warning: false },
1710 LifetimeElisionCandidate::Named,
1711 );
1712 return;
1713 }
1714
1715 if ident.name == kw::UnderscoreLifetime {
1716 return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1717 }
1718
1719 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1720 while let Some(rib) = lifetime_rib_iter.next() {
1721 let normalized_ident = ident.normalize_to_macros_2_0();
1722 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1723 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1724
1725 if let LifetimeRes::Param { param, binder } = res {
1726 match self.lifetime_uses.entry(param) {
1727 Entry::Vacant(v) => {
1728 debug!("First use of {:?} at {:?}", res, ident.span);
1729 let use_set = self
1730 .lifetime_ribs
1731 .iter()
1732 .rev()
1733 .find_map(|rib| match rib.kind {
1734 LifetimeRibKind::Item
1737 | LifetimeRibKind::AnonymousReportError
1738 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1739 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1740 LifetimeRibKind::AnonymousCreateParameter {
1743 binder: anon_binder,
1744 ..
1745 } => Some(if binder == anon_binder {
1746 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1747 } else {
1748 LifetimeUseSet::Many
1749 }),
1750 LifetimeRibKind::Elided(r) => Some(if res == r {
1753 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1754 } else {
1755 LifetimeUseSet::Many
1756 }),
1757 LifetimeRibKind::Generics { .. }
1758 | LifetimeRibKind::ConstParamTy => None,
1759 LifetimeRibKind::ConcreteAnonConst(_) => {
1760 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1761 }
1762 })
1763 .unwrap_or(LifetimeUseSet::Many);
1764 debug!(?use_ctxt, ?use_set);
1765 v.insert(use_set);
1766 }
1767 Entry::Occupied(mut o) => {
1768 debug!("Many uses of {:?} at {:?}", res, ident.span);
1769 *o.get_mut() = LifetimeUseSet::Many;
1770 }
1771 }
1772 }
1773 return;
1774 }
1775
1776 match rib.kind {
1777 LifetimeRibKind::Item => break,
1778 LifetimeRibKind::ConstParamTy => {
1779 self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1780 self.record_lifetime_res(
1781 lifetime.id,
1782 LifetimeRes::Error,
1783 LifetimeElisionCandidate::Ignore,
1784 );
1785 return;
1786 }
1787 LifetimeRibKind::ConcreteAnonConst(cause) => {
1788 self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1789 self.record_lifetime_res(
1790 lifetime.id,
1791 LifetimeRes::Error,
1792 LifetimeElisionCandidate::Ignore,
1793 );
1794 return;
1795 }
1796 LifetimeRibKind::AnonymousCreateParameter { .. }
1797 | LifetimeRibKind::Elided(_)
1798 | LifetimeRibKind::Generics { .. }
1799 | LifetimeRibKind::ElisionFailure
1800 | LifetimeRibKind::AnonymousReportError
1801 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1802 }
1803 }
1804
1805 let normalized_ident = ident.normalize_to_macros_2_0();
1806 let outer_res = lifetime_rib_iter
1807 .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1808
1809 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1810 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1811 }
1812
1813 #[instrument(level = "debug", skip(self))]
1814 fn resolve_anonymous_lifetime(
1815 &mut self,
1816 lifetime: &Lifetime,
1817 id_for_lint: NodeId,
1818 elided: bool,
1819 ) {
1820 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1821
1822 let kind =
1823 if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1824 let missing_lifetime = MissingLifetime {
1825 id: lifetime.id,
1826 span: lifetime.ident.span,
1827 kind,
1828 count: 1,
1829 id_for_lint,
1830 };
1831 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1832 for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1833 debug!(?rib.kind);
1834 match rib.kind {
1835 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1836 let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1837 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1838 return;
1839 }
1840 LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1841 let mut lifetimes_in_scope = vec![];
1842 for rib in self.lifetime_ribs[..i].iter().rev() {
1843 lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1844 if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1846 && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1847 {
1848 lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1849 }
1850 if let LifetimeRibKind::Item = rib.kind {
1851 break;
1852 }
1853 }
1854 if lifetimes_in_scope.is_empty() {
1855 self.record_lifetime_res(
1856 lifetime.id,
1857 LifetimeRes::Static { suppress_elision_warning: true },
1859 elision_candidate,
1860 );
1861 return;
1862 } else if emit_lint {
1863 self.r.lint_buffer.buffer_lint(
1864 lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1865 node_id,
1866 lifetime.ident.span,
1867 lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1868 elided,
1869 span: lifetime.ident.span,
1870 lifetimes_in_scope: lifetimes_in_scope.into(),
1871 },
1872 );
1873 }
1874 }
1875 LifetimeRibKind::AnonymousReportError => {
1876 if elided {
1877 let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1878 if let LifetimeRibKind::Generics {
1879 span,
1880 kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1881 ..
1882 } = rib.kind
1883 {
1884 Some(errors::ElidedAnonymousLivetimeReportErrorSuggestion {
1885 lo: span.shrink_to_lo(),
1886 hi: lifetime.ident.span.shrink_to_hi(),
1887 })
1888 } else {
1889 None
1890 }
1891 });
1892 if !self.in_func_body
1895 && let Some((module, _)) = &self.current_trait_ref
1896 && let Some(ty) = &self.diag_metadata.current_self_type
1897 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1898 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1899 {
1900 if def_id_matches_path(
1901 self.r.tcx,
1902 trait_id,
1903 &["core", "iter", "traits", "iterator", "Iterator"],
1904 ) {
1905 self.r.dcx().emit_err(errors::LendingIteratorReportError {
1906 lifetime: lifetime.ident.span,
1907 ty: ty.span,
1908 });
1909 } else {
1910 self.r.dcx().emit_err(errors::AnonymousLivetimeNonGatReportError {
1911 lifetime: lifetime.ident.span,
1912 });
1913 }
1914 } else {
1915 self.r.dcx().emit_err(errors::ElidedAnonymousLivetimeReportError {
1916 span: lifetime.ident.span,
1917 suggestion,
1918 });
1919 }
1920 } else {
1921 self.r.dcx().emit_err(errors::ExplicitAnonymousLivetimeReportError {
1922 span: lifetime.ident.span,
1923 });
1924 };
1925 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1926 return;
1927 }
1928 LifetimeRibKind::Elided(res) => {
1929 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1930 return;
1931 }
1932 LifetimeRibKind::ElisionFailure => {
1933 self.diag_metadata.current_elision_failures.push(missing_lifetime);
1934 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1935 return;
1936 }
1937 LifetimeRibKind::Item => break,
1938 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1939 LifetimeRibKind::ConcreteAnonConst(_) => {
1940 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1942 }
1943 }
1944 }
1945 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1946 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1947 }
1948
1949 #[instrument(level = "debug", skip(self))]
1950 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1951 let id = self.r.next_node_id();
1952 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1953
1954 self.record_lifetime_res(
1955 anchor_id,
1956 LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
1957 LifetimeElisionCandidate::Ignore,
1958 );
1959 self.resolve_anonymous_lifetime(<, anchor_id, true);
1960 }
1961
1962 #[instrument(level = "debug", skip(self))]
1963 fn create_fresh_lifetime(
1964 &mut self,
1965 ident: Ident,
1966 binder: NodeId,
1967 kind: MissingLifetimeKind,
1968 ) -> LifetimeRes {
1969 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1970 debug!(?ident.span);
1971
1972 let param = self.r.next_node_id();
1974 let res = LifetimeRes::Fresh { param, binder, kind };
1975 self.record_lifetime_param(param, res);
1976
1977 self.r
1979 .extra_lifetime_params_map
1980 .entry(binder)
1981 .or_insert_with(Vec::new)
1982 .push((ident, param, res));
1983 res
1984 }
1985
1986 #[instrument(level = "debug", skip(self))]
1987 fn resolve_elided_lifetimes_in_path(
1988 &mut self,
1989 partial_res: PartialRes,
1990 path: &[Segment],
1991 source: PathSource<'_>,
1992 path_span: Span,
1993 ) {
1994 let proj_start = path.len() - partial_res.unresolved_segments();
1995 for (i, segment) in path.iter().enumerate() {
1996 if segment.has_lifetime_args {
1997 continue;
1998 }
1999 let Some(segment_id) = segment.id else {
2000 continue;
2001 };
2002
2003 let type_def_id = match partial_res.base_res() {
2006 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2007 self.r.tcx.parent(def_id)
2008 }
2009 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2010 self.r.tcx.parent(def_id)
2011 }
2012 Res::Def(DefKind::Struct, def_id)
2013 | Res::Def(DefKind::Union, def_id)
2014 | Res::Def(DefKind::Enum, def_id)
2015 | Res::Def(DefKind::TyAlias, def_id)
2016 | Res::Def(DefKind::Trait, def_id)
2017 if i + 1 == proj_start =>
2018 {
2019 def_id
2020 }
2021 _ => continue,
2022 };
2023
2024 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2025 if expected_lifetimes == 0 {
2026 continue;
2027 }
2028
2029 let node_ids = self.r.next_node_ids(expected_lifetimes);
2030 self.record_lifetime_res(
2031 segment_id,
2032 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2033 LifetimeElisionCandidate::Ignore,
2034 );
2035
2036 let inferred = match source {
2037 PathSource::Trait(..)
2038 | PathSource::TraitItem(..)
2039 | PathSource::Type
2040 | PathSource::PreciseCapturingArg(..)
2041 | PathSource::ReturnTypeNotation => false,
2042 PathSource::Expr(..)
2043 | PathSource::Pat
2044 | PathSource::Struct
2045 | PathSource::TupleStruct(..)
2046 | PathSource::DefineOpaques
2047 | PathSource::Delegation => true,
2048 };
2049 if inferred {
2050 for id in node_ids {
2053 self.record_lifetime_res(
2054 id,
2055 LifetimeRes::Infer,
2056 LifetimeElisionCandidate::Named,
2057 );
2058 }
2059 continue;
2060 }
2061
2062 let elided_lifetime_span = if segment.has_generic_args {
2063 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2065 } else {
2066 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2070 };
2071 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2072
2073 let kind = if segment.has_generic_args {
2074 MissingLifetimeKind::Comma
2075 } else {
2076 MissingLifetimeKind::Brackets
2077 };
2078 let missing_lifetime = MissingLifetime {
2079 id: node_ids.start,
2080 id_for_lint: segment_id,
2081 span: elided_lifetime_span,
2082 kind,
2083 count: expected_lifetimes,
2084 };
2085 let mut should_lint = true;
2086 for rib in self.lifetime_ribs.iter().rev() {
2087 match rib.kind {
2088 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2095 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2096 let sess = self.r.tcx.sess;
2097 let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2098 sess.source_map(),
2099 expected_lifetimes,
2100 path_span,
2101 !segment.has_generic_args,
2102 elided_lifetime_span,
2103 );
2104 self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2105 span: path_span,
2106 subdiag,
2107 });
2108 should_lint = false;
2109
2110 for id in node_ids {
2111 self.record_lifetime_res(
2112 id,
2113 LifetimeRes::Error,
2114 LifetimeElisionCandidate::Named,
2115 );
2116 }
2117 break;
2118 }
2119 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2121 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2123 for id in node_ids {
2124 let res = self.create_fresh_lifetime(ident, binder, kind);
2125 self.record_lifetime_res(
2126 id,
2127 res,
2128 replace(&mut candidate, LifetimeElisionCandidate::Named),
2129 );
2130 }
2131 break;
2132 }
2133 LifetimeRibKind::Elided(res) => {
2134 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2135 for id in node_ids {
2136 self.record_lifetime_res(
2137 id,
2138 res,
2139 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2140 );
2141 }
2142 break;
2143 }
2144 LifetimeRibKind::ElisionFailure => {
2145 self.diag_metadata.current_elision_failures.push(missing_lifetime);
2146 for id in node_ids {
2147 self.record_lifetime_res(
2148 id,
2149 LifetimeRes::Error,
2150 LifetimeElisionCandidate::Ignore,
2151 );
2152 }
2153 break;
2154 }
2155 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2160 for id in node_ids {
2161 self.record_lifetime_res(
2162 id,
2163 LifetimeRes::Error,
2164 LifetimeElisionCandidate::Ignore,
2165 );
2166 }
2167 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2168 break;
2169 }
2170 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2171 LifetimeRibKind::ConcreteAnonConst(_) => {
2172 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2174 }
2175 }
2176 }
2177
2178 if should_lint {
2179 self.r.lint_buffer.buffer_lint(
2180 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2181 segment_id,
2182 elided_lifetime_span,
2183 lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2184 expected_lifetimes,
2185 path_span,
2186 !segment.has_generic_args,
2187 elided_lifetime_span,
2188 ),
2189 );
2190 }
2191 }
2192 }
2193
2194 #[instrument(level = "debug", skip(self))]
2195 fn record_lifetime_res(
2196 &mut self,
2197 id: NodeId,
2198 res: LifetimeRes,
2199 candidate: LifetimeElisionCandidate,
2200 ) {
2201 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2202 panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2203 }
2204
2205 match candidate {
2206 LifetimeElisionCandidate::Missing(missing @ MissingLifetime { .. }) => {
2207 debug_assert_eq!(id, missing.id);
2208 match res {
2209 LifetimeRes::Static { suppress_elision_warning } => {
2210 if !suppress_elision_warning {
2211 self.r.lint_buffer.buffer_lint(
2212 lint::builtin::ELIDED_NAMED_LIFETIMES,
2213 missing.id_for_lint,
2214 missing.span,
2215 BuiltinLintDiag::ElidedNamedLifetimes {
2216 elided: (missing.span, missing.kind),
2217 resolution: lint::ElidedLifetimeResolution::Static,
2218 },
2219 );
2220 }
2221 }
2222 LifetimeRes::Param { param, binder: _ } => {
2223 let tcx = self.r.tcx();
2224 self.r.lint_buffer.buffer_lint(
2225 lint::builtin::ELIDED_NAMED_LIFETIMES,
2226 missing.id_for_lint,
2227 missing.span,
2228 BuiltinLintDiag::ElidedNamedLifetimes {
2229 elided: (missing.span, missing.kind),
2230 resolution: lint::ElidedLifetimeResolution::Param(
2231 tcx.item_name(param.into()),
2232 tcx.source_span(param),
2233 ),
2234 },
2235 );
2236 }
2237 LifetimeRes::Fresh { .. }
2238 | LifetimeRes::Infer
2239 | LifetimeRes::Error
2240 | LifetimeRes::ElidedAnchor { .. } => {}
2241 }
2242 }
2243 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {}
2244 }
2245
2246 match res {
2247 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2248 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2249 candidates.push((res, candidate));
2250 }
2251 }
2252 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2253 }
2254 }
2255
2256 #[instrument(level = "debug", skip(self))]
2257 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2258 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2259 panic!(
2260 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2261 )
2262 }
2263 }
2264
2265 #[instrument(level = "debug", skip(self, inputs))]
2267 fn resolve_fn_signature(
2268 &mut self,
2269 fn_id: NodeId,
2270 has_self: bool,
2271 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2272 output_ty: &'ast FnRetTy,
2273 ) {
2274 let elision_lifetime = self.resolve_fn_params(has_self, inputs);
2276 debug!(?elision_lifetime);
2277
2278 let outer_failures = take(&mut self.diag_metadata.current_elision_failures);
2279 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2280 self.r.lifetime_elision_allowed.insert(fn_id);
2281 LifetimeRibKind::Elided(*res)
2282 } else {
2283 LifetimeRibKind::ElisionFailure
2284 };
2285 self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2286 let elision_failures =
2287 replace(&mut self.diag_metadata.current_elision_failures, outer_failures);
2288 if !elision_failures.is_empty() {
2289 let Err(failure_info) = elision_lifetime else { bug!() };
2290 self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2291 }
2292 }
2293
2294 fn resolve_fn_params(
2298 &mut self,
2299 has_self: bool,
2300 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)>,
2301 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2302 enum Elision {
2303 None,
2305 Self_(LifetimeRes),
2307 Param(LifetimeRes),
2309 Err,
2311 }
2312
2313 let outer_candidates = self.lifetime_elision_candidates.take();
2315
2316 let mut elision_lifetime = Elision::None;
2318 let mut parameter_info = Vec::new();
2320 let mut all_candidates = Vec::new();
2321
2322 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2323 for (index, (pat, ty)) in inputs.enumerate() {
2324 debug!(?pat, ?ty);
2325 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2326 if let Some(pat) = pat {
2327 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2328 }
2329 });
2330
2331 debug_assert_matches!(self.lifetime_elision_candidates, None);
2333 self.lifetime_elision_candidates = Some(Default::default());
2334 self.visit_ty(ty);
2335 let local_candidates = self.lifetime_elision_candidates.take();
2336
2337 if let Some(candidates) = local_candidates {
2338 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2339 let lifetime_count = distinct.len();
2340 if lifetime_count != 0 {
2341 parameter_info.push(ElisionFnParameter {
2342 index,
2343 ident: if let Some(pat) = pat
2344 && let PatKind::Ident(_, ident, _) = pat.kind
2345 {
2346 Some(ident)
2347 } else {
2348 None
2349 },
2350 lifetime_count,
2351 span: ty.span,
2352 });
2353 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2354 match candidate {
2355 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2356 None
2357 }
2358 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2359 }
2360 }));
2361 }
2362 if !distinct.is_empty() {
2363 match elision_lifetime {
2364 Elision::None => {
2366 if let Some(res) = distinct.get_only() {
2367 elision_lifetime = Elision::Param(*res)
2369 } else {
2370 elision_lifetime = Elision::Err;
2372 }
2373 }
2374 Elision::Param(_) => elision_lifetime = Elision::Err,
2376 Elision::Self_(_) | Elision::Err => {}
2378 }
2379 }
2380 }
2381
2382 if index == 0 && has_self {
2384 let self_lifetime = self.find_lifetime_for_self(ty);
2385 elision_lifetime = match self_lifetime {
2386 Set1::One(lifetime) => Elision::Self_(lifetime),
2388 Set1::Many => Elision::Err,
2393 Set1::Empty => Elision::None,
2396 }
2397 }
2398 debug!("(resolving function / closure) recorded parameter");
2399 }
2400
2401 debug_assert_matches!(self.lifetime_elision_candidates, None);
2403 self.lifetime_elision_candidates = outer_candidates;
2404
2405 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2406 return Ok(res);
2407 }
2408
2409 Err((all_candidates, parameter_info))
2411 }
2412
2413 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2415 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2419 r: &'a Resolver<'ra, 'tcx>,
2420 impl_self: Option<Res>,
2421 lifetime: Set1<LifetimeRes>,
2422 }
2423
2424 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2425 fn visit_ty(&mut self, ty: &'ra Ty) {
2426 trace!("FindReferenceVisitor considering ty={:?}", ty);
2427 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2428 let mut visitor =
2430 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2431 visitor.visit_ty(ty);
2432 trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2433 if visitor.self_found {
2434 let lt_id = if let Some(lt) = lt {
2435 lt.id
2436 } else {
2437 let res = self.r.lifetimes_res_map[&ty.id];
2438 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2439 start
2440 };
2441 let lt_res = self.r.lifetimes_res_map[<_id];
2442 trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2443 self.lifetime.insert(lt_res);
2444 }
2445 }
2446 visit::walk_ty(self, ty)
2447 }
2448
2449 fn visit_expr(&mut self, _: &'ra Expr) {}
2452 }
2453
2454 struct SelfVisitor<'a, 'ra, 'tcx> {
2457 r: &'a Resolver<'ra, 'tcx>,
2458 impl_self: Option<Res>,
2459 self_found: bool,
2460 }
2461
2462 impl SelfVisitor<'_, '_, '_> {
2463 fn is_self_ty(&self, ty: &Ty) -> bool {
2465 match ty.kind {
2466 TyKind::ImplicitSelf => true,
2467 TyKind::Path(None, _) => {
2468 let path_res = self.r.partial_res_map[&ty.id].full_res();
2469 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2470 return true;
2471 }
2472 self.impl_self.is_some() && path_res == self.impl_self
2473 }
2474 _ => false,
2475 }
2476 }
2477 }
2478
2479 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2480 fn visit_ty(&mut self, ty: &'ra Ty) {
2481 trace!("SelfVisitor considering ty={:?}", ty);
2482 if self.is_self_ty(ty) {
2483 trace!("SelfVisitor found Self");
2484 self.self_found = true;
2485 }
2486 visit::walk_ty(self, ty)
2487 }
2488
2489 fn visit_expr(&mut self, _: &'ra Expr) {}
2492 }
2493
2494 let impl_self = self
2495 .diag_metadata
2496 .current_self_type
2497 .as_ref()
2498 .and_then(|ty| {
2499 if let TyKind::Path(None, _) = ty.kind {
2500 self.r.partial_res_map.get(&ty.id)
2501 } else {
2502 None
2503 }
2504 })
2505 .and_then(|res| res.full_res())
2506 .filter(|res| {
2507 matches!(
2511 res,
2512 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2513 )
2514 });
2515 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2516 visitor.visit_ty(ty);
2517 trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2518 visitor.lifetime
2519 }
2520
2521 fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2524 let mut suggestion = None;
2525
2526 for i in (0..self.label_ribs.len()).rev() {
2527 let rib = &self.label_ribs[i];
2528
2529 if let RibKind::MacroDefinition(def) = rib.kind
2530 && def == self.r.macro_def(label.span.ctxt())
2533 {
2534 label.span.remove_mark();
2535 }
2536
2537 let ident = label.normalize_to_macro_rules();
2538 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2539 let definition_span = ident.span;
2540 return if self.is_label_valid_from_rib(i) {
2541 Ok((*id, definition_span))
2542 } else {
2543 Err(ResolutionError::UnreachableLabel {
2544 name: label.name,
2545 definition_span,
2546 suggestion,
2547 })
2548 };
2549 }
2550
2551 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2554 }
2555
2556 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2557 }
2558
2559 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2561 let ribs = &self.label_ribs[rib_index + 1..];
2562 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2563 }
2564
2565 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2566 debug!("resolve_adt");
2567 let kind = self.r.local_def_kind(item.id);
2568 self.with_current_self_item(item, |this| {
2569 this.with_generic_param_rib(
2570 &generics.params,
2571 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2572 LifetimeRibKind::Generics {
2573 binder: item.id,
2574 kind: LifetimeBinderKind::Item,
2575 span: generics.span,
2576 },
2577 |this| {
2578 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2579 this.with_self_rib(
2580 Res::SelfTyAlias {
2581 alias_to: item_def_id,
2582 forbid_generic: false,
2583 is_trait_impl: false,
2584 },
2585 |this| {
2586 visit::walk_item(this, item);
2587 },
2588 );
2589 },
2590 );
2591 });
2592 }
2593
2594 fn future_proof_import(&mut self, use_tree: &UseTree) {
2595 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2596 let ident = segment.ident;
2597 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2598 return;
2599 }
2600
2601 let nss = match use_tree.kind {
2602 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2603 _ => &[TypeNS],
2604 };
2605 let report_error = |this: &Self, ns| {
2606 if this.should_report_errs() {
2607 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2608 this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2609 }
2610 };
2611
2612 for &ns in nss {
2613 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2614 Some(LexicalScopeBinding::Res(..)) => {
2615 report_error(self, ns);
2616 }
2617 Some(LexicalScopeBinding::Item(binding)) => {
2618 if let Some(LexicalScopeBinding::Res(..)) =
2619 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2620 {
2621 report_error(self, ns);
2622 }
2623 }
2624 None => {}
2625 }
2626 }
2627 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2628 for (use_tree, _) in items {
2629 self.future_proof_import(use_tree);
2630 }
2631 }
2632 }
2633
2634 fn resolve_item(&mut self, item: &'ast Item) {
2635 let mod_inner_docs =
2636 matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2637 if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2638 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2639 }
2640
2641 debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2642
2643 let def_kind = self.r.local_def_kind(item.id);
2644 match item.kind {
2645 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2646 self.with_generic_param_rib(
2647 &generics.params,
2648 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2649 LifetimeRibKind::Generics {
2650 binder: item.id,
2651 kind: LifetimeBinderKind::Item,
2652 span: generics.span,
2653 },
2654 |this| visit::walk_item(this, item),
2655 );
2656 }
2657
2658 ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2659 self.with_generic_param_rib(
2660 &generics.params,
2661 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2662 LifetimeRibKind::Generics {
2663 binder: item.id,
2664 kind: LifetimeBinderKind::Function,
2665 span: generics.span,
2666 },
2667 |this| visit::walk_item(this, item),
2668 );
2669 self.resolve_define_opaques(define_opaque);
2670 }
2671
2672 ItemKind::Enum(_, _, ref generics)
2673 | ItemKind::Struct(_, _, ref generics)
2674 | ItemKind::Union(_, _, ref generics) => {
2675 self.resolve_adt(item, generics);
2676 }
2677
2678 ItemKind::Impl(box Impl {
2679 ref generics,
2680 ref of_trait,
2681 ref self_ty,
2682 items: ref impl_items,
2683 ..
2684 }) => {
2685 self.diag_metadata.current_impl_items = Some(impl_items);
2686 self.resolve_implementation(
2687 &item.attrs,
2688 generics,
2689 of_trait,
2690 self_ty,
2691 item.id,
2692 impl_items,
2693 );
2694 self.diag_metadata.current_impl_items = None;
2695 }
2696
2697 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2698 self.with_generic_param_rib(
2700 &generics.params,
2701 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2702 LifetimeRibKind::Generics {
2703 binder: item.id,
2704 kind: LifetimeBinderKind::Item,
2705 span: generics.span,
2706 },
2707 |this| {
2708 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2709 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2710 this.visit_generics(generics);
2711 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2712 this.resolve_trait_items(items);
2713 });
2714 },
2715 );
2716 }
2717
2718 ItemKind::TraitAlias(_, ref generics, ref bounds) => {
2719 self.with_generic_param_rib(
2721 &generics.params,
2722 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2723 LifetimeRibKind::Generics {
2724 binder: item.id,
2725 kind: LifetimeBinderKind::Item,
2726 span: generics.span,
2727 },
2728 |this| {
2729 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2730 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2731 this.visit_generics(generics);
2732 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2733 });
2734 },
2735 );
2736 }
2737
2738 ItemKind::Mod(..) => {
2739 self.with_mod_rib(item.id, |this| {
2740 if mod_inner_docs {
2741 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2742 }
2743 let old_macro_rules = this.parent_scope.macro_rules;
2744 visit::walk_item(this, item);
2745 if item.attrs.iter().all(|attr| {
2748 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2749 }) {
2750 this.parent_scope.macro_rules = old_macro_rules;
2751 }
2752 });
2753 }
2754
2755 ItemKind::Static(box ast::StaticItem {
2756 ident,
2757 ref ty,
2758 ref expr,
2759 ref define_opaque,
2760 ..
2761 }) => {
2762 self.with_static_rib(def_kind, |this| {
2763 this.with_lifetime_rib(
2764 LifetimeRibKind::Elided(LifetimeRes::Static {
2765 suppress_elision_warning: true,
2766 }),
2767 |this| {
2768 this.visit_ty(ty);
2769 },
2770 );
2771 if let Some(expr) = expr {
2772 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Static)));
2775 }
2776 });
2777 self.resolve_define_opaques(define_opaque);
2778 }
2779
2780 ItemKind::Const(box ast::ConstItem {
2781 ident,
2782 ref generics,
2783 ref ty,
2784 ref expr,
2785 ref define_opaque,
2786 ..
2787 }) => {
2788 self.with_generic_param_rib(
2789 &generics.params,
2790 RibKind::Item(
2791 if self.r.tcx.features().generic_const_items() {
2792 HasGenericParams::Yes(generics.span)
2793 } else {
2794 HasGenericParams::No
2795 },
2796 def_kind,
2797 ),
2798 LifetimeRibKind::Generics {
2799 binder: item.id,
2800 kind: LifetimeBinderKind::ConstItem,
2801 span: generics.span,
2802 },
2803 |this| {
2804 this.visit_generics(generics);
2805
2806 this.with_lifetime_rib(
2807 LifetimeRibKind::Elided(LifetimeRes::Static {
2808 suppress_elision_warning: true,
2809 }),
2810 |this| this.visit_ty(ty),
2811 );
2812
2813 if let Some(expr) = expr {
2814 this.resolve_const_body(expr, Some((ident, ConstantItemKind::Const)));
2815 }
2816 },
2817 );
2818 self.resolve_define_opaques(define_opaque);
2819 }
2820
2821 ItemKind::Use(ref use_tree) => {
2822 let maybe_exported = match use_tree.kind {
2823 UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2824 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2825 };
2826 self.resolve_doc_links(&item.attrs, maybe_exported);
2827
2828 self.future_proof_import(use_tree);
2829 }
2830
2831 ItemKind::MacroDef(_, ref macro_def) => {
2832 if macro_def.macro_rules {
2835 let def_id = self.r.local_def_id(item.id);
2836 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2837 }
2838 }
2839
2840 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2841 visit::walk_item(self, item);
2842 }
2843
2844 ItemKind::Delegation(ref delegation) => {
2845 let span = delegation.path.segments.last().unwrap().ident.span;
2846 self.with_generic_param_rib(
2847 &[],
2848 RibKind::Item(HasGenericParams::Yes(span), def_kind),
2849 LifetimeRibKind::Generics {
2850 binder: item.id,
2851 kind: LifetimeBinderKind::Function,
2852 span,
2853 },
2854 |this| this.resolve_delegation(delegation),
2855 );
2856 }
2857
2858 ItemKind::ExternCrate(..) => {}
2859
2860 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2861 panic!("unexpanded macro in resolve!")
2862 }
2863 }
2864 }
2865
2866 fn with_generic_param_rib<'c, F>(
2867 &'c mut self,
2868 params: &'c [GenericParam],
2869 kind: RibKind<'ra>,
2870 lifetime_kind: LifetimeRibKind,
2871 f: F,
2872 ) where
2873 F: FnOnce(&mut Self),
2874 {
2875 debug!("with_generic_param_rib");
2876 let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. } =
2877 lifetime_kind
2878 else {
2879 panic!()
2880 };
2881
2882 let mut function_type_rib = Rib::new(kind);
2883 let mut function_value_rib = Rib::new(kind);
2884 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2885
2886 if !params.is_empty() {
2888 let mut seen_bindings = FxHashMap::default();
2889 let mut seen_lifetimes = FxHashSet::default();
2891
2892 for ns in [ValueNS, TypeNS] {
2894 for parent_rib in self.ribs[ns].iter().rev() {
2895 if matches!(parent_rib.kind, RibKind::Module(..)) {
2898 break;
2899 }
2900
2901 seen_bindings
2902 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2903 }
2904 }
2905
2906 for rib in self.lifetime_ribs.iter().rev() {
2908 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2909 if let LifetimeRibKind::Item = rib.kind {
2910 break;
2911 }
2912 }
2913
2914 for param in params {
2915 let ident = param.ident.normalize_to_macros_2_0();
2916 debug!("with_generic_param_rib: {}", param.id);
2917
2918 if let GenericParamKind::Lifetime = param.kind
2919 && let Some(&original) = seen_lifetimes.get(&ident)
2920 {
2921 diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
2922 self.record_lifetime_param(param.id, LifetimeRes::Error);
2924 continue;
2925 }
2926
2927 match seen_bindings.entry(ident) {
2928 Entry::Occupied(entry) => {
2929 let span = *entry.get();
2930 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
2931 self.report_error(param.ident.span, err);
2932 let rib = match param.kind {
2933 GenericParamKind::Lifetime => {
2934 self.record_lifetime_param(param.id, LifetimeRes::Error);
2936 continue;
2937 }
2938 GenericParamKind::Type { .. } => &mut function_type_rib,
2939 GenericParamKind::Const { .. } => &mut function_value_rib,
2940 };
2941
2942 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
2944 rib.bindings.insert(ident, Res::Err);
2945 continue;
2946 }
2947 Entry::Vacant(entry) => {
2948 entry.insert(param.ident.span);
2949 }
2950 }
2951
2952 if param.ident.name == kw::UnderscoreLifetime {
2953 self.r
2954 .dcx()
2955 .emit_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span });
2956 self.record_lifetime_param(param.id, LifetimeRes::Error);
2958 continue;
2959 }
2960
2961 if param.ident.name == kw::StaticLifetime {
2962 self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
2963 span: param.ident.span,
2964 lifetime: param.ident,
2965 });
2966 self.record_lifetime_param(param.id, LifetimeRes::Error);
2968 continue;
2969 }
2970
2971 let def_id = self.r.local_def_id(param.id);
2972
2973 let (rib, def_kind) = match param.kind {
2975 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2976 GenericParamKind::Const { .. } => {
2977 (&mut function_value_rib, DefKind::ConstParam)
2978 }
2979 GenericParamKind::Lifetime => {
2980 let res = LifetimeRes::Param { param: def_id, binder };
2981 self.record_lifetime_param(param.id, res);
2982 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2983 continue;
2984 }
2985 };
2986
2987 let res = match kind {
2988 RibKind::Item(..) | RibKind::AssocItem => {
2989 Res::Def(def_kind, def_id.to_def_id())
2990 }
2991 RibKind::Normal => {
2992 if self.r.tcx.features().non_lifetime_binders()
2995 && matches!(param.kind, GenericParamKind::Type { .. })
2996 {
2997 Res::Def(def_kind, def_id.to_def_id())
2998 } else {
2999 Res::Err
3000 }
3001 }
3002 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
3003 };
3004 self.r.record_partial_res(param.id, PartialRes::new(res));
3005 rib.bindings.insert(ident, res);
3006 }
3007 }
3008
3009 self.lifetime_ribs.push(function_lifetime_rib);
3010 self.ribs[ValueNS].push(function_value_rib);
3011 self.ribs[TypeNS].push(function_type_rib);
3012
3013 f(self);
3014
3015 self.ribs[TypeNS].pop();
3016 self.ribs[ValueNS].pop();
3017 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3018
3019 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3021 for (_, res) in function_lifetime_rib.bindings.values() {
3022 candidates.retain(|(r, _)| r != res);
3023 }
3024 }
3025
3026 if let LifetimeBinderKind::BareFnType
3027 | LifetimeBinderKind::WhereBound
3028 | LifetimeBinderKind::Function
3029 | LifetimeBinderKind::ImplBlock = generics_kind
3030 {
3031 self.maybe_report_lifetime_uses(generics_span, params)
3032 }
3033 }
3034
3035 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3036 self.label_ribs.push(Rib::new(kind));
3037 f(self);
3038 self.label_ribs.pop();
3039 }
3040
3041 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3042 let kind = RibKind::Item(HasGenericParams::No, def_kind);
3043 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3044 }
3045
3046 #[instrument(level = "debug", skip(self, f))]
3055 fn with_constant_rib(
3056 &mut self,
3057 is_repeat: IsRepeatExpr,
3058 may_use_generics: ConstantHasGenerics,
3059 item: Option<(Ident, ConstantItemKind)>,
3060 f: impl FnOnce(&mut Self),
3061 ) {
3062 let f = |this: &mut Self| {
3063 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3064 this.with_rib(
3065 TypeNS,
3066 RibKind::ConstantItem(
3067 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3068 item,
3069 ),
3070 |this| {
3071 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3072 },
3073 )
3074 })
3075 };
3076
3077 if let ConstantHasGenerics::No(cause) = may_use_generics {
3078 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3079 } else {
3080 f(self)
3081 }
3082 }
3083
3084 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3085 let previous_value =
3087 replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3088 let result = f(self);
3089 self.diag_metadata.current_self_type = previous_value;
3090 result
3091 }
3092
3093 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3094 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3095 let result = f(self);
3096 self.diag_metadata.current_self_item = previous_value;
3097 result
3098 }
3099
3100 fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
3102 let trait_assoc_items =
3103 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3104
3105 let walk_assoc_item =
3106 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3107 this.with_generic_param_rib(
3108 &generics.params,
3109 RibKind::AssocItem,
3110 LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind },
3111 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3112 );
3113 };
3114
3115 for item in trait_items {
3116 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3117 match &item.kind {
3118 AssocItemKind::Const(box ast::ConstItem {
3119 generics,
3120 ty,
3121 expr,
3122 define_opaque,
3123 ..
3124 }) => {
3125 self.with_generic_param_rib(
3126 &generics.params,
3127 RibKind::AssocItem,
3128 LifetimeRibKind::Generics {
3129 binder: item.id,
3130 span: generics.span,
3131 kind: LifetimeBinderKind::ConstItem,
3132 },
3133 |this| {
3134 this.with_lifetime_rib(
3135 LifetimeRibKind::StaticIfNoLifetimeInScope {
3136 lint_id: item.id,
3137 emit_lint: false,
3138 },
3139 |this| {
3140 this.visit_generics(generics);
3141 this.visit_ty(ty);
3142
3143 if let Some(expr) = expr {
3146 this.resolve_const_body(expr, None);
3152 }
3153 },
3154 )
3155 },
3156 );
3157
3158 self.resolve_define_opaques(define_opaque);
3159 }
3160 AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3161 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3162
3163 self.resolve_define_opaques(define_opaque);
3164 }
3165 AssocItemKind::Delegation(delegation) => {
3166 self.with_generic_param_rib(
3167 &[],
3168 RibKind::AssocItem,
3169 LifetimeRibKind::Generics {
3170 binder: item.id,
3171 kind: LifetimeBinderKind::Function,
3172 span: delegation.path.segments.last().unwrap().ident.span,
3173 },
3174 |this| this.resolve_delegation(delegation),
3175 );
3176 }
3177 AssocItemKind::Type(box TyAlias { generics, .. }) => self
3178 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3179 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3180 }),
3181 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3182 panic!("unexpanded macro in resolve!")
3183 }
3184 };
3185 }
3186
3187 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3188 }
3189
3190 fn with_optional_trait_ref<T>(
3192 &mut self,
3193 opt_trait_ref: Option<&TraitRef>,
3194 self_type: &'ast Ty,
3195 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3196 ) -> T {
3197 let mut new_val = None;
3198 let mut new_id = None;
3199 if let Some(trait_ref) = opt_trait_ref {
3200 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3201 self.diag_metadata.currently_processing_impl_trait =
3202 Some((trait_ref.clone(), self_type.clone()));
3203 let res = self.smart_resolve_path_fragment(
3204 &None,
3205 &path,
3206 PathSource::Trait(AliasPossibility::No),
3207 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3208 RecordPartialRes::Yes,
3209 None,
3210 );
3211 self.diag_metadata.currently_processing_impl_trait = None;
3212 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3213 new_id = Some(def_id);
3214 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3215 }
3216 }
3217 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3218 let result = f(self, new_id);
3219 self.current_trait_ref = original_trait_ref;
3220 result
3221 }
3222
3223 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3224 let mut self_type_rib = Rib::new(RibKind::Normal);
3225
3226 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3228 self.ribs[ns].push(self_type_rib);
3229 f(self);
3230 self.ribs[ns].pop();
3231 }
3232
3233 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3234 self.with_self_rib_ns(TypeNS, self_res, f)
3235 }
3236
3237 fn resolve_implementation(
3238 &mut self,
3239 attrs: &[ast::Attribute],
3240 generics: &'ast Generics,
3241 opt_trait_reference: &'ast Option<TraitRef>,
3242 self_type: &'ast Ty,
3243 item_id: NodeId,
3244 impl_items: &'ast [P<AssocItem>],
3245 ) {
3246 debug!("resolve_implementation");
3247 self.with_generic_param_rib(
3249 &generics.params,
3250 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3251 LifetimeRibKind::Generics {
3252 span: generics.span,
3253 binder: item_id,
3254 kind: LifetimeBinderKind::ImplBlock,
3255 },
3256 |this| {
3257 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3259 this.with_lifetime_rib(
3260 LifetimeRibKind::AnonymousCreateParameter {
3261 binder: item_id,
3262 report_in_path: true
3263 },
3264 |this| {
3265 this.with_optional_trait_ref(
3267 opt_trait_reference.as_ref(),
3268 self_type,
3269 |this, trait_id| {
3270 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3271
3272 let item_def_id = this.r.local_def_id(item_id);
3273
3274 if let Some(trait_id) = trait_id {
3276 this.r
3277 .trait_impls
3278 .entry(trait_id)
3279 .or_default()
3280 .push(item_def_id);
3281 }
3282
3283 let item_def_id = item_def_id.to_def_id();
3284 let res = Res::SelfTyAlias {
3285 alias_to: item_def_id,
3286 forbid_generic: false,
3287 is_trait_impl: trait_id.is_some()
3288 };
3289 this.with_self_rib(res, |this| {
3290 if let Some(trait_ref) = opt_trait_reference.as_ref() {
3291 visit::walk_trait_ref(this, trait_ref);
3293 }
3294 this.visit_ty(self_type);
3296 this.visit_generics(generics);
3298
3299 this.with_current_self_type(self_type, |this| {
3301 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3302 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3303 let mut seen_trait_items = Default::default();
3304 for item in impl_items {
3305 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3306 }
3307 });
3308 });
3309 });
3310 },
3311 )
3312 },
3313 );
3314 });
3315 },
3316 );
3317 }
3318
3319 fn resolve_impl_item(
3320 &mut self,
3321 item: &'ast AssocItem,
3322 seen_trait_items: &mut FxHashMap<DefId, Span>,
3323 trait_id: Option<DefId>,
3324 ) {
3325 use crate::ResolutionError::*;
3326 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3327 match &item.kind {
3328 AssocItemKind::Const(box ast::ConstItem {
3329 ident,
3330 generics,
3331 ty,
3332 expr,
3333 define_opaque,
3334 ..
3335 }) => {
3336 debug!("resolve_implementation AssocItemKind::Const");
3337 self.with_generic_param_rib(
3338 &generics.params,
3339 RibKind::AssocItem,
3340 LifetimeRibKind::Generics {
3341 binder: item.id,
3342 span: generics.span,
3343 kind: LifetimeBinderKind::ConstItem,
3344 },
3345 |this| {
3346 this.with_lifetime_rib(
3347 LifetimeRibKind::AnonymousCreateParameter {
3350 binder: item.id,
3351 report_in_path: true,
3352 },
3353 |this| {
3354 this.with_lifetime_rib(
3355 LifetimeRibKind::StaticIfNoLifetimeInScope {
3356 lint_id: item.id,
3357 emit_lint: true,
3359 },
3360 |this| {
3361 this.check_trait_item(
3364 item.id,
3365 *ident,
3366 &item.kind,
3367 ValueNS,
3368 item.span,
3369 seen_trait_items,
3370 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3371 );
3372
3373 this.visit_generics(generics);
3374 this.visit_ty(ty);
3375 if let Some(expr) = expr {
3376 this.resolve_const_body(expr, None);
3382 }
3383 },
3384 )
3385 },
3386 );
3387 },
3388 );
3389 self.resolve_define_opaques(define_opaque);
3390 }
3391 AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3392 debug!("resolve_implementation AssocItemKind::Fn");
3393 self.with_generic_param_rib(
3395 &generics.params,
3396 RibKind::AssocItem,
3397 LifetimeRibKind::Generics {
3398 binder: item.id,
3399 span: generics.span,
3400 kind: LifetimeBinderKind::Function,
3401 },
3402 |this| {
3403 this.check_trait_item(
3406 item.id,
3407 *ident,
3408 &item.kind,
3409 ValueNS,
3410 item.span,
3411 seen_trait_items,
3412 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3413 );
3414
3415 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3416 },
3417 );
3418
3419 self.resolve_define_opaques(define_opaque);
3420 }
3421 AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3422 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3423 debug!("resolve_implementation AssocItemKind::Type");
3424 self.with_generic_param_rib(
3426 &generics.params,
3427 RibKind::AssocItem,
3428 LifetimeRibKind::Generics {
3429 binder: item.id,
3430 span: generics.span,
3431 kind: LifetimeBinderKind::Item,
3432 },
3433 |this| {
3434 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3435 this.check_trait_item(
3438 item.id,
3439 *ident,
3440 &item.kind,
3441 TypeNS,
3442 item.span,
3443 seen_trait_items,
3444 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3445 );
3446
3447 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3448 });
3449 },
3450 );
3451 self.diag_metadata.in_non_gat_assoc_type = None;
3452 }
3453 AssocItemKind::Delegation(box delegation) => {
3454 debug!("resolve_implementation AssocItemKind::Delegation");
3455 self.with_generic_param_rib(
3456 &[],
3457 RibKind::AssocItem,
3458 LifetimeRibKind::Generics {
3459 binder: item.id,
3460 kind: LifetimeBinderKind::Function,
3461 span: delegation.path.segments.last().unwrap().ident.span,
3462 },
3463 |this| {
3464 this.check_trait_item(
3465 item.id,
3466 delegation.ident,
3467 &item.kind,
3468 ValueNS,
3469 item.span,
3470 seen_trait_items,
3471 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3472 );
3473
3474 this.resolve_delegation(delegation)
3475 },
3476 );
3477 }
3478 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3479 panic!("unexpanded macro in resolve!")
3480 }
3481 }
3482 }
3483
3484 fn check_trait_item<F>(
3485 &mut self,
3486 id: NodeId,
3487 mut ident: Ident,
3488 kind: &AssocItemKind,
3489 ns: Namespace,
3490 span: Span,
3491 seen_trait_items: &mut FxHashMap<DefId, Span>,
3492 err: F,
3493 ) where
3494 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3495 {
3496 let Some((module, _)) = self.current_trait_ref else {
3498 return;
3499 };
3500 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3501 let key = BindingKey::new(ident, ns);
3502 let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
3503 debug!(?binding);
3504 if binding.is_none() {
3505 let ns = match ns {
3508 ValueNS => TypeNS,
3509 TypeNS => ValueNS,
3510 _ => ns,
3511 };
3512 let key = BindingKey::new(ident, ns);
3513 binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
3514 debug!(?binding);
3515 }
3516
3517 let feed_visibility = |this: &mut Self, def_id| {
3518 let vis = this.r.tcx.visibility(def_id);
3519 let vis = if vis.is_visible_locally() {
3520 vis.expect_local()
3521 } else {
3522 this.r.dcx().span_delayed_bug(
3523 span,
3524 "error should be emitted when an unexpected trait item is used",
3525 );
3526 rustc_middle::ty::Visibility::Public
3527 };
3528 this.r.feed_visibility(this.r.feed(id), vis);
3529 };
3530
3531 let Some(binding) = binding else {
3532 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3534 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3535 let path_names = path_names_to_string(path);
3536 self.report_error(span, err(ident, path_names, candidate));
3537 feed_visibility(self, module.def_id());
3538 return;
3539 };
3540
3541 let res = binding.res();
3542 let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3543 feed_visibility(self, id_in_trait);
3544
3545 match seen_trait_items.entry(id_in_trait) {
3546 Entry::Occupied(entry) => {
3547 self.report_error(
3548 span,
3549 ResolutionError::TraitImplDuplicate {
3550 name: ident,
3551 old_span: *entry.get(),
3552 trait_item_span: binding.span,
3553 },
3554 );
3555 return;
3556 }
3557 Entry::Vacant(entry) => {
3558 entry.insert(span);
3559 }
3560 };
3561
3562 match (def_kind, kind) {
3563 (DefKind::AssocTy, AssocItemKind::Type(..))
3564 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3565 | (DefKind::AssocConst, AssocItemKind::Const(..))
3566 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3567 self.r.record_partial_res(id, PartialRes::new(res));
3568 return;
3569 }
3570 _ => {}
3571 }
3572
3573 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3575 let (code, kind) = match kind {
3576 AssocItemKind::Const(..) => (E0323, "const"),
3577 AssocItemKind::Fn(..) => (E0324, "method"),
3578 AssocItemKind::Type(..) => (E0325, "type"),
3579 AssocItemKind::Delegation(..) => (E0324, "method"),
3580 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3581 span_bug!(span, "unexpanded macro")
3582 }
3583 };
3584 let trait_path = path_names_to_string(path);
3585 self.report_error(
3586 span,
3587 ResolutionError::TraitImplMismatch {
3588 name: ident,
3589 kind,
3590 code,
3591 trait_path,
3592 trait_item_span: binding.span,
3593 },
3594 );
3595 }
3596
3597 fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3598 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3599 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3600 this.visit_expr(expr)
3601 });
3602 })
3603 }
3604
3605 fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3606 self.smart_resolve_path(
3607 delegation.id,
3608 &delegation.qself,
3609 &delegation.path,
3610 PathSource::Delegation,
3611 );
3612 if let Some(qself) = &delegation.qself {
3613 self.visit_ty(&qself.ty);
3614 }
3615 self.visit_path(&delegation.path, delegation.id);
3616 let Some(body) = &delegation.body else { return };
3617 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3618 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3620
3621 let span = delegation.path.segments.last().unwrap().ident.span;
3622 this.fresh_binding(
3623 Ident::new(kw::SelfLower, span),
3624 delegation.id,
3625 PatternSource::FnParam,
3626 &mut bindings,
3627 );
3628 this.visit_block(body);
3629 });
3630 }
3631
3632 fn resolve_params(&mut self, params: &'ast [Param]) {
3633 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3634 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3635 for Param { pat, .. } in params {
3636 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3637 }
3638 });
3639 for Param { ty, .. } in params {
3640 self.visit_ty(ty);
3641 }
3642 }
3643
3644 fn resolve_local(&mut self, local: &'ast Local) {
3645 debug!("resolving local ({:?})", local);
3646 visit_opt!(self, visit_ty, &local.ty);
3648
3649 if let Some((init, els)) = local.kind.init_else_opt() {
3651 self.visit_expr(init);
3652
3653 if let Some(els) = els {
3655 self.visit_block(els);
3656 }
3657 }
3658
3659 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3661 }
3662
3663 fn compute_and_check_binding_map(
3683 &mut self,
3684 pat: &Pat,
3685 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3686 let mut binding_map = FxIndexMap::default();
3687 let mut is_never_pat = false;
3688
3689 pat.walk(&mut |pat| {
3690 match pat.kind {
3691 PatKind::Ident(annotation, ident, ref sub_pat)
3692 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3693 {
3694 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3695 }
3696 PatKind::Or(ref ps) => {
3697 match self.compute_and_check_or_pat_binding_map(ps) {
3700 Ok(bm) => binding_map.extend(bm),
3701 Err(IsNeverPattern) => is_never_pat = true,
3702 }
3703 return false;
3704 }
3705 PatKind::Never => is_never_pat = true,
3706 _ => {}
3707 }
3708
3709 true
3710 });
3711
3712 if is_never_pat {
3713 for (_, binding) in binding_map {
3714 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3715 }
3716 Err(IsNeverPattern)
3717 } else {
3718 Ok(binding_map)
3719 }
3720 }
3721
3722 fn is_base_res_local(&self, nid: NodeId) -> bool {
3723 matches!(
3724 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3725 Some(Res::Local(..))
3726 )
3727 }
3728
3729 fn compute_and_check_or_pat_binding_map(
3749 &mut self,
3750 pats: &[P<Pat>],
3751 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3752 let mut missing_vars = FxIndexMap::default();
3753 let mut inconsistent_vars = FxIndexMap::default();
3754
3755 let not_never_pats = pats
3757 .iter()
3758 .filter_map(|pat| {
3759 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3760 Some((binding_map, pat))
3761 })
3762 .collect::<Vec<_>>();
3763
3764 for (map_outer, pat_outer) in not_never_pats.iter() {
3766 let inners = not_never_pats
3768 .iter()
3769 .filter(|(_, pat)| pat.id != pat_outer.id)
3770 .flat_map(|(map, _)| map);
3771
3772 for (&name, binding_inner) in inners {
3773 match map_outer.get(&name) {
3774 None => {
3775 let binding_error =
3777 missing_vars.entry(name).or_insert_with(|| BindingError {
3778 name,
3779 origin: BTreeSet::new(),
3780 target: BTreeSet::new(),
3781 could_be_path: name.as_str().starts_with(char::is_uppercase),
3782 });
3783 binding_error.origin.insert(binding_inner.span);
3784 binding_error.target.insert(pat_outer.span);
3785 }
3786 Some(binding_outer) => {
3787 if binding_outer.annotation != binding_inner.annotation {
3788 inconsistent_vars
3790 .entry(name)
3791 .or_insert((binding_inner.span, binding_outer.span));
3792 }
3793 }
3794 }
3795 }
3796 }
3797
3798 for (name, mut v) in missing_vars {
3800 if inconsistent_vars.contains_key(&name) {
3801 v.could_be_path = false;
3802 }
3803 self.report_error(
3804 *v.origin.iter().next().unwrap(),
3805 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3806 );
3807 }
3808
3809 for (name, v) in inconsistent_vars {
3811 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3812 }
3813
3814 if not_never_pats.is_empty() {
3816 Err(IsNeverPattern)
3818 } else {
3819 let mut binding_map = FxIndexMap::default();
3820 for (bm, _) in not_never_pats {
3821 binding_map.extend(bm);
3822 }
3823 Ok(binding_map)
3824 }
3825 }
3826
3827 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3829 let mut is_or_or_never = false;
3830 pat.walk(&mut |pat| match pat.kind {
3831 PatKind::Or(..) | PatKind::Never => {
3832 is_or_or_never = true;
3833 false
3834 }
3835 _ => true,
3836 });
3837 if is_or_or_never {
3838 let _ = self.compute_and_check_binding_map(pat);
3839 }
3840 }
3841
3842 fn resolve_arm(&mut self, arm: &'ast Arm) {
3843 self.with_rib(ValueNS, RibKind::Normal, |this| {
3844 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3845 visit_opt!(this, visit_expr, &arm.guard);
3846 visit_opt!(this, visit_expr, &arm.body);
3847 });
3848 }
3849
3850 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3852 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3853 self.resolve_pattern(pat, pat_src, &mut bindings);
3854 }
3855
3856 fn resolve_pattern(
3857 &mut self,
3858 pat: &'ast Pat,
3859 pat_src: PatternSource,
3860 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3861 ) {
3862 visit::walk_pat(self, pat);
3866 self.resolve_pattern_inner(pat, pat_src, bindings);
3867 self.check_consistent_bindings(pat);
3869 }
3870
3871 #[tracing::instrument(skip(self, bindings), level = "debug")]
3891 fn resolve_pattern_inner(
3892 &mut self,
3893 pat: &Pat,
3894 pat_src: PatternSource,
3895 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3896 ) {
3897 pat.walk(&mut |pat| {
3899 match pat.kind {
3900 PatKind::Ident(bmode, ident, ref sub) => {
3901 let has_sub = sub.is_some();
3904 let res = self
3905 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3906 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3907 self.r.record_partial_res(pat.id, PartialRes::new(res));
3908 self.r.record_pat_span(pat.id, pat.span);
3909 }
3910 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3911 self.smart_resolve_path(
3912 pat.id,
3913 qself,
3914 path,
3915 PathSource::TupleStruct(
3916 pat.span,
3917 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3918 ),
3919 );
3920 }
3921 PatKind::Path(ref qself, ref path) => {
3922 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3923 }
3924 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3925 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3926 self.record_patterns_with_skipped_bindings(pat, rest);
3927 }
3928 PatKind::Or(ref ps) => {
3929 bindings.push((PatBoundCtx::Or, Default::default()));
3933 for p in ps {
3934 bindings.push((PatBoundCtx::Product, Default::default()));
3938 self.resolve_pattern_inner(p, pat_src, bindings);
3939 let collected = bindings.pop().unwrap().1;
3942 bindings.last_mut().unwrap().1.extend(collected);
3943 }
3944 let collected = bindings.pop().unwrap().1;
3948 bindings.last_mut().unwrap().1.extend(collected);
3949
3950 return false;
3952 }
3953 _ => {}
3954 }
3955 true
3956 });
3957 }
3958
3959 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
3960 match rest {
3961 ast::PatFieldsRest::Rest | ast::PatFieldsRest::Recovered(_) => {
3962 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
3964 && let Some(res) = partial_res.full_res()
3965 && let Some(def_id) = res.opt_def_id()
3966 {
3967 self.ribs[ValueNS]
3968 .last_mut()
3969 .unwrap()
3970 .patterns_with_skipped_bindings
3971 .entry(def_id)
3972 .or_default()
3973 .push((
3974 pat.span,
3975 match rest {
3976 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
3977 _ => Ok(()),
3978 },
3979 ));
3980 }
3981 }
3982 ast::PatFieldsRest::None => {}
3983 }
3984 }
3985
3986 fn fresh_binding(
3987 &mut self,
3988 ident: Ident,
3989 pat_id: NodeId,
3990 pat_src: PatternSource,
3991 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3992 ) -> Res {
3993 let ident = ident.normalize_to_macro_rules();
3997
3998 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
3999 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
4001 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
4004
4005 if already_bound_and {
4006 use ResolutionError::*;
4008 let error = match pat_src {
4009 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4011 _ => IdentifierBoundMoreThanOnceInSamePattern,
4013 };
4014 self.report_error(ident.span, error(ident));
4015 }
4016
4017 bindings.last_mut().unwrap().1.insert(ident);
4019
4020 if already_bound_or {
4021 self.innermost_rib_bindings(ValueNS)[&ident]
4024 } else {
4025 let res = Res::Local(pat_id);
4027 self.innermost_rib_bindings(ValueNS).insert(ident, res);
4028 res
4029 }
4030 }
4031
4032 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4033 &mut self.ribs[ns].last_mut().unwrap().bindings
4034 }
4035
4036 fn try_resolve_as_non_binding(
4037 &mut self,
4038 pat_src: PatternSource,
4039 ann: BindingMode,
4040 ident: Ident,
4041 has_sub: bool,
4042 ) -> Option<Res> {
4043 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4047
4048 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4049 let (res, binding) = match ls_binding {
4050 LexicalScopeBinding::Item(binding)
4051 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4052 {
4053 self.r.record_use(ident, binding, Used::Other);
4058 return None;
4059 }
4060 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4061 LexicalScopeBinding::Res(res) => (res, None),
4062 };
4063
4064 match res {
4065 Res::SelfCtor(_) | Res::Def(
4067 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4068 _,
4069 ) if is_syntactic_ambiguity => {
4070 if let Some(binding) = binding {
4072 self.r.record_use(ident, binding, Used::Other);
4073 }
4074 Some(res)
4075 }
4076 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4077 let binding = binding.expect("no binding for a ctor or static");
4083 self.report_error(
4084 ident.span,
4085 ResolutionError::BindingShadowsSomethingUnacceptable {
4086 shadowing_binding: pat_src,
4087 name: ident.name,
4088 participle: if binding.is_import() { "imported" } else { "defined" },
4089 article: binding.res().article(),
4090 shadowed_binding: binding.res(),
4091 shadowed_binding_span: binding.span,
4092 },
4093 );
4094 None
4095 }
4096 Res::Def(DefKind::ConstParam, def_id) => {
4097 self.report_error(
4100 ident.span,
4101 ResolutionError::BindingShadowsSomethingUnacceptable {
4102 shadowing_binding: pat_src,
4103 name: ident.name,
4104 participle: "defined",
4105 article: res.article(),
4106 shadowed_binding: res,
4107 shadowed_binding_span: self.r.def_span(def_id),
4108 }
4109 );
4110 None
4111 }
4112 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4113 None
4115 }
4116 Res::SelfCtor(_) => {
4117 self.r.dcx().span_delayed_bug(
4120 ident.span,
4121 "unexpected `SelfCtor` in pattern, expected identifier"
4122 );
4123 None
4124 }
4125 _ => span_bug!(
4126 ident.span,
4127 "unexpected resolution for an identifier in pattern: {:?}",
4128 res,
4129 ),
4130 }
4131 }
4132
4133 fn smart_resolve_path(
4139 &mut self,
4140 id: NodeId,
4141 qself: &Option<P<QSelf>>,
4142 path: &Path,
4143 source: PathSource<'ast>,
4144 ) {
4145 self.smart_resolve_path_fragment(
4146 qself,
4147 &Segment::from_path(path),
4148 source,
4149 Finalize::new(id, path.span),
4150 RecordPartialRes::Yes,
4151 None,
4152 );
4153 }
4154
4155 #[instrument(level = "debug", skip(self))]
4156 fn smart_resolve_path_fragment(
4157 &mut self,
4158 qself: &Option<P<QSelf>>,
4159 path: &[Segment],
4160 source: PathSource<'ast>,
4161 finalize: Finalize,
4162 record_partial_res: RecordPartialRes,
4163 parent_qself: Option<&QSelf>,
4164 ) -> PartialRes {
4165 let ns = source.namespace();
4166
4167 let Finalize { node_id, path_span, .. } = finalize;
4168 let report_errors = |this: &mut Self, res: Option<Res>| {
4169 if this.should_report_errs() {
4170 let (err, candidates) = this.smart_resolve_report_errors(
4171 path,
4172 None,
4173 path_span,
4174 source,
4175 res,
4176 parent_qself,
4177 );
4178
4179 let def_id = this.parent_scope.module.nearest_parent_mod();
4180 let instead = res.is_some();
4181 let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4182 && path[0].ident.span.lo() == end.span.lo()
4183 && !matches!(start.kind, ExprKind::Lit(_))
4184 {
4185 let mut sugg = ".";
4186 let mut span = start.span.between(end.span);
4187 if span.lo() + BytePos(2) == span.hi() {
4188 span = span.with_lo(span.lo() + BytePos(1));
4191 sugg = "";
4192 }
4193 Some((
4194 span,
4195 "you might have meant to write `.` instead of `..`",
4196 sugg.to_string(),
4197 Applicability::MaybeIncorrect,
4198 ))
4199 } else if res.is_none()
4200 && let PathSource::Type
4201 | PathSource::Expr(_)
4202 | PathSource::PreciseCapturingArg(..) = source
4203 {
4204 this.suggest_adding_generic_parameter(path, source)
4205 } else {
4206 None
4207 };
4208
4209 let ue = UseError {
4210 err,
4211 candidates,
4212 def_id,
4213 instead,
4214 suggestion,
4215 path: path.into(),
4216 is_call: source.is_call(),
4217 };
4218
4219 this.r.use_injections.push(ue);
4220 }
4221
4222 PartialRes::new(Res::Err)
4223 };
4224
4225 let report_errors_for_call =
4231 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4232 let (following_seg, prefix_path) = match path.split_last() {
4236 Some((last, path)) if !path.is_empty() => (Some(last), path),
4237 _ => return Some(parent_err),
4238 };
4239
4240 let (mut err, candidates) = this.smart_resolve_report_errors(
4241 prefix_path,
4242 following_seg,
4243 path_span,
4244 PathSource::Type,
4245 None,
4246 parent_qself,
4247 );
4248
4249 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4264
4265 err.messages = take(&mut parent_err.messages);
4267 err.code = take(&mut parent_err.code);
4268 swap(&mut err.span, &mut parent_err.span);
4269 err.children = take(&mut parent_err.children);
4270 err.sort_span = parent_err.sort_span;
4271 err.is_lint = parent_err.is_lint.clone();
4272
4273 match &mut err.suggestions {
4275 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4276 Suggestions::Enabled(parent_suggestions) => {
4277 typo_suggestions.append(parent_suggestions)
4279 }
4280 Suggestions::Sealed(_) | Suggestions::Disabled => {
4281 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4286 }
4287 },
4288 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4289 }
4290
4291 parent_err.cancel();
4292
4293 let def_id = this.parent_scope.module.nearest_parent_mod();
4294
4295 if this.should_report_errs() {
4296 if candidates.is_empty() {
4297 if path.len() == 2
4298 && let [segment] = prefix_path
4299 {
4300 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4306 } else {
4307 err.emit();
4312 }
4313 } else {
4314 this.r.use_injections.push(UseError {
4316 err,
4317 candidates,
4318 def_id,
4319 instead: false,
4320 suggestion: None,
4321 path: prefix_path.into(),
4322 is_call: source.is_call(),
4323 });
4324 }
4325 } else {
4326 err.cancel();
4327 }
4328
4329 None
4332 };
4333
4334 let partial_res = match self.resolve_qpath_anywhere(
4335 qself,
4336 path,
4337 ns,
4338 path_span,
4339 source.defer_to_typeck(),
4340 finalize,
4341 ) {
4342 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4343 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4345 && let [Segment { ident, .. }] = path
4346 && items.iter().any(|item| {
4347 if let AssocItemKind::Type(alias) = &item.kind
4348 && alias.ident == *ident
4349 {
4350 true
4351 } else {
4352 false
4353 }
4354 })
4355 {
4356 let mut diag = self.r.tcx.dcx().struct_allow("");
4357 diag.span_suggestion_verbose(
4358 path_span.shrink_to_lo(),
4359 "there is an associated type with the same name",
4360 "Self::",
4361 Applicability::MaybeIncorrect,
4362 );
4363 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4364 }
4365
4366 if source.is_expected(res) || res == Res::Err {
4367 partial_res
4368 } else {
4369 report_errors(self, Some(res))
4370 }
4371 }
4372
4373 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4374 if ns == ValueNS {
4378 let item_name = path.last().unwrap().ident;
4379 let traits = self.traits_in_scope(item_name, ns);
4380 self.r.trait_map.insert(node_id, traits);
4381 }
4382
4383 if PrimTy::from_name(path[0].ident.name).is_some() {
4384 let mut std_path = Vec::with_capacity(1 + path.len());
4385
4386 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4387 std_path.extend(path);
4388 if let PathResult::Module(_) | PathResult::NonModule(_) =
4389 self.resolve_path(&std_path, Some(ns), None)
4390 {
4391 let item_span =
4393 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4394
4395 self.r.confused_type_with_std_module.insert(item_span, path_span);
4396 self.r.confused_type_with_std_module.insert(path_span, path_span);
4397 }
4398 }
4399
4400 partial_res
4401 }
4402
4403 Err(err) => {
4404 if let Some(err) = report_errors_for_call(self, err) {
4405 self.report_error(err.span, err.node);
4406 }
4407
4408 PartialRes::new(Res::Err)
4409 }
4410
4411 _ => report_errors(self, None),
4412 };
4413
4414 if record_partial_res == RecordPartialRes::Yes {
4415 self.r.record_partial_res(node_id, partial_res);
4417 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4418 self.lint_unused_qualifications(path, ns, finalize);
4419 }
4420
4421 partial_res
4422 }
4423
4424 fn self_type_is_available(&mut self) -> bool {
4425 let binding = self
4426 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4427 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4428 }
4429
4430 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4431 let ident = Ident::new(kw::SelfLower, self_span);
4432 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4433 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4434 }
4435
4436 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4440 if self.should_report_errs() {
4441 self.r.report_error(span, resolution_error);
4442 }
4443 }
4444
4445 #[inline]
4446 fn should_report_errs(&self) -> bool {
4450 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4451 && !self.r.glob_error.is_some()
4452 }
4453
4454 fn resolve_qpath_anywhere(
4456 &mut self,
4457 qself: &Option<P<QSelf>>,
4458 path: &[Segment],
4459 primary_ns: Namespace,
4460 span: Span,
4461 defer_to_typeck: bool,
4462 finalize: Finalize,
4463 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4464 let mut fin_res = None;
4465
4466 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4467 if i == 0 || ns != primary_ns {
4468 match self.resolve_qpath(qself, path, ns, finalize)? {
4469 Some(partial_res)
4470 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4471 {
4472 return Ok(Some(partial_res));
4473 }
4474 partial_res => {
4475 if fin_res.is_none() {
4476 fin_res = partial_res;
4477 }
4478 }
4479 }
4480 }
4481 }
4482
4483 assert!(primary_ns != MacroNS);
4484
4485 if qself.is_none() {
4486 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
4487 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
4488 if let Ok((_, res)) =
4489 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false, None)
4490 {
4491 return Ok(Some(PartialRes::new(res)));
4492 }
4493 }
4494
4495 Ok(fin_res)
4496 }
4497
4498 fn resolve_qpath(
4500 &mut self,
4501 qself: &Option<P<QSelf>>,
4502 path: &[Segment],
4503 ns: Namespace,
4504 finalize: Finalize,
4505 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4506 debug!(
4507 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4508 qself, path, ns, finalize,
4509 );
4510
4511 if let Some(qself) = qself {
4512 if qself.position == 0 {
4513 return Ok(Some(PartialRes::with_unresolved_segments(
4517 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4518 path.len(),
4519 )));
4520 }
4521
4522 let num_privacy_errors = self.r.privacy_errors.len();
4523 let trait_res = self.smart_resolve_path_fragment(
4525 &None,
4526 &path[..qself.position],
4527 PathSource::Trait(AliasPossibility::No),
4528 Finalize::new(finalize.node_id, qself.path_span),
4529 RecordPartialRes::No,
4530 Some(&qself),
4531 );
4532
4533 if trait_res.expect_full_res() == Res::Err {
4534 return Ok(Some(trait_res));
4535 }
4536
4537 self.r.privacy_errors.truncate(num_privacy_errors);
4540
4541 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4549 let partial_res = self.smart_resolve_path_fragment(
4550 &None,
4551 &path[..=qself.position],
4552 PathSource::TraitItem(ns),
4553 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4554 RecordPartialRes::No,
4555 Some(&qself),
4556 );
4557
4558 return Ok(Some(PartialRes::with_unresolved_segments(
4562 partial_res.base_res(),
4563 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4564 )));
4565 }
4566
4567 let result = match self.resolve_path(path, Some(ns), Some(finalize)) {
4568 PathResult::NonModule(path_res) => path_res,
4569 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4570 PartialRes::new(module.res().unwrap())
4571 }
4572 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4576 PartialRes::new(Res::Err)
4577 }
4578 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4591 if (ns == TypeNS || path.len() > 1)
4592 && PrimTy::from_name(path[0].ident.name).is_some() =>
4593 {
4594 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4595 let tcx = self.r.tcx();
4596
4597 let gate_err_sym_msg = match prim {
4598 PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4599 Some((sym::f16, "the type `f16` is unstable"))
4600 }
4601 PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4602 Some((sym::f128, "the type `f128` is unstable"))
4603 }
4604 _ => None,
4605 };
4606
4607 if let Some((sym, msg)) = gate_err_sym_msg {
4608 let span = path[0].ident.span;
4609 if !span.allows_unstable(sym) {
4610 feature_err(tcx.sess, sym, span, msg).emit();
4611 }
4612 };
4613
4614 if let Some(id) = path[0].id {
4616 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4617 }
4618
4619 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4620 }
4621 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4622 PartialRes::new(module.res().unwrap())
4623 }
4624 PathResult::Failed {
4625 is_error_from_last_segment: false,
4626 span,
4627 label,
4628 suggestion,
4629 module,
4630 segment_name,
4631 error_implied_by_parse_error: _,
4632 } => {
4633 return Err(respan(
4634 span,
4635 ResolutionError::FailedToResolve {
4636 segment: Some(segment_name),
4637 label,
4638 suggestion,
4639 module,
4640 },
4641 ));
4642 }
4643 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4644 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4645 };
4646
4647 Ok(Some(result))
4648 }
4649
4650 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4651 if let Some(label) = label {
4652 if label.ident.as_str().as_bytes()[1] != b'_' {
4653 self.diag_metadata.unused_labels.insert(id, label.ident.span);
4654 }
4655
4656 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4657 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4658 }
4659
4660 self.with_label_rib(RibKind::Normal, |this| {
4661 let ident = label.ident.normalize_to_macro_rules();
4662 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4663 f(this);
4664 });
4665 } else {
4666 f(self);
4667 }
4668 }
4669
4670 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4671 self.with_resolved_label(label, id, |this| this.visit_block(block));
4672 }
4673
4674 fn resolve_block(&mut self, block: &'ast Block) {
4675 debug!("(resolving block) entering block");
4676 let orig_module = self.parent_scope.module;
4678 let anonymous_module = self.r.block_map.get(&block.id).cloned(); let mut num_macro_definition_ribs = 0;
4681 if let Some(anonymous_module) = anonymous_module {
4682 debug!("(resolving block) found anonymous module, moving down");
4683 self.ribs[ValueNS].push(Rib::new(RibKind::Module(anonymous_module)));
4684 self.ribs[TypeNS].push(Rib::new(RibKind::Module(anonymous_module)));
4685 self.parent_scope.module = anonymous_module;
4686 } else {
4687 self.ribs[ValueNS].push(Rib::new(RibKind::Normal));
4688 }
4689
4690 for stmt in &block.stmts {
4692 if let StmtKind::Item(ref item) = stmt.kind
4693 && let ItemKind::MacroDef(..) = item.kind
4694 {
4695 num_macro_definition_ribs += 1;
4696 let res = self.r.local_def_id(item.id).to_def_id();
4697 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4698 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4699 }
4700
4701 self.visit_stmt(stmt);
4702 }
4703
4704 self.parent_scope.module = orig_module;
4706 for _ in 0..num_macro_definition_ribs {
4707 self.ribs[ValueNS].pop();
4708 self.label_ribs.pop();
4709 }
4710 self.last_block_rib = self.ribs[ValueNS].pop();
4711 if anonymous_module.is_some() {
4712 self.ribs[TypeNS].pop();
4713 }
4714 debug!("(resolving block) leaving block");
4715 }
4716
4717 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4718 debug!(
4719 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4720 constant, anon_const_kind
4721 );
4722
4723 let is_trivial_const_arg = constant
4724 .value
4725 .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4726 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4727 this.resolve_expr(&constant.value, None)
4728 })
4729 }
4730
4731 fn resolve_anon_const_manual(
4738 &mut self,
4739 is_trivial_const_arg: bool,
4740 anon_const_kind: AnonConstKind,
4741 resolve_expr: impl FnOnce(&mut Self),
4742 ) {
4743 let is_repeat_expr = match anon_const_kind {
4744 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4745 _ => IsRepeatExpr::No,
4746 };
4747
4748 let may_use_generics = match anon_const_kind {
4749 AnonConstKind::EnumDiscriminant => {
4750 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4751 }
4752 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4753 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4754 AnonConstKind::ConstArg(_) => {
4755 if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4756 ConstantHasGenerics::Yes
4757 } else {
4758 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4759 }
4760 }
4761 };
4762
4763 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4764 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4765 resolve_expr(this);
4766 });
4767 });
4768 }
4769
4770 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4771 self.resolve_expr(&f.expr, Some(e));
4772 self.visit_ident(&f.ident);
4773 walk_list!(self, visit_attribute, f.attrs.iter());
4774 }
4775
4776 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4777 self.record_candidate_traits_for_expr_if_necessary(expr);
4781
4782 match expr.kind {
4784 ExprKind::Path(ref qself, ref path) => {
4785 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4786 visit::walk_expr(self, expr);
4787 }
4788
4789 ExprKind::Struct(ref se) => {
4790 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct);
4791 if let Some(qself) = &se.qself {
4795 self.visit_ty(&qself.ty);
4796 }
4797 self.visit_path(&se.path, expr.id);
4798 walk_list!(self, resolve_expr_field, &se.fields, expr);
4799 match &se.rest {
4800 StructRest::Base(expr) => self.visit_expr(expr),
4801 StructRest::Rest(_span) => {}
4802 StructRest::None => {}
4803 }
4804 }
4805
4806 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4807 match self.resolve_label(label.ident) {
4808 Ok((node_id, _)) => {
4809 self.r.label_res_map.insert(expr.id, node_id);
4811 self.diag_metadata.unused_labels.swap_remove(&node_id);
4812 }
4813 Err(error) => {
4814 self.report_error(label.ident.span, error);
4815 }
4816 }
4817
4818 visit::walk_expr(self, expr);
4820 }
4821
4822 ExprKind::Break(None, Some(ref e)) => {
4823 self.resolve_expr(e, Some(expr));
4826 }
4827
4828 ExprKind::Let(ref pat, ref scrutinee, _, _) => {
4829 self.visit_expr(scrutinee);
4830 self.resolve_pattern_top(pat, PatternSource::Let);
4831 }
4832
4833 ExprKind::If(ref cond, ref then, ref opt_else) => {
4834 self.with_rib(ValueNS, RibKind::Normal, |this| {
4835 let old = this.diag_metadata.in_if_condition.replace(cond);
4836 this.visit_expr(cond);
4837 this.diag_metadata.in_if_condition = old;
4838 this.visit_block(then);
4839 });
4840 if let Some(expr) = opt_else {
4841 self.visit_expr(expr);
4842 }
4843 }
4844
4845 ExprKind::Loop(ref block, label, _) => {
4846 self.resolve_labeled_block(label, expr.id, block)
4847 }
4848
4849 ExprKind::While(ref cond, ref block, label) => {
4850 self.with_resolved_label(label, expr.id, |this| {
4851 this.with_rib(ValueNS, RibKind::Normal, |this| {
4852 let old = this.diag_metadata.in_if_condition.replace(cond);
4853 this.visit_expr(cond);
4854 this.diag_metadata.in_if_condition = old;
4855 this.visit_block(block);
4856 })
4857 });
4858 }
4859
4860 ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4861 self.visit_expr(iter);
4862 self.with_rib(ValueNS, RibKind::Normal, |this| {
4863 this.resolve_pattern_top(pat, PatternSource::For);
4864 this.resolve_labeled_block(label, expr.id, body);
4865 });
4866 }
4867
4868 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4869
4870 ExprKind::Field(ref subexpression, _) => {
4872 self.resolve_expr(subexpression, Some(expr));
4873 }
4874 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
4875 self.resolve_expr(receiver, Some(expr));
4876 for arg in args {
4877 self.resolve_expr(arg, None);
4878 }
4879 self.visit_path_segment(seg);
4880 }
4881
4882 ExprKind::Call(ref callee, ref arguments) => {
4883 self.resolve_expr(callee, Some(expr));
4884 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
4885 for (idx, argument) in arguments.iter().enumerate() {
4886 if const_args.contains(&idx) {
4889 let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
4890 self.r.tcx.features().min_generic_const_args(),
4891 );
4892 self.resolve_anon_const_manual(
4893 is_trivial_const_arg,
4894 AnonConstKind::ConstArg(IsRepeatExpr::No),
4895 |this| this.resolve_expr(argument, None),
4896 );
4897 } else {
4898 self.resolve_expr(argument, None);
4899 }
4900 }
4901 }
4902 ExprKind::Type(ref _type_expr, ref _ty) => {
4903 visit::walk_expr(self, expr);
4904 }
4905 ExprKind::Closure(box ast::Closure {
4907 binder: ClosureBinder::For { ref generic_params, span },
4908 ..
4909 }) => {
4910 self.with_generic_param_rib(
4911 generic_params,
4912 RibKind::Normal,
4913 LifetimeRibKind::Generics {
4914 binder: expr.id,
4915 kind: LifetimeBinderKind::Closure,
4916 span,
4917 },
4918 |this| visit::walk_expr(this, expr),
4919 );
4920 }
4921 ExprKind::Closure(..) => visit::walk_expr(self, expr),
4922 ExprKind::Gen(..) => {
4923 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
4924 }
4925 ExprKind::Repeat(ref elem, ref ct) => {
4926 self.visit_expr(elem);
4927 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
4928 }
4929 ExprKind::ConstBlock(ref ct) => {
4930 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
4931 }
4932 ExprKind::Index(ref elem, ref idx, _) => {
4933 self.resolve_expr(elem, Some(expr));
4934 self.visit_expr(idx);
4935 }
4936 ExprKind::Assign(ref lhs, ref rhs, _) => {
4937 if !self.diag_metadata.is_assign_rhs {
4938 self.diag_metadata.in_assignment = Some(expr);
4939 }
4940 self.visit_expr(lhs);
4941 self.diag_metadata.is_assign_rhs = true;
4942 self.diag_metadata.in_assignment = None;
4943 self.visit_expr(rhs);
4944 self.diag_metadata.is_assign_rhs = false;
4945 }
4946 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
4947 self.diag_metadata.in_range = Some((start, end));
4948 self.resolve_expr(start, Some(expr));
4949 self.resolve_expr(end, Some(expr));
4950 self.diag_metadata.in_range = None;
4951 }
4952 _ => {
4953 visit::walk_expr(self, expr);
4954 }
4955 }
4956 }
4957
4958 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
4959 match expr.kind {
4960 ExprKind::Field(_, ident) => {
4961 let traits = self.traits_in_scope(ident, ValueNS);
4966 self.r.trait_map.insert(expr.id, traits);
4967 }
4968 ExprKind::MethodCall(ref call) => {
4969 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
4970 let traits = self.traits_in_scope(call.seg.ident, ValueNS);
4971 self.r.trait_map.insert(expr.id, traits);
4972 }
4973 _ => {
4974 }
4976 }
4977 }
4978
4979 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
4980 self.r.traits_in_scope(
4981 self.current_trait_ref.as_ref().map(|(module, _)| *module),
4982 &self.parent_scope,
4983 ident.span.ctxt(),
4984 Some((ident.name, ns)),
4985 )
4986 }
4987
4988 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
4989 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
4993 let res = *doc_link_resolutions
4994 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
4995 .or_default()
4996 .entry((Symbol::intern(path_str), ns))
4997 .or_insert_with_key(|(path, ns)| {
4998 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
4999 if let Some(res) = res
5000 && let Some(def_id) = res.opt_def_id()
5001 && self.is_invalid_proc_macro_item_for_doc(def_id)
5002 {
5003 return None;
5006 }
5007 res
5008 });
5009 self.r.doc_link_resolutions = doc_link_resolutions;
5010 res
5011 }
5012
5013 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5014 if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5015 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5016 {
5017 return false;
5018 }
5019 let Some(local_did) = did.as_local() else { return true };
5020 !self.r.proc_macros.contains(&local_did)
5021 }
5022
5023 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5024 match self.r.tcx.sess.opts.resolve_doc_links {
5025 ResolveDocLinks::None => return,
5026 ResolveDocLinks::ExportedMetadata
5027 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5028 || !maybe_exported.eval(self.r) =>
5029 {
5030 return;
5031 }
5032 ResolveDocLinks::Exported
5033 if !maybe_exported.eval(self.r)
5034 && !rustdoc::has_primitive_or_keyword_docs(attrs) =>
5035 {
5036 return;
5037 }
5038 ResolveDocLinks::ExportedMetadata
5039 | ResolveDocLinks::Exported
5040 | ResolveDocLinks::All => {}
5041 }
5042
5043 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5044 return;
5045 }
5046
5047 let mut need_traits_in_scope = false;
5048 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5049 let mut any_resolved = false;
5051 let mut need_assoc = false;
5052 for ns in [TypeNS, ValueNS, MacroNS] {
5053 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5054 any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5057 } else if ns != MacroNS {
5058 need_assoc = true;
5059 }
5060 }
5061
5062 if need_assoc || !any_resolved {
5064 let mut path = &path_str[..];
5065 while let Some(idx) = path.rfind("::") {
5066 path = &path[..idx];
5067 need_traits_in_scope = true;
5068 for ns in [TypeNS, ValueNS, MacroNS] {
5069 self.resolve_and_cache_rustdoc_path(path, ns);
5070 }
5071 }
5072 }
5073 }
5074
5075 if need_traits_in_scope {
5076 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5078 doc_link_traits_in_scope
5079 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5080 .or_insert_with(|| {
5081 self.r
5082 .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5083 .into_iter()
5084 .filter_map(|tr| {
5085 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5086 return None;
5089 }
5090 Some(tr.def_id)
5091 })
5092 .collect()
5093 });
5094 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5095 }
5096 }
5097
5098 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5099 if let Some(seg) = path.first()
5101 && seg.ident.name == kw::PathRoot
5102 {
5103 return;
5104 }
5105
5106 if finalize.path_span.from_expansion()
5107 || path.iter().any(|seg| seg.ident.span.from_expansion())
5108 {
5109 return;
5110 }
5111
5112 let end_pos =
5113 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5114 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5115 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5124 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5125 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5126 (res == binding.res()).then_some((seg, binding))
5127 });
5128
5129 if let Some((seg, binding)) = unqualified {
5130 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5131 binding,
5132 node_id: finalize.node_id,
5133 path_span: finalize.path_span,
5134 removal_span: path[0].ident.span.until(seg.ident.span),
5135 });
5136 }
5137 }
5138
5139 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5140 if let Some(define_opaque) = define_opaque {
5141 for (id, path) in define_opaque {
5142 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5143 }
5144 }
5145 }
5146}
5147
5148struct ItemInfoCollector<'a, 'ra, 'tcx> {
5151 r: &'a mut Resolver<'ra, 'tcx>,
5152}
5153
5154impl ItemInfoCollector<'_, '_, '_> {
5155 fn collect_fn_info(
5156 &mut self,
5157 header: FnHeader,
5158 decl: &FnDecl,
5159 id: NodeId,
5160 attrs: &[Attribute],
5161 ) {
5162 let sig = DelegationFnSig {
5163 header,
5164 param_count: decl.inputs.len(),
5165 has_self: decl.has_self(),
5166 c_variadic: decl.c_variadic(),
5167 target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5168 };
5169 self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5170 }
5171}
5172
5173impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5174 fn visit_item(&mut self, item: &'ast Item) {
5175 match &item.kind {
5176 ItemKind::TyAlias(box TyAlias { generics, .. })
5177 | ItemKind::Const(box ConstItem { generics, .. })
5178 | ItemKind::Fn(box Fn { generics, .. })
5179 | ItemKind::Enum(_, _, generics)
5180 | ItemKind::Struct(_, _, generics)
5181 | ItemKind::Union(_, _, generics)
5182 | ItemKind::Impl(box Impl { generics, .. })
5183 | ItemKind::Trait(box Trait { generics, .. })
5184 | ItemKind::TraitAlias(_, generics, _) => {
5185 if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5186 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5187 }
5188
5189 let def_id = self.r.local_def_id(item.id);
5190 let count = generics
5191 .params
5192 .iter()
5193 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5194 .count();
5195 self.r.item_generics_num_lifetimes.insert(def_id, count);
5196 }
5197
5198 ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5199 for foreign_item in items {
5200 if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5201 let new_header =
5202 FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5203 self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5204 }
5205 }
5206 }
5207
5208 ItemKind::Mod(..)
5209 | ItemKind::Static(..)
5210 | ItemKind::Use(..)
5211 | ItemKind::ExternCrate(..)
5212 | ItemKind::MacroDef(..)
5213 | ItemKind::GlobalAsm(..)
5214 | ItemKind::MacCall(..)
5215 | ItemKind::DelegationMac(..) => {}
5216 ItemKind::Delegation(..) => {
5217 }
5222 }
5223 visit::walk_item(self, item)
5224 }
5225
5226 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5227 if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5228 self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5229 }
5230 visit::walk_assoc_item(self, item, ctxt);
5231 }
5232}
5233
5234impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5235 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5236 visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5237 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5238 late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5239 visit::walk_crate(&mut late_resolution_visitor, krate);
5240 for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5241 self.lint_buffer.buffer_lint(
5242 lint::builtin::UNUSED_LABELS,
5243 *id,
5244 *span,
5245 BuiltinLintDiag::UnusedLabel,
5246 );
5247 }
5248 }
5249}
5250
5251fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5253 let mut path = expected_path.iter().rev();
5254 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5255 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5256 return false;
5257 }
5258 def_id = parent;
5259 }
5260 true
5261}