-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
late.rs
2105 lines (1919 loc) · 88.4 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
//! "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 `resolve_imports.rs`.
use GenericParameters::*;
use RibKind::*;
use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
use crate::{Module, ModuleOrUniformRoot, NameBindingKind, ParentScope, PathResult};
use crate::{ResolutionError, Resolver, Segment, UseError};
use log::debug;
use rustc::{bug, lint, span_bug};
use rustc::hir::def::{self, PartialRes, DefKind, CtorKind, PerNS};
use rustc::hir::def::Namespace::{self, *};
use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
use rustc::hir::TraitCandidate;
use rustc::util::nodemap::{FxHashMap, FxHashSet};
use smallvec::{smallvec, SmallVec};
use syntax::{unwrap_or, walk_list};
use syntax::ast::*;
use syntax::ptr::P;
use syntax::symbol::{kw, sym};
use syntax::util::lev_distance::find_best_match_for_name;
use syntax::visit::{self, Visitor, FnKind};
use syntax_pos::Span;
use std::collections::BTreeSet;
use std::mem::replace;
mod diagnostics;
type Res = def::Res<NodeId>;
type IdentMap<T> = FxHashMap<Ident, T>;
/// Map from the name in a pattern to its binding mode.
type BindingMap = IdentMap<BindingInfo>;
#[derive(Copy, Clone, Debug)]
struct BindingInfo {
span: Span,
binding_mode: BindingMode,
}
#[derive(Copy, Clone)]
enum GenericParameters<'a, 'b> {
NoGenericParams,
HasGenericParams(// Type parameters.
&'b Generics,
// The kind of the rib used for type parameters.
RibKind<'a>),
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum PatternSource {
Match,
Let,
For,
FnParam,
}
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",
}
}
}
/// 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.
enum PatBoundCtx {
/// A product pattern context, e.g., `Variant(a, b)`.
Product,
/// An or-pattern context, e.g., `p_0 | ... | p_n`.
Or,
}
/// The rib kind restricts certain accesses,
/// e.g. to a `Res::Local` of an outer item.
#[derive(Copy, Clone, Debug)]
crate enum RibKind<'a> {
/// No restriction needs to be applied.
NormalRibKind,
/// 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).
AssocItemRibKind,
/// We passed through a function definition. Disallow upvars.
/// Permit only those const parameters that are specified in the function's generics.
FnItemRibKind,
/// We passed through an item scope. Disallow upvars.
ItemRibKind,
/// We're in a constant item. Can't refer to dynamic stuff.
ConstantItemRibKind,
/// We passed through a module.
ModuleRibKind(Module<'a>),
/// We passed through a `macro_rules!` statement
MacroDefinition(DefId),
/// All bindings in this rib are type parameters that can't be used
/// from the default of a type parameter because they're not declared
/// before said type parameter. Also see the `visit_generics` override.
ForwardTyParamBanRibKind,
/// We forbid the use of type parameters as the types of const parameters.
TyParamAsConstParamTy,
}
impl RibKind<'_> {
// Whether this rib kind contains generic parameters, as opposed to local
// variables.
crate fn contains_params(&self) -> bool {
match self {
NormalRibKind
| FnItemRibKind
| ConstantItemRibKind
| ModuleRibKind(_)
| MacroDefinition(_) => false,
AssocItemRibKind
| ItemRibKind
| ForwardTyParamBanRibKind
| TyParamAsConstParamTy => 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)]
crate struct Rib<'a, R = Res> {
pub bindings: IdentMap<R>,
pub kind: RibKind<'a>,
}
impl<'a, R> Rib<'a, R> {
fn new(kind: RibKind<'a>) -> Rib<'a, R> {
Rib {
bindings: Default::default(),
kind,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
crate enum AliasPossibility {
No,
Maybe,
}
#[derive(Copy, Clone, Debug)]
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,
// `m::A::B` in `<T as m::A>::B::C`.
TraitItem(Namespace),
}
impl<'a> PathSource<'a> {
fn namespace(self) -> Namespace {
match self {
PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
PathSource::TraitItem(ns) => ns,
}
}
fn defer_to_typeck(self) -> bool {
match self {
PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
PathSource::Struct | PathSource::TupleStruct => true,
PathSource::Trait(_) | PathSource::TraitItem(..) => false,
}
}
fn descr_expected(self) -> &'static str {
match self {
PathSource::Type => "type",
PathSource::Trait(_) => "trait",
PathSource::Pat => "unit struct/variant or constant",
PathSource::Struct => "struct, variant or union type",
PathSource::TupleStruct => "tuple struct/variant",
PathSource::TraitItem(ns) => match ns {
TypeNS => "associated type",
ValueNS => "method or associated constant",
MacroNS => bug!("associated macro"),
},
PathSource::Expr(parent) => match parent.map(|p| &p.node) {
// "function" here means "anything callable" rather than `DefKind::Fn`,
// this is not precise but usually more helpful than just "value".
Some(&ExprKind::Call(..)) => "function",
_ => "value",
},
}
}
crate fn is_expected(self, res: Res) -> bool {
match self {
PathSource::Type => match res {
Res::Def(DefKind::Struct, _)
| Res::Def(DefKind::Union, _)
| Res::Def(DefKind::Enum, _)
| Res::Def(DefKind::Trait, _)
| Res::Def(DefKind::TraitAlias, _)
| Res::Def(DefKind::TyAlias, _)
| Res::Def(DefKind::AssocTy, _)
| Res::PrimTy(..)
| Res::Def(DefKind::TyParam, _)
| Res::SelfTy(..)
| Res::Def(DefKind::OpaqueTy, _)
| Res::Def(DefKind::ForeignTy, _) => true,
_ => false,
},
PathSource::Trait(AliasPossibility::No) => match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
},
PathSource::Trait(AliasPossibility::Maybe) => match res {
Res::Def(DefKind::Trait, _) => true,
Res::Def(DefKind::TraitAlias, _) => true,
_ => false,
},
PathSource::Expr(..) => match res {
Res::Def(DefKind::Ctor(_, CtorKind::Const), _)
| Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
| Res::Def(DefKind::Const, _)
| Res::Def(DefKind::Static, _)
| Res::Local(..)
| Res::Def(DefKind::Fn, _)
| Res::Def(DefKind::Method, _)
| Res::Def(DefKind::AssocConst, _)
| Res::SelfCtor(..)
| Res::Def(DefKind::ConstParam, _) => true,
_ => false,
},
PathSource::Pat => match res {
Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) |
Res::SelfCtor(..) => true,
_ => false,
},
PathSource::TupleStruct => match res {
Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
_ => false,
},
PathSource::Struct => match res {
Res::Def(DefKind::Struct, _)
| Res::Def(DefKind::Union, _)
| Res::Def(DefKind::Variant, _)
| Res::Def(DefKind::TyAlias, _)
| Res::Def(DefKind::AssocTy, _)
| Res::SelfTy(..) => true,
_ => false,
},
PathSource::TraitItem(ns) => match res {
Res::Def(DefKind::AssocConst, _)
| Res::Def(DefKind::Method, _) if ns == ValueNS => true,
Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
_ => false,
},
}
}
fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
syntax::diagnostic_used!(E0404);
syntax::diagnostic_used!(E0405);
syntax::diagnostic_used!(E0412);
syntax::diagnostic_used!(E0422);
syntax::diagnostic_used!(E0423);
syntax::diagnostic_used!(E0425);
syntax::diagnostic_used!(E0531);
syntax::diagnostic_used!(E0532);
syntax::diagnostic_used!(E0573);
syntax::diagnostic_used!(E0574);
syntax::diagnostic_used!(E0575);
syntax::diagnostic_used!(E0576);
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) => "E0423",
(PathSource::Expr(..), false) => "E0425",
(PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
(PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
(PathSource::TraitItem(..), true) => "E0575",
(PathSource::TraitItem(..), false) => "E0576",
}
}
}
struct LateResolutionVisitor<'a, 'b> {
r: &'b mut Resolver<'a>,
/// The module that represents the current item scope.
parent_scope: ParentScope<'a>,
/// The current set of local scopes for types and values.
/// FIXME #4948: Reuse ribs to avoid allocation.
ribs: PerNS<Vec<Rib<'a>>>,
/// The current set of local scopes, for labels.
label_ribs: Vec<Rib<'a, NodeId>>,
/// The trait that the current context can refer to.
current_trait_ref: Option<(Module<'a>, TraitRef)>,
/// The current trait's associated types' ident, used for diagnostic suggestions.
current_trait_assoc_types: Vec<Ident>,
/// 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>,
/// 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 `fn(): fn()`.
current_type_ascription: Vec<Span>,
}
/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
impl<'a, 'tcx> Visitor<'tcx> for LateResolutionVisitor<'a, '_> {
fn visit_item(&mut self, item: &'tcx Item) {
self.resolve_item(item);
}
fn visit_arm(&mut self, arm: &'tcx Arm) {
self.resolve_arm(arm);
}
fn visit_block(&mut self, block: &'tcx Block) {
self.resolve_block(block);
}
fn visit_anon_const(&mut self, constant: &'tcx AnonConst) {
debug!("visit_anon_const {:?}", constant);
self.with_constant_rib(|this| {
visit::walk_anon_const(this, constant);
});
}
fn visit_expr(&mut self, expr: &'tcx Expr) {
self.resolve_expr(expr, None);
}
fn visit_local(&mut self, local: &'tcx Local) {
self.resolve_local(local);
}
fn visit_ty(&mut self, ty: &'tcx Ty) {
match ty.node {
TyKind::Path(ref qself, ref path) => {
self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
}
TyKind::ImplicitSelf => {
let self_ty = Ident::with_dummy_span(kw::SelfUpper);
let res = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
.map_or(Res::Err, |d| d.res());
self.r.record_partial_res(ty.id, PartialRes::new(res));
}
_ => (),
}
visit::walk_ty(self, ty);
}
fn visit_poly_trait_ref(&mut self,
tref: &'tcx PolyTraitRef,
m: &'tcx TraitBoundModifier) {
self.smart_resolve_path(tref.trait_ref.ref_id, None,
&tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
visit::walk_poly_trait_ref(self, tref, m);
}
fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
let generic_params = match foreign_item.node {
ForeignItemKind::Fn(_, ref generics) => {
HasGenericParams(generics, ItemRibKind)
}
ForeignItemKind::Static(..) => NoGenericParams,
ForeignItemKind::Ty => NoGenericParams,
ForeignItemKind::Macro(..) => NoGenericParams,
};
self.with_generic_param_rib(generic_params, |this| {
visit::walk_foreign_item(this, foreign_item);
});
}
fn visit_fn(&mut self, fn_kind: FnKind<'tcx>, declaration: &'tcx FnDecl, _: Span, _: NodeId) {
debug!("(resolving function) entering function");
let rib_kind = match fn_kind {
FnKind::ItemFn(..) => FnItemRibKind,
FnKind::Method(..) | FnKind::Closure(_) => NormalRibKind,
};
// Create a value rib for the function.
self.with_rib(ValueNS, rib_kind, |this| {
// Create a label rib for the function.
this.with_label_rib(rib_kind, |this| {
// Add each argument to the rib.
this.resolve_params(&declaration.inputs);
visit::walk_fn_ret_ty(this, &declaration.output);
// Resolve the function body, potentially inside the body of an async closure
match fn_kind {
FnKind::ItemFn(.., body) |
FnKind::Method(.., body) => this.visit_block(body),
FnKind::Closure(body) => this.visit_expr(body),
};
debug!("(resolving function) leaving function");
})
});
}
fn visit_generics(&mut self, generics: &'tcx Generics) {
// For type parameter defaults, we have to ban access
// to following type parameters, as the InternalSubsts can only
// provide previous type parameters as they're built. We
// put all the parameters on the ban list and then remove
// them one by one as they are processed and become available.
let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
let mut found_default = false;
default_ban_rib.bindings.extend(generics.params.iter()
.filter_map(|param| match param.kind {
GenericParamKind::Const { .. } |
GenericParamKind::Lifetime { .. } => None,
GenericParamKind::Type { ref default, .. } => {
found_default |= default.is_some();
if found_default {
Some((Ident::with_dummy_span(param.ident.name), Res::Err))
} else {
None
}
}
}));
// We also ban access to type parameters for use as the types of const parameters.
let mut const_ty_param_ban_rib = Rib::new(TyParamAsConstParamTy);
const_ty_param_ban_rib.bindings.extend(generics.params.iter()
.filter(|param| {
if let GenericParamKind::Type { .. } = param.kind {
true
} else {
false
}
})
.map(|param| (Ident::with_dummy_span(param.ident.name), Res::Err)));
for param in &generics.params {
match param.kind {
GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
GenericParamKind::Type { ref default, .. } => {
for bound in ¶m.bounds {
self.visit_param_bound(bound);
}
if let Some(ref ty) = default {
self.ribs[TypeNS].push(default_ban_rib);
self.visit_ty(ty);
default_ban_rib = self.ribs[TypeNS].pop().unwrap();
}
// Allow all following defaults to refer to this type parameter.
default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
}
GenericParamKind::Const { ref ty } => {
self.ribs[TypeNS].push(const_ty_param_ban_rib);
for bound in ¶m.bounds {
self.visit_param_bound(bound);
}
self.visit_ty(ty);
const_ty_param_ban_rib = self.ribs[TypeNS].pop().unwrap();
}
}
}
for p in &generics.where_clause.predicates {
self.visit_where_predicate(p);
}
}
}
impl<'a, 'b> LateResolutionVisitor<'a, '_> {
fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b> {
// During late resolution we only track the module component of the parent scope,
// although it may be useful to track other components as well for diagnostics.
let graph_root = resolver.graph_root;
let parent_scope = ParentScope::module(graph_root);
let start_rib_kind = ModuleRibKind(graph_root);
LateResolutionVisitor {
r: resolver,
parent_scope,
ribs: PerNS {
value_ns: vec![Rib::new(start_rib_kind)],
type_ns: vec![Rib::new(start_rib_kind)],
macro_ns: vec![Rib::new(start_rib_kind)],
},
label_ribs: Vec::new(),
current_trait_ref: None,
current_trait_assoc_types: Vec::new(),
current_self_type: None,
current_self_item: None,
unused_labels: Default::default(),
current_type_ascription: Vec::new(),
}
}
fn resolve_ident_in_lexical_scope(&mut self,
ident: Ident,
ns: Namespace,
record_used_id: Option<NodeId>,
path_span: Span)
-> Option<LexicalScopeBinding<'a>> {
self.r.resolve_ident_in_lexical_scope(
ident, ns, &self.parent_scope, record_used_id, path_span, &self.ribs[ns]
)
}
fn resolve_path(
&mut self,
path: &[Segment],
opt_ns: Option<Namespace>, // `None` indicates a module path in import
record_used: bool,
path_span: Span,
crate_lint: CrateLint,
) -> PathResult<'a> {
self.r.resolve_path_with_ribs(
path, opt_ns, &self.parent_scope, record_used, path_span, crate_lint, Some(&self.ribs)
)
}
// AST resolution
//
// We maintain a list of value ribs and type ribs.
//
// Simultaneously, we keep track of the current position in the module
// graph in the `parent_scope.module` pointer. When we go to resolve a name in
// the value or type namespaces, we first look through all the ribs and
// then query the module graph. When we resolve a name in the module
// namespace, we can skip all the ribs (since nested modules are not
// allowed within blocks in Rust) and jump straight to the current module
// graph node.
//
// Named implementations are handled separately. When we find a method
// call, we consult the module node to find all of the implementations in
// scope. This information is lazily cached in the module node. We then
// generate a fake "implementation scope" containing all the
// implementations thus found, for compatibility with old resolve pass.
/// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
fn with_rib<T>(
&mut self,
ns: Namespace,
kind: RibKind<'a>,
work: impl FnOnce(&mut Self) -> T,
) -> T {
self.ribs[ns].push(Rib::new(kind));
let ret = work(self);
self.ribs[ns].pop();
ret
}
fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
let id = self.r.definitions.local_def_id(id);
let module = self.r.module_map.get(&id).cloned(); // clones a reference
if let Some(module) = module {
// Move down in the graph.
let orig_module = replace(&mut self.parent_scope.module, module);
self.with_rib(ValueNS, ModuleRibKind(module), |this| {
this.with_rib(TypeNS, ModuleRibKind(module), |this| {
let ret = f(this);
this.parent_scope.module = orig_module;
ret
})
})
} else {
f(self)
}
}
/// Searches the current set of local scopes for labels. Returns the first non-`None` label that
/// is returned by the given predicate function
///
/// Stops after meeting a closure.
fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
where P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>
{
for rib in self.label_ribs.iter().rev() {
match rib.kind {
NormalRibKind => {}
// If an invocation of this macro created `ident`, give up on `ident`
// and switch to `ident`'s source from the macro definition.
MacroDefinition(def) => {
if def == self.r.macro_def(ident.span.ctxt()) {
ident.span.remove_mark();
}
}
_ => {
// Do not resolve labels across function boundary
return None;
}
}
let r = pred(rib, ident);
if r.is_some() {
return r;
}
}
None
}
fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
debug!("resolve_adt");
self.with_current_self_item(item, |this| {
this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
let item_def_id = this.r.definitions.local_def_id(item.id);
this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
visit::walk_item(this, item);
});
});
});
}
fn future_proof_import(&mut self, use_tree: &UseTree) {
let segments = &use_tree.prefix.segments;
if !segments.is_empty() {
let ident = segments[0].ident;
if ident.is_path_segment_keyword() || ident.span.rust_2015() {
return;
}
let nss = match use_tree.kind {
UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
_ => &[TypeNS],
};
let report_error = |this: &Self, ns| {
let what = if ns == TypeNS { "type parameters" } else { "local variables" };
this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
};
for &ns in nss {
match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
Some(LexicalScopeBinding::Res(..)) => {
report_error(self, ns);
}
Some(LexicalScopeBinding::Item(binding)) => {
let orig_blacklisted_binding =
replace(&mut self.r.blacklisted_binding, Some(binding));
if let Some(LexicalScopeBinding::Res(..)) =
self.resolve_ident_in_lexical_scope(ident, ns, None,
use_tree.prefix.span) {
report_error(self, ns);
}
self.r.blacklisted_binding = orig_blacklisted_binding;
}
None => {}
}
}
} else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
for (use_tree, _) in use_trees {
self.future_proof_import(use_tree);
}
}
}
fn resolve_item(&mut self, item: &Item) {
let name = item.ident.name;
debug!("(resolving item) resolving {} ({:?})", name, item.node);
match item.node {
ItemKind::TyAlias(_, ref generics) |
ItemKind::OpaqueTy(_, ref generics) |
ItemKind::Fn(_, _, ref generics, _) => {
self.with_generic_param_rib(
HasGenericParams(generics, ItemRibKind),
|this| visit::walk_item(this, item)
);
}
ItemKind::Enum(_, ref generics) |
ItemKind::Struct(_, ref generics) |
ItemKind::Union(_, ref generics) => {
self.resolve_adt(item, generics);
}
ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
self.resolve_implementation(generics,
opt_trait_ref,
&self_type,
item.id,
impl_items),
ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
// Create a new rib for the trait-wide type parameters.
self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
let local_def_id = this.r.definitions.local_def_id(item.id);
this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
this.visit_generics(generics);
walk_list!(this, visit_param_bound, bounds);
for trait_item in trait_items {
this.with_trait_items(trait_items, |this| {
let generic_params = HasGenericParams(
&trait_item.generics,
AssocItemRibKind,
);
this.with_generic_param_rib(generic_params, |this| {
match trait_item.node {
TraitItemKind::Const(ref ty, ref default) => {
this.visit_ty(ty);
// Only impose the restrictions of
// ConstRibKind for an actual constant
// expression in a provided default.
if let Some(ref expr) = *default{
this.with_constant_rib(|this| {
this.visit_expr(expr);
});
}
}
TraitItemKind::Method(_, _) => {
visit::walk_trait_item(this, trait_item)
}
TraitItemKind::Type(..) => {
visit::walk_trait_item(this, trait_item)
}
TraitItemKind::Macro(_) => {
panic!("unexpanded macro in resolve!")
}
};
});
});
}
});
});
}
ItemKind::TraitAlias(ref generics, ref bounds) => {
// Create a new rib for the trait-wide type parameters.
self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
let local_def_id = this.r.definitions.local_def_id(item.id);
this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
this.visit_generics(generics);
walk_list!(this, visit_param_bound, bounds);
});
});
}
ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
self.with_scope(item.id, |this| {
visit::walk_item(this, item);
});
}
ItemKind::Static(ref ty, _, ref expr) |
ItemKind::Const(ref ty, ref expr) => {
debug!("resolve_item ItemKind::Const");
self.with_item_rib(|this| {
this.visit_ty(ty);
this.with_constant_rib(|this| {
this.visit_expr(expr);
});
});
}
ItemKind::Use(ref use_tree) => {
self.future_proof_import(use_tree);
}
ItemKind::ExternCrate(..) |
ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
// do nothing, these are just around to be encoded
}
ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
}
}
fn with_generic_param_rib<'c, F>(&'c mut self, generic_params: GenericParameters<'a, 'c>, f: F)
where F: FnOnce(&mut Self)
{
debug!("with_generic_param_rib");
match generic_params {
HasGenericParams(generics, rib_kind) => {
let mut function_type_rib = Rib::new(rib_kind);
let mut function_value_rib = Rib::new(rib_kind);
let mut seen_bindings = FxHashMap::default();
// We also can't shadow bindings from the parent item
if let AssocItemRibKind = rib_kind {
let mut add_bindings_for_ns = |ns| {
let parent_rib = self.ribs[ns].iter()
.rfind(|rib| if let ItemRibKind = rib.kind { true } else { false })
.expect("associated item outside of an item");
seen_bindings.extend(
parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)),
);
};
add_bindings_for_ns(ValueNS);
add_bindings_for_ns(TypeNS);
}
for param in &generics.params {
match param.kind {
GenericParamKind::Lifetime { .. } => {}
GenericParamKind::Type { .. } => {
let ident = param.ident.modern();
debug!("with_generic_param_rib: {}", param.id);
if seen_bindings.contains_key(&ident) {
let span = seen_bindings.get(&ident).unwrap();
let err = ResolutionError::NameAlreadyUsedInParameterList(
ident.name,
*span,
);
self.r.report_error(param.ident.span, err);
}
seen_bindings.entry(ident).or_insert(param.ident.span);
// Plain insert (no renaming).
let res = Res::Def(
DefKind::TyParam,
self.r.definitions.local_def_id(param.id),
);
function_type_rib.bindings.insert(ident, res);
self.r.record_partial_res(param.id, PartialRes::new(res));
}
GenericParamKind::Const { .. } => {
let ident = param.ident.modern();
debug!("with_generic_param_rib: {}", param.id);
if seen_bindings.contains_key(&ident) {
let span = seen_bindings.get(&ident).unwrap();
let err = ResolutionError::NameAlreadyUsedInParameterList(
ident.name,
*span,
);
self.r.report_error(param.ident.span, err);
}
seen_bindings.entry(ident).or_insert(param.ident.span);
let res = Res::Def(
DefKind::ConstParam,
self.r.definitions.local_def_id(param.id),
);
function_value_rib.bindings.insert(ident, res);
self.r.record_partial_res(param.id, PartialRes::new(res));
}
}
}
self.ribs[ValueNS].push(function_value_rib);
self.ribs[TypeNS].push(function_type_rib);
}
NoGenericParams => {
// Nothing to do.
}
}
f(self);
if let HasGenericParams(..) = generic_params {
self.ribs[TypeNS].pop();
self.ribs[ValueNS].pop();
}
}
fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
self.label_ribs.push(Rib::new(kind));
f(self);
self.label_ribs.pop();
}
fn with_item_rib(&mut self, f: impl FnOnce(&mut Self)) {
self.with_rib(ValueNS, ItemRibKind, |this| this.with_rib(TypeNS, ItemRibKind, f))
}
fn with_constant_rib(&mut self, f: impl FnOnce(&mut Self)) {
debug!("with_constant_rib");
self.with_rib(ValueNS, ConstantItemRibKind, |this| {
this.with_label_rib(ConstantItemRibKind, f);
});
}
fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
// Handle nested impls (inside fn bodies)
let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
let result = f(self);
self.current_self_type = previous_value;
result
}
fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
let result = f(self);
self.current_self_item = previous_value;
result
}
/// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
fn with_trait_items<T>(
&mut self,
trait_items: &Vec<TraitItem>,
f: impl FnOnce(&mut Self) -> T,
) -> T {
let trait_assoc_types = replace(
&mut self.current_trait_assoc_types,
trait_items.iter().filter_map(|item| match &item.node {
TraitItemKind::Type(bounds, _) if bounds.len() == 0 => Some(item.ident),
_ => None,
}).collect(),
);
let result = f(self);
self.current_trait_assoc_types = trait_assoc_types;
result
}
/// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
fn with_optional_trait_ref<T>(
&mut self,
opt_trait_ref: Option<&TraitRef>,
f: impl FnOnce(&mut Self, Option<DefId>) -> T
) -> T {
let mut new_val = None;
let mut new_id = None;
if let Some(trait_ref) = opt_trait_ref {
let path: Vec<_> = Segment::from_path(&trait_ref.path);
let res = self.smart_resolve_path_fragment(
trait_ref.ref_id,
None,
&path,
trait_ref.path.span,
PathSource::Trait(AliasPossibility::No),
CrateLint::SimplePath(trait_ref.ref_id),
).base_res();
if res != Res::Err {
new_id = Some(res.def_id());
let span = trait_ref.path.span;
if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
self.resolve_path(
&path,
Some(TypeNS),
false,
span,
CrateLint::SimplePath(trait_ref.ref_id),
)
{
new_val = Some((module, trait_ref.clone()));
}
}
}
let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
let result = f(self, new_id);
self.current_trait_ref = original_trait_ref;
result
}
fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
let mut self_type_rib = Rib::new(NormalRibKind);
// Plain insert (no renaming, since types are not currently hygienic)
self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
self.ribs[ns].push(self_type_rib);
f(self);
self.ribs[ns].pop();
}