1 /* global addClass, getNakedUrl, getSettingValue */
2 /* global onEachLazy, removeClass, searchState, browserSupportsHistoryApi, exports */
7 // This mapping table should match the discriminants of
8 // `rustdoc::formats::item_type::ItemType` type in Rust.
38 // used for special search precedence
39 const TY_PRIMITIVE = itemTypes.indexOf("primitive");
40 const TY_KEYWORD = itemTypes.indexOf("keyword");
41 const ROOT_PATH = typeof window !== "undefined" ? window.rootPath : "../";
43 function hasOwnPropertyRustdoc(obj, property) {
44 return Object.prototype.hasOwnProperty.call(obj, property);
47 // In the search display, allows to switch between tabs.
48 function printTab(nb) {
50 let foundCurrentTab = false;
51 let foundCurrentResultSet = false;
52 onEachLazy(document.getElementById("titles").childNodes, elem => {
54 addClass(elem, "selected");
55 foundCurrentTab = true;
57 removeClass(elem, "selected");
62 onEachLazy(document.getElementById("results").childNodes, elem => {
64 addClass(elem, "active");
65 foundCurrentResultSet = true;
67 removeClass(elem, "active");
71 if (foundCurrentTab && foundCurrentResultSet) {
72 searchState.currentTab = nb;
73 } else if (nb !== 0) {
79 * A function to compute the Levenshtein distance between two strings
80 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
81 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
82 * This code is an unmodified version of the code written by Marco de Wit
83 * and was found at https://stackoverflow.com/a/18514751/745719
85 const levenshtein_row2 = [];
86 function levenshtein(s1, s2) {
90 const s1_len = s1.length, s2_len = s2.length;
91 if (s1_len && s2_len) {
92 let i1 = 0, i2 = 0, a, b, c, c2;
93 const row = levenshtein_row2;
98 c2 = s2.charCodeAt(i2);
102 for (i1 = 0; i1 < s1_len; ++i1) {
103 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
105 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
111 return s1_len + s2_len;
114 function initSearch(rawSearchIndex) {
115 const MAX_LEV_DISTANCE = 3;
116 const MAX_RESULTS = 200;
117 const NO_TYPE_FILTER = -1;
123 const ALIASES = Object.create(null);
125 function isWhitespace(c) {
126 return " \t\n\r".indexOf(c) !== -1;
129 function isSpecialStartCharacter(c) {
130 return "<\"".indexOf(c) !== -1;
133 function isEndCharacter(c) {
134 return ",>-".indexOf(c) !== -1;
137 function isStopCharacter(c) {
138 return isWhitespace(c) || isEndCharacter(c);
141 function isErrorCharacter(c) {
142 return "()".indexOf(c) !== -1;
145 function itemTypeFromName(typename) {
146 for (let i = 0, len = itemTypes.length; i < len; ++i) {
147 if (itemTypes[i] === typename) {
152 throw new Error("Unknown type filter `" + typename + "`");
156 * If we encounter a `"`, then we try to extract the string from it until we find another `"`.
158 * This function will throw an error in the following cases:
159 * * There is already another string element.
160 * * We are parsing a generic argument.
161 * * There is more than one element.
162 * * There is no closing `"`.
164 * @param {ParsedQuery} query
165 * @param {ParserState} parserState
166 * @param {boolean} isInGenerics
168 function getStringElem(query, parserState, isInGenerics) {
170 throw new Error("`\"` cannot be used in generics");
171 } else if (query.literalSearch) {
172 throw new Error("Cannot have more than one literal search element");
173 } else if (parserState.totalElems - parserState.genericsElems > 0) {
174 throw new Error("Cannot use literal search when there is more than one element");
176 parserState.pos += 1;
177 const start = parserState.pos;
178 const end = getIdentEndPosition(parserState);
179 if (parserState.pos >= parserState.length) {
180 throw new Error("Unclosed `\"`");
181 } else if (parserState.userQuery[end] !== "\"") {
182 throw new Error(`Unexpected \`${parserState.userQuery[end]}\` in a string element`);
183 } else if (start === end) {
184 throw new Error("Cannot have empty string element");
186 // To skip the quote at the end.
187 parserState.pos += 1;
188 query.literalSearch = true;
192 * Returns `true` if the current parser position is starting with "::".
194 * @param {ParserState} parserState
198 function isPathStart(parserState) {
199 return parserState.userQuery.slice(parserState.pos, parserState.pos + 2) === "::";
203 * Returns `true` if the current parser position is starting with "->".
205 * @param {ParserState} parserState
209 function isReturnArrow(parserState) {
210 return parserState.userQuery.slice(parserState.pos, parserState.pos + 2) === "->";
214 * Returns `true` if the given `c` character is valid for an ident.
220 function isIdentCharacter(c) {
223 (c >= "0" && c <= "9") ||
224 (c >= "a" && c <= "z") ||
225 (c >= "A" && c <= "Z"));
229 * Returns `true` if the given `c` character is a separator.
235 function isSeparatorCharacter(c) {
236 return c === "," || isWhitespaceCharacter(c);
240 * Returns `true` if the given `c` character is a whitespace.
246 function isWhitespaceCharacter(c) {
247 return c === " " || c === "\t";
251 * @param {ParsedQuery} query
252 * @param {ParserState} parserState
253 * @param {string} name - Name of the query element.
254 * @param {Array<QueryElement>} generics - List of generics of this query element.
256 * @return {QueryElement} - The newly created `QueryElement`.
258 function createQueryElement(query, parserState, name, generics, isInGenerics) {
259 if (name === "*" || (name.length === 0 && generics.length === 0)) {
262 if (query.literalSearch && parserState.totalElems - parserState.genericsElems > 0) {
263 throw new Error("You cannot have more than one element if you use quotes");
265 const pathSegments = name.split("::");
266 if (pathSegments.length > 1) {
267 for (let i = 0, len = pathSegments.length; i < len; ++i) {
268 const pathSegment = pathSegments[i];
270 if (pathSegment.length === 0) {
272 throw new Error("Paths cannot start with `::`");
273 } else if (i + 1 === len) {
274 throw new Error("Paths cannot end with `::`");
276 throw new Error("Unexpected `::::`");
280 // In case we only have something like `<p>`, there is no name.
281 if (pathSegments.length === 0 || (pathSegments.length === 1 && pathSegments[0] === "")) {
282 throw new Error("Found generics without a path");
284 parserState.totalElems += 1;
286 parserState.genericsElems += 1;
290 fullPath: pathSegments,
291 pathWithoutLast: pathSegments.slice(0, pathSegments.length - 1),
292 pathLast: pathSegments[pathSegments.length - 1],
298 * This function goes through all characters until it reaches an invalid ident character or the
299 * end of the query. It returns the position of the last character of the ident.
301 * @param {ParserState} parserState
305 function getIdentEndPosition(parserState) {
306 let end = parserState.pos;
307 let foundExclamation = false;
308 while (parserState.pos < parserState.length) {
309 const c = parserState.userQuery[parserState.pos];
310 if (!isIdentCharacter(c)) {
312 if (foundExclamation) {
313 throw new Error("Cannot have more than one `!` in an ident");
314 } else if (parserState.pos + 1 < parserState.length &&
315 isIdentCharacter(parserState.userQuery[parserState.pos + 1])
317 throw new Error("`!` can only be at the end of an ident");
319 foundExclamation = true;
320 } else if (isErrorCharacter(c)) {
321 throw new Error(`Unexpected \`${c}\``);
323 isStopCharacter(c) ||
324 isSpecialStartCharacter(c) ||
325 isSeparatorCharacter(c)
328 } else if (c === ":") { // If we allow paths ("str::string" for example).
329 if (!isPathStart(parserState)) {
333 parserState.pos += 1;
334 foundExclamation = false;
336 throw new Error(`Unexpected \`${c}\``);
339 parserState.pos += 1;
340 end = parserState.pos;
346 * @param {ParsedQuery} query
347 * @param {ParserState} parserState
348 * @param {Array<QueryElement>} elems - This is where the new {QueryElement} will be added.
349 * @param {boolean} isInGenerics
351 function getNextElem(query, parserState, elems, isInGenerics) {
354 let start = parserState.pos;
356 // We handle the strings on their own mostly to make code easier to follow.
357 if (parserState.userQuery[parserState.pos] === "\"") {
359 getStringElem(query, parserState, isInGenerics);
360 end = parserState.pos - 1;
362 end = getIdentEndPosition(parserState);
364 if (parserState.pos < parserState.length &&
365 parserState.userQuery[parserState.pos] === "<"
368 throw new Error("Unexpected `<` after `<`");
369 } else if (start >= end) {
370 throw new Error("Found generics without a path");
372 parserState.pos += 1;
373 getItemsBefore(query, parserState, generics, ">");
375 if (start >= end && generics.length === 0) {
382 parserState.userQuery.slice(start, end),
390 * This function parses the next query element until it finds `endChar`, calling `getNextElem`
391 * to collect each element.
393 * If there is no `endChar`, this function will implicitly stop at the end without raising an
396 * @param {ParsedQuery} query
397 * @param {ParserState} parserState
398 * @param {Array<QueryElement>} elems - This is where the new {QueryElement} will be added.
399 * @param {string} endChar - This function will stop when it'll encounter this
402 function getItemsBefore(query, parserState, elems, endChar) {
403 let foundStopChar = true;
405 while (parserState.pos < parserState.length) {
406 const c = parserState.userQuery[parserState.pos];
409 } else if (isSeparatorCharacter(c)) {
410 parserState.pos += 1;
411 foundStopChar = true;
413 } else if (c === ":" && isPathStart(parserState)) {
414 throw new Error("Unexpected `::`: paths cannot start with `::`");
415 } else if (c === ":" || isEndCharacter(c)) {
417 if (endChar === ">") {
419 } else if (endChar === "") {
422 throw new Error("Unexpected `" + c + "` after " + extra);
424 if (!foundStopChar) {
425 if (endChar !== "") {
426 throw new Error(`Expected \`,\`, \` \` or \`${endChar}\`, found \`${c}\``);
428 throw new Error(`Expected \`,\` or \` \`, found \`${c}\``);
430 const posBefore = parserState.pos;
431 getNextElem(query, parserState, elems, endChar === ">");
432 // This case can be encountered if `getNextElem` encountered a "stop character" right
433 // from the start. For example if you have `,,` or `<>`. In this case, we simply move up
434 // the current position to continue the parsing.
435 if (posBefore === parserState.pos) {
436 parserState.pos += 1;
438 foundStopChar = false;
440 // We are either at the end of the string or on the `endChar`` character, let's move forward
442 parserState.pos += 1;
446 * Checks that the type filter doesn't have unwanted characters like `<>` (which are ignored
449 * @param {ParserState} parserState
451 function checkExtraTypeFilterCharacters(parserState) {
452 const query = parserState.userQuery;
454 for (let pos = 0; pos < parserState.pos; ++pos) {
455 if (!isIdentCharacter(query[pos]) && !isWhitespaceCharacter(query[pos])) {
456 throw new Error(`Unexpected \`${query[pos]}\` in type filter`);
462 * Parses the provided `query` input to fill `parserState`. If it encounters an error while
463 * parsing `query`, it'll throw an error.
465 * @param {ParsedQuery} query
466 * @param {ParserState} parserState
468 function parseInput(query, parserState) {
470 let foundStopChar = true;
472 while (parserState.pos < parserState.length) {
473 c = parserState.userQuery[parserState.pos];
474 if (isStopCharacter(c)) {
475 foundStopChar = true;
476 if (isSeparatorCharacter(c)) {
477 parserState.pos += 1;
479 } else if (c === "-" || c === ">") {
480 if (isReturnArrow(parserState)) {
483 throw new Error(`Unexpected \`${c}\` (did you mean \`->\`?)`);
485 throw new Error(`Unexpected \`${c}\``);
486 } else if (c === ":" && !isPathStart(parserState)) {
487 if (parserState.typeFilter !== null) {
488 throw new Error("Unexpected `:`");
490 if (query.elems.length === 0) {
491 throw new Error("Expected type filter before `:`");
492 } else if (query.elems.length !== 1 || parserState.totalElems !== 1) {
493 throw new Error("Unexpected `:`");
494 } else if (query.literalSearch) {
495 throw new Error("You cannot use quotes on type filter");
497 checkExtraTypeFilterCharacters(parserState);
498 // The type filter doesn't count as an element since it's a modifier.
499 parserState.typeFilter = query.elems.pop().name;
500 parserState.pos += 1;
501 parserState.totalElems = 0;
502 query.literalSearch = false;
503 foundStopChar = true;
506 if (!foundStopChar) {
507 if (parserState.typeFilter !== null) {
508 throw new Error(`Expected \`,\`, \` \` or \`->\`, found \`${c}\``);
510 throw new Error(`Expected \`,\`, \` \`, \`:\` or \`->\`, found \`${c}\``);
512 before = query.elems.length;
513 getNextElem(query, parserState, query.elems, false);
514 if (query.elems.length === before) {
515 // Nothing was added, weird... Let's increase the position to not remain stuck.
516 parserState.pos += 1;
518 foundStopChar = false;
520 while (parserState.pos < parserState.length) {
521 c = parserState.userQuery[parserState.pos];
522 if (isReturnArrow(parserState)) {
523 parserState.pos += 2;
524 // Get returned elements.
525 getItemsBefore(query, parserState, query.returned, "");
526 // Nothing can come afterward!
527 if (query.returned.length === 0) {
528 throw new Error("Expected at least one item after `->`");
532 parserState.pos += 1;
538 * Takes the user search input and returns an empty `ParsedQuery`.
540 * @param {string} userQuery
542 * @return {ParsedQuery}
544 function newParsedQuery(userQuery) {
547 userQuery: userQuery.toLowerCase(),
548 typeFilter: NO_TYPE_FILTER,
551 // Total number of "top" elements (does not include generics).
553 literalSearch: false,
559 * Build an URL with search parameters.
561 * @param {string} search - The current search being performed.
562 * @param {string|null} filterCrates - The current filtering crate (if any).
566 function buildUrl(search, filterCrates) {
567 let extra = "?search=" + encodeURIComponent(search);
569 if (filterCrates !== null) {
570 extra += "&filter-crate=" + encodeURIComponent(filterCrates);
572 return getNakedUrl() + extra + window.location.hash;
576 * Return the filtering crate or `null` if there is none.
578 * @return {string|null}
580 function getFilterCrates() {
581 const elem = document.getElementById("crate-search");
584 elem.value !== "all crates" &&
585 hasOwnPropertyRustdoc(rawSearchIndex, elem.value)
595 * The supported syntax by this parser is as follow:
597 * ident = *(ALPHA / DIGIT / "_") [!]
598 * path = ident *(DOUBLE-COLON ident)
599 * arg = path [generics]
600 * arg-without-generic = path
601 * type-sep = COMMA/WS *(COMMA/WS)
602 * nonempty-arg-list = *(type-sep) arg *(type-sep arg) *(type-sep)
603 * nonempty-arg-list-without-generics = *(type-sep) arg-without-generic
604 * *(type-sep arg-without-generic) *(type-sep)
605 * generics = OPEN-ANGLE-BRACKET [ nonempty-arg-list-without-generics ] *(type-sep)
606 * CLOSE-ANGLE-BRACKET/EOF
607 * return-args = RETURN-ARROW *(type-sep) nonempty-arg-list
609 * exact-search = [type-filter *WS COLON] [ RETURN-ARROW ] *WS QUOTE ident QUOTE [ generics ]
610 * type-search = [type-filter *WS COLON] [ nonempty-arg-list ] [ return-args ]
612 * query = *WS (exact-search / type-search) *WS
633 * "associatedconstant" /
642 * OPEN-ANGLE-BRACKET = "<"
643 * CLOSE-ANGLE-BRACKET = ">"
645 * DOUBLE-COLON = "::"
648 * RETURN-ARROW = "->"
650 * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z
654 * @param {string} val - The user query
656 * @return {ParsedQuery} - The parsed query
658 function parseQuery(userQuery) {
659 userQuery = userQuery.trim();
660 const parserState = {
661 length: userQuery.length,
663 // Total number of elements (includes generics).
667 userQuery: userQuery.toLowerCase(),
669 let query = newParsedQuery(userQuery);
672 parseInput(query, parserState);
673 if (parserState.typeFilter !== null) {
674 let typeFilter = parserState.typeFilter;
675 if (typeFilter === "const") {
676 typeFilter = "constant";
678 query.typeFilter = itemTypeFromName(typeFilter);
681 query = newParsedQuery(userQuery);
682 query.error = err.message;
683 query.typeFilter = -1;
687 if (!query.literalSearch) {
688 // If there is more than one element in the query, we switch to literalSearch in any
690 query.literalSearch = parserState.totalElems > 1;
692 query.foundElems = query.elems.length + query.returned.length;
697 * Creates the query results.
699 * @param {Array<Result>} results_in_args
700 * @param {Array<Result>} results_returned
701 * @param {Array<Result>} results_in_args
702 * @param {ParsedQuery} parsedQuery
704 * @return {ResultsTable}
706 function createQueryResults(results_in_args, results_returned, results_others, parsedQuery) {
708 "in_args": results_in_args,
709 "returned": results_returned,
710 "others": results_others,
711 "query": parsedQuery,
716 * Executes the parsed query and builds a {ResultsTable}.
718 * @param {ParsedQuery} parsedQuery - The parsed user query
719 * @param {Object} searchWords - The list of search words to query against
720 * @param {Object} [filterCrates] - Crate to search in if defined
721 * @param {Object} [currentCrate] - Current crate, to rank results from this crate higher
723 * @return {ResultsTable}
725 function execQuery(parsedQuery, searchWords, filterCrates, currentCrate) {
726 const results_others = {}, results_in_args = {}, results_returned = {};
728 function transformResults(results) {
729 const duplicates = {};
732 for (const result of results) {
733 if (result.id > -1) {
734 const obj = searchIndex[result.id];
735 obj.lev = result.lev;
736 const res = buildHrefAndPath(obj);
737 obj.displayPath = pathSplitter(res[0]);
738 obj.fullPath = obj.displayPath + obj.name;
739 // To be sure than it some items aren't considered as duplicate.
740 obj.fullPath += "|" + obj.ty;
742 if (duplicates[obj.fullPath]) {
745 duplicates[obj.fullPath] = true;
749 if (out.length >= MAX_RESULTS) {
757 function sortResults(results, isType, preferredCrate) {
758 const userQuery = parsedQuery.userQuery;
760 for (const entry in results) {
761 if (hasOwnPropertyRustdoc(results, entry)) {
762 const result = results[entry];
763 result.word = searchWords[result.id];
764 result.item = searchIndex[result.id] || {};
769 // if there are no results then return to default and fail
770 if (results.length === 0) {
774 results.sort((aaa, bbb) => {
777 // sort by exact match with regard to the last word (mismatch goes later)
778 a = (aaa.word !== userQuery);
779 b = (bbb.word !== userQuery);
784 // Sort by non levenshtein results and then levenshtein results by the distance
785 // (less changes required to match means higher rankings)
792 // sort by crate (current crate comes first)
793 a = (aaa.item.crate !== preferredCrate);
794 b = (bbb.item.crate !== preferredCrate);
799 // sort by item name length (longer goes later)
806 // sort by item name (lexicographically larger goes later)
810 return (a > b ? +1 : -1);
813 // sort by index of keyword in item name (no literal occurrence goes later)
819 // (later literal occurrence, if any, goes later)
826 // special precedence for primitive and keyword pages
827 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
828 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
831 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
832 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
836 // sort by description (no description goes later)
837 a = (aaa.item.desc === "");
838 b = (bbb.item.desc === "");
843 // sort by type (later occurrence in `itemTypes` goes later)
850 // sort by path (lexicographically larger goes later)
854 return (a > b ? +1 : -1);
861 let nameSplit = null;
862 if (parsedQuery.elems.length === 1) {
863 const hasPath = typeof parsedQuery.elems[0].path === "undefined";
864 nameSplit = hasPath ? null : parsedQuery.elems[0].path;
867 for (const result of results) {
868 // this validation does not make sense when searching by types
869 if (result.dontValidate) {
872 const name = result.item.name.toLowerCase(),
873 path = result.item.path.toLowerCase(),
874 parent = result.item.parent;
876 if (!isType && !validateResult(name, path, nameSplit, parent)) {
880 return transformResults(results);
884 * This function checks if the object (`row`) generics match the given type (`elem`)
885 * generics. If there are no generics on `row`, `defaultLev` is returned.
887 * @param {Row} row - The object to check.
888 * @param {QueryElement} elem - The element from the parsed query.
889 * @param {integer} defaultLev - This is the value to return in case there are no generics.
891 * @return {integer} - Returns the best match (if any) or `MAX_LEV_DISTANCE + 1`.
893 function checkGenerics(row, elem, defaultLev) {
894 if (row.generics.length === 0) {
895 return elem.generics.length === 0 ? defaultLev : MAX_LEV_DISTANCE + 1;
896 } else if (row.generics.length > 0 && row.generics[0].name === null) {
897 return checkGenerics(row.generics[0], elem, defaultLev);
899 // The names match, but we need to be sure that all generics kinda
902 if (elem.generics.length > 0 && row.generics.length >= elem.generics.length) {
903 const elems = Object.create(null);
904 for (const entry of row.generics) {
905 elem_name = entry.name;
906 if (elem_name === "") {
907 // Pure generic, needs to check into it.
908 if (checkGenerics(entry, elem, MAX_LEV_DISTANCE + 1) !== 0) {
909 return MAX_LEV_DISTANCE + 1;
913 if (elems[elem_name] === undefined) {
914 elems[elem_name] = 0;
916 elems[elem_name] += 1;
918 // We need to find the type that matches the most to remove it in order
920 for (const generic of elem.generics) {
922 if (elems[generic.name]) {
923 match = generic.name;
925 for (elem_name in elems) {
926 if (!hasOwnPropertyRustdoc(elems, elem_name)) {
929 if (elem_name === generic) {
935 if (match === null) {
936 return MAX_LEV_DISTANCE + 1;
939 if (elems[match] === 0) {
945 return MAX_LEV_DISTANCE + 1;
949 * This function checks if the object (`row`) matches the given type (`elem`) and its
953 * @param {QueryElement} elem - The element from the parsed query.
955 * @return {integer} - Returns a Levenshtein distance to the best match.
957 function checkIfInGenerics(row, elem) {
958 let lev = MAX_LEV_DISTANCE + 1;
959 for (const entry of row.generics) {
960 lev = Math.min(checkType(entry, elem, true), lev);
969 * This function checks if the object (`row`) matches the given type (`elem`) and its
973 * @param {QueryElement} elem - The element from the parsed query.
974 * @param {boolean} literalSearch
976 * @return {integer} - Returns a Levenshtein distance to the best match. If there is
977 * no match, returns `MAX_LEV_DISTANCE + 1`.
979 function checkType(row, elem, literalSearch) {
980 if (row.name === null) {
981 // This is a pure "generic" search, no need to run other checks.
982 if (row.generics.length > 0) {
983 return checkIfInGenerics(row, elem);
985 return MAX_LEV_DISTANCE + 1;
988 let lev = levenshtein(row.name, elem.name);
991 // The name didn't match, let's try to check if the generics do.
992 if (elem.generics.length === 0) {
993 const checkGeneric = row.generics.length > 0;
994 if (checkGeneric && row.generics
995 .findIndex(tmp_elem => tmp_elem.name === elem.name) !== -1) {
999 return MAX_LEV_DISTANCE + 1;
1000 } else if (elem.generics.length > 0) {
1001 return checkGenerics(row, elem, MAX_LEV_DISTANCE + 1);
1004 } else if (row.generics.length > 0) {
1005 if (elem.generics.length === 0) {
1009 // The name didn't match so we now check if the type we're looking for is inside
1011 lev = checkIfInGenerics(row, elem);
1012 // Now whatever happens, the returned distance is "less good" so we should mark
1013 // it as such, and so we add 0.5 to the distance to make it "less good".
1015 } else if (lev > MAX_LEV_DISTANCE) {
1016 // So our item's name doesn't match at all and has generics.
1018 // Maybe it's present in a sub generic? For example "f<A<B<C>>>()", if we're
1019 // looking for "B<C>", we'll need to go down.
1020 return checkIfInGenerics(row, elem);
1022 // At this point, the name kinda match and we have generics to check, so
1024 const tmp_lev = checkGenerics(row, elem, lev);
1025 if (tmp_lev > MAX_LEV_DISTANCE) {
1026 return MAX_LEV_DISTANCE + 1;
1028 // We compute the median value of both checks and return it.
1029 return (tmp_lev + lev) / 2;
1031 } else if (elem.generics.length > 0) {
1032 // In this case, we were expecting generics but there isn't so we simply reject this
1034 return MAX_LEV_DISTANCE + 1;
1036 // No generics on our query or on the target type so we can return without doing
1042 * This function checks if the object (`row`) has an argument with the given type (`elem`).
1045 * @param {QueryElement} elem - The element from the parsed query.
1046 * @param {integer} typeFilter
1048 * @return {integer} - Returns a Levenshtein distance to the best match. If there is no
1049 * match, returns `MAX_LEV_DISTANCE + 1`.
1051 function findArg(row, elem, typeFilter) {
1052 let lev = MAX_LEV_DISTANCE + 1;
1054 if (row && row.type && row.type.inputs && row.type.inputs.length > 0) {
1055 for (const input of row.type.inputs) {
1056 if (!typePassesFilter(typeFilter, input.ty)) {
1059 lev = Math.min(lev, checkType(input, elem, parsedQuery.literalSearch));
1065 return parsedQuery.literalSearch ? MAX_LEV_DISTANCE + 1 : lev;
1069 * This function checks if the object (`row`) returns the given type (`elem`).
1072 * @param {QueryElement} elem - The element from the parsed query.
1073 * @param {integer} typeFilter
1075 * @return {integer} - Returns a Levenshtein distance to the best match. If there is no
1076 * match, returns `MAX_LEV_DISTANCE + 1`.
1078 function checkReturned(row, elem, typeFilter) {
1079 let lev = MAX_LEV_DISTANCE + 1;
1081 if (row && row.type && row.type.output.length > 0) {
1082 const ret = row.type.output;
1083 for (const ret_ty of ret) {
1084 if (!typePassesFilter(typeFilter, ret_ty.ty)) {
1087 lev = Math.min(lev, checkType(ret_ty, elem, parsedQuery.literalSearch));
1093 return parsedQuery.literalSearch ? MAX_LEV_DISTANCE + 1 : lev;
1096 function checkPath(contains, ty) {
1097 if (contains.length === 0) {
1100 let ret_lev = MAX_LEV_DISTANCE + 1;
1101 const path = ty.path.split("::");
1103 if (ty.parent && ty.parent.name) {
1104 path.push(ty.parent.name.toLowerCase());
1107 const length = path.length;
1108 const clength = contains.length;
1109 if (clength > length) {
1110 return MAX_LEV_DISTANCE + 1;
1112 for (let i = 0; i < length; ++i) {
1113 if (i + clength > length) {
1117 let aborted = false;
1118 for (let x = 0; x < clength; ++x) {
1119 const lev = levenshtein(path[i + x], contains[x]);
1120 if (lev > MAX_LEV_DISTANCE) {
1127 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
1133 function typePassesFilter(filter, type) {
1134 // No filter or Exact mach
1135 if (filter <= NO_TYPE_FILTER || filter === type) return true;
1137 // Match related items
1138 const name = itemTypes[type];
1139 switch (itemTypes[filter]) {
1141 return name === "associatedconstant";
1143 return name === "method" || name === "tymethod";
1145 return name === "primitive" || name === "associatedtype";
1147 return name === "traitalias";
1154 function createAliasFromItem(item) {
1161 parent: item.parent,
1167 function handleAliases(ret, query, filterCrates, currentCrate) {
1168 const lowerQuery = query.toLowerCase();
1169 // We separate aliases and crate aliases because we want to have current crate
1170 // aliases to be before the others in the displayed results.
1172 const crateAliases = [];
1173 if (filterCrates !== null) {
1174 if (ALIASES[filterCrates] && ALIASES[filterCrates][lowerQuery]) {
1175 const query_aliases = ALIASES[filterCrates][lowerQuery];
1176 for (const alias of query_aliases) {
1177 aliases.push(createAliasFromItem(searchIndex[alias]));
1181 Object.keys(ALIASES).forEach(crate => {
1182 if (ALIASES[crate][lowerQuery]) {
1183 const pushTo = crate === currentCrate ? crateAliases : aliases;
1184 const query_aliases = ALIASES[crate][lowerQuery];
1185 for (const alias of query_aliases) {
1186 pushTo.push(createAliasFromItem(searchIndex[alias]));
1192 const sortFunc = (aaa, bbb) => {
1193 if (aaa.path < bbb.path) {
1195 } else if (aaa.path === bbb.path) {
1200 crateAliases.sort(sortFunc);
1201 aliases.sort(sortFunc);
1203 const pushFunc = alias => {
1204 alias.alias = query;
1205 const res = buildHrefAndPath(alias);
1206 alias.displayPath = pathSplitter(res[0]);
1207 alias.fullPath = alias.displayPath + alias.name;
1208 alias.href = res[1];
1210 ret.others.unshift(alias);
1211 if (ret.others.length > MAX_RESULTS) {
1216 aliases.forEach(pushFunc);
1217 crateAliases.forEach(pushFunc);
1221 * This function adds the given result into the provided `results` map if it matches the
1222 * following condition:
1224 * * If it is a "literal search" (`parsedQuery.literalSearch`), then `lev` must be 0.
1225 * * If it is not a "literal search", `lev` must be <= `MAX_LEV_DISTANCE`.
1227 * The `results` map contains information which will be used to sort the search results:
1229 * * `fullId` is a `string`` used as the key of the object we use for the `results` map.
1230 * * `id` is the index in both `searchWords` and `searchIndex` arrays for this element.
1231 * * `index` is an `integer`` used to sort by the position of the word in the item's name.
1232 * * `lev` is the main metric used to sort the search results.
1234 * @param {Results} results
1235 * @param {string} fullId
1236 * @param {integer} id
1237 * @param {integer} index
1238 * @param {integer} lev
1240 function addIntoResults(results, fullId, id, index, lev) {
1241 if (lev === 0 || (!parsedQuery.literalSearch && lev <= MAX_LEV_DISTANCE)) {
1242 if (results[fullId] !== undefined) {
1243 const result = results[fullId];
1244 if (result.dontValidate || result.lev <= lev) {
1251 dontValidate: parsedQuery.literalSearch,
1258 * This function is called in case the query is only one element (with or without generics).
1259 * This element will be compared to arguments' and returned values' items and also to items.
1261 * Other important thing to note: since there is only one element, we use levenshtein
1262 * distance for name comparisons.
1265 * @param {integer} pos - Position in the `searchIndex`.
1266 * @param {QueryElement} elem - The element from the parsed query.
1267 * @param {Results} results_others - Unqualified results (not in arguments nor in
1269 * @param {Results} results_in_args - Matching arguments results.
1270 * @param {Results} results_returned - Matching returned arguments results.
1272 function handleSingleArg(
1280 if (!row || (filterCrates !== null && row.crate !== filterCrates)) {
1283 let lev, lev_add = 0, index = -1;
1284 const fullId = row.id;
1286 const in_args = findArg(row, elem, parsedQuery.typeFilter);
1287 const returned = checkReturned(row, elem, parsedQuery.typeFilter);
1289 addIntoResults(results_in_args, fullId, pos, index, in_args);
1290 addIntoResults(results_returned, fullId, pos, index, returned);
1292 if (!typePassesFilter(parsedQuery.typeFilter, row.ty)) {
1295 const searchWord = searchWords[pos];
1297 if (parsedQuery.literalSearch) {
1298 if (searchWord === elem.name) {
1299 addIntoResults(results_others, fullId, pos, -1, 0);
1304 // No need to check anything else if it's a "pure" generics search.
1305 if (elem.name.length === 0) {
1306 if (row.type !== null) {
1307 lev = checkGenerics(row.type, elem, MAX_LEV_DISTANCE + 1);
1308 addIntoResults(results_others, fullId, pos, index, lev);
1313 if (elem.fullPath.length > 1) {
1314 lev = checkPath(elem.pathWithoutLast, row);
1315 if (lev > MAX_LEV_DISTANCE || (parsedQuery.literalSearch && lev !== 0)) {
1317 } else if (lev > 0) {
1322 if (searchWord.indexOf(elem.pathLast) > -1 ||
1323 row.normalizedName.indexOf(elem.pathLast) > -1
1325 index = row.normalizedName.indexOf(elem.pathLast);
1327 lev = levenshtein(searchWord, elem.pathLast);
1328 if (lev > 0 && elem.pathLast.length > 2 && searchWord.indexOf(elem.pathLast) > -1) {
1329 if (elem.pathLast.length < 6) {
1336 if (lev > MAX_LEV_DISTANCE) {
1338 } else if (index !== -1 && elem.fullPath.length < 2) {
1344 addIntoResults(results_others, fullId, pos, index, lev);
1348 * This function is called in case the query has more than one element. In this case, it'll
1349 * try to match the items which validates all the elements. For `aa -> bb` will look for
1350 * functions which have a parameter `aa` and has `bb` in its returned values.
1353 * @param {integer} pos - Position in the `searchIndex`.
1354 * @param {Object} results
1356 function handleArgs(row, pos, results) {
1357 if (!row || (filterCrates !== null && row.crate !== filterCrates)) {
1364 // If the result is too "bad", we return false and it ends this search.
1365 function checkArgs(elems, callback) {
1366 for (const elem of elems) {
1367 // There is more than one parameter to the query so all checks should be "exact"
1368 const lev = callback(row, elem, NO_TYPE_FILTER);
1378 if (!checkArgs(parsedQuery.elems, findArg)) {
1381 if (!checkArgs(parsedQuery.returned, checkReturned)) {
1388 const lev = Math.round(totalLev / nbLev);
1389 addIntoResults(results, row.id, pos, 0, lev);
1392 function innerRunQuery() {
1393 let elem, i, nSearchWords, in_returned, row;
1395 if (parsedQuery.foundElems === 1) {
1396 if (parsedQuery.elems.length === 1) {
1397 elem = parsedQuery.elems[0];
1398 for (i = 0, nSearchWords = searchWords.length; i < nSearchWords; ++i) {
1399 // It means we want to check for this element everywhere (in names, args and
1410 } else if (parsedQuery.returned.length === 1) {
1411 // We received one returned argument to check, so looking into returned values.
1412 elem = parsedQuery.returned[0];
1413 for (i = 0, nSearchWords = searchWords.length; i < nSearchWords; ++i) {
1414 row = searchIndex[i];
1415 in_returned = checkReturned(row, elem, parsedQuery.typeFilter);
1416 addIntoResults(results_others, row.id, i, -1, in_returned);
1419 } else if (parsedQuery.foundElems > 0) {
1420 for (i = 0, nSearchWords = searchWords.length; i < nSearchWords; ++i) {
1421 handleArgs(searchIndex[i], i, results_others);
1426 if (parsedQuery.error === null) {
1430 const ret = createQueryResults(
1431 sortResults(results_in_args, true, currentCrate),
1432 sortResults(results_returned, true, currentCrate),
1433 sortResults(results_others, false, currentCrate),
1435 handleAliases(ret, parsedQuery.original.replace(/"/g, ""), filterCrates, currentCrate);
1436 if (parsedQuery.error !== null && ret.others.length !== 0) {
1437 // It means some doc aliases were found so let's "remove" the error!
1438 ret.query.error = null;
1444 * Validate performs the following boolean logic. For example:
1445 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1446 * exists in (name || path || parent) OR => ("file" && "open") exists in
1449 * This could be written functionally, but I wanted to minimise
1450 * functions on stack.
1452 * @param {string} name - The name of the result
1453 * @param {string} path - The path of the result
1454 * @param {string} keys - The keys to be used (["file", "open"])
1455 * @param {Object} parent - The parent of the result
1457 * @return {boolean} - Whether the result is valid or not
1459 function validateResult(name, path, keys, parent) {
1460 if (!keys || !keys.length) {
1463 for (const key of keys) {
1464 // each check is for validation so we negate the conditions and invalidate
1466 // check for an exact name match
1467 name.indexOf(key) > -1 ||
1468 // then an exact path match
1469 path.indexOf(key) > -1 ||
1470 // next if there is a parent, check for exact parent match
1471 (parent !== undefined && parent.name !== undefined &&
1472 parent.name.toLowerCase().indexOf(key) > -1) ||
1473 // lastly check to see if the name was a levenshtein match
1474 levenshtein(name, key) <= MAX_LEV_DISTANCE)) {
1481 function nextTab(direction) {
1482 const next = (searchState.currentTab + direction + 3) % searchState.focusedByTab.length;
1483 searchState.focusedByTab[searchState.currentTab] = document.activeElement;
1485 focusSearchResult();
1488 // Focus the first search result on the active tab, or the result that
1489 // was focused last time this tab was active.
1490 function focusSearchResult() {
1491 const target = searchState.focusedByTab[searchState.currentTab] ||
1492 document.querySelectorAll(".search-results.active a").item(0) ||
1493 document.querySelectorAll("#titles > button").item(searchState.currentTab);
1499 function buildHrefAndPath(item) {
1502 const type = itemTypes[item.ty];
1503 const name = item.name;
1504 let path = item.path;
1506 if (type === "mod") {
1507 displayPath = path + "::";
1508 href = ROOT_PATH + path.replace(/::/g, "/") + "/" +
1509 name + "/index.html";
1510 } else if (type === "import") {
1511 displayPath = item.path + "::";
1512 href = ROOT_PATH + item.path.replace(/::/g, "/") + "/index.html#reexport." + name;
1513 } else if (type === "primitive" || type === "keyword") {
1515 href = ROOT_PATH + path.replace(/::/g, "/") +
1516 "/" + type + "." + name + ".html";
1517 } else if (type === "externcrate") {
1519 href = ROOT_PATH + name + "/index.html";
1520 } else if (item.parent !== undefined) {
1521 const myparent = item.parent;
1522 let anchor = "#" + type + "." + name;
1523 const parentType = itemTypes[myparent.ty];
1524 let pageType = parentType;
1525 let pageName = myparent.name;
1527 if (parentType === "primitive") {
1528 displayPath = myparent.name + "::";
1529 } else if (type === "structfield" && parentType === "variant") {
1530 // Structfields belonging to variants are special: the
1531 // final path element is the enum name.
1532 const enumNameIdx = item.path.lastIndexOf("::");
1533 const enumName = item.path.substr(enumNameIdx + 2);
1534 path = item.path.substr(0, enumNameIdx);
1535 displayPath = path + "::" + enumName + "::" + myparent.name + "::";
1536 anchor = "#variant." + myparent.name + ".field." + name;
1538 pageName = enumName;
1540 displayPath = path + "::" + myparent.name + "::";
1542 href = ROOT_PATH + path.replace(/::/g, "/") +
1547 displayPath = item.path + "::";
1548 href = ROOT_PATH + item.path.replace(/::/g, "/") +
1549 "/" + type + "." + name + ".html";
1551 return [displayPath, href];
1554 function pathSplitter(path) {
1555 const tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1556 if (tmp.endsWith("<span>")) {
1557 return tmp.slice(0, tmp.length - 6);
1563 * Render a set of search results for a single tab.
1564 * @param {Array<?>} array - The search results for this tab
1565 * @param {ParsedQuery} query
1566 * @param {boolean} display - True if this is the active tab
1568 function addTab(array, query, display) {
1569 let extraClass = "";
1570 if (display === true) {
1571 extraClass = " active";
1574 const output = document.createElement("div");
1576 if (array.length > 0) {
1577 output.className = "search-results " + extraClass;
1579 array.forEach(item => {
1580 const name = item.name;
1581 const type = itemTypes[item.ty];
1586 if (type === "primitive") {
1587 extra = " <i>(primitive type)</i>";
1588 } else if (type === "keyword") {
1589 extra = " <i>(keyword)</i>";
1592 const link = document.createElement("a");
1593 link.className = "result-" + type;
1594 link.href = item.href;
1596 const resultName = document.createElement("div");
1597 resultName.className = "result-name";
1599 if (item.is_alias) {
1600 const alias = document.createElement("span");
1601 alias.className = "alias";
1603 const bold = document.createElement("b");
1604 bold.innerText = item.alias;
1605 alias.appendChild(bold);
1607 alias.insertAdjacentHTML(
1609 "<span class=\"grey\"><i> - see </i></span>");
1611 resultName.appendChild(alias);
1613 resultName.insertAdjacentHTML(
1615 item.displayPath + "<span class=\"" + type + "\">" + name + extra + "</span>");
1616 link.appendChild(resultName);
1618 const description = document.createElement("div");
1619 description.className = "desc";
1620 description.insertAdjacentHTML("beforeend", item.desc);
1622 link.appendChild(description);
1623 output.appendChild(link);
1625 } else if (query.error === null) {
1626 output.className = "search-failed" + extraClass;
1627 output.innerHTML = "No results :(<br/>" +
1628 "Try on <a href=\"https://duckduckgo.com/?q=" +
1629 encodeURIComponent("rust " + query.userQuery) +
1630 "\">DuckDuckGo</a>?<br/><br/>" +
1631 "Or try looking in one of these:<ul><li>The <a " +
1632 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1633 " for technical details about the language.</li><li><a " +
1634 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1635 "Example</a> for expository code examples.</a></li><li>The <a " +
1636 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1637 "introductions to language features and the language itself.</li><li><a " +
1638 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1639 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul>";
1641 return [output, length];
1644 function makeTabHeader(tabNb, text, nbElems) {
1645 if (searchState.currentTab === tabNb) {
1646 return "<button class=\"selected\">" + text +
1647 " <div class=\"count\">(" + nbElems + ")</div></button>";
1649 return "<button>" + text + " <div class=\"count\">(" + nbElems + ")</div></button>";
1653 * @param {ResultsTable} results
1654 * @param {boolean} go_to_first
1655 * @param {string} filterCrates
1657 function showResults(results, go_to_first, filterCrates) {
1658 const search = searchState.outputElement();
1659 if (go_to_first || (results.others.length === 1
1660 && getSettingValue("go-to-only-result") === "true"
1661 // By default, the search DOM element is "empty" (meaning it has no children not
1662 // text content). Once a search has been run, it won't be empty, even if you press
1663 // ESC or empty the search input (which also "cancels" the search).
1664 && (!search.firstChild || search.firstChild.innerText !== searchState.loadingText))
1666 const elem = document.createElement("a");
1667 elem.href = results.others[0].href;
1668 removeClass(elem, "active");
1669 // For firefox, we need the element to be in the DOM so it can be clicked.
1670 document.body.appendChild(elem);
1674 if (results.query === undefined) {
1675 results.query = parseQuery(searchState.input.value);
1678 currentResults = results.query.userQuery;
1680 const ret_others = addTab(results.others, results.query, true);
1681 const ret_in_args = addTab(results.in_args, results.query, false);
1682 const ret_returned = addTab(results.returned, results.query, false);
1684 // Navigate to the relevant tab if the current tab is empty, like in case users search
1685 // for "-> String". If they had selected another tab previously, they have to click on
1687 let currentTab = searchState.currentTab;
1688 if ((currentTab === 0 && ret_others[1] === 0) ||
1689 (currentTab === 1 && ret_in_args[1] === 0) ||
1690 (currentTab === 2 && ret_returned[1] === 0)) {
1691 if (ret_others[1] !== 0) {
1693 } else if (ret_in_args[1] !== 0) {
1695 } else if (ret_returned[1] !== 0) {
1701 const crates_list = Object.keys(rawSearchIndex);
1702 if (crates_list.length > 1) {
1703 crates = " in <div id=\"crate-search-div\"><select id=\"crate-search\">" +
1704 "<option value=\"all crates\">all crates</option>";
1705 for (const c of crates_list) {
1706 crates += `<option value="${c}" ${c === filterCrates && "selected"}>${c}</option>`;
1708 crates += "</select></div>";
1711 let output = `<h1 class="search-results-title">Results${crates}</h1>`;
1712 if (results.query.error !== null) {
1713 output += `<h3>Query parser error: "${results.query.error}".</h3>`;
1714 output += "<div id=\"titles\">" +
1715 makeTabHeader(0, "In Names", ret_others[1]) +
1718 } else if (results.query.foundElems <= 1 && results.query.returned.length === 0) {
1719 output += "<div id=\"titles\">" +
1720 makeTabHeader(0, "In Names", ret_others[1]) +
1721 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1722 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1725 const signatureTabTitle =
1726 results.query.elems.length === 0 ? "In Function Return Types" :
1727 results.query.returned.length === 0 ? "In Function Parameters" :
1728 "In Function Signatures";
1729 output += "<div id=\"titles\">" +
1730 makeTabHeader(0, signatureTabTitle, ret_others[1]) +
1735 const resultsElem = document.createElement("div");
1736 resultsElem.id = "results";
1737 resultsElem.appendChild(ret_others[0]);
1738 resultsElem.appendChild(ret_in_args[0]);
1739 resultsElem.appendChild(ret_returned[0]);
1741 search.innerHTML = output;
1742 const crateSearch = document.getElementById("crate-search");
1744 crateSearch.addEventListener("input", updateCrate);
1746 search.appendChild(resultsElem);
1747 // Reset focused elements.
1748 searchState.showResults(search);
1749 const elems = document.getElementById("titles").childNodes;
1750 searchState.focusedByTab = [];
1752 for (const elem of elems) {
1754 elem.onclick = () => printTab(j);
1755 searchState.focusedByTab.push(null);
1758 printTab(currentTab);
1762 * Perform a search based on the current state of the search input element
1763 * and display the results.
1764 * @param {Event} [e] - The event that triggered this search, if any
1765 * @param {boolean} [forced]
1767 function search(e, forced) {
1768 const params = searchState.getQueryStringParams();
1769 const query = parseQuery(searchState.input.value.trim());
1775 if (!forced && query.userQuery === currentResults) {
1776 if (query.userQuery.length > 0) {
1782 let filterCrates = getFilterCrates();
1784 // In case we have no information about the saved crate and there is a URL query parameter,
1785 // we override it with the URL query parameter.
1786 if (filterCrates === null && params["filter-crate"] !== undefined) {
1787 filterCrates = params["filter-crate"];
1790 // Update document title to maintain a meaningful browser history
1791 searchState.title = "Results for " + query.original + " - Rust";
1793 // Because searching is incremental by character, only the most
1794 // recent search query is added to the browser history.
1795 if (browserSupportsHistoryApi()) {
1796 const newURL = buildUrl(query.original, filterCrates);
1798 if (!history.state && !params.search) {
1799 history.pushState(null, "", newURL);
1801 history.replaceState(null, "", newURL);
1806 execQuery(query, searchWords, filterCrates, window.currentCrate),
1812 * Convert a list of RawFunctionType / ID to object-based FunctionType.
1814 * Crates often have lots of functions in them, and it's common to have a large number of
1815 * functions that operate on a small set of data types, so the search index compresses them
1816 * by encoding function parameter and return types as indexes into an array of names.
1818 * Even when a general-purpose compression algorithm is used, this is still a win. I checked.
1819 * https://github.com/rust-lang/rust/pull/98475#issue-1284395985
1821 * The format for individual function types is encoded in
1822 * librustdoc/html/render/mod.rs: impl Serialize for RenderType
1824 * @param {null|Array<RawFunctionType>} types
1825 * @param {Array<{name: string, ty: number}>} lowercasePaths
1827 * @return {Array<FunctionSearchType>}
1829 function buildItemSearchTypeAll(types, lowercasePaths) {
1830 const PATH_INDEX_DATA = 0;
1831 const GENERICS_DATA = 1;
1832 return types.map(type => {
1833 let pathIndex, generics;
1834 if (typeof type === "number") {
1838 pathIndex = type[PATH_INDEX_DATA];
1839 generics = buildItemSearchTypeAll(type[GENERICS_DATA], lowercasePaths);
1842 // `0` is used as a sentinel because it's fewer bytes than `null`
1843 name: pathIndex === 0 ? null : lowercasePaths[pathIndex - 1].name,
1844 ty: pathIndex === 0 ? null : lowercasePaths[pathIndex - 1].ty,
1851 * Convert from RawFunctionSearchType to FunctionSearchType.
1853 * Crates often have lots of functions in them, and function signatures are sometimes complex,
1854 * so rustdoc uses a pretty tight encoding for them. This function converts it to a simpler,
1855 * object-based encoding so that the actual search code is more readable and easier to debug.
1857 * The raw function search type format is generated using serde in
1858 * librustdoc/html/render/mod.rs: impl Serialize for IndexItemFunctionType
1860 * @param {RawFunctionSearchType} functionSearchType
1861 * @param {Array<{name: string, ty: number}>} lowercasePaths
1863 * @return {null|FunctionSearchType}
1865 function buildFunctionSearchType(functionSearchType, lowercasePaths) {
1866 const INPUTS_DATA = 0;
1867 const OUTPUT_DATA = 1;
1868 // `0` is used as a sentinel because it's fewer bytes than `null`
1869 if (functionSearchType === 0) {
1873 if (typeof functionSearchType[INPUTS_DATA] === "number") {
1874 const pathIndex = functionSearchType[INPUTS_DATA];
1876 name: pathIndex === 0 ? null : lowercasePaths[pathIndex - 1].name,
1877 ty: pathIndex === 0 ? null : lowercasePaths[pathIndex - 1].ty,
1881 inputs = buildItemSearchTypeAll(functionSearchType[INPUTS_DATA], lowercasePaths);
1883 if (functionSearchType.length > 1) {
1884 if (typeof functionSearchType[OUTPUT_DATA] === "number") {
1885 const pathIndex = functionSearchType[OUTPUT_DATA];
1887 name: pathIndex === 0 ? null : lowercasePaths[pathIndex - 1].name,
1888 ty: pathIndex === 0 ? null : lowercasePaths[pathIndex - 1].ty,
1892 output = buildItemSearchTypeAll(functionSearchType[OUTPUT_DATA], lowercasePaths);
1902 function buildIndex(rawSearchIndex) {
1905 * @type {Array<string>}
1907 const searchWords = [];
1909 let currentIndex = 0;
1912 for (const crate in rawSearchIndex) {
1913 if (!hasOwnPropertyRustdoc(rawSearchIndex, crate)) {
1920 * The raw search data for a given crate. `n`, `t`, `d`, and `q`, `i`, and `f`
1921 * are arrays with the same length. n[i] contains the name of an item.
1922 * t[i] contains the type of that item (as a small integer that represents an
1923 * offset in `itemTypes`). d[i] contains the description of that item.
1925 * q[i] contains the full path of the item, or an empty string indicating
1928 * i[i] contains an item's parent, usually a module. For compactness,
1929 * it is a set of indexes into the `p` array.
1931 * f[i] contains function signatures, or `0` if the item isn't a function.
1932 * Functions are themselves encoded as arrays. The first item is a list of
1933 * types representing the function's inputs, and the second list item is a list
1934 * of types representing the function's output. Tuples are flattened.
1935 * Types are also represented as arrays; the first item is an index into the `p`
1936 * array, while the second is a list of types representing any generic parameters.
1938 * `a` defines aliases with an Array of pairs: [name, offset], where `offset`
1939 * points into the n/t/d/q/i/f arrays.
1941 * `doc` contains the description of the crate.
1943 * `p` is a list of path/type pairs. It is used for parents and function parameters.
1953 * f: Array<RawFunctionSearchType>,
1957 const crateCorpus = rawSearchIndex[crate];
1959 searchWords.push(crate);
1960 // This object should have exactly the same set of fields as the "row"
1961 // object defined below. Your JavaScript runtime will thank you.
1962 // https://mathiasbynens.be/notes/shapes-ics
1965 ty: 1, // == ExternCrate
1968 desc: crateCorpus.doc,
1972 normalizedName: crate.indexOf("_") === -1 ? crate : crate.replace(/_/g, ""),
1975 searchIndex.push(crateRow);
1978 // an array of (Number) item types
1979 const itemTypes = crateCorpus.t;
1980 // an array of (String) item names
1981 const itemNames = crateCorpus.n;
1982 // an array of (String) full paths (or empty string for previous path)
1983 const itemPaths = crateCorpus.q;
1984 // an array of (String) descriptions
1985 const itemDescs = crateCorpus.d;
1986 // an array of (Number) the parent path index + 1 to `paths`, or 0 if none
1987 const itemParentIdxs = crateCorpus.i;
1988 // an array of (Object | null) the type of the function, if any
1989 const itemFunctionSearchTypes = crateCorpus.f;
1990 // an array of [(Number) item type,
1992 const paths = crateCorpus.p;
1993 // an array of [(String) alias name
1994 // [Number] index to items]
1995 const aliases = crateCorpus.a;
1997 // an array of [{name: String, ty: Number}]
1998 const lowercasePaths = [];
2000 // convert `rawPaths` entries into object form
2001 // generate normalizedPaths for function search mode
2002 let len = paths.length;
2003 for (i = 0; i < len; ++i) {
2004 lowercasePaths.push({ty: paths[i][0], name: paths[i][1].toLowerCase()});
2005 paths[i] = {ty: paths[i][0], name: paths[i][1]};
2008 // convert `item*` into an object form, and construct word indices.
2010 // before any analysis is performed lets gather the search terms to
2011 // search against apart from the rest of the data. This is a quick
2012 // operation that is cached for the life of the page state so that
2013 // all other search operations have access to this cached data for
2014 // faster analysis operations
2015 len = itemTypes.length;
2017 for (i = 0; i < len; ++i) {
2018 // This object should have exactly the same set of fields as the "crateRow"
2019 // object defined above.
2020 if (typeof itemNames[i] === "string") {
2021 word = itemNames[i].toLowerCase();
2022 searchWords.push(word);
2025 searchWords.push("");
2031 path: itemPaths[i] ? itemPaths[i] : lastPath,
2033 parent: itemParentIdxs[i] > 0 ? paths[itemParentIdxs[i] - 1] : undefined,
2034 type: buildFunctionSearchType(itemFunctionSearchTypes[i], lowercasePaths),
2036 normalizedName: word.indexOf("_") === -1 ? word : word.replace(/_/g, ""),
2039 searchIndex.push(row);
2040 lastPath = row.path;
2045 ALIASES[crate] = Object.create(null);
2046 for (const alias_name in aliases) {
2047 if (!hasOwnPropertyRustdoc(aliases, alias_name)) {
2051 if (!hasOwnPropertyRustdoc(ALIASES[crate], alias_name)) {
2052 ALIASES[crate][alias_name] = [];
2054 for (const local_alias of aliases[alias_name]) {
2055 ALIASES[crate][alias_name].push(local_alias + currentIndex);
2059 currentIndex += crateSize;
2065 * Callback for when the search form is submitted.
2066 * @param {Event} [e] - The event that triggered this call, if any
2068 function onSearchSubmit(e) {
2070 searchState.clearInputTimeout();
2074 function putBackSearch() {
2075 const search_input = searchState.input;
2076 if (!searchState.input) {
2079 if (search_input.value !== "" && !searchState.isDisplayed()) {
2080 searchState.showResults();
2081 if (browserSupportsHistoryApi()) {
2082 history.replaceState(null, "",
2083 buildUrl(search_input.value, getFilterCrates()));
2085 document.title = searchState.title;
2089 function registerSearchEvents() {
2090 const params = searchState.getQueryStringParams();
2092 // Populate search bar with query string search term when provided,
2093 // but only if the input bar is empty. This avoid the obnoxious issue
2094 // where you start trying to do a search, and the index loads, and
2095 // suddenly your search is gone!
2096 if (searchState.input.value === "") {
2097 searchState.input.value = params.search || "";
2100 const searchAfter500ms = () => {
2101 searchState.clearInputTimeout();
2102 if (searchState.input.value.length === 0) {
2103 if (browserSupportsHistoryApi()) {
2104 history.replaceState(null, window.currentCrate + " - Rust",
2105 getNakedUrl() + window.location.hash);
2107 searchState.hideResults();
2109 searchState.timeout = setTimeout(search, 500);
2112 searchState.input.onkeyup = searchAfter500ms;
2113 searchState.input.oninput = searchAfter500ms;
2114 document.getElementsByClassName("search-form")[0].onsubmit = onSearchSubmit;
2115 searchState.input.onchange = e => {
2116 if (e.target !== document.activeElement) {
2117 // To prevent doing anything when it's from a blur event.
2120 // Do NOT e.preventDefault() here. It will prevent pasting.
2121 searchState.clearInputTimeout();
2122 // zero-timeout necessary here because at the time of event handler execution the
2123 // pasted content is not in the input field yet. Shouldn’t make any difference for
2125 setTimeout(search, 0);
2127 searchState.input.onpaste = searchState.input.onchange;
2129 searchState.outputElement().addEventListener("keydown", e => {
2130 // We only handle unmodified keystrokes here. We don't want to interfere with,
2131 // for instance, alt-left and alt-right for history navigation.
2132 if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
2135 // up and down arrow select next/previous search result, or the
2136 // search box if we're already at the top.
2137 if (e.which === 38) { // up
2138 const previous = document.activeElement.previousElementSibling;
2142 searchState.focus();
2145 } else if (e.which === 40) { // down
2146 const next = document.activeElement.nextElementSibling;
2150 const rect = document.activeElement.getBoundingClientRect();
2151 if (window.innerHeight - rect.bottom < rect.height) {
2152 window.scrollBy(0, rect.height);
2155 } else if (e.which === 37) { // left
2158 } else if (e.which === 39) { // right
2164 searchState.input.addEventListener("keydown", e => {
2165 if (e.which === 40) { // down
2166 focusSearchResult();
2171 searchState.input.addEventListener("focus", () => {
2175 searchState.input.addEventListener("blur", () => {
2176 searchState.input.placeholder = searchState.input.origPlaceholder;
2179 // Push and pop states are used to add search results to the browser
2181 if (browserSupportsHistoryApi()) {
2182 // Store the previous <title> so we can revert back to it later.
2183 const previousTitle = document.title;
2185 window.addEventListener("popstate", e => {
2186 const params = searchState.getQueryStringParams();
2187 // Revert to the previous title manually since the History
2188 // API ignores the title parameter.
2189 document.title = previousTitle;
2190 // When browsing forward to search results the previous
2191 // search will be repeated, so the currentResults are
2192 // cleared to ensure the search is successful.
2193 currentResults = null;
2194 // Synchronize search bar with query string state and
2195 // perform the search. This will empty the bar if there's
2196 // nothing there, which lets you really go back to a
2197 // previous state with nothing in the bar.
2198 if (params.search && params.search.length > 0) {
2199 searchState.input.value = params.search;
2200 // Some browsers fire "onpopstate" for every page load
2201 // (Chrome), while others fire the event only when actually
2202 // popping a state (Firefox), which is why search() is
2203 // called both here and at the end of the startSearch()
2207 searchState.input.value = "";
2208 // When browsing back from search results the main page
2209 // visibility must be reset.
2210 searchState.hideResults();
2215 // This is required in firefox to avoid this problem: Navigating to a search result
2216 // with the keyboard, hitting enter, and then hitting back would take you back to
2217 // the doc page, rather than the search that should overlay it.
2218 // This was an interaction between the back-forward cache and our handlers
2219 // that try to sync state between the URL and the search input. To work around it,
2220 // do a small amount of re-init on page show.
2221 window.onpageshow = () => {
2222 const qSearch = searchState.getQueryStringParams().search;
2223 if (searchState.input.value === "" && qSearch) {
2224 searchState.input.value = qSearch;
2230 function updateCrate(ev) {
2231 if (ev.target.value === "all crates") {
2232 // If we don't remove it from the URL, it'll be picked up again by the search.
2233 const params = searchState.getQueryStringParams();
2234 const query = searchState.input.value.trim();
2235 if (!history.state && !params.search) {
2236 history.pushState(null, "", buildUrl(query, null));
2238 history.replaceState(null, "", buildUrl(query, null));
2241 // In case you "cut" the entry from the search input, then change the crate filter
2242 // before paste back the previous search, you get the old search results without
2243 // the filter. To prevent this, we need to remove the previous results.
2244 currentResults = null;
2245 search(undefined, true);
2249 * @type {Array<string>}
2251 const searchWords = buildIndex(rawSearchIndex);
2252 if (typeof window !== "undefined") {
2253 registerSearchEvents();
2254 // If there's a search term in the URL, execute the search now.
2255 if (window.searchState.getQueryStringParams().search) {
2260 if (typeof exports !== "undefined") {
2261 exports.initSearch = initSearch;
2262 exports.execQuery = execQuery;
2263 exports.parseQuery = parseQuery;
2268 if (typeof window !== "undefined") {
2269 window.initSearch = initSearch;
2270 if (window.searchIndex !== undefined) {
2271 initSearch(window.searchIndex);
2274 // Running in Node, not a browser. Run initSearch just to produce the