-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathcollector.rs
2524 lines (2328 loc) · 102 KB
/
collector.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
//! The core of the module-level name resolution algorithm.
//!
//! `DefCollector::collect` contains the fixed-point iteration loop which
//! resolves imports and expands macros.
use std::{cmp::Ordering, iter, mem, ops::Not};
use base_db::{CrateId, Dependency, FileId};
use cfg::{CfgExpr, CfgOptions};
use either::Either;
use hir_expand::{
attrs::{Attr, AttrId},
builtin_attr_macro::{find_builtin_attr, BuiltinAttrExpander},
builtin_derive_macro::find_builtin_derive,
builtin_fn_macro::find_builtin_macro,
name::{name, AsName, Name},
proc_macro::CustomProcMacroExpander,
ExpandResult, ExpandTo, HirFileId, InFile, MacroCallId, MacroCallKind, MacroCallLoc,
MacroDefId, MacroDefKind,
};
use itertools::{izip, Itertools};
use la_arena::Idx;
use limit::Limit;
use rustc_hash::{FxHashMap, FxHashSet};
use span::{Edition, ErasedFileAstId, FileAstId, Span, SyntaxContextId};
use stdx::always;
use syntax::ast;
use triomphe::Arc;
use crate::{
attr::Attrs,
db::DefDatabase,
item_scope::{ImportId, ImportOrExternCrate, ImportType, PerNsGlobImports},
item_tree::{
self, ExternCrate, Fields, FileItemTreeId, ImportKind, ItemTree, ItemTreeId, ItemTreeNode,
Macro2, MacroCall, MacroRules, Mod, ModItem, ModKind, TreeId,
},
macro_call_as_call_id, macro_call_as_call_id_with_eager,
nameres::{
attr_resolution::{attr_macro_as_call_id, derive_macro_as_call_id},
diagnostics::DefDiagnostic,
mod_resolution::ModDir,
path_resolution::ReachedFixedPoint,
proc_macro::{parse_macro_name_and_helper_attrs, ProcMacroDef, ProcMacroKind},
sub_namespace_match, BuiltinShadowMode, DefMap, MacroSubNs, ModuleData, ModuleOrigin,
ResolveMode,
},
path::{ImportAlias, ModPath, PathKind},
per_ns::PerNs,
tt,
visibility::{RawVisibility, Visibility},
AdtId, AstId, AstIdWithPath, ConstLoc, CrateRootModuleId, EnumLoc, EnumVariantLoc,
ExternBlockLoc, ExternCrateId, ExternCrateLoc, FunctionId, FunctionLoc, ImplLoc, Intern,
ItemContainerId, LocalModuleId, Lookup, Macro2Id, Macro2Loc, MacroExpander, MacroId,
MacroRulesId, MacroRulesLoc, MacroRulesLocFlags, ModuleDefId, ModuleId, ProcMacroId,
ProcMacroLoc, StaticLoc, StructLoc, TraitAliasLoc, TraitLoc, TypeAliasLoc, UnionLoc,
UnresolvedMacro, UseId, UseLoc,
};
static GLOB_RECURSION_LIMIT: Limit = Limit::new(100);
static EXPANSION_DEPTH_LIMIT: Limit = Limit::new(128);
static FIXED_POINT_LIMIT: Limit = Limit::new(8192);
pub(super) fn collect_defs(db: &dyn DefDatabase, def_map: DefMap, tree_id: TreeId) -> DefMap {
let crate_graph = db.crate_graph();
let krate = &crate_graph[def_map.krate];
// populate external prelude and dependency list
let mut deps =
FxHashMap::with_capacity_and_hasher(krate.dependencies.len(), Default::default());
for dep in &krate.dependencies {
tracing::debug!("crate dep {:?} -> {:?}", dep.name, dep.crate_id);
deps.insert(dep.as_name(), dep.clone());
}
let proc_macros = if krate.is_proc_macro {
match db.proc_macros().get(&def_map.krate) {
Some(Ok(proc_macros)) => {
Ok(proc_macros
.iter()
.enumerate()
.map(|(idx, it)| {
// FIXME: a hacky way to create a Name from string.
let name = tt::Ident {
text: it.name.clone(),
span: Span {
range: syntax::TextRange::empty(syntax::TextSize::new(0)),
anchor: span::SpanAnchor {
file_id: FileId::BOGUS,
ast_id: span::ROOT_ERASED_FILE_AST_ID,
},
ctx: SyntaxContextId::ROOT,
},
};
(
name.as_name(),
if it.disabled {
CustomProcMacroExpander::disabled()
} else {
CustomProcMacroExpander::new(
hir_expand::proc_macro::ProcMacroId::new(idx as u32),
)
},
)
})
.collect())
}
Some(Err(e)) => Err(e.clone().into_boxed_str()),
None => Err("No proc-macros present for crate".to_owned().into_boxed_str()),
}
} else {
Ok(vec![])
};
let mut collector = DefCollector {
db,
def_map,
deps,
glob_imports: FxHashMap::default(),
unresolved_imports: Vec::new(),
indeterminate_imports: Vec::new(),
unresolved_macros: Vec::new(),
mod_dirs: FxHashMap::default(),
cfg_options: &krate.cfg_options,
proc_macros,
from_glob_import: Default::default(),
skip_attrs: Default::default(),
is_proc_macro: krate.is_proc_macro,
};
if tree_id.is_block() {
collector.seed_with_inner(tree_id);
} else {
collector.seed_with_top_level();
}
collector.collect();
let mut def_map = collector.finish();
def_map.shrink_to_fit();
def_map
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum PartialResolvedImport {
/// None of any namespaces is resolved
Unresolved,
/// One of namespaces is resolved
Indeterminate(PerNs),
/// All namespaces are resolved, OR it comes from other crate
Resolved(PerNs),
}
impl PartialResolvedImport {
fn namespaces(self) -> PerNs {
match self {
PartialResolvedImport::Unresolved => PerNs::none(),
PartialResolvedImport::Indeterminate(ns) | PartialResolvedImport::Resolved(ns) => ns,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum ImportSource {
Use { use_tree: Idx<ast::UseTree>, id: UseId, is_prelude: bool, kind: ImportKind },
ExternCrate { id: ExternCrateId },
}
#[derive(Debug, Eq, PartialEq)]
struct Import {
path: ModPath,
alias: Option<ImportAlias>,
visibility: RawVisibility,
source: ImportSource,
}
impl Import {
fn from_use(
tree: &ItemTree,
item_tree_id: ItemTreeId<item_tree::Use>,
id: UseId,
is_prelude: bool,
mut cb: impl FnMut(Self),
) {
let it = &tree[item_tree_id.value];
let visibility = &tree[it.visibility];
it.use_tree.expand(|idx, path, kind, alias| {
cb(Self {
path,
alias,
visibility: visibility.clone(),
source: ImportSource::Use { use_tree: idx, id, is_prelude, kind },
});
});
}
fn from_extern_crate(
tree: &ItemTree,
item_tree_id: ItemTreeId<item_tree::ExternCrate>,
id: ExternCrateId,
) -> Self {
let it = &tree[item_tree_id.value];
let visibility = &tree[it.visibility];
Self {
path: ModPath::from_segments(PathKind::Plain, iter::once(it.name.clone())),
alias: it.alias.clone(),
visibility: visibility.clone(),
source: ImportSource::ExternCrate { id },
}
}
}
#[derive(Debug, Eq, PartialEq)]
struct ImportDirective {
/// The module this import directive is in.
module_id: LocalModuleId,
import: Import,
status: PartialResolvedImport,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct MacroDirective {
module_id: LocalModuleId,
depth: usize,
kind: MacroDirectiveKind,
container: ItemContainerId,
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum MacroDirectiveKind {
FnLike {
ast_id: AstIdWithPath<ast::MacroCall>,
expand_to: ExpandTo,
ctxt: SyntaxContextId,
},
Derive {
ast_id: AstIdWithPath<ast::Adt>,
derive_attr: AttrId,
derive_pos: usize,
ctxt: SyntaxContextId,
/// The "parent" macro it is resolved to.
derive_macro_id: MacroCallId,
},
Attr {
ast_id: AstIdWithPath<ast::Item>,
attr: Attr,
mod_item: ModItem,
/* is this needed? */ tree: TreeId,
},
}
/// Walks the tree of module recursively
struct DefCollector<'a> {
db: &'a dyn DefDatabase,
def_map: DefMap,
deps: FxHashMap<Name, Dependency>,
glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, Visibility, UseId)>>,
unresolved_imports: Vec<ImportDirective>,
indeterminate_imports: Vec<ImportDirective>,
unresolved_macros: Vec<MacroDirective>,
mod_dirs: FxHashMap<LocalModuleId, ModDir>,
cfg_options: &'a CfgOptions,
/// List of procedural macros defined by this crate. This is read from the dynamic library
/// built by the build system, and is the list of proc. macros we can actually expand. It is
/// empty when proc. macro support is disabled (in which case we still do name resolution for
/// them).
proc_macros: Result<Vec<(Name, CustomProcMacroExpander)>, Box<str>>,
is_proc_macro: bool,
from_glob_import: PerNsGlobImports,
/// If we fail to resolve an attribute on a `ModItem`, we fall back to ignoring the attribute.
/// This map is used to skip all attributes up to and including the one that failed to resolve,
/// in order to not expand them twice.
///
/// This also stores the attributes to skip when we resolve derive helpers and non-macro
/// non-builtin attributes in general.
skip_attrs: FxHashMap<InFile<ModItem>, AttrId>,
}
impl DefCollector<'_> {
fn seed_with_top_level(&mut self) {
let _p = tracing::span!(tracing::Level::INFO, "seed_with_top_level").entered();
let file_id = self.db.crate_graph()[self.def_map.krate].root_file_id;
let item_tree = self.db.file_item_tree(file_id.into());
let attrs = item_tree.top_level_attrs(self.db, self.def_map.krate);
let crate_data = Arc::get_mut(&mut self.def_map.data).unwrap();
if let Err(e) = &self.proc_macros {
crate_data.proc_macro_loading_error = Some(e.clone());
}
for (name, dep) in &self.deps {
if dep.is_prelude() {
crate_data
.extern_prelude
.insert(name.clone(), (CrateRootModuleId { krate: dep.crate_id }, None));
}
}
// Process other crate-level attributes.
for attr in &*attrs {
if let Some(cfg) = attr.cfg() {
if self.cfg_options.check(&cfg) == Some(false) {
return;
}
}
let Some(attr_name) = attr.path.as_ident() else { continue };
match () {
() if *attr_name == hir_expand::name![recursion_limit] => {
if let Some(limit) = attr.string_value() {
if let Ok(limit) = limit.parse() {
crate_data.recursion_limit = Some(limit);
}
}
}
() if *attr_name == hir_expand::name![crate_type] => {
if let Some("proc-macro") = attr.string_value() {
self.is_proc_macro = true;
}
}
() if *attr_name == hir_expand::name![no_core] => crate_data.no_core = true,
() if *attr_name == hir_expand::name![no_std] => crate_data.no_std = true,
() if attr_name.as_text().as_deref() == Some("rustc_coherence_is_core") => {
crate_data.rustc_coherence_is_core = true;
}
() if *attr_name == hir_expand::name![feature] => {
let features = attr
.parse_path_comma_token_tree(self.db.upcast())
.into_iter()
.flatten()
.filter_map(|(feat, _)| match feat.segments() {
[name] => Some(name.to_smol_str()),
_ => None,
});
crate_data.unstable_features.extend(features);
}
() if *attr_name == hir_expand::name![register_attr] => {
if let Some(ident) = attr.single_ident_value() {
crate_data.registered_attrs.push(ident.text.clone());
cov_mark::hit!(register_attr);
}
}
() if *attr_name == hir_expand::name![register_tool] => {
if let Some(ident) = attr.single_ident_value() {
crate_data.registered_tools.push(ident.text.clone());
cov_mark::hit!(register_tool);
}
}
() => (),
}
}
crate_data.shrink_to_fit();
self.inject_prelude();
ModCollector {
def_collector: self,
macro_depth: 0,
module_id: DefMap::ROOT,
tree_id: TreeId::new(file_id.into(), None),
item_tree: &item_tree,
mod_dir: ModDir::root(),
}
.collect_in_top_module(item_tree.top_level_items());
}
fn seed_with_inner(&mut self, tree_id: TreeId) {
let item_tree = tree_id.item_tree(self.db);
let is_cfg_enabled = item_tree
.top_level_attrs(self.db, self.def_map.krate)
.cfg()
.map_or(true, |cfg| self.cfg_options.check(&cfg) != Some(false));
if is_cfg_enabled {
ModCollector {
def_collector: self,
macro_depth: 0,
module_id: DefMap::ROOT,
tree_id,
item_tree: &item_tree,
mod_dir: ModDir::root(),
}
.collect_in_top_module(item_tree.top_level_items());
}
}
fn resolution_loop(&mut self) {
let _p = tracing::span!(tracing::Level::INFO, "DefCollector::resolution_loop").entered();
// main name resolution fixed-point loop.
let mut i = 0;
'resolve_attr: loop {
let _p = tracing::span!(tracing::Level::INFO, "resolve_macros loop").entered();
'resolve_macros: loop {
self.db.unwind_if_cancelled();
{
let _p = tracing::span!(tracing::Level::INFO, "resolve_imports loop").entered();
'resolve_imports: loop {
if self.resolve_imports() == ReachedFixedPoint::Yes {
break 'resolve_imports;
}
}
}
if self.resolve_macros() == ReachedFixedPoint::Yes {
break 'resolve_macros;
}
i += 1;
if FIXED_POINT_LIMIT.check(i).is_err() {
tracing::error!("name resolution is stuck");
break 'resolve_attr;
}
}
if self.reseed_with_unresolved_attribute() == ReachedFixedPoint::Yes {
break 'resolve_attr;
}
}
}
fn collect(&mut self) {
let _p = tracing::span!(tracing::Level::INFO, "DefCollector::collect").entered();
self.resolution_loop();
// Resolve all indeterminate resolved imports again
// As some of the macros will expand newly import shadowing partial resolved imports
// FIXME: We maybe could skip this, if we handle the indeterminate imports in `resolve_imports`
// correctly
let partial_resolved = self.indeterminate_imports.drain(..).map(|directive| {
ImportDirective { status: PartialResolvedImport::Unresolved, ..directive }
});
self.unresolved_imports.extend(partial_resolved);
self.resolve_imports();
let unresolved_imports = mem::take(&mut self.unresolved_imports);
// show unresolved imports in completion, etc
for directive in &unresolved_imports {
self.record_resolved_import(directive);
}
self.unresolved_imports = unresolved_imports;
if self.is_proc_macro {
// A crate exporting procedural macros is not allowed to export anything else.
//
// Additionally, while the proc macro entry points must be `pub`, they are not publicly
// exported in type/value namespace. This function reduces the visibility of all items
// in the crate root that aren't proc macros.
let module_id = self.def_map.module_id(DefMap::ROOT);
let root = &mut self.def_map.modules[DefMap::ROOT];
root.scope.censor_non_proc_macros(module_id);
}
}
/// When the fixed-point loop reaches a stable state, we might still have
/// some unresolved attributes left over. This takes one of them, and feeds
/// the item it's applied to back into name resolution.
///
/// This effectively ignores the fact that the macro is there and just treats the items as
/// normal code.
///
/// This improves UX for unresolved attributes, and replicates the
/// behavior before we supported proc. attribute macros.
fn reseed_with_unresolved_attribute(&mut self) -> ReachedFixedPoint {
cov_mark::hit!(unresolved_attribute_fallback);
let unresolved_attr =
self.unresolved_macros.iter().enumerate().find_map(|(idx, directive)| match &directive
.kind
{
MacroDirectiveKind::Attr { ast_id, mod_item, attr, tree } => {
self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call(
directive.module_id,
MacroCallKind::Attr {
ast_id: ast_id.ast_id,
attr_args: None,
invoc_attr_index: attr.id,
},
attr.path().clone(),
));
self.skip_attrs.insert(ast_id.ast_id.with_value(*mod_item), attr.id);
Some((idx, directive, *mod_item, *tree))
}
_ => None,
});
match unresolved_attr {
Some((pos, &MacroDirective { module_id, depth, container, .. }, mod_item, tree_id)) => {
let item_tree = &tree_id.item_tree(self.db);
let mod_dir = self.mod_dirs[&module_id].clone();
ModCollector {
def_collector: self,
macro_depth: depth,
module_id,
tree_id,
item_tree,
mod_dir,
}
.collect(&[mod_item], container);
self.unresolved_macros.swap_remove(pos);
// Continue name resolution with the new data.
ReachedFixedPoint::No
}
None => ReachedFixedPoint::Yes,
}
}
fn inject_prelude(&mut self) {
// See compiler/rustc_builtin_macros/src/standard_library_imports.rs
if self.def_map.data.no_core {
// libcore does not get a prelude.
return;
}
let krate = if self.def_map.data.no_std {
name![core]
} else {
let std = name![std];
if self.def_map.extern_prelude().any(|(name, _)| *name == std) {
std
} else {
// If `std` does not exist for some reason, fall back to core. This mostly helps
// keep r-a's own tests minimal.
name![core]
}
};
let edition = match self.def_map.data.edition {
Edition::Edition2015 => name![rust_2015],
Edition::Edition2018 => name![rust_2018],
Edition::Edition2021 => name![rust_2021],
// FIXME: update this when rust_2024 exists
Edition::Edition2024 => name![rust_2021],
};
let path_kind = match self.def_map.data.edition {
Edition::Edition2015 => PathKind::Plain,
_ => PathKind::Abs,
};
let path = ModPath::from_segments(path_kind, [krate, name![prelude], edition]);
let (per_ns, _) =
self.def_map.resolve_path(self.db, DefMap::ROOT, &path, BuiltinShadowMode::Other, None);
match per_ns.types {
Some((ModuleDefId::ModuleId(m), _, import)) => {
// FIXME: This should specifically look for a glob import somehow and record that here
self.def_map.prelude = Some((
m,
import.and_then(ImportOrExternCrate::into_import).map(|it| it.import),
));
}
types => {
tracing::debug!(
"could not resolve prelude path `{}` to module (resolved to {:?})",
path.display(self.db.upcast()),
types
);
}
}
}
/// Adds a definition of procedural macro `name` to the root module.
///
/// # Notes on procedural macro resolution
///
/// Procedural macro functionality is provided by the build system: It has to build the proc
/// macro and pass the resulting dynamic library to rust-analyzer.
///
/// When procedural macro support is enabled, the list of proc macros exported by a crate is
/// known before we resolve names in the crate. This list is stored in `self.proc_macros` and is
/// derived from the dynamic library.
///
/// However, we *also* would like to be able to at least *resolve* macros on our own, without
/// help by the build system. So, when the macro isn't found in `self.proc_macros`, we instead
/// use a dummy expander that always errors. This comes with the drawback of macros potentially
/// going out of sync with what the build system sees (since we resolve using VFS state, but
/// Cargo builds only on-disk files). We could and probably should add diagnostics for that.
fn export_proc_macro(
&mut self,
def: ProcMacroDef,
id: ItemTreeId<item_tree::Function>,
fn_id: FunctionId,
) {
let kind = def.kind.to_basedb_kind();
let (expander, kind) =
match self.proc_macros.as_ref().map(|it| it.iter().find(|(n, _)| n == &def.name)) {
Ok(Some(&(_, expander))) => (expander, kind),
_ => (CustomProcMacroExpander::dummy(), kind),
};
let proc_macro_id = ProcMacroLoc {
container: self.def_map.crate_root(),
id,
expander,
kind,
edition: self.def_map.data.edition,
}
.intern(self.db);
self.define_proc_macro(def.name.clone(), proc_macro_id);
let crate_data = Arc::get_mut(&mut self.def_map.data).unwrap();
if let ProcMacroKind::Derive { helpers } = def.kind {
crate_data.exported_derives.insert(self.db.macro_def(proc_macro_id.into()), helpers);
}
crate_data.fn_proc_macro_mapping.insert(fn_id, proc_macro_id);
}
/// Define a macro with `macro_rules`.
///
/// It will define the macro in legacy textual scope, and if it has `#[macro_export]`,
/// then it is also defined in the root module scope.
/// You can `use` or invoke it by `crate::macro_name` anywhere, before or after the definition.
///
/// It is surprising that the macro will never be in the current module scope.
/// These code fails with "unresolved import/macro",
/// ```rust,compile_fail
/// mod m { macro_rules! foo { () => {} } }
/// use m::foo as bar;
/// ```
///
/// ```rust,compile_fail
/// macro_rules! foo { () => {} }
/// self::foo!();
/// crate::foo!();
/// ```
///
/// Well, this code compiles, because the plain path `foo` in `use` is searched
/// in the legacy textual scope only.
/// ```rust
/// macro_rules! foo { () => {} }
/// use foo as bar;
/// ```
fn define_macro_rules(
&mut self,
module_id: LocalModuleId,
name: Name,
macro_: MacroRulesId,
export: bool,
) {
// Textual scoping
self.define_legacy_macro(module_id, name.clone(), macro_.into());
// Module scoping
// In Rust, `#[macro_export]` macros are unconditionally visible at the
// crate root, even if the parent modules is **not** visible.
if export {
let module_id = DefMap::ROOT;
self.def_map.modules[module_id].scope.declare(macro_.into());
self.update(
module_id,
&[(Some(name), PerNs::macros(macro_.into(), Visibility::Public, None))],
Visibility::Public,
None,
);
}
}
/// Define a legacy textual scoped macro in module
///
/// We use a map `legacy_macros` to store all legacy textual scoped macros visible per module.
/// It will clone all macros from parent legacy scope, whose definition is prior to
/// the definition of current module.
/// And also, `macro_use` on a module will import all legacy macros visible inside to
/// current legacy scope, with possible shadowing.
fn define_legacy_macro(&mut self, module_id: LocalModuleId, name: Name, mac: MacroId) {
// Always shadowing
self.def_map.modules[module_id].scope.define_legacy_macro(name, mac);
}
/// Define a macro 2.0 macro
///
/// The scoped of macro 2.0 macro is equal to normal function
fn define_macro_def(
&mut self,
module_id: LocalModuleId,
name: Name,
macro_: Macro2Id,
vis: &RawVisibility,
) {
let vis = self
.def_map
.resolve_visibility(self.db, module_id, vis, false)
.unwrap_or(Visibility::Public);
self.def_map.modules[module_id].scope.declare(macro_.into());
self.update(
module_id,
&[(Some(name), PerNs::macros(macro_.into(), Visibility::Public, None))],
vis,
None,
);
}
/// Define a proc macro
///
/// A proc macro is similar to normal macro scope, but it would not visible in legacy textual scoped.
/// And unconditionally exported.
fn define_proc_macro(&mut self, name: Name, macro_: ProcMacroId) {
let module_id = DefMap::ROOT;
self.def_map.modules[module_id].scope.declare(macro_.into());
self.update(
module_id,
&[(Some(name), PerNs::macros(macro_.into(), Visibility::Public, None))],
Visibility::Public,
None,
);
}
/// Import exported macros from another crate. `names`, if `Some(_)`, specifies the name of
/// macros to be imported. Otherwise this method imports all exported macros.
///
/// Exported macros are just all macros in the root module scope.
/// Note that it contains not only all `#[macro_export]` macros, but also all aliases
/// created by `use` in the root module, ignoring the visibility of `use`.
fn import_macros_from_extern_crate(
&mut self,
krate: CrateId,
names: Option<Vec<Name>>,
extern_crate: Option<ExternCrateId>,
) {
let def_map = self.db.crate_def_map(krate);
// `#[macro_use]` brings macros into macro_use prelude. Yes, even non-`macro_rules!`
// macros.
let root_scope = &def_map[DefMap::ROOT].scope;
match names {
Some(names) => {
for name in names {
// FIXME: Report diagnostic on 404.
if let Some(def) = root_scope.get(&name).take_macros() {
self.def_map.macro_use_prelude.insert(name, (def, extern_crate));
}
}
}
None => {
for (name, def) in root_scope.macros() {
self.def_map.macro_use_prelude.insert(name.clone(), (def, extern_crate));
}
}
}
}
/// Tries to resolve every currently unresolved import.
fn resolve_imports(&mut self) -> ReachedFixedPoint {
let mut res = ReachedFixedPoint::Yes;
let imports = mem::take(&mut self.unresolved_imports);
self.unresolved_imports = imports
.into_iter()
.filter_map(|mut directive| {
directive.status = self.resolve_import(directive.module_id, &directive.import);
match directive.status {
PartialResolvedImport::Indeterminate(_) => {
self.record_resolved_import(&directive);
self.indeterminate_imports.push(directive);
res = ReachedFixedPoint::No;
None
}
PartialResolvedImport::Resolved(_) => {
self.record_resolved_import(&directive);
res = ReachedFixedPoint::No;
None
}
PartialResolvedImport::Unresolved => Some(directive),
}
})
.collect();
res
}
fn resolve_import(&self, module_id: LocalModuleId, import: &Import) -> PartialResolvedImport {
let _p = tracing::span!(tracing::Level::INFO, "resolve_import", import_path = %import.path.display(self.db.upcast()))
.entered();
tracing::debug!("resolving import: {:?} ({:?})", import, self.def_map.data.edition);
match import.source {
ImportSource::ExternCrate { .. } => {
let name = import
.path
.as_ident()
.expect("extern crate should have been desugared to one-element path");
let res = self.resolve_extern_crate(name);
match res {
Some(res) => PartialResolvedImport::Resolved(PerNs::types(
res.into(),
Visibility::Public,
None,
)),
None => PartialResolvedImport::Unresolved,
}
}
ImportSource::Use { .. } => {
let res = self.def_map.resolve_path_fp_with_macro(
self.db,
ResolveMode::Import,
module_id,
&import.path,
BuiltinShadowMode::Module,
None, // An import may resolve to any kind of macro.
);
let def = res.resolved_def;
if res.reached_fixedpoint == ReachedFixedPoint::No || def.is_none() {
return PartialResolvedImport::Unresolved;
}
if res.from_differing_crate {
return PartialResolvedImport::Resolved(
def.filter_visibility(|v| matches!(v, Visibility::Public)),
);
}
// Check whether all namespaces are resolved.
if def.is_full() {
PartialResolvedImport::Resolved(def)
} else {
PartialResolvedImport::Indeterminate(def)
}
}
}
}
fn resolve_extern_crate(&self, name: &Name) -> Option<CrateRootModuleId> {
if *name == name![self] {
cov_mark::hit!(extern_crate_self_as);
Some(self.def_map.crate_root())
} else {
self.deps.get(name).map(|dep| CrateRootModuleId { krate: dep.crate_id })
}
}
fn record_resolved_import(&mut self, directive: &ImportDirective) {
let _p = tracing::span!(tracing::Level::INFO, "record_resolved_import").entered();
let module_id = directive.module_id;
let import = &directive.import;
let mut def = directive.status.namespaces();
let vis = self
.def_map
.resolve_visibility(self.db, module_id, &directive.import.visibility, false)
.unwrap_or(Visibility::Public);
match import.source {
ImportSource::ExternCrate { .. }
| ImportSource::Use { kind: ImportKind::Plain | ImportKind::TypeOnly, .. } => {
let name = match &import.alias {
Some(ImportAlias::Alias(name)) => Some(name),
Some(ImportAlias::Underscore) => None,
None => match import.path.segments().last() {
Some(last_segment) => Some(last_segment),
None => {
cov_mark::hit!(bogus_paths);
return;
}
},
};
let imp = match import.source {
// extern crates in the crate root are special-cased to insert entries into the extern prelude: rust-lang/rust#54658
ImportSource::ExternCrate { id, .. } => {
if self.def_map.block.is_none() && module_id == DefMap::ROOT {
if let (Some(ModuleDefId::ModuleId(def)), Some(name)) =
(def.take_types(), name)
{
if let Ok(def) = def.try_into() {
Arc::get_mut(&mut self.def_map.data)
.unwrap()
.extern_prelude
.insert(name.clone(), (def, Some(id)));
}
}
}
ImportType::ExternCrate(id)
}
ImportSource::Use { kind, id, use_tree, .. } => {
if kind == ImportKind::TypeOnly {
def.values = None;
def.macros = None;
}
ImportType::Import(ImportId { import: id, idx: use_tree })
}
};
tracing::debug!("resolved import {:?} ({:?}) to {:?}", name, import, def);
self.update(module_id, &[(name.cloned(), def)], vis, Some(imp));
}
ImportSource::Use { kind: ImportKind::Glob, id, .. } => {
tracing::debug!("glob import: {:?}", import);
match def.take_types() {
Some(ModuleDefId::ModuleId(m)) => {
if let ImportSource::Use { id, is_prelude: true, .. } = import.source {
// Note: This dodgily overrides the injected prelude. The rustc
// implementation seems to work the same though.
cov_mark::hit!(std_prelude);
self.def_map.prelude = Some((m, Some(id)));
} else if m.krate != self.def_map.krate {
cov_mark::hit!(glob_across_crates);
// glob import from other crate => we can just import everything once
let item_map = m.def_map(self.db);
let scope = &item_map[m.local_id].scope;
// Module scoped macros is included
let items = scope
.resolutions()
// only keep visible names...
.map(|(n, res)| {
(n, res.filter_visibility(|v| v.is_visible_from_other_crate()))
})
.filter(|(_, res)| !res.is_none())
.collect::<Vec<_>>();
self.update(module_id, &items, vis, Some(ImportType::Glob(id)));
} else {
// glob import from same crate => we do an initial
// import, and then need to propagate any further
// additions
let def_map;
let scope = if m.block == self.def_map.block_id() {
&self.def_map[m.local_id].scope
} else {
def_map = m.def_map(self.db);
&def_map[m.local_id].scope
};
// Module scoped macros is included
let items = scope
.resolutions()
// only keep visible names...
.map(|(n, res)| {
(
n,
res.filter_visibility(|v| {
v.is_visible_from_def_map(
self.db,
&self.def_map,
module_id,
)
}),
)
})
.filter(|(_, res)| !res.is_none())
.collect::<Vec<_>>();
self.update(module_id, &items, vis, Some(ImportType::Glob(id)));
// record the glob import in case we add further items
let glob = self.glob_imports.entry(m.local_id).or_default();
if !glob.iter().any(|(mid, _, _)| *mid == module_id) {
glob.push((module_id, vis, id));
}
}
}
Some(ModuleDefId::AdtId(AdtId::EnumId(e))) => {
cov_mark::hit!(glob_enum);
// glob import from enum => just import all the variants
// We need to check if the def map the enum is from is us, if it is we can't
// call the def-map query since we are currently constructing it!
let loc = e.lookup(self.db);
let tree = loc.id.item_tree(self.db);
let current_def_map = self.def_map.krate == loc.container.krate
&& self.def_map.block_id() == loc.container.block;
let def_map;
let resolutions = if current_def_map {
&self.def_map.enum_definitions[&e]
} else {
def_map = loc.container.def_map(self.db);
&def_map.enum_definitions[&e]
}
.iter()
.map(|&variant| {
let name = tree[variant.lookup(self.db).id.value].name.clone();
let res = PerNs::both(variant.into(), variant.into(), vis, None);
(Some(name), res)
})
.collect::<Vec<_>>();
self.update(module_id, &resolutions, vis, Some(ImportType::Glob(id)));
}
Some(d) => {
tracing::debug!("glob import {:?} from non-module/enum {:?}", import, d);
}
None => {
tracing::debug!("glob import {:?} didn't resolve as type", import);
}
}
}
}
}
fn update(
&mut self,
// The module for which `resolutions` have been resolve
module_id: LocalModuleId,
resolutions: &[(Option<Name>, PerNs)],
// Visibility this import will have
vis: Visibility,
import: Option<ImportType>,