-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
indexed_crate.rs
2096 lines (1887 loc) · 76.4 KB
/
indexed_crate.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
use std::{
borrow::Borrow,
collections::{hash_map::Entry, HashMap, HashSet},
};
#[cfg(feature = "rayon")]
use rayon::prelude::*;
use rustdoc_types::{Crate, Id, Item};
use crate::{adapter::supported_item_kind, sealed_trait, visibility_tracker::VisibilityTracker};
/// The rustdoc for a crate, together with associated indexed data to speed up common operations.
///
/// Besides the parsed rustdoc, it also contains some manually-inlined `rustdoc_types::Trait`s
/// of the most common built-in traits.
/// This is a temporary step, until we're able to combine rustdocs of multiple crates.
#[derive(Debug, Clone)]
pub struct IndexedCrate<'a> {
pub(crate) inner: &'a Crate,
/// Track which items are publicly visible and under which names.
pub(crate) visibility_tracker: VisibilityTracker<'a>,
/// index: importable name (in any namespace) -> list of items under that name
pub(crate) imports_index: Option<HashMap<Path<'a>, Vec<(&'a Item, Modifiers)>>>,
/// index: impl owner + impl'd item name -> list of (impl itself, the named item))
pub(crate) impl_index: Option<HashMap<ImplEntry<'a>, Vec<(&'a Item, &'a Item)>>>,
/// Trait items defined in external crates are not present in the `inner: &Crate` field,
/// even if they are implemented by a type in that crate. This also includes
/// Rust's built-in traits like `Debug, Send, Eq` etc.
///
/// This change is approximately as of rustdoc v23,
/// in <https://github.com/rust-lang/rust/pull/105182>
///
/// As a temporary workaround, we manually create the trait items
/// for the most common Rust built-in traits and link to those items
/// as if they were still part of the rustdoc JSON file.
///
/// A more complete future solution may generate multiple crates' rustdoc JSON
/// and link to the external crate's trait items as necessary.
pub(crate) manually_inlined_builtin_traits: HashMap<Id, Item>,
}
/// Map a Key to a List (Vec) of values
///
/// It also has some nice operations for pushing a value to the list, or extending the list with
/// many values.
struct MapList<K, V>(HashMap<K, Vec<V>>);
#[cfg(feature = "rayon")]
impl<K: std::cmp::Eq + std::hash::Hash + Send, V: Send> FromParallelIterator<(K, V)>
for MapList<K, V>
{
#[inline]
fn from_par_iter<I>(par_iter: I) -> Self
where
I: IntoParallelIterator<Item = (K, V)>,
{
par_iter
.into_par_iter()
.fold(Self::new, |mut map, (key, value)| {
map.insert(key, value);
map
})
// Reduce left is faster than reduce right (about 19% less time in our benchmarks)
.reduce(Self::new, |mut l, r| {
l.merge(r);
l
})
}
}
impl<K: std::cmp::Eq + std::hash::Hash, V> FromIterator<(K, V)> for MapList<K, V> {
#[inline]
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
// We could use Iterator::size_hint here to preallocate some space, but I couldn't measure
// a perf inprovement from that.
let mut map = Self::new();
for (key, value) in iter {
map.insert(key, value);
}
map
}
}
impl<K: std::cmp::Eq + std::hash::Hash, V> Extend<(K, V)> for MapList<K, V> {
#[inline]
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
// We could use Iterator::size_hint here to reserve some space, but I measured a 2%-3%
// regression when doing that.
for (key, value) in iter.into_iter() {
self.insert(key, value);
}
}
}
impl<K: std::cmp::Eq + std::hash::Hash, V> MapList<K, V> {
#[inline]
pub fn new() -> Self {
Self(HashMap::new())
}
#[inline]
pub fn into_inner(self) -> HashMap<K, Vec<V>> {
self.0
}
#[inline]
pub fn insert(&mut self, key: K, value: V) {
match self.0.entry(key) {
Entry::Occupied(mut entry) => entry.get_mut().push(value),
Entry::Vacant(entry) => {
entry.insert(vec![value]);
}
}
}
#[inline]
#[cfg(feature = "rayon")]
pub fn insert_many(&mut self, key: K, mut value: Vec<V>) {
match self.0.entry(key) {
Entry::Occupied(mut entry) => entry.get_mut().append(&mut value),
Entry::Vacant(entry) => {
entry.insert(value);
}
}
}
#[inline]
#[cfg(feature = "rayon")]
pub fn merge(&mut self, other: Self) {
self.0.reserve(other.0.len());
for (key, value) in other.0 {
self.insert_many(key, value);
}
}
}
/// Build the impl index
///
/// When compiled using the `rayon` feature, build it in parallel. Specifically, this paralelizes
/// the work of gathering all of the impls for the items in the index.
fn build_impl_index(index: &HashMap<Id, Item>) -> MapList<ImplEntry<'_>, (&Item, &Item)> {
#[cfg(feature = "rayon")]
let iter = index.par_iter();
#[cfg(not(feature = "rayon"))]
let iter = index.iter();
iter.filter_map(|(id, item)| {
let impls = match &item.inner {
rustdoc_types::ItemEnum::Struct(s) => s.impls.as_slice(),
rustdoc_types::ItemEnum::Enum(e) => e.impls.as_slice(),
rustdoc_types::ItemEnum::Union(u) => u.impls.as_slice(),
_ => return None,
};
#[cfg(feature = "rayon")]
let iter = impls.par_iter();
#[cfg(not(feature = "rayon"))]
let iter = impls.iter();
Some((id, iter.filter_map(|impl_id| index.get(impl_id))))
})
.flat_map(|(id, impl_items)| {
impl_items.flat_map(move |impl_item| {
let impl_inner = match &impl_item.inner {
rustdoc_types::ItemEnum::Impl(impl_inner) => impl_inner,
_ => unreachable!("expected impl but got another item type: {impl_item:?}"),
};
let trait_provided_methods: HashSet<_> = impl_inner
.provided_trait_methods
.iter()
.map(|x| x.as_str())
.collect();
let trait_items = impl_inner
.trait_
.as_ref()
.and_then(|trait_path| index.get(&trait_path.id))
.map(move |trait_item| {
if let rustdoc_types::ItemEnum::Trait(trait_item) = &trait_item.inner {
trait_item.items.as_slice()
} else {
&[]
}
})
.unwrap_or(&[]);
#[cfg(feature = "rayon")]
let trait_items = trait_items.par_iter();
#[cfg(not(feature = "rayon"))]
let trait_items = trait_items.iter();
let trait_provided_items = trait_items
.filter_map(|id| index.get(id))
.filter(move |item| {
item.name
.as_deref()
.map(|name| trait_provided_methods.contains(name))
.unwrap_or_default()
})
.map(move |provided_item| {
(
ImplEntry::new(
id,
provided_item
.name
.as_deref()
.expect("item should have had a name"),
),
(impl_item, provided_item),
)
});
#[cfg(feature = "rayon")]
let impl_items = impl_inner.items.par_iter();
#[cfg(not(feature = "rayon"))]
let impl_items = impl_inner.items.iter();
impl_items
.filter_map(move |item_id| {
let item = index.get(item_id)?;
let item_name = item.name.as_deref()?;
Some((ImplEntry::new(id, item_name), (impl_item, item)))
})
.chain(trait_provided_items)
})
})
.collect()
}
impl<'a> IndexedCrate<'a> {
pub fn new(crate_: &'a Crate) -> Self {
let mut value = Self {
inner: crate_,
visibility_tracker: VisibilityTracker::from_crate(crate_),
manually_inlined_builtin_traits: create_manually_inlined_builtin_traits(crate_),
imports_index: None,
impl_index: None,
};
// Build the imports index
//
// This is inlined because we need access to `value`, but `value` is not a valid
// `IndexedCrate` yet. Do not extract into a separate function.
#[cfg(feature = "rayon")]
let iter = crate_.index.par_iter();
#[cfg(not(feature = "rayon"))]
let iter = crate_.index.iter();
value.imports_index = Some(
iter.filter_map(|(_id, item)| {
if !supported_item_kind(item) {
return None;
}
let importable_paths = value.publicly_importable_names(&item.id);
#[cfg(feature = "rayon")]
let iter = importable_paths.into_par_iter();
#[cfg(not(feature = "rayon"))]
let iter = importable_paths.into_iter();
Some(iter.map(move |importable_path| {
(importable_path.path, (item, importable_path.modifiers))
}))
})
.flatten()
.collect::<MapList<_, _>>()
.into_inner(),
);
value.impl_index = Some(build_impl_index(&crate_.index).into_inner());
value
}
/// Return all the paths with which the given item can be imported from this crate.
pub fn publicly_importable_names(&self, id: &'a Id) -> Vec<ImportablePath<'a>> {
if self.inner.index.contains_key(id) {
self.visibility_tracker
.collect_publicly_importable_names(id)
} else {
Default::default()
}
}
/// Return `true` if our analysis indicates the trait is sealed, and `false` otherwise.
///
/// Our analysis is conservative: it has false-negatives but no false-positives.
/// If this method returns `true`, the trait is *definitely* sealed or else you've found a bug.
/// It may be possible to construct traits that *technically* are sealed for which our analysis
/// returns `false`.
///
/// The goal of this method is to reflect author intent, not technicalities.
/// When Rustaceans seal traits on purpose, they do so with a limited number of techniques
/// that are well-defined and immediately recognizable to readers in the community:
/// <https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/>
///
/// The analysis here looks for such techniques, which are always applied at the type signature
/// level. It does not inspect function bodies or do interprocedural analysis.
///
/// ## Panics
///
/// This method will panic if the provided `id` is not an item in this crate,
/// or does not correspond to a trait in this crate.
///
/// ## Re-entrancy
///
/// This method is re-entrant: calling it may cause additional calls to itself, inquiring about
/// the sealed-ness of a trait's supertraits.
///
/// We rely on rustc to reject supertrait cycles in order to prevent infinite loops.
/// Here's a supertrait cycle that must be rejected by rustc:
/// ```compile_fail
/// pub trait First: Third {}
///
/// pub trait Second: First {}
///
/// pub trait Third: Second {}
/// ```
pub fn is_trait_sealed(&self, id: &'a Id) -> bool {
let trait_item = &self.inner.index[id];
sealed_trait::is_trait_sealed(self, trait_item)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct Path<'a> {
pub(crate) components: Vec<&'a str>,
}
impl<'a> Path<'a> {
fn new(components: Vec<&'a str>) -> Self {
Self { components }
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct Modifiers {
pub(crate) doc_hidden: bool,
pub(crate) deprecated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct ImportablePath<'a> {
pub(crate) path: Path<'a>,
pub(crate) modifiers: Modifiers,
}
impl<'a> ImportablePath<'a> {
pub(crate) fn new(components: Vec<&'a str>, doc_hidden: bool, deprecated: bool) -> Self {
Self {
path: Path::new(components),
modifiers: Modifiers {
doc_hidden,
deprecated,
},
}
}
pub(crate) fn public_api(&self) -> bool {
self.modifiers.deprecated || !self.modifiers.doc_hidden
}
}
impl<'a: 'b, 'b> Borrow<[&'b str]> for Path<'a> {
fn borrow(&self) -> &[&'b str] {
&self.components
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct ImplEntry<'a> {
/// Tuple of:
/// - the Id of the struct/enum/union that owns the item,
/// - the name of the item in the owner's `impl` block.
///
/// Stored as a tuple to make the `Borrow` impl work.
pub(crate) data: (&'a Id, &'a str),
}
impl<'a> ImplEntry<'a> {
#[inline]
fn new(owner_id: &'a Id, item_name: &'a str) -> Self {
Self {
data: (owner_id, item_name),
}
}
#[allow(dead_code)]
#[inline]
pub(crate) fn owner_id(&self) -> &'a Id {
self.data.0
}
#[allow(dead_code)]
#[inline]
pub(crate) fn item_name(&self) -> &'a str {
self.data.1
}
}
impl<'a: 'b, 'b> Borrow<(&'b Id, &'b str)> for ImplEntry<'a> {
fn borrow(&self) -> &(&'b Id, &'b str) {
&(self.data)
}
}
#[derive(Debug)]
struct ManualTraitItem {
name: &'static str,
is_auto: bool,
is_unsafe: bool,
}
/// Limiting the creation of manually inlined traits to only those that are used by the lints.
/// There are other foreign traits, but it is not obvious how the manually inlined traits
/// should look like for them.
const MANUAL_TRAIT_ITEMS: [ManualTraitItem; 14] = [
ManualTraitItem {
name: "Debug",
is_auto: false,
is_unsafe: false,
},
ManualTraitItem {
name: "Clone",
is_auto: false,
is_unsafe: false,
},
ManualTraitItem {
name: "Copy",
is_auto: false,
is_unsafe: false,
},
ManualTraitItem {
name: "PartialOrd",
is_auto: false,
is_unsafe: false,
},
ManualTraitItem {
name: "Ord",
is_auto: false,
is_unsafe: false,
},
ManualTraitItem {
name: "PartialEq",
is_auto: false,
is_unsafe: false,
},
ManualTraitItem {
name: "Eq",
is_auto: false,
is_unsafe: false,
},
ManualTraitItem {
name: "Hash",
is_auto: false,
is_unsafe: false,
},
ManualTraitItem {
name: "Send",
is_auto: true,
is_unsafe: true,
},
ManualTraitItem {
name: "Sync",
is_auto: true,
is_unsafe: true,
},
ManualTraitItem {
name: "Unpin",
is_auto: true,
is_unsafe: false,
},
ManualTraitItem {
name: "RefUnwindSafe",
is_auto: true,
is_unsafe: false,
},
ManualTraitItem {
name: "UnwindSafe",
is_auto: true,
is_unsafe: false,
},
ManualTraitItem {
name: "Sized",
is_auto: false,
is_unsafe: false,
},
];
fn new_trait(manual_trait_item: &ManualTraitItem, id: Id, crate_id: u32) -> Item {
Item {
id,
crate_id,
name: Some(manual_trait_item.name.to_string()),
span: None,
visibility: rustdoc_types::Visibility::Public,
docs: None,
links: HashMap::new(),
attrs: Vec::new(),
deprecation: None,
inner: rustdoc_types::ItemEnum::Trait(rustdoc_types::Trait {
is_auto: manual_trait_item.is_auto,
is_unsafe: manual_trait_item.is_unsafe,
is_object_safe: matches!(
manual_trait_item.name,
"Debug"
| "PartialEq"
| "PartialOrd"
| "Send"
| "Sync"
| "Unpin"
| "UnwindSafe"
| "RefUnwindSafe"
),
// The `item`, `generics`, `bounds` and `implementations`
// are not currently present in the schema,
// so it is safe to fill them with empty containers,
// even though some traits in reality have some values in them.
items: Vec::new(),
generics: rustdoc_types::Generics {
params: Vec::new(),
where_predicates: Vec::new(),
},
bounds: Vec::new(),
implementations: Vec::new(),
}),
}
}
fn create_manually_inlined_builtin_traits(crate_: &Crate) -> HashMap<Id, Item> {
let paths = crate_
.index
.values()
.map(|item| &item.inner)
.filter_map(|item_enum| match item_enum {
rustdoc_types::ItemEnum::Impl(impl_) => Some(impl_),
_ => None,
})
.filter_map(|impl_| impl_.trait_.as_ref());
paths
.filter_map(|path| {
MANUAL_TRAIT_ITEMS
.iter()
.find(|manual| manual.name == path.name)
.and_then(|manual| {
crate_.paths.get(&path.id).map(|item_summary| {
(
path.id.clone(),
new_trait(manual, path.id.clone(), item_summary.crate_id),
)
})
})
})
.collect()
}
#[cfg(test)]
mod tests {
use itertools::Itertools;
use rustdoc_types::{Crate, Id};
use crate::{test_util::load_pregenerated_rustdoc, ImportablePath, IndexedCrate};
fn find_item_id<'a>(crate_: &'a Crate, name: &str) -> &'a Id {
crate_
.index
.iter()
.filter_map(|(id, item)| (item.name.as_deref() == Some(name)).then_some(id))
.exactly_one()
.expect("exactly one matching name")
}
/// Ensure that methods, consts, and fields within structs are not importable.
#[test]
fn structs_are_not_modules() {
let rustdoc = load_pregenerated_rustdoc("structs_are_not_modules");
let indexed_crate = IndexedCrate::new(&rustdoc);
let top_level_function = find_item_id(&rustdoc, "top_level_function");
let method = find_item_id(&rustdoc, "method");
let associated_fn = find_item_id(&rustdoc, "associated_fn");
let field = find_item_id(&rustdoc, "field");
let const_item = find_item_id(&rustdoc, "THE_ANSWER");
// All the items are public.
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(top_level_function));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(method));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(associated_fn));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(field));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(const_item));
// But only `top_level_function` is importable.
assert_eq!(
vec![ImportablePath::new(
vec!["structs_are_not_modules", "top_level_function"],
false,
false,
)],
indexed_crate.publicly_importable_names(top_level_function)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(method)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(associated_fn)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(field)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(const_item)
);
}
/// Ensure that methods and consts within enums are not importable.
/// However, enum variants are the exception: they are importable!
#[test]
fn enums_are_not_modules() {
let rustdoc = load_pregenerated_rustdoc("enums_are_not_modules");
let indexed_crate = IndexedCrate::new(&rustdoc);
let top_level_function = find_item_id(&rustdoc, "top_level_function");
let variant = find_item_id(&rustdoc, "Variant");
let method = find_item_id(&rustdoc, "method");
let associated_fn = find_item_id(&rustdoc, "associated_fn");
let const_item = find_item_id(&rustdoc, "THE_ANSWER");
// All the items are public.
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(top_level_function));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(variant));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(method));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(associated_fn));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(const_item));
// But only `top_level_function` and `Foo::variant` is importable.
assert_eq!(
vec![ImportablePath::new(
vec!["enums_are_not_modules", "top_level_function"],
false,
false,
)],
indexed_crate.publicly_importable_names(top_level_function)
);
assert_eq!(
vec![ImportablePath::new(
vec!["enums_are_not_modules", "Foo", "Variant"],
false,
false,
)],
indexed_crate.publicly_importable_names(variant)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(method)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(associated_fn)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(const_item)
);
}
/// Ensure that methods, consts, and fields within unions are not importable.
#[test]
fn unions_are_not_modules() {
let rustdoc = load_pregenerated_rustdoc("unions_are_not_modules");
let indexed_crate = IndexedCrate::new(&rustdoc);
let top_level_function = find_item_id(&rustdoc, "top_level_function");
let method = find_item_id(&rustdoc, "method");
let associated_fn = find_item_id(&rustdoc, "associated_fn");
let left_field = find_item_id(&rustdoc, "left");
let right_field = find_item_id(&rustdoc, "right");
let const_item = find_item_id(&rustdoc, "THE_ANSWER");
// All the items are public.
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(top_level_function));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(method));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(associated_fn));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(left_field));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(right_field));
assert!(indexed_crate
.visibility_tracker
.visible_parent_ids()
.contains_key(const_item));
// But only `top_level_function` is importable.
assert_eq!(
vec![ImportablePath::new(
vec!["unions_are_not_modules", "top_level_function"],
false,
false,
)],
indexed_crate.publicly_importable_names(top_level_function)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(method)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(associated_fn)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(left_field)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(right_field)
);
assert_eq!(
Vec::<ImportablePath<'_>>::new(),
indexed_crate.publicly_importable_names(const_item)
);
}
mod reexports {
use std::collections::{BTreeMap, BTreeSet};
use itertools::Itertools;
use maplit::{btreemap, btreeset};
use rustdoc_types::{ItemEnum, Visibility};
use crate::{test_util::load_pregenerated_rustdoc, ImportablePath, IndexedCrate};
fn assert_exported_items_match(
test_crate: &str,
expected_items: &BTreeMap<&str, BTreeSet<&str>>,
) {
let rustdoc = load_pregenerated_rustdoc(test_crate);
let indexed_crate = IndexedCrate::new(&rustdoc);
for (&expected_item_name, expected_importable_paths) in expected_items {
assert!(
!expected_item_name.contains(':'),
"only direct item names can be checked at the moment: {expected_item_name}"
);
let item_id_candidates = rustdoc
.index
.iter()
.filter_map(|(id, item)| {
(item.name.as_deref() == Some(expected_item_name)).then_some(id)
})
.collect_vec();
if item_id_candidates.len() != 1 {
panic!(
"Expected to find exactly one item with name {expected_item_name}, \
but found these matching IDs: {item_id_candidates:?}"
);
}
let item_id = item_id_candidates[0];
let actual_items: Vec<_> = indexed_crate
.publicly_importable_names(item_id)
.into_iter()
.map(|importable| importable.path.components.into_iter().join("::"))
.collect();
let deduplicated_actual_items: BTreeSet<_> =
actual_items.iter().map(|x| x.as_str()).collect();
assert_eq!(
actual_items.len(),
deduplicated_actual_items.len(),
"duplicates found: {actual_items:?}"
);
assert_eq!(
expected_importable_paths, &deduplicated_actual_items,
"mismatch for item name {expected_item_name}",
);
}
}
/// Allows testing for items with overlapping names, such as a function and a type
/// with the same name (which Rust considers in separate namespaces).
fn assert_duplicated_exported_items_match(
test_crate: &str,
expected_items_and_counts: &BTreeMap<&str, (usize, BTreeSet<&str>)>,
) {
let rustdoc = load_pregenerated_rustdoc(test_crate);
let indexed_crate = IndexedCrate::new(&rustdoc);
for (&expected_item_name, (expected_count, expected_importable_paths)) in
expected_items_and_counts
{
assert!(
!expected_item_name.contains(':'),
"only direct item names can be checked at the moment: {expected_item_name}"
);
let item_id_candidates = rustdoc
.index
.iter()
.filter_map(|(id, item)| {
(item.name.as_deref() == Some(expected_item_name)).then_some(id)
})
.collect_vec();
if item_id_candidates.len() != *expected_count {
panic!(
"Expected to find exactly {expected_count} items with name \
{expected_item_name}, but found these matching IDs: {item_id_candidates:?}"
);
}
for item_id in item_id_candidates {
let actual_items: Vec<_> = indexed_crate
.publicly_importable_names(item_id)
.into_iter()
.map(|importable| importable.path.components.into_iter().join("::"))
.collect();
let deduplicated_actual_items: BTreeSet<_> =
actual_items.iter().map(|x| x.as_str()).collect();
assert_eq!(
actual_items.len(),
deduplicated_actual_items.len(),
"duplicates found: {actual_items:?}"
);
assert_eq!(expected_importable_paths, &deduplicated_actual_items);
}
}
}
#[test]
fn pub_inside_pub_crate_mod() {
let test_crate = "pub_inside_pub_crate_mod";
let expected_items = btreemap! {
"Foo" => btreeset![],
"Bar" => btreeset![
"pub_inside_pub_crate_mod::Bar",
],
};
assert_exported_items_match(test_crate, &expected_items);
}
#[test]
fn reexport() {
let test_crate = "reexport";
let expected_items = btreemap! {
"foo" => btreeset![
"reexport::foo",
"reexport::inner::foo",
],
};
assert_exported_items_match(test_crate, &expected_items);
}
#[test]
fn reexport_from_private_module() {
let test_crate = "reexport_from_private_module";
let expected_items = btreemap! {
"foo" => btreeset![
"reexport_from_private_module::foo",
],
"Bar" => btreeset![
"reexport_from_private_module::Bar",
],
"Baz" => btreeset![
"reexport_from_private_module::nested::Baz",
],
"quux" => btreeset![
"reexport_from_private_module::quux",
],
};
assert_exported_items_match(test_crate, &expected_items);
}
#[test]
fn renaming_reexport() {
let test_crate = "renaming_reexport";
let expected_items = btreemap! {
"foo" => btreeset![
"renaming_reexport::bar",
"renaming_reexport::inner::foo",
],
};
assert_exported_items_match(test_crate, &expected_items);
}
#[test]
fn renaming_reexport_of_reexport() {
let test_crate = "renaming_reexport_of_reexport";
let expected_items = btreemap! {
"foo" => btreeset![
"renaming_reexport_of_reexport::bar",
"renaming_reexport_of_reexport::foo",
"renaming_reexport_of_reexport::inner::foo",
],
};
assert_exported_items_match(test_crate, &expected_items);
}
#[test]
fn renaming_mod_reexport() {
let test_crate = "renaming_mod_reexport";
let expected_items = btreemap! {
"foo" => btreeset![
"renaming_mod_reexport::inner::a::foo",
"renaming_mod_reexport::inner::b::foo",
"renaming_mod_reexport::direct::foo",
],
};
assert_exported_items_match(test_crate, &expected_items);
}
#[test]
fn glob_reexport() {
let test_crate = "glob_reexport";
let expected_items = btreemap! {
"foo" => btreeset![
"glob_reexport::foo",
"glob_reexport::inner::foo",
],
"Bar" => btreeset![
"glob_reexport::Bar",
"glob_reexport::inner::Bar",
],
"nested" => btreeset![
"glob_reexport::nested",
],
"Baz" => btreeset![
"glob_reexport::Baz",
],
"First" => btreeset![
"glob_reexport::First",
"glob_reexport::Baz::First",
],
"Second" => btreeset![
"glob_reexport::Second",
"glob_reexport::Baz::Second",
],
};
assert_exported_items_match(test_crate, &expected_items);
}
#[test]