-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
late.rs
5032 lines (4626 loc) · 212 KB
/
late.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ignore-tidy-filelength
//! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
//! It runs when the crate is fully expanded and its module structure is fully built.
//! So it just walks through the crate and resolves all the expressions, types, etc.
//!
//! If you wonder why there's no `early.rs`, that's because it's split into three files -
//! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
use std::assert_matches::debug_assert_matches;
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::collections::hash_map::Entry;
use std::mem::{replace, swap, take};
use rustc_ast::ptr::P;
use rustc_ast::visit::{AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, visit_opt, walk_list};
use rustc_ast::*;
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
use rustc_errors::codes::*;
use rustc_errors::{Applicability, DiagArgValue, IntoDiagArg, StashKey, Suggestions};
use rustc_hir::def::Namespace::{self, *};
use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS};
use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId};
use rustc_hir::{MissingLifetimeKind, PrimTy, TraitCandidate};
use rustc_middle::middle::resolve_bound_vars::Set1;
use rustc_middle::ty::DelegationFnSig;
use rustc_middle::{bug, span_bug};
use rustc_session::config::{CrateType, ResolveDocLinks};
use rustc_session::lint::{self, BuiltinLintDiag};
use rustc_session::parse::feature_err;
use rustc_span::source_map::{Spanned, respan};
use rustc_span::symbol::{Ident, Symbol, kw, sym};
use rustc_span::{BytePos, Span, SyntaxContext};
use smallvec::{SmallVec, smallvec};
use tracing::{debug, instrument, trace};
use crate::{
BindingError, BindingKey, Finalize, LexicalScopeBinding, Module, ModuleOrUniformRoot,
NameBinding, ParentScope, PathResult, ResolutionError, Resolver, Segment, TyCtxt, UseError,
Used, errors, path_names_to_string, rustdoc,
};
mod diagnostics;
type Res = def::Res<NodeId>;
type IdentMap<T> = FxHashMap<Ident, T>;
use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
#[derive(Copy, Clone, Debug)]
struct BindingInfo {
span: Span,
annotation: BindingMode,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum PatternSource {
Match,
Let,
For,
FnParam,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum IsRepeatExpr {
No,
Yes,
}
struct IsNeverPattern;
/// Describes whether an `AnonConst` is a type level const arg or
/// some other form of anon const (i.e. inline consts or enum discriminants)
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum AnonConstKind {
EnumDiscriminant,
InlineConst,
ConstArg(IsRepeatExpr),
}
impl PatternSource {
fn descr(self) -> &'static str {
match self {
PatternSource::Match => "match binding",
PatternSource::Let => "let binding",
PatternSource::For => "for binding",
PatternSource::FnParam => "function parameter",
}
}
}
impl IntoDiagArg for PatternSource {
fn into_diag_arg(self) -> DiagArgValue {
DiagArgValue::Str(Cow::Borrowed(self.descr()))
}
}
/// Denotes whether the context for the set of already bound bindings is a `Product`
/// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
/// See those functions for more information.
#[derive(PartialEq)]
enum PatBoundCtx {
/// A product pattern context, e.g., `Variant(a, b)`.
Product,
/// An or-pattern context, e.g., `p_0 | ... | p_n`.
Or,
}
/// Does this the item (from the item rib scope) allow generic parameters?
#[derive(Copy, Clone, Debug)]
pub(crate) enum HasGenericParams {
Yes(Span),
No,
}
/// May this constant have generics?
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum ConstantHasGenerics {
Yes,
No(NoConstantGenericsReason),
}
impl ConstantHasGenerics {
fn force_yes_if(self, b: bool) -> Self {
if b { Self::Yes } else { self }
}
}
/// Reason for why an anon const is not allowed to reference generic parameters
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum NoConstantGenericsReason {
/// Const arguments are only allowed to use generic parameters when:
/// - `feature(generic_const_exprs)` is enabled
/// or
/// - the const argument is a sole const generic parameter, i.e. `foo::<{ N }>()`
///
/// If neither of the above are true then this is used as the cause.
NonTrivialConstArg,
/// Enum discriminants are not allowed to reference generic parameters ever, this
/// is used when an anon const is in the following position:
///
/// ```rust,compile_fail
/// enum Foo<const N: isize> {
/// Variant = { N }, // this anon const is not allowed to use generics
/// }
/// ```
IsEnumDiscriminant,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum ConstantItemKind {
Const,
Static,
}
impl ConstantItemKind {
pub(crate) fn as_str(&self) -> &'static str {
match self {
Self::Const => "const",
Self::Static => "static",
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum RecordPartialRes {
Yes,
No,
}
/// The rib kind restricts certain accesses,
/// e.g. to a `Res::Local` of an outer item.
#[derive(Copy, Clone, Debug)]
pub(crate) enum RibKind<'ra> {
/// No restriction needs to be applied.
Normal,
/// We passed through an impl or trait and are now in one of its
/// methods or associated types. Allow references to ty params that impl or trait
/// binds. Disallow any other upvars (including other ty params that are
/// upvars).
AssocItem,
/// We passed through a function, closure or coroutine signature. Disallow labels.
FnOrCoroutine,
/// We passed through an item scope. Disallow upvars.
Item(HasGenericParams, DefKind),
/// We're in a constant item. Can't refer to dynamic stuff.
///
/// The item may reference generic parameters in trivial constant expressions.
/// All other constants aren't allowed to use generic params at all.
ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
/// We passed through a module.
Module(Module<'ra>),
/// We passed through a `macro_rules!` statement
MacroDefinition(DefId),
/// All bindings in this rib are generic parameters that can't be used
/// from the default of a generic parameter because they're not declared
/// before said generic parameter. Also see the `visit_generics` override.
ForwardGenericParamBan,
/// We are inside of the type of a const parameter. Can't refer to any
/// parameters.
ConstParamTy,
/// We are inside a `sym` inline assembly operand. Can only refer to
/// globals.
InlineAsmSym,
}
impl RibKind<'_> {
/// Whether this rib kind contains generic parameters, as opposed to local
/// variables.
pub(crate) fn contains_params(&self) -> bool {
match self {
RibKind::Normal
| RibKind::FnOrCoroutine
| RibKind::ConstantItem(..)
| RibKind::Module(_)
| RibKind::MacroDefinition(_)
| RibKind::ConstParamTy
| RibKind::InlineAsmSym => false,
RibKind::AssocItem | RibKind::Item(..) | RibKind::ForwardGenericParamBan => true,
}
}
/// This rib forbids referring to labels defined in upwards ribs.
fn is_label_barrier(self) -> bool {
match self {
RibKind::Normal | RibKind::MacroDefinition(..) => false,
RibKind::AssocItem
| RibKind::FnOrCoroutine
| RibKind::Item(..)
| RibKind::ConstantItem(..)
| RibKind::Module(..)
| RibKind::ForwardGenericParamBan
| RibKind::ConstParamTy
| RibKind::InlineAsmSym => true,
}
}
}
/// A single local scope.
///
/// A rib represents a scope names can live in. Note that these appear in many places, not just
/// around braces. At any place where the list of accessible names (of the given namespace)
/// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
/// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
/// etc.
///
/// Different [rib kinds](enum@RibKind) are transparent for different names.
///
/// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
/// resolving, the name is looked up from inside out.
#[derive(Debug)]
pub(crate) struct Rib<'ra, R = Res> {
pub bindings: IdentMap<R>,
pub kind: RibKind<'ra>,
}
impl<'ra, R> Rib<'ra, R> {
fn new(kind: RibKind<'ra>) -> Rib<'ra, R> {
Rib { bindings: Default::default(), kind }
}
}
#[derive(Clone, Copy, Debug)]
enum LifetimeUseSet {
One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
Many,
}
#[derive(Copy, Clone, Debug)]
enum LifetimeRibKind {
// -- Ribs introducing named lifetimes
//
/// This rib declares generic parameters.
/// Only for this kind the `LifetimeRib::bindings` field can be non-empty.
Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
// -- Ribs introducing unnamed lifetimes
//
/// Create a new anonymous lifetime parameter and reference it.
///
/// If `report_in_path`, report an error when encountering lifetime elision in a path:
/// ```compile_fail
/// struct Foo<'a> { x: &'a () }
/// async fn foo(x: Foo) {}
/// ```
///
/// Note: the error should not trigger when the elided lifetime is in a pattern or
/// expression-position path:
/// ```
/// struct Foo<'a> { x: &'a () }
/// async fn foo(Foo { x: _ }: Foo<'_>) {}
/// ```
AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
/// Replace all anonymous lifetimes by provided lifetime.
Elided(LifetimeRes),
// -- Barrier ribs that stop lifetime lookup, or continue it but produce an error later.
//
/// Give a hard error when either `&` or `'_` is written. Used to
/// rule out things like `where T: Foo<'_>`. Does not imply an
/// error on default object bounds (e.g., `Box<dyn Foo>`).
AnonymousReportError,
/// Resolves elided lifetimes to `'static` if there are no other lifetimes in scope,
/// otherwise give a warning that the previous behavior of introducing a new early-bound
/// lifetime is a bug and will be removed (if `emit_lint` is enabled).
StaticIfNoLifetimeInScope { lint_id: NodeId, emit_lint: bool },
/// Signal we cannot find which should be the anonymous lifetime.
ElisionFailure,
/// This rib forbids usage of generic parameters inside of const parameter types.
///
/// While this is desirable to support eventually, it is difficult to do and so is
/// currently forbidden. See rust-lang/project-const-generics#28 for more info.
ConstParamTy,
/// Usage of generic parameters is forbidden in various positions for anon consts:
/// - const arguments when `generic_const_exprs` is not enabled
/// - enum discriminant values
///
/// This rib emits an error when a lifetime would resolve to a lifetime parameter.
ConcreteAnonConst(NoConstantGenericsReason),
/// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
Item,
}
#[derive(Copy, Clone, Debug)]
enum LifetimeBinderKind {
BareFnType,
PolyTrait,
WhereBound,
Item,
ConstItem,
Function,
Closure,
ImplBlock,
}
impl LifetimeBinderKind {
fn descr(self) -> &'static str {
use LifetimeBinderKind::*;
match self {
BareFnType => "type",
PolyTrait => "bound",
WhereBound => "bound",
Item | ConstItem => "item",
ImplBlock => "impl block",
Function => "function",
Closure => "closure",
}
}
}
#[derive(Debug)]
struct LifetimeRib {
kind: LifetimeRibKind,
// We need to preserve insertion order for async fns.
bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
}
impl LifetimeRib {
fn new(kind: LifetimeRibKind) -> LifetimeRib {
LifetimeRib { bindings: Default::default(), kind }
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum AliasPossibility {
No,
Maybe,
}
#[derive(Copy, Clone, Debug)]
pub(crate) enum PathSource<'a> {
// Type paths `Path`.
Type,
// Trait paths in bounds or impls.
Trait(AliasPossibility),
// Expression paths `path`, with optional parent context.
Expr(Option<&'a Expr>),
// Paths in path patterns `Path`.
Pat,
// Paths in struct expressions and patterns `Path { .. }`.
Struct,
// Paths in tuple struct patterns `Path(..)`.
TupleStruct(Span, &'a [Span]),
// `m::A::B` in `<T as m::A>::B::C`.
TraitItem(Namespace),
// Paths in delegation item
Delegation,
/// An arg in a `use<'a, N>` precise-capturing bound.
PreciseCapturingArg(Namespace),
// Paths that end with `(..)`, for return type notation.
ReturnTypeNotation,
}
impl<'a> PathSource<'a> {
fn namespace(self) -> Namespace {
match self {
PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
PathSource::Expr(..)
| PathSource::Pat
| PathSource::TupleStruct(..)
| PathSource::Delegation
| PathSource::ReturnTypeNotation => ValueNS,
PathSource::TraitItem(ns) => ns,
PathSource::PreciseCapturingArg(ns) => ns,
}
}
fn defer_to_typeck(self) -> bool {
match self {
PathSource::Type
| PathSource::Expr(..)
| PathSource::Pat
| PathSource::Struct
| PathSource::TupleStruct(..)
| PathSource::ReturnTypeNotation => true,
PathSource::Trait(_)
| PathSource::TraitItem(..)
| PathSource::Delegation
| PathSource::PreciseCapturingArg(..) => false,
}
}
fn descr_expected(self) -> &'static str {
match &self {
PathSource::Type => "type",
PathSource::Trait(_) => "trait",
PathSource::Pat => "unit struct, unit variant or constant",
PathSource::Struct => "struct, variant or union type",
PathSource::TupleStruct(..) => "tuple struct or tuple variant",
PathSource::TraitItem(ns) => match ns {
TypeNS => "associated type",
ValueNS => "method or associated constant",
MacroNS => bug!("associated macro"),
},
PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
// "function" here means "anything callable" rather than `DefKind::Fn`,
// this is not precise but usually more helpful than just "value".
Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
// the case of `::some_crate()`
ExprKind::Path(_, path)
if let [segment, _] = path.segments.as_slice()
&& segment.ident.name == kw::PathRoot =>
{
"external crate"
}
ExprKind::Path(_, path) => {
let mut msg = "function";
if let Some(segment) = path.segments.iter().last() {
if let Some(c) = segment.ident.to_string().chars().next() {
if c.is_uppercase() {
msg = "function, tuple struct or tuple variant";
}
}
}
msg
}
_ => "function",
},
_ => "value",
},
PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
PathSource::PreciseCapturingArg(..) => "type or const parameter",
}
}
fn is_call(self) -> bool {
matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
}
pub(crate) fn is_expected(self, res: Res) -> bool {
match self {
PathSource::Type => matches!(
res,
Res::Def(
DefKind::Struct
| DefKind::Union
| DefKind::Enum
| DefKind::Trait
| DefKind::TraitAlias
| DefKind::TyAlias
| DefKind::AssocTy
| DefKind::TyParam
| DefKind::OpaqueTy
| DefKind::ForeignTy,
_,
) | Res::PrimTy(..)
| Res::SelfTyParam { .. }
| Res::SelfTyAlias { .. }
),
PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
PathSource::Trait(AliasPossibility::Maybe) => {
matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
}
PathSource::Expr(..) => matches!(
res,
Res::Def(
DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
| DefKind::Const
| DefKind::Static { .. }
| DefKind::Fn
| DefKind::AssocFn
| DefKind::AssocConst
| DefKind::ConstParam,
_,
) | Res::Local(..)
| Res::SelfCtor(..)
),
PathSource::Pat => {
res.expected_in_unit_struct_pat()
|| matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
}
PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
PathSource::Struct => matches!(
res,
Res::Def(
DefKind::Struct
| DefKind::Union
| DefKind::Variant
| DefKind::TyAlias
| DefKind::AssocTy,
_,
) | Res::SelfTyParam { .. }
| Res::SelfTyAlias { .. }
),
PathSource::TraitItem(ns) => match res {
Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
_ => false,
},
PathSource::ReturnTypeNotation => match res {
Res::Def(DefKind::AssocFn, _) => true,
_ => false,
},
PathSource::Delegation => matches!(res, Res::Def(DefKind::Fn | DefKind::AssocFn, _)),
PathSource::PreciseCapturingArg(ValueNS) => {
matches!(res, Res::Def(DefKind::ConstParam, _))
}
// We allow `SelfTyAlias` here so we can give a more descriptive error later.
PathSource::PreciseCapturingArg(TypeNS) => matches!(
res,
Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
),
PathSource::PreciseCapturingArg(MacroNS) => false,
}
}
fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
match (self, has_unexpected_resolution) {
(PathSource::Trait(_), true) => E0404,
(PathSource::Trait(_), false) => E0405,
(PathSource::Type, true) => E0573,
(PathSource::Type, false) => E0412,
(PathSource::Struct, true) => E0574,
(PathSource::Struct, false) => E0422,
(PathSource::Expr(..), true) | (PathSource::Delegation, true) => E0423,
(PathSource::Expr(..), false) | (PathSource::Delegation, false) => E0425,
(PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
(PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
(PathSource::TraitItem(..), true) | (PathSource::ReturnTypeNotation, true) => E0575,
(PathSource::TraitItem(..), false) | (PathSource::ReturnTypeNotation, false) => E0576,
(PathSource::PreciseCapturingArg(..), true) => E0799,
(PathSource::PreciseCapturingArg(..), false) => E0800,
}
}
}
/// At this point for most items we can answer whether that item is exported or not,
/// but some items like impls require type information to determine exported-ness, so we make a
/// conservative estimate for them (e.g. based on nominal visibility).
#[derive(Clone, Copy)]
enum MaybeExported<'a> {
Ok(NodeId),
Impl(Option<DefId>),
ImplItem(Result<DefId, &'a Visibility>),
NestedUse(&'a Visibility),
}
impl MaybeExported<'_> {
fn eval(self, r: &Resolver<'_, '_>) -> bool {
let def_id = match self {
MaybeExported::Ok(node_id) => Some(r.local_def_id(node_id)),
MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
trait_def_id.as_local()
}
MaybeExported::Impl(None) => return true,
MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
return vis.kind.is_pub();
}
};
def_id.map_or(true, |def_id| r.effective_visibilities.is_exported(def_id))
}
}
/// Used for recording UnnecessaryQualification.
#[derive(Debug)]
pub(crate) struct UnnecessaryQualification<'ra> {
pub binding: LexicalScopeBinding<'ra>,
pub node_id: NodeId,
pub path_span: Span,
pub removal_span: Span,
}
#[derive(Default)]
struct DiagMetadata<'ast> {
/// The current trait's associated items' ident, used for diagnostic suggestions.
current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
/// The current self type if inside an impl (used for better errors).
current_self_type: Option<Ty>,
/// The current self item if inside an ADT (used for better errors).
current_self_item: Option<NodeId>,
/// The current trait (used to suggest).
current_item: Option<&'ast Item>,
/// When processing generic arguments and encountering an unresolved ident not found,
/// suggest introducing a type or const param depending on the context.
currently_processing_generic_args: bool,
/// The current enclosing (non-closure) function (used for better errors).
current_function: Option<(FnKind<'ast>, Span)>,
/// A list of labels as of yet unused. Labels will be removed from this map when
/// they are used (in a `break` or `continue` statement)
unused_labels: FxHashMap<NodeId, Span>,
/// Only used for better errors on `let x = { foo: bar };`.
/// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
/// needed for cases where this parses as a correct type ascription.
current_block_could_be_bare_struct_literal: Option<Span>,
/// Only used for better errors on `let <pat>: <expr, not type>;`.
current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
current_pat: Option<&'ast Pat>,
/// Used to detect possible `if let` written without `let` and to provide structured suggestion.
in_if_condition: Option<&'ast Expr>,
/// Used to detect possible new binding written without `let` and to provide structured suggestion.
in_assignment: Option<&'ast Expr>,
is_assign_rhs: bool,
/// If we are setting an associated type in trait impl, is it a non-GAT type?
in_non_gat_assoc_type: Option<bool>,
/// Used to detect possible `.` -> `..` typo when calling methods.
in_range: Option<(&'ast Expr, &'ast Expr)>,
/// If we are currently in a trait object definition. Used to point at the bounds when
/// encountering a struct or enum.
current_trait_object: Option<&'ast [ast::GenericBound]>,
/// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
current_where_predicate: Option<&'ast WherePredicate>,
current_type_path: Option<&'ast Ty>,
/// The current impl items (used to suggest).
current_impl_items: Option<&'ast [P<AssocItem>]>,
/// When processing impl trait
currently_processing_impl_trait: Option<(TraitRef, Ty)>,
/// Accumulate the errors due to missed lifetime elision,
/// and report them all at once for each function.
current_elision_failures: Vec<MissingLifetime>,
}
struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
r: &'a mut Resolver<'ra, 'tcx>,
/// The module that represents the current item scope.
parent_scope: ParentScope<'ra>,
/// The current set of local scopes for types and values.
ribs: PerNS<Vec<Rib<'ra>>>,
/// Previous popped `rib`, only used for diagnostic.
last_block_rib: Option<Rib<'ra>>,
/// The current set of local scopes, for labels.
label_ribs: Vec<Rib<'ra, NodeId>>,
/// The current set of local scopes for lifetimes.
lifetime_ribs: Vec<LifetimeRib>,
/// We are looking for lifetimes in an elision context.
/// The set contains all the resolutions that we encountered so far.
/// They will be used to determine the correct lifetime for the fn return type.
/// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
/// lifetimes.
lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
/// The trait that the current context can refer to.
current_trait_ref: Option<(Module<'ra>, TraitRef)>,
/// Fields used to add information to diagnostic errors.
diag_metadata: Box<DiagMetadata<'ast>>,
/// State used to know whether to ignore resolution errors for function bodies.
///
/// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
/// In most cases this will be `None`, in which case errors will always be reported.
/// If it is `true`, then it will be updated when entering a nested function or trait body.
in_func_body: bool,
/// Count the number of places a lifetime is used.
lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
}
/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
impl<'ra: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
fn visit_attribute(&mut self, _: &'ast Attribute) {
// We do not want to resolve expressions that appear in attributes,
// as they do not correspond to actual code.
}
fn visit_item(&mut self, item: &'ast Item) {
let prev = replace(&mut self.diag_metadata.current_item, Some(item));
// Always report errors in items we just entered.
let old_ignore = replace(&mut self.in_func_body, false);
self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
self.in_func_body = old_ignore;
self.diag_metadata.current_item = prev;
}
fn visit_arm(&mut self, arm: &'ast Arm) {
self.resolve_arm(arm);
}
fn visit_block(&mut self, block: &'ast Block) {
let old_macro_rules = self.parent_scope.macro_rules;
self.resolve_block(block);
self.parent_scope.macro_rules = old_macro_rules;
}
fn visit_anon_const(&mut self, _constant: &'ast AnonConst) {
bug!("encountered anon const without a manual call to `resolve_anon_const`");
}
fn visit_expr(&mut self, expr: &'ast Expr) {
self.resolve_expr(expr, None);
}
fn visit_pat(&mut self, p: &'ast Pat) {
let prev = self.diag_metadata.current_pat;
self.diag_metadata.current_pat = Some(p);
visit::walk_pat(self, p);
self.diag_metadata.current_pat = prev;
}
fn visit_local(&mut self, local: &'ast Local) {
let local_spans = match local.pat.kind {
// We check for this to avoid tuple struct fields.
PatKind::Wild => None,
_ => Some((
local.pat.span,
local.ty.as_ref().map(|ty| ty.span),
local.kind.init().map(|init| init.span),
)),
};
let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
self.resolve_local(local);
self.diag_metadata.current_let_binding = original;
}
fn visit_ty(&mut self, ty: &'ast Ty) {
let prev = self.diag_metadata.current_trait_object;
let prev_ty = self.diag_metadata.current_type_path;
match &ty.kind {
TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
// Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
// NodeId `ty.id`.
// This span will be used in case of elision failure.
let span = self.r.tcx.sess.source_map().start_point(ty.span);
self.resolve_elided_lifetime(ty.id, span);
visit::walk_ty(self, ty);
}
TyKind::Path(qself, path) => {
self.diag_metadata.current_type_path = Some(ty);
// If we have a path that ends with `(..)`, then it must be
// return type notation. Resolve that path in the *value*
// namespace.
let source = if let Some(seg) = path.segments.last()
&& let Some(args) = &seg.args
&& matches!(**args, GenericArgs::ParenthesizedElided(..))
{
PathSource::ReturnTypeNotation
} else {
PathSource::Type
};
self.smart_resolve_path(ty.id, qself, path, source);
// Check whether we should interpret this as a bare trait object.
if qself.is_none()
&& let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
&& let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
partial_res.full_res()
{
// This path is actually a bare trait object. In case of a bare `Fn`-trait
// object with anonymous lifetimes, we need this rib to correctly place the
// synthetic lifetimes.
let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
self.with_generic_param_rib(
&[],
RibKind::Normal,
LifetimeRibKind::Generics {
binder: ty.id,
kind: LifetimeBinderKind::PolyTrait,
span,
},
|this| this.visit_path(path, ty.id),
);
} else {
visit::walk_ty(self, ty)
}
}
TyKind::ImplicitSelf => {
let self_ty = Ident::with_dummy_span(kw::SelfUpper);
let res = self
.resolve_ident_in_lexical_scope(
self_ty,
TypeNS,
Some(Finalize::new(ty.id, ty.span)),
None,
)
.map_or(Res::Err, |d| d.res());
self.r.record_partial_res(ty.id, PartialRes::new(res));
visit::walk_ty(self, ty)
}
TyKind::ImplTrait(..) => {
let candidates = self.lifetime_elision_candidates.take();
visit::walk_ty(self, ty);
self.lifetime_elision_candidates = candidates;
}
TyKind::TraitObject(bounds, ..) => {
self.diag_metadata.current_trait_object = Some(&bounds[..]);
visit::walk_ty(self, ty)
}
TyKind::BareFn(bare_fn) => {
let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo());
self.with_generic_param_rib(
&bare_fn.generic_params,
RibKind::Normal,
LifetimeRibKind::Generics {
binder: ty.id,
kind: LifetimeBinderKind::BareFnType,
span,
},
|this| {
this.visit_generic_params(&bare_fn.generic_params, false);
this.with_lifetime_rib(
LifetimeRibKind::AnonymousCreateParameter {
binder: ty.id,
report_in_path: false,
},
|this| {
this.resolve_fn_signature(
ty.id,
false,
// We don't need to deal with patterns in parameters, because
// they are not possible for foreign or bodiless functions.
bare_fn
.decl
.inputs
.iter()
.map(|Param { ty, .. }| (None, &**ty)),
&bare_fn.decl.output,
)
},
);
},
)
}
TyKind::Array(element_ty, length) => {
self.visit_ty(element_ty);
self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
}
TyKind::Typeof(ct) => {
self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
}
_ => visit::walk_ty(self, ty),
}
self.diag_metadata.current_trait_object = prev;
self.diag_metadata.current_type_path = prev_ty;
}
fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
self.with_generic_param_rib(
&tref.bound_generic_params,
RibKind::Normal,
LifetimeRibKind::Generics {
binder: tref.trait_ref.ref_id,
kind: LifetimeBinderKind::PolyTrait,
span,
},
|this| {
this.visit_generic_params(&tref.bound_generic_params, false);
this.smart_resolve_path(
tref.trait_ref.ref_id,
&None,
&tref.trait_ref.path,
PathSource::Trait(AliasPossibility::Maybe),
);
this.visit_trait_ref(&tref.trait_ref);
},
);
}
fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
self.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
let def_kind = self.r.local_def_kind(foreign_item.id);
match foreign_item.kind {
ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
self.with_generic_param_rib(
&generics.params,
RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
LifetimeRibKind::Generics {
binder: foreign_item.id,
kind: LifetimeBinderKind::Item,
span: generics.span,
},
|this| visit::walk_item(this, foreign_item),
);
}
ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
self.with_generic_param_rib(
&generics.params,
RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
LifetimeRibKind::Generics {
binder: foreign_item.id,
kind: LifetimeBinderKind::Function,
span: generics.span,
},
|this| visit::walk_item(this, foreign_item),
);
}
ForeignItemKind::Static(..) => {
self.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
}
ForeignItemKind::MacCall(..) => {
panic!("unexpanded macro in resolve!")
}
}
}
fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
let previous_value = self.diag_metadata.current_function;
match fn_kind {
// Bail if the function is foreign, and thus cannot validly have
// a body, or if there's no body for some other reason.
FnKind::Fn(FnCtxt::Foreign, _, sig, _, generics, _)
| FnKind::Fn(_, _, sig, _, generics, None) => {
self.visit_fn_header(&sig.header);
self.visit_generics(generics);
self.with_lifetime_rib(
LifetimeRibKind::AnonymousCreateParameter {
binder: fn_id,
report_in_path: false,
},
|this| {
this.resolve_fn_signature(
fn_id,
sig.decl.has_self(),
sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
&sig.decl.output,
);
},
);
return;
}
FnKind::Fn(..) => {
self.diag_metadata.current_function = Some((fn_kind, sp));
}
// Do not update `current_function` for closures: it suggests `self` parameters.
FnKind::Closure(..) => {}
};
debug!("(resolving function) entering function");
// Create a value rib for the function.
self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
// Create a label rib for the function.
this.with_label_rib(RibKind::FnOrCoroutine, |this| {
match fn_kind {
FnKind::Fn(_, _, sig, _, generics, body) => {
this.visit_generics(generics);
let declaration = &sig.decl;
let coro_node_id = sig