-
-
Notifications
You must be signed in to change notification settings - Fork 14.9k
Expand file tree
/
Copy pathsearch_index.rs
More file actions
2526 lines (2450 loc) · 107 KB
/
search_index.rs
File metadata and controls
2526 lines (2450 loc) · 107 KB
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
pub(crate) mod encode;
mod serde;
use std::collections::BTreeSet;
use std::collections::hash_map::Entry;
use std::path::Path;
use std::string::FromUtf8Error;
use std::{io, iter};
use ::serde::de::{self, Deserializer, Error as _};
use ::serde::ser::{SerializeSeq, Serializer};
use ::serde::{Deserialize, Serialize};
use rustc_ast::join_path_syms;
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
use rustc_data_structures::thin_vec::ThinVec;
use rustc_hir::find_attr;
use rustc_middle::ty::TyCtxt;
use rustc_span::def_id::DefId;
use rustc_span::sym;
use rustc_span::symbol::{Symbol, kw};
use stringdex::internals as stringdex_internals;
use tracing::instrument;
use crate::clean::types::{Function, Generics, ItemId, Type, WherePredicate};
use crate::clean::{self, utils};
use crate::config::ShouldMerge;
use crate::error::Error;
use crate::formats::cache::{Cache, OrphanImplItem};
use crate::formats::item_type::ItemType;
use crate::html::markdown::short_markdown_summary;
use crate::html::render::{self, IndexItem, IndexItemFunctionType, RenderType, RenderTypeId};
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub(crate) struct SerializedSearchIndex {
// data from disk
names: Vec<String>,
path_data: Vec<Option<PathData>>,
entry_data: Vec<Option<EntryData>>,
descs: Vec<String>,
function_data: Vec<Option<IndexItemFunctionType>>,
alias_pointers: Vec<Option<usize>>,
// inverted index for concrete types and generics
type_data: Vec<Option<TypeData>>,
/// inverted index of generics
///
/// - The outermost list has one entry per alpha-normalized generic.
///
/// - The second layer is sorted by number of types that appear in the
/// type signature. The search engine iterates over these in order from
/// smallest to largest. Functions with less stuff in their type
/// signature are more likely to be what the user wants, because we never
/// show functions that are *missing* parts of the query, so removing..
///
/// - The final layer is the list of functions.
generic_inverted_index: Vec<Vec<Vec<u32>>>,
// generated in-memory backref cache
#[serde(skip)]
crate_paths_index: FxHashMap<(ItemType, Vec<Symbol>), usize>,
}
impl SerializedSearchIndex {
fn load(doc_root: &Path, resource_suffix: &str) -> Result<SerializedSearchIndex, Error> {
let mut names: Vec<String> = Vec::new();
let mut path_data: Vec<Option<PathData>> = Vec::new();
let mut entry_data: Vec<Option<EntryData>> = Vec::new();
let mut descs: Vec<String> = Vec::new();
let mut function_data: Vec<Option<IndexItemFunctionType>> = Vec::new();
let mut type_data: Vec<Option<TypeData>> = Vec::new();
let mut alias_pointers: Vec<Option<usize>> = Vec::new();
let mut generic_inverted_index: Vec<Vec<Vec<u32>>> = Vec::new();
match perform_read_strings(resource_suffix, doc_root, "name", &mut names) {
Ok(()) => {
perform_read_serde(resource_suffix, doc_root, "path", &mut path_data)?;
perform_read_serde(resource_suffix, doc_root, "entry", &mut entry_data)?;
perform_read_strings(resource_suffix, doc_root, "desc", &mut descs)?;
perform_read_serde(resource_suffix, doc_root, "function", &mut function_data)?;
perform_read_serde(resource_suffix, doc_root, "type", &mut type_data)?;
perform_read_serde(resource_suffix, doc_root, "alias", &mut alias_pointers)?;
perform_read_postings(
resource_suffix,
doc_root,
"generic_inverted_index",
&mut generic_inverted_index,
)?;
}
Err(_) => {
names.clear();
}
}
fn perform_read_strings(
resource_suffix: &str,
doc_root: &Path,
column_name: &str,
column: &mut Vec<String>,
) -> Result<(), Error> {
let root_path = doc_root.join(format!("search.index/root{resource_suffix}.js"));
let column_path = doc_root.join(format!("search.index/{column_name}/"));
let mut consume = |_, cell: &[u8]| {
column.push(String::from_utf8(cell.to_vec())?);
Ok::<_, FromUtf8Error>(())
};
stringdex_internals::read_data_from_disk_column(
root_path,
column_name.as_bytes(),
column_path.clone(),
&mut consume,
)
.map_err(|error| Error {
file: column_path,
error: format!("failed to read column from disk: {error}"),
})
}
fn perform_read_serde(
resource_suffix: &str,
doc_root: &Path,
column_name: &str,
column: &mut Vec<Option<impl for<'de> Deserialize<'de> + 'static>>,
) -> Result<(), Error> {
let root_path = doc_root.join(format!("search.index/root{resource_suffix}.js"));
let column_path = doc_root.join(format!("search.index/{column_name}/"));
let mut consume = |_, cell: &[u8]| {
if cell.is_empty() {
column.push(None);
} else {
column.push(Some(serde_json::from_slice(cell)?));
}
Ok::<_, serde_json::Error>(())
};
stringdex_internals::read_data_from_disk_column(
root_path,
column_name.as_bytes(),
column_path.clone(),
&mut consume,
)
.map_err(|error| Error {
file: column_path,
error: format!("failed to read column from disk: {error}"),
})
}
fn perform_read_postings(
resource_suffix: &str,
doc_root: &Path,
column_name: &str,
column: &mut Vec<Vec<Vec<u32>>>,
) -> Result<(), Error> {
let root_path = doc_root.join(format!("search.index/root{resource_suffix}.js"));
let column_path = doc_root.join(format!("search.index/{column_name}/"));
fn consumer(
column: &mut Vec<Vec<Vec<u32>>>,
) -> impl FnMut(u32, &[u8]) -> io::Result<()> {
|_, cell| {
let mut postings = Vec::new();
encode::read_postings_from_string(&mut postings, cell);
column.push(postings);
Ok(())
}
}
stringdex_internals::read_data_from_disk_column(
root_path,
column_name.as_bytes(),
column_path.clone(),
&mut consumer(column),
)
.map_err(|error| Error {
file: column_path,
error: format!("failed to read column from disk: {error}"),
})
}
assert_eq!(names.len(), path_data.len());
assert_eq!(path_data.len(), entry_data.len());
assert_eq!(entry_data.len(), descs.len());
assert_eq!(descs.len(), function_data.len());
assert_eq!(function_data.len(), type_data.len());
assert_eq!(type_data.len(), alias_pointers.len());
// generic_inverted_index is not the same length as other columns,
// because it's actually a completely different set of objects
let mut crate_paths_index: FxHashMap<(ItemType, Vec<Symbol>), usize> = FxHashMap::default();
for (i, (name, path_data)) in names.iter().zip(path_data.iter()).enumerate() {
if let Some(path_data) = path_data {
let full_path = if path_data.module_path.is_empty() {
vec![Symbol::intern(name)]
} else {
let mut full_path = path_data.module_path.to_vec();
full_path.push(Symbol::intern(name));
full_path
};
crate_paths_index.insert((path_data.ty, full_path), i);
}
}
Ok(SerializedSearchIndex {
names,
path_data,
entry_data,
descs,
function_data,
type_data,
alias_pointers,
generic_inverted_index,
crate_paths_index,
})
}
fn push(
&mut self,
name: String,
path_data: Option<PathData>,
entry_data: Option<EntryData>,
desc: String,
function_data: Option<IndexItemFunctionType>,
type_data: Option<TypeData>,
alias_pointer: Option<usize>,
) -> usize {
let index = self.names.len();
assert_eq!(self.names.len(), self.path_data.len());
if let Some(path_data) = &path_data
&& let name = Symbol::intern(&name)
&& let fqp = if path_data.module_path.is_empty() {
vec![name]
} else {
let mut v = path_data.module_path.clone();
v.push(name);
v
}
&& let Some(&other_path) = self.crate_paths_index.get(&(path_data.ty, fqp))
&& self.path_data.get(other_path).map_or(false, Option::is_some)
{
self.path_data.push(None);
} else {
self.path_data.push(path_data);
}
self.names.push(name);
assert_eq!(self.entry_data.len(), self.descs.len());
self.entry_data.push(entry_data);
assert_eq!(self.descs.len(), self.function_data.len());
self.descs.push(desc);
assert_eq!(self.function_data.len(), self.type_data.len());
self.function_data.push(function_data);
assert_eq!(self.type_data.len(), self.alias_pointers.len());
self.type_data.push(type_data);
self.alias_pointers.push(alias_pointer);
index
}
/// Add potential search result to the database and return the row ID.
///
/// The returned ID can be used to attach more data to the search result.
fn add_entry(&mut self, name: Symbol, entry_data: EntryData, desc: String) -> usize {
let fqp = if let Some(module_path_index) = entry_data.module_path {
self.path_data[module_path_index]
.as_ref()
.unwrap()
.module_path
.iter()
.copied()
.chain([Symbol::intern(&self.names[module_path_index]), name])
.collect()
} else {
vec![name]
};
// If a path with the same name already exists, but no entry does,
// we can fill in the entry without having to allocate a new row ID.
//
// Because paths and entries both share the same index, using the same
// ID saves space by making the tree smaller.
if let Some(&other_path) = self.crate_paths_index.get(&(entry_data.ty, fqp))
&& self.entry_data[other_path].is_none()
&& self.descs[other_path].is_empty()
{
self.entry_data[other_path] = Some(entry_data);
self.descs[other_path] = desc;
other_path
} else {
self.push(name.as_str().to_string(), None, Some(entry_data), desc, None, None, None)
}
}
fn push_path(&mut self, name: String, path_data: PathData) -> usize {
self.push(name, Some(path_data), None, String::new(), None, None, None)
}
fn push_type(&mut self, name: String, path_data: PathData, type_data: TypeData) -> usize {
self.push(name, Some(path_data), None, String::new(), None, Some(type_data), None)
}
fn push_alias(&mut self, name: String, alias_pointer: usize) -> usize {
self.push(name, None, None, String::new(), None, None, Some(alias_pointer))
}
fn get_id_by_module_path(&mut self, path: &[Symbol]) -> usize {
let ty = if path.len() == 1 { ItemType::ExternCrate } else { ItemType::Module };
match self.crate_paths_index.entry((ty, path.to_vec())) {
Entry::Occupied(index) => *index.get(),
Entry::Vacant(slot) => {
slot.insert(self.path_data.len());
let (name, module_path) = path.split_last().unwrap();
self.push_path(
name.as_str().to_string(),
PathData { ty, module_path: module_path.to_vec(), exact_module_path: None },
)
}
}
}
pub(crate) fn union(mut self, other: &SerializedSearchIndex) -> SerializedSearchIndex {
let other_entryid_offset = self.names.len();
let mut map_other_pathid_to_self_pathid = Vec::new();
let mut skips = FxHashSet::default();
for (other_pathid, other_path_data) in other.path_data.iter().enumerate() {
if let Some(other_path_data) = other_path_data {
let name = Symbol::intern(&other.names[other_pathid]);
let fqp =
other_path_data.module_path.iter().copied().chain(iter::once(name)).collect();
let self_pathid = other_entryid_offset + other_pathid;
let self_pathid = match self.crate_paths_index.entry((other_path_data.ty, fqp)) {
Entry::Vacant(slot) => {
slot.insert(self_pathid);
self_pathid
}
Entry::Occupied(existing_entryid) => {
skips.insert(other_pathid);
let self_pathid = *existing_entryid.get();
let new_type_data = match (
self.type_data[self_pathid].take(),
other.type_data[other_pathid].as_ref(),
) {
(Some(self_type_data), None) => Some(self_type_data),
(None, Some(other_type_data)) => Some(TypeData {
search_unbox: other_type_data.search_unbox,
inverted_function_inputs_index: other_type_data
.inverted_function_inputs_index
.iter()
.cloned()
.map(|mut list: Vec<u32>| {
for fnid in &mut list {
assert!(
other.function_data
[usize::try_from(*fnid).unwrap()]
.is_some(),
);
// this is valid because we call `self.push()` once, exactly, for every entry,
// even if we're just pushing a tombstone
*fnid += u32::try_from(other_entryid_offset).unwrap();
}
list
})
.collect(),
inverted_function_output_index: other_type_data
.inverted_function_output_index
.iter()
.cloned()
.map(|mut list: Vec<u32>| {
for fnid in &mut list {
assert!(
other.function_data
[usize::try_from(*fnid).unwrap()]
.is_some(),
);
// this is valid because we call `self.push()` once, exactly, for every entry,
// even if we're just pushing a tombstone
*fnid += u32::try_from(other_entryid_offset).unwrap();
}
list
})
.collect(),
}),
(Some(mut self_type_data), Some(other_type_data)) => {
for (size, other_list) in other_type_data
.inverted_function_inputs_index
.iter()
.enumerate()
{
while self_type_data.inverted_function_inputs_index.len()
<= size
{
self_type_data
.inverted_function_inputs_index
.push(Vec::new());
}
self_type_data.inverted_function_inputs_index[size].extend(
other_list.iter().copied().map(|fnid| {
assert!(
other.function_data[usize::try_from(fnid).unwrap()]
.is_some(),
);
// this is valid because we call `self.push()` once, exactly, for every entry,
// even if we're just pushing a tombstone
fnid + u32::try_from(other_entryid_offset).unwrap()
}),
)
}
for (size, other_list) in other_type_data
.inverted_function_output_index
.iter()
.enumerate()
{
while self_type_data.inverted_function_output_index.len()
<= size
{
self_type_data
.inverted_function_output_index
.push(Vec::new());
}
self_type_data.inverted_function_output_index[size].extend(
other_list.iter().copied().map(|fnid| {
assert!(
other.function_data[usize::try_from(fnid).unwrap()]
.is_some(),
);
// this is valid because we call `self.push()` once, exactly, for every entry,
// even if we're just pushing a tombstone
fnid + u32::try_from(other_entryid_offset).unwrap()
}),
)
}
Some(self_type_data)
}
(None, None) => None,
};
self.type_data[self_pathid] = new_type_data;
self_pathid
}
};
map_other_pathid_to_self_pathid.push(self_pathid);
} else {
// if this gets used, we want it to crash
// this should be impossible as a valid index, since some of the
// memory must be used for stuff other than the list
map_other_pathid_to_self_pathid.push(!0);
}
}
for other_entryid in 0..other.names.len() {
if skips.contains(&other_entryid) {
// we push tombstone entries to keep the IDs lined up
self.push(String::new(), None, None, String::new(), None, None, None);
} else {
self.push(
other.names[other_entryid].clone(),
other.path_data[other_entryid].clone(),
other.entry_data[other_entryid].as_ref().map(|other_entry_data| EntryData {
parent: other_entry_data
.parent
.map(|parent| map_other_pathid_to_self_pathid[parent])
.clone(),
module_path: other_entry_data
.module_path
.map(|path| map_other_pathid_to_self_pathid[path])
.clone(),
exact_module_path: other_entry_data
.exact_module_path
.map(|exact_path| map_other_pathid_to_self_pathid[exact_path])
.clone(),
krate: map_other_pathid_to_self_pathid[other_entry_data.krate],
..other_entry_data.clone()
}),
other.descs[other_entryid].clone(),
other.function_data[other_entryid].clone().map(|mut func| {
fn map_fn_sig_item(
map_other_pathid_to_self_pathid: &Vec<usize>,
ty: &mut RenderType,
) {
match ty.id {
None => {}
Some(RenderTypeId::Index(generic)) if generic < 0 => {}
Some(RenderTypeId::Index(id)) => {
let id = usize::try_from(id).unwrap();
let id = map_other_pathid_to_self_pathid[id];
assert!(id != !0);
ty.id = Some(RenderTypeId::Index(isize::try_from(id).unwrap()));
}
_ => unreachable!(),
}
if let Some(generics) = &mut ty.generics {
for generic in generics {
map_fn_sig_item(map_other_pathid_to_self_pathid, generic);
}
}
if let Some(bindings) = &mut ty.bindings {
for (param, constraints) in bindings {
*param = match *param {
param @ RenderTypeId::Index(generic) if generic < 0 => {
param
}
RenderTypeId::Index(id) => {
let id = usize::try_from(id).unwrap();
let id = map_other_pathid_to_self_pathid[id];
assert!(id != !0);
RenderTypeId::Index(isize::try_from(id).unwrap())
}
_ => unreachable!(),
};
for constraint in constraints {
map_fn_sig_item(
map_other_pathid_to_self_pathid,
constraint,
);
}
}
}
}
for input in &mut func.inputs {
map_fn_sig_item(&map_other_pathid_to_self_pathid, input);
}
for output in &mut func.output {
map_fn_sig_item(&map_other_pathid_to_self_pathid, output);
}
for clause in &mut func.where_clause {
for entry in clause {
map_fn_sig_item(&map_other_pathid_to_self_pathid, entry);
}
}
func
}),
other.type_data[other_entryid].as_ref().map(|type_data| TypeData {
inverted_function_inputs_index: type_data
.inverted_function_inputs_index
.iter()
.cloned()
.map(|mut list| {
for fnid in &mut list {
assert!(
other.function_data[usize::try_from(*fnid).unwrap()]
.is_some(),
);
// this is valid because we call `self.push()` once, exactly, for every entry,
// even if we're just pushing a tombstone
*fnid += u32::try_from(other_entryid_offset).unwrap();
}
list
})
.collect(),
inverted_function_output_index: type_data
.inverted_function_output_index
.iter()
.cloned()
.map(|mut list| {
for fnid in &mut list {
assert!(
other.function_data[usize::try_from(*fnid).unwrap()]
.is_some(),
);
// this is valid because we call `self.push()` once, exactly, for every entry,
// even if we're just pushing a tombstone
*fnid += u32::try_from(other_entryid_offset).unwrap();
}
list
})
.collect(),
search_unbox: type_data.search_unbox,
}),
other.alias_pointers[other_entryid]
.map(|alias_pointer| alias_pointer + other_entryid_offset),
);
}
}
if other.generic_inverted_index.len() > self.generic_inverted_index.len() {
self.generic_inverted_index.resize(other.generic_inverted_index.len(), Vec::new());
}
for (other_generic_inverted_index, self_generic_inverted_index) in
iter::zip(&other.generic_inverted_index, &mut self.generic_inverted_index)
{
if other_generic_inverted_index.len() > self_generic_inverted_index.len() {
self_generic_inverted_index.resize(other_generic_inverted_index.len(), Vec::new());
}
for (other_list, self_list) in
iter::zip(other_generic_inverted_index, self_generic_inverted_index)
{
self_list.extend(
other_list
.iter()
.copied()
.map(|fnid| fnid + u32::try_from(other_entryid_offset).unwrap()),
);
}
}
self
}
pub(crate) fn sort(self) -> SerializedSearchIndex {
let mut idlist: Vec<usize> = (0..self.names.len()).collect();
// nameless entries are tombstones, and will be removed after sorting
// sort shorter names first, so that we can present them in order out of search.js
idlist.sort_by_key(|&id| {
(
self.names[id].is_empty(),
self.names[id].len(),
&self.names[id],
self.entry_data[id].as_ref().map_or("", |entry| self.names[entry.krate].as_str()),
self.path_data[id].as_ref().map_or(&[][..], |entry| &entry.module_path[..]),
)
});
let map = FxHashMap::from_iter(
idlist.iter().enumerate().map(|(new_id, &old_id)| (old_id, new_id)),
);
let mut new = SerializedSearchIndex::default();
for &id in &idlist {
if self.names[id].is_empty() {
break;
}
new.push(
self.names[id].clone(),
self.path_data[id].clone(),
self.entry_data[id].as_ref().map(
|EntryData {
krate,
ty,
module_path,
exact_module_path,
parent,
trait_parent,
deprecated,
unstable,
associated_item_disambiguator,
}| EntryData {
krate: *map.get(krate).unwrap(),
ty: *ty,
module_path: module_path.and_then(|path_id| map.get(&path_id).copied()),
exact_module_path: exact_module_path
.and_then(|path_id| map.get(&path_id).copied()),
parent: parent.and_then(|path_id| map.get(&path_id).copied()),
trait_parent: trait_parent.and_then(|path_id| map.get(&path_id).copied()),
deprecated: *deprecated,
unstable: *unstable,
associated_item_disambiguator: associated_item_disambiguator.clone(),
},
),
self.descs[id].clone(),
self.function_data[id].clone().map(|mut func| {
fn map_fn_sig_item(map: &FxHashMap<usize, usize>, ty: &mut RenderType) {
match ty.id {
None => {}
Some(RenderTypeId::Index(generic)) if generic < 0 => {}
Some(RenderTypeId::Index(id)) => {
let id = usize::try_from(id).unwrap();
let id = *map.get(&id).unwrap();
assert!(id != !0);
ty.id = Some(RenderTypeId::Index(isize::try_from(id).unwrap()));
}
_ => unreachable!(),
}
if let Some(generics) = &mut ty.generics {
for generic in generics {
map_fn_sig_item(map, generic);
}
}
if let Some(bindings) = &mut ty.bindings {
for (param, constraints) in bindings {
*param = match *param {
param @ RenderTypeId::Index(generic) if generic < 0 => param,
RenderTypeId::Index(id) => {
let id = usize::try_from(id).unwrap();
let id = *map.get(&id).unwrap();
assert!(id != !0);
RenderTypeId::Index(isize::try_from(id).unwrap())
}
_ => unreachable!(),
};
for constraint in constraints {
map_fn_sig_item(map, constraint);
}
}
}
}
for input in &mut func.inputs {
map_fn_sig_item(&map, input);
}
for output in &mut func.output {
map_fn_sig_item(&map, output);
}
for clause in &mut func.where_clause {
for entry in clause {
map_fn_sig_item(&map, entry);
}
}
func
}),
self.type_data[id].as_ref().map(
|TypeData {
search_unbox,
inverted_function_inputs_index,
inverted_function_output_index,
}| {
let inverted_function_inputs_index: Vec<Vec<u32>> =
inverted_function_inputs_index
.iter()
.cloned()
.map(|mut list| {
for id in &mut list {
*id = u32::try_from(
*map.get(&usize::try_from(*id).unwrap()).unwrap(),
)
.unwrap();
}
list.sort();
list
})
.collect();
let inverted_function_output_index: Vec<Vec<u32>> =
inverted_function_output_index
.iter()
.cloned()
.map(|mut list| {
for id in &mut list {
*id = u32::try_from(
*map.get(&usize::try_from(*id).unwrap()).unwrap(),
)
.unwrap();
}
list.sort();
list
})
.collect();
TypeData {
search_unbox: *search_unbox,
inverted_function_inputs_index,
inverted_function_output_index,
}
},
),
self.alias_pointers[id].and_then(|alias| {
if self.names[alias].is_empty() { None } else { map.get(&alias).copied() }
}),
);
}
new.generic_inverted_index = self
.generic_inverted_index
.into_iter()
.map(|mut postings| {
for list in postings.iter_mut() {
let mut new_list: Vec<u32> = list
.iter()
.copied()
.filter_map(|id| u32::try_from(*map.get(&usize::try_from(id).ok()?)?).ok())
.collect();
new_list.sort();
*list = new_list;
}
postings
})
.collect();
new
}
pub(crate) fn write_to(self, doc_root: &Path, resource_suffix: &str) -> Result<(), Error> {
let SerializedSearchIndex {
names,
path_data,
entry_data,
descs,
function_data,
type_data,
alias_pointers,
generic_inverted_index,
crate_paths_index: _,
} = self;
let mut serialized_root = Vec::new();
serialized_root.extend_from_slice(br#"rr_('{"normalizedName":{"I":""#);
let normalized_names = names
.iter()
.map(|name| {
if name.contains("_") {
name.replace("_", "").to_ascii_lowercase()
} else {
name.to_ascii_lowercase()
}
})
.collect::<Vec<String>>();
let names_search_tree = stringdex_internals::tree::encode_search_tree_ukkonen(
normalized_names.iter().map(|name| name.as_bytes()),
);
let dir_path = doc_root.join(format!("search.index/"));
let _ = std::fs::remove_dir_all(&dir_path); // if already missing, no problem
stringdex_internals::write_tree_to_disk(
&names_search_tree,
&dir_path,
&mut serialized_root,
)
.map_err(|error| Error {
file: dir_path,
error: format!("failed to write name tree to disk: {error}"),
})?;
std::mem::drop(names_search_tree);
serialized_root.extend_from_slice(br#"","#);
serialized_root.extend_from_slice(&perform_write_strings(
doc_root,
"normalizedName",
normalized_names.into_iter(),
)?);
serialized_root.extend_from_slice(br#"},"crateNames":{"#);
let mut crates: Vec<&[u8]> = entry_data
.iter()
.filter_map(|entry_data| Some(names[entry_data.as_ref()?.krate].as_bytes()))
.collect();
crates.sort();
crates.dedup();
serialized_root.extend_from_slice(&perform_write_strings(
doc_root,
"crateNames",
crates.into_iter(),
)?);
serialized_root.extend_from_slice(br#"},"name":{"#);
serialized_root.extend_from_slice(&perform_write_strings(doc_root, "name", names.iter())?);
serialized_root.extend_from_slice(br#"},"path":{"#);
serialized_root.extend_from_slice(&perform_write_serde(doc_root, "path", path_data)?);
serialized_root.extend_from_slice(br#"},"entry":{"#);
serialized_root.extend_from_slice(&perform_write_serde(doc_root, "entry", entry_data)?);
serialized_root.extend_from_slice(br#"},"desc":{"#);
serialized_root.extend_from_slice(&perform_write_strings(
doc_root,
"desc",
descs.into_iter(),
)?);
serialized_root.extend_from_slice(br#"},"function":{"#);
serialized_root.extend_from_slice(&perform_write_serde(
doc_root,
"function",
function_data,
)?);
serialized_root.extend_from_slice(br#"},"type":{"#);
serialized_root.extend_from_slice(&perform_write_serde(doc_root, "type", type_data)?);
serialized_root.extend_from_slice(br#"},"alias":{"#);
serialized_root.extend_from_slice(&perform_write_serde(doc_root, "alias", alias_pointers)?);
serialized_root.extend_from_slice(br#"},"generic_inverted_index":{"#);
serialized_root.extend_from_slice(&perform_write_postings(
doc_root,
"generic_inverted_index",
generic_inverted_index,
)?);
serialized_root.extend_from_slice(br#"}}')"#);
fn perform_write_strings(
doc_root: &Path,
dirname: &str,
mut column: impl Iterator<Item = impl AsRef<[u8]> + Clone> + ExactSizeIterator,
) -> Result<Vec<u8>, Error> {
let dir_path = doc_root.join(format!("search.index/{dirname}"));
stringdex_internals::write_data_to_disk(&mut column, &dir_path).map_err(|error| Error {
file: dir_path,
error: format!("failed to write column to disk: {error}"),
})
}
fn perform_write_serde(
doc_root: &Path,
dirname: &str,
column: Vec<Option<impl Serialize>>,
) -> Result<Vec<u8>, Error> {
perform_write_strings(
doc_root,
dirname,
column.into_iter().map(|value| {
if let Some(value) = value {
serde_json::to_vec(&value).unwrap()
} else {
Vec::new()
}
}),
)
}
fn perform_write_postings(
doc_root: &Path,
dirname: &str,
column: Vec<Vec<Vec<u32>>>,
) -> Result<Vec<u8>, Error> {
perform_write_strings(
doc_root,
dirname,
column.into_iter().map(|postings| {
let mut buf = Vec::new();
encode::write_postings_to_string(&postings, &mut buf);
buf
}),
)
}
std::fs::write(
doc_root.join(format!("search.index/root{resource_suffix}.js")),
serialized_root,
)
.map_err(|error| Error {
file: doc_root.join(format!("search.index/root{resource_suffix}.js")),
error: format!("failed to write root to disk: {error}"),
})?;
Ok(())
}
}
#[derive(Clone, Debug)]
struct EntryData {
krate: usize,
ty: ItemType,
module_path: Option<usize>,
exact_module_path: Option<usize>,
parent: Option<usize>,
trait_parent: Option<usize>,
deprecated: bool,
unstable: bool,
associated_item_disambiguator: Option<String>,
}
impl Serialize for EntryData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None)?;
seq.serialize_element(&self.krate)?;
seq.serialize_element(&self.ty)?;
seq.serialize_element(&self.module_path.map(|id| id + 1).unwrap_or(0))?;
seq.serialize_element(&self.exact_module_path.map(|id| id + 1).unwrap_or(0))?;
seq.serialize_element(&self.parent.map(|id| id + 1).unwrap_or(0))?;
seq.serialize_element(&self.trait_parent.map(|id| id + 1).unwrap_or(0))?;
seq.serialize_element(&if self.deprecated { 1 } else { 0 })?;
seq.serialize_element(&if self.unstable { 1 } else { 0 })?;
if let Some(disambig) = &self.associated_item_disambiguator {
seq.serialize_element(&disambig)?;
}
seq.end()
}
}
impl<'de> Deserialize<'de> for EntryData {
fn deserialize<D>(deserializer: D) -> Result<EntryData, D::Error>
where
D: Deserializer<'de>,
{
struct EntryDataVisitor;
impl<'de> de::Visitor<'de> for EntryDataVisitor {
type Value = EntryData;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "path data")
}
fn visit_seq<A: de::SeqAccess<'de>>(self, mut v: A) -> Result<EntryData, A::Error> {
let krate: usize =
v.next_element()?.ok_or_else(|| A::Error::missing_field("krate"))?;
let ty: ItemType =
v.next_element()?.ok_or_else(|| A::Error::missing_field("ty"))?;
let module_path: SerializedOptional32 =
v.next_element()?.ok_or_else(|| A::Error::missing_field("module_path"))?;
let exact_module_path: SerializedOptional32 = v
.next_element()?
.ok_or_else(|| A::Error::missing_field("exact_module_path"))?;
let parent: SerializedOptional32 =
v.next_element()?.ok_or_else(|| A::Error::missing_field("parent"))?;
let trait_parent: SerializedOptional32 =
v.next_element()?.ok_or_else(|| A::Error::missing_field("trait_parent"))?;
let deprecated: u32 = v.next_element()?.unwrap_or(0);
let unstable: u32 = v.next_element()?.unwrap_or(0);
let associated_item_disambiguator: Option<String> = v.next_element()?;
Ok(EntryData {
krate,
ty,
module_path: Option::<i32>::from(module_path).map(|path| path as usize),
exact_module_path: Option::<i32>::from(exact_module_path)
.map(|path| path as usize),
parent: Option::<i32>::from(parent).map(|path| path as usize),
trait_parent: Option::<i32>::from(trait_parent).map(|path| path as usize),
deprecated: deprecated != 0,
unstable: unstable != 0,
associated_item_disambiguator,
})
}
}
deserializer.deserialize_any(EntryDataVisitor)
}
}
#[derive(Clone, Debug)]
struct PathData {
ty: ItemType,
module_path: Vec<Symbol>,
exact_module_path: Option<Vec<Symbol>>,
}
impl Serialize for PathData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None)?;
seq.serialize_element(&self.ty)?;
seq.serialize_element(&if self.module_path.is_empty() {
String::new()
} else {
join_path_syms(&self.module_path)
})?;
if let Some(ref path) = self.exact_module_path {
seq.serialize_element(&if path.is_empty() {
String::new()
} else {
join_path_syms(path)
})?;
}
seq.end()
}
}