Skip to content

Commit 3216e3e

Browse files
committed
rustdoc-search: merge type params into search-index
This commit tweaks the format to reduce its size and merges it into the index, which should reduce the amount of network traffic overall.
1 parent 765fe32 commit 3216e3e

File tree

5 files changed

+38
-84
lines changed

5 files changed

+38
-84
lines changed

src/librustdoc/html/render/search_index.rs

+19-20
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ use encode::{bitmap_to_string, write_vlqhex_to_string};
4949
pub(crate) struct SerializedSearchIndex {
5050
pub(crate) index: String,
5151
pub(crate) desc: Vec<(usize, String)>,
52-
pub(crate) param_names: String,
5352
}
5453

5554
const DESC_INDEX_SHARD_LEN: usize = 128 * 1024;
@@ -622,9 +621,25 @@ pub(crate) fn build_index<'tcx>(
622621
full_paths.push((*index, path));
623622
}
624623

624+
let param_names: Vec<(usize, String)> = {
625+
let mut prev = Vec::new();
626+
let mut result = Vec::new();
627+
for (index, item) in self.items.iter().enumerate() {
628+
if let Some(ty) = &item.search_type
629+
&& let my =
630+
ty.param_names.iter().map(|sym| sym.as_str()).collect::<Vec<_>>()
631+
&& my != prev
632+
{
633+
result.push((index, my.join(",")));
634+
prev = my;
635+
}
636+
}
637+
result
638+
};
639+
625640
let has_aliases = !self.aliases.is_empty();
626641
let mut crate_data =
627-
serializer.serialize_struct("CrateData", if has_aliases { 9 } else { 8 })?;
642+
serializer.serialize_struct("CrateData", if has_aliases { 13 } else { 12 })?;
628643
crate_data.serialize_field("t", &types)?;
629644
crate_data.serialize_field("n", &names)?;
630645
crate_data.serialize_field("q", &full_paths)?;
@@ -636,6 +651,7 @@ pub(crate) fn build_index<'tcx>(
636651
crate_data.serialize_field("b", &self.associated_item_disambiguators)?;
637652
crate_data.serialize_field("c", &bitmap_to_string(&deprecated))?;
638653
crate_data.serialize_field("e", &bitmap_to_string(&self.empty_desc))?;
654+
crate_data.serialize_field("P", &param_names)?;
639655
if has_aliases {
640656
crate_data.serialize_field("a", &self.aliases)?;
641657
}
@@ -682,23 +698,6 @@ pub(crate) fn build_index<'tcx>(
682698
desc.iter().map(|(len, _)| *len).sum::<usize>() + empty_desc.len()
683699
);
684700

685-
let param_names = {
686-
let result: Vec<Vec<&str>> = crate_items
687-
.iter()
688-
.map(|item| match &item.search_type {
689-
Some(ty) => ty.param_names.iter().map(|sym| sym.as_str()).collect(),
690-
None => Vec::new(),
691-
})
692-
.collect();
693-
serde_json::to_string(&result)
694-
.expect("failed serde conversion")
695-
// All these `replace` calls are because we have to go through JS string for JSON content.
696-
.replace('\\', r"\\")
697-
.replace('\'', r"\'")
698-
// We need to escape double quotes for the JSON.
699-
.replace("\\\"", "\\\\\"")
700-
};
701-
702701
// The index, which is actually used to search, is JSON
703702
// It uses `JSON.parse(..)` to actually load, since JSON
704703
// parses faster than the full JavaScript syntax.
@@ -720,7 +719,7 @@ pub(crate) fn build_index<'tcx>(
720719
// We need to escape double quotes for the JSON.
721720
.replace("\\\"", "\\\\\"")
722721
);
723-
SerializedSearchIndex { index, desc, param_names }
722+
SerializedSearchIndex { index, desc }
724723
}
725724

726725
pub(crate) fn get_function_type_for_search<'tcx>(

src/librustdoc/html/render/write_shared.rs

-16
Original file line numberDiff line numberDiff line change
@@ -361,22 +361,6 @@ else if (window.initSearch) window.initSearch(searchIndex);
361361
&path
362362
);
363363
}
364-
let output_filename = static_files::suffix_path(
365-
&format!("{kratename}-param-names.js"),
366-
&cx.shared.resource_suffix,
367-
);
368-
let path = search_desc_dir.join(output_filename);
369-
try_err!(
370-
std::fs::write(
371-
&path,
372-
&format!(
373-
r##"searchState.loadedParamNames('{kratename}','{data}')"##,
374-
data = search_index.param_names,
375-
)
376-
.into_bytes()
377-
),
378-
&path
379-
);
380364

381365
write_invocation_specific("crates.js", &|| {
382366
let krates = krates.iter().map(|k| format!("\"{k}\"")).join(",");

src/librustdoc/html/static/js/main.js

-20
Original file line numberDiff line numberDiff line change
@@ -353,26 +353,6 @@ function preLoadCss(cssUrl) {
353353
loadedDescShard: function(crate, shard, data) {
354354
this.descShards.get(crate)[shard].resolve(data.split("\n"));
355355
},
356-
paramNameShards: new Map(),
357-
paramNameResolvers: new Map(),
358-
loadParamNames: async function(crate) {
359-
if (this.paramNameShards.has(crate)) {
360-
return this.paramNameShards.get(crate);
361-
}
362-
const promise = new Promise((resolve, reject) => {
363-
this.paramNameResolvers.set(crate, resolve);
364-
const url = resourcePath(
365-
`search.desc/${crate}/${crate}-param-names`,
366-
".js",
367-
);
368-
loadScript(url, reject);
369-
});
370-
this.paramNameShards.set(crate, promise);
371-
return promise;
372-
},
373-
loadedParamNames: function(crate, data) {
374-
this.paramNameResolvers.get(crate)(JSON.parse(data));
375-
},
376356
};
377357

378358
const toggleAllDocsId = "toggle-all-docs";

src/librustdoc/html/static/js/search.js

+19-1
Original file line numberDiff line numberDiff line change
@@ -1501,7 +1501,7 @@ function initSearch(rawSearchIndex) {
15011501
const mappedNames = new Map();
15021502
const whereClause = new Map();
15031503

1504-
const fnParamNames = (await searchState.loadParamNames(obj.crate))[obj.bitIndex - 1];
1504+
const fnParamNames = obj.paramNames;
15051505
const queryParamNames = [];
15061506
/**
15071507
* Recursively writes a map of IDs to query generic names,
@@ -2525,6 +2525,7 @@ function initSearch(rawSearchIndex) {
25252525
ty: item.ty,
25262526
parent: item.parent,
25272527
type: item.type,
2528+
paramNames: item.paramNames,
25282529
is_alias: true,
25292530
bitIndex: item.bitIndex,
25302531
implDisambiguator: item.implDisambiguator,
@@ -4011,6 +4012,13 @@ ${item.displayPath}<span class="${type}">${name}</span>\
40114012
searchIndexEmptyDesc.set(crate, new RoaringBitmap(crateCorpus.e));
40124013
let descIndex = 0;
40134014

4015+
/**
4016+
* List of generic function type parameter names.
4017+
* Used for display, not for searching.
4018+
* @type {[string]}
4019+
*/
4020+
let lastParamNames = [];
4021+
40144022
// This object should have exactly the same set of fields as the "row"
40154023
// object defined below. Your JavaScript runtime will thank you.
40164024
// https://mathiasbynens.be/notes/shapes-ics
@@ -4025,6 +4033,7 @@ ${item.displayPath}<span class="${type}">${name}</span>\
40254033
desc: crateCorpus.doc,
40264034
parent: undefined,
40274035
type: null,
4036+
paramNames: lastParamNames,
40284037
id,
40294038
word: crate,
40304039
normalizedName: crate.indexOf("_") === -1 ? crate : crate.replace(/_/g, ""),
@@ -4061,6 +4070,10 @@ ${item.displayPath}<span class="${type}">${name}</span>\
40614070
// an array of [(String) alias name
40624071
// [Number] index to items]
40634072
const aliases = crateCorpus.a;
4073+
// an array of [(Number) item index,
4074+
// (String) comma-separated list of function generic param names]
4075+
// an item whose index is not present will fall back to the previous present path
4076+
const itemParamNames = new Map(crateCorpus.P);
40644077

40654078
// an array of [{name: String, ty: Number}]
40664079
const lowercasePaths = [];
@@ -4119,6 +4132,9 @@ ${item.displayPath}<span class="${type}">${name}</span>\
41194132
word = itemNames[i].toLowerCase();
41204133
}
41214134
const path = itemPaths.has(i) ? itemPaths.get(i) : lastPath;
4135+
const paramNames = itemParamNames.has(i) ?
4136+
itemParamNames.get(i).split(",") :
4137+
lastParamNames;
41224138
const type = itemFunctionDecoder.next();
41234139
if (type !== null) {
41244140
if (type) {
@@ -4149,6 +4165,7 @@ ${item.displayPath}<span class="${type}">${name}</span>\
41494165
exactPath: itemReexports.has(i) ? itemPaths.get(itemReexports.get(i)) : path,
41504166
parent: itemParentIdxs[i] > 0 ? paths[itemParentIdxs[i] - 1] : undefined,
41514167
type,
4168+
paramNames,
41524169
id,
41534170
word,
41544171
normalizedName: word.indexOf("_") === -1 ? word : word.replace(/_/g, ""),
@@ -4158,6 +4175,7 @@ ${item.displayPath}<span class="${type}">${name}</span>\
41584175
id += 1;
41594176
searchIndex.push(row);
41604177
lastPath = row.path;
4178+
lastParamNames = row.paramNames;
41614179
if (!searchIndexEmptyDesc.get(crate).contains(bitIndex)) {
41624180
descIndex += 1;
41634181
}

src/tools/rustdoc-js/tester.js

-27
Original file line numberDiff line numberDiff line change
@@ -428,33 +428,6 @@ function loadSearchJS(doc_folder, resource_suffix) {
428428
//console.log(this.descShards);
429429
this.descShards.get(crate)[shard].resolve(data.split("\n"));
430430
},
431-
paramNameShards: new Map(),
432-
paramNameResolvers: new Map(),
433-
loadParamNames: async function(crate) {
434-
if (this.paramNameShards.has(crate)) {
435-
return this.paramNameShards.get(crate);
436-
} else {
437-
const promise = new Promise((resolve, reject) => {
438-
this.paramNameResolvers.set(crate, resolve);
439-
const fname = `${crate}-param-names${resource_suffix}.js`;
440-
fs.readFile(
441-
`${doc_folder}/search.desc/${crate}/${fname}`,
442-
(err, data) => {
443-
if (err) {
444-
reject(err);
445-
} else {
446-
eval(data.toString("utf8"));
447-
}
448-
},
449-
);
450-
});
451-
this.paramNameShards.set(crate, promise);
452-
return promise;
453-
}
454-
},
455-
loadedParamNames: function(crate, data) {
456-
this.paramNameResolvers.get(crate)(JSON.parse(data));
457-
},
458431
};
459432

460433
const staticFiles = path.join(doc_folder, "static.files");

0 commit comments

Comments
 (0)