1 /* global addClass, getNakedUrl, getSettingValue, hasOwnPropertyRustdoc, initSearch, onEach */
2 /* global onEachLazy, removeClass, searchState, updateLocalStorage */
5 // This mapping table should match the discriminants of
6 // `rustdoc::html::item_type::ItemType` type in Rust.
7 var itemTypes = ["mod",
34 // used for special search precedence
35 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
36 var TY_KEYWORD = itemTypes.indexOf("keyword");
38 // In the search display, allows to switch between tabs.
39 function printTab(nb) {
40 if (nb === 0 || nb === 1 || nb === 2) {
41 searchState.currentTab = nb;
44 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
46 addClass(elem, "selected");
48 removeClass(elem, "selected");
52 onEachLazy(document.getElementById("results").childNodes, function(elem) {
54 addClass(elem, "active");
56 removeClass(elem, "active");
62 function removeEmptyStringsFromArray(x) {
63 for (var i = 0, len = x.length; i < len; ++i) {
72 * A function to compute the Levenshtein distance between two strings
73 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
74 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
75 * This code is an unmodified version of the code written by Marco de Wit
76 * and was found at https://stackoverflow.com/a/18514751/745719
78 var levenshtein_row2 = [];
79 function levenshtein(s1, s2) {
83 var s1_len = s1.length, s2_len = s2.length;
84 if (s1_len && s2_len) {
85 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
90 c2 = s2.charCodeAt(i2);
94 for (i1 = 0; i1 < s1_len; ++i1) {
95 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
97 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
103 return s1_len + s2_len;
106 window.initSearch = function(rawSearchIndex) {
107 var MAX_LEV_DISTANCE = 3;
108 var MAX_RESULTS = 200;
109 var GENERICS_DATA = 2;
113 var NO_TYPE_FILTER = -1;
114 var currentResults, index, searchIndex;
116 var params = searchState.getQueryStringParams();
118 // Populate search bar with query string search term when provided,
119 // but only if the input bar is empty. This avoid the obnoxious issue
120 // where you start trying to do a search, and the index loads, and
121 // suddenly your search is gone!
122 if (searchState.input.value === "") {
123 searchState.input.value = params.search || "";
127 * Executes the query and builds an index of results
128 * @param {[Object]} query [The user query]
129 * @param {[type]} searchWords [The list of search words to query
131 * @param {[type]} filterCrates [Crate to search in if defined]
132 * @return {[type]} [A search index of results]
134 function execQuery(query, searchWords, filterCrates) {
135 function itemTypeFromName(typename) {
136 for (var i = 0, len = itemTypes.length; i < len; ++i) {
137 if (itemTypes[i] === typename) {
141 return NO_TYPE_FILTER;
144 var valLower = query.query.toLowerCase(),
146 typeFilter = itemTypeFromName(query.type),
147 results = {}, results_in_args = {}, results_returned = {},
148 split = valLower.split("::");
150 removeEmptyStringsFromArray(split);
152 function transformResults(results) {
154 for (var i = 0, len = results.length; i < len; ++i) {
155 if (results[i].id > -1) {
156 var obj = searchIndex[results[i].id];
157 obj.lev = results[i].lev;
158 var res = buildHrefAndPath(obj);
159 obj.displayPath = pathSplitter(res[0]);
160 obj.fullPath = obj.displayPath + obj.name;
161 // To be sure than it some items aren't considered as duplicate.
162 obj.fullPath += "|" + obj.ty;
165 if (out.length >= MAX_RESULTS) {
173 function sortResults(results, isType) {
175 for (var entry in results) {
176 if (hasOwnPropertyRustdoc(results, entry)) {
177 ar.push(results[entry]);
182 for (i = 0, len = results.length; i < len; ++i) {
184 result.word = searchWords[result.id];
185 result.item = searchIndex[result.id] || {};
187 // if there are no results then return to default and fail
188 if (results.length === 0) {
192 results.sort(function(aaa, bbb) {
195 // sort by exact match with regard to the last word (mismatch goes later)
196 a = (aaa.word !== val);
197 b = (bbb.word !== val);
198 if (a !== b) { return a - b; }
200 // Sort by non levenshtein results and then levenshtein results by the distance
201 // (less changes required to match means higher rankings)
204 if (a !== b) { return a - b; }
206 // sort by crate (non-current crate goes later)
207 a = (aaa.item.crate !== window.currentCrate);
208 b = (bbb.item.crate !== window.currentCrate);
209 if (a !== b) { return a - b; }
211 // sort by item name length (longer goes later)
214 if (a !== b) { return a - b; }
216 // sort by item name (lexicographically larger goes later)
219 if (a !== b) { return (a > b ? +1 : -1); }
221 // sort by index of keyword in item name (no literal occurrence goes later)
224 if (a !== b) { return a - b; }
225 // (later literal occurrence, if any, goes later)
228 if (a !== b) { return a - b; }
230 // special precedence for primitive and keyword pages
231 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
232 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
235 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
236 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
240 // sort by description (no description goes later)
241 a = (aaa.item.desc === "");
242 b = (bbb.item.desc === "");
243 if (a !== b) { return a - b; }
245 // sort by type (later occurrence in `itemTypes` goes later)
248 if (a !== b) { return a - b; }
250 // sort by path (lexicographically larger goes later)
253 if (a !== b) { return (a > b ? +1 : -1); }
259 for (i = 0, len = results.length; i < len; ++i) {
262 // this validation does not make sense when searching by types
263 if (result.dontValidate) {
266 var name = result.item.name.toLowerCase(),
267 path = result.item.path.toLowerCase(),
268 parent = result.item.parent;
270 if (!isType && !validateResult(name, path, split, parent)) {
274 return transformResults(results);
277 function extractGenerics(val) {
278 val = val.toLowerCase();
279 if (val.indexOf("<") !== -1) {
280 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
282 name: val.substring(0, val.indexOf("<")),
283 generics: values.split(/\s*,\s*/),
292 function checkGenerics(obj, val) {
293 // The names match, but we need to be sure that all generics kinda
295 var tmp_lev, elem_name;
296 if (val.generics.length > 0) {
297 if (obj.length > GENERICS_DATA &&
298 obj[GENERICS_DATA].length >= val.generics.length) {
299 var elems = Object.create(null);
300 var elength = obj[GENERICS_DATA].length;
301 for (var x = 0; x < elength; ++x) {
302 if (!elems[obj[GENERICS_DATA][x][NAME]]) {
303 elems[obj[GENERICS_DATA][x][NAME]] = 0;
305 elems[obj[GENERICS_DATA][x][NAME]] += 1;
309 // We need to find the type that matches the most to remove it in order
311 var vlength = val.generics.length;
312 for (x = 0; x < vlength; ++x) {
313 var lev = MAX_LEV_DISTANCE + 1;
314 var firstGeneric = val.generics[x];
316 if (elems[firstGeneric]) {
317 match = firstGeneric;
320 for (elem_name in elems) {
321 tmp_lev = levenshtein(elem_name, firstGeneric);
328 if (match !== null) {
330 if (elems[match] == 0) {
336 return MAX_LEV_DISTANCE + 1;
339 return Math.ceil(total / done);
342 return MAX_LEV_DISTANCE + 1;
345 // Check for type name and type generics (if any).
346 function checkType(obj, val, literalSearch) {
347 var lev_distance = MAX_LEV_DISTANCE + 1;
348 var tmp_lev = MAX_LEV_DISTANCE + 1;
349 var len, x, firstGeneric;
350 if (obj[NAME] === val.name) {
352 if (val.generics && val.generics.length !== 0) {
353 if (obj.length > GENERICS_DATA &&
354 obj[GENERICS_DATA].length > 0) {
355 var elems = Object.create(null);
356 len = obj[GENERICS_DATA].length;
357 for (x = 0; x < len; ++x) {
358 if (!elems[obj[GENERICS_DATA][x][NAME]]) {
359 elems[obj[GENERICS_DATA][x][NAME]] = 0;
361 elems[obj[GENERICS_DATA][x][NAME]] += 1;
365 len = val.generics.length;
366 for (x = 0; x < len; ++x) {
367 firstGeneric = val.generics[x];
368 if (elems[firstGeneric]) {
369 elems[firstGeneric] -= 1;
383 // If the type has generics but don't match, then it won't return at this point.
384 // Otherwise, `checkGenerics` will return 0 and it'll return.
385 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
386 tmp_lev = checkGenerics(obj, val);
387 if (tmp_lev <= MAX_LEV_DISTANCE) {
392 } else if (literalSearch) {
393 if ((!val.generics || val.generics.length === 0) &&
394 obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
395 return obj[GENERICS_DATA].some(
397 return gen[NAME] === val.name;
402 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
403 if (lev_distance <= MAX_LEV_DISTANCE) {
404 // The generics didn't match but the name kinda did so we give it
405 // a levenshtein distance value that isn't *this* good so it goes
406 // into the search results but not too high.
407 lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2);
409 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
410 // We can check if the type we're looking for is inside the generics!
411 var olength = obj[GENERICS_DATA].length;
412 for (x = 0; x < olength; ++x) {
413 tmp_lev = Math.min(levenshtein(obj[GENERICS_DATA][x][NAME], val.name), tmp_lev);
416 // If we didn't find a good enough result, we go check inside the generics of
418 for (x = 0; x < olength && tmp_lev !== 0; ++x) {
420 checkType(obj[GENERICS_DATA][x], val, literalSearch),
426 // Now whatever happens, the returned distance is "less good" so we should mark it
427 // as such, and so we add 1 to the distance to make it "less good".
428 return Math.min(lev_distance, tmp_lev) + 1;
431 function findArg(obj, val, literalSearch, typeFilter) {
432 var lev_distance = MAX_LEV_DISTANCE + 1;
434 if (obj && obj.type && obj.type[INPUTS_DATA] && obj.type[INPUTS_DATA].length > 0) {
435 var length = obj.type[INPUTS_DATA].length;
436 for (var i = 0; i < length; i++) {
437 var tmp = obj.type[INPUTS_DATA][i];
438 if (!typePassesFilter(typeFilter, tmp[1])) {
441 tmp = checkType(tmp, val, literalSearch);
448 lev_distance = Math.min(tmp, lev_distance);
449 if (lev_distance === 0) {
454 return literalSearch ? false : lev_distance;
457 function checkReturned(obj, val, literalSearch, typeFilter) {
458 var lev_distance = MAX_LEV_DISTANCE + 1;
460 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
461 var ret = obj.type[OUTPUT_DATA];
462 if (typeof ret[0] === "string") {
465 for (var x = 0, len = ret.length; x < len; ++x) {
467 if (!typePassesFilter(typeFilter, tmp[1])) {
470 tmp = checkType(tmp, val, literalSearch);
477 lev_distance = Math.min(tmp, lev_distance);
478 if (lev_distance === 0) {
483 return literalSearch ? false : lev_distance;
486 function checkPath(contains, lastElem, ty) {
487 if (contains.length === 0) {
490 var ret_lev = MAX_LEV_DISTANCE + 1;
491 var path = ty.path.split("::");
493 if (ty.parent && ty.parent.name) {
494 path.push(ty.parent.name.toLowerCase());
497 var length = path.length;
498 var clength = contains.length;
499 if (clength > length) {
500 return MAX_LEV_DISTANCE + 1;
502 for (var i = 0; i < length; ++i) {
503 if (i + clength > length) {
508 for (var x = 0; x < clength; ++x) {
509 var lev = levenshtein(path[i + x], contains[x]);
510 if (lev > MAX_LEV_DISTANCE) {
517 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
523 function typePassesFilter(filter, type) {
525 if (filter <= NO_TYPE_FILTER) return true;
528 if (filter === type) return true;
530 // Match related items
531 var name = itemTypes[type];
532 switch (itemTypes[filter]) {
534 return name === "associatedconstant";
536 return name === "method" || name === "tymethod";
538 return name === "primitive" || name === "associatedtype";
540 return name === "traitalias";
547 function createAliasFromItem(item) {
560 function handleAliases(ret, query, filterCrates) {
561 // We separate aliases and crate aliases because we want to have current crate
562 // aliases to be before the others in the displayed results.
564 var crateAliases = [];
565 if (filterCrates !== undefined) {
566 if (ALIASES[filterCrates] && ALIASES[filterCrates][query.search]) {
567 var query_aliases = ALIASES[filterCrates][query.search];
568 var len = query_aliases.length;
569 for (var i = 0; i < len; ++i) {
570 aliases.push(createAliasFromItem(searchIndex[query_aliases[i]]));
574 Object.keys(ALIASES).forEach(function(crate) {
575 if (ALIASES[crate][query.search]) {
576 var pushTo = crate === window.currentCrate ? crateAliases : aliases;
577 var query_aliases = ALIASES[crate][query.search];
578 var len = query_aliases.length;
579 for (var i = 0; i < len; ++i) {
580 pushTo.push(createAliasFromItem(searchIndex[query_aliases[i]]));
586 var sortFunc = function(aaa, bbb) {
587 if (aaa.path < bbb.path) {
589 } else if (aaa.path === bbb.path) {
594 crateAliases.sort(sortFunc);
595 aliases.sort(sortFunc);
597 var pushFunc = function(alias) {
598 alias.alias = query.raw;
599 var res = buildHrefAndPath(alias);
600 alias.displayPath = pathSplitter(res[0]);
601 alias.fullPath = alias.displayPath + alias.name;
604 ret.others.unshift(alias);
605 if (ret.others.length > MAX_RESULTS) {
609 onEach(aliases, pushFunc);
610 onEach(crateAliases, pushFunc);
613 // quoted values mean literal search
614 var nSearchWords = searchWords.length;
621 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
622 val.charAt(val.length - 1) === val.charAt(0))
624 val = extractGenerics(val.substr(1, val.length - 2));
625 for (i = 0; i < nSearchWords; ++i) {
626 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
629 in_args = findArg(searchIndex[i], val, true, typeFilter);
630 returned = checkReturned(searchIndex[i], val, true, typeFilter);
634 if (searchWords[i] === val.name
635 && typePassesFilter(typeFilter, searchIndex[i].ty)
636 && results[fullId] === undefined) {
643 if (in_args && results_in_args[fullId] === undefined) {
644 results_in_args[fullId] = {
650 if (returned && results_returned[fullId] === undefined) {
651 results_returned[fullId] = {
658 query.inputs = [val];
662 } else if (val.search("->") > -1) {
663 var trimmer = function(s) { return s.trim(); };
664 var parts = val.split("->").map(trimmer);
665 var input = parts[0];
666 // sort inputs so that order does not matter
667 var inputs = input.split(",").map(trimmer).sort();
668 for (i = 0, len = inputs.length; i < len; ++i) {
669 inputs[i] = extractGenerics(inputs[i]);
671 var output = extractGenerics(parts[1]);
673 for (i = 0; i < nSearchWords; ++i) {
674 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
677 var type = searchIndex[i].type;
684 returned = checkReturned(ty, output, true, NO_TYPE_FILTER);
685 if (output.name === "*" || returned) {
687 var is_module = false;
693 for (it = 0, len = inputs.length; allFound && it < len; it++) {
694 allFound = checkType(type, inputs[it], true);
699 results_in_args[fullId] = {
706 results_returned[fullId] = {
721 query.inputs = inputs.map(function(input) {
724 query.output = output.name;
726 query.inputs = [val];
729 // gather matching search results up to a certain maximum
730 val = val.replace(/_/g, "");
732 var valGenerics = extractGenerics(val);
734 var paths = valLower.split("::");
735 removeEmptyStringsFromArray(paths);
736 val = paths[paths.length - 1];
737 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
740 for (j = 0; j < nSearchWords; ++j) {
742 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
746 if (paths.length > 1) {
747 lev = checkPath(contains, paths[paths.length - 1], ty);
748 if (lev > MAX_LEV_DISTANCE) {
750 } else if (lev > 0) {
755 returned = MAX_LEV_DISTANCE + 1;
756 in_args = MAX_LEV_DISTANCE + 1;
758 // we want lev results to go lower than others
759 lev = MAX_LEV_DISTANCE + 1;
762 if (searchWords[j].indexOf(split[i]) > -1 ||
763 searchWords[j].indexOf(val) > -1 ||
764 ty.normalizedName.indexOf(val) > -1)
766 // filter type: ... queries
767 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
768 index = ty.normalizedName.indexOf(val);
771 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
772 if (typePassesFilter(typeFilter, ty.ty)) {
775 lev = MAX_LEV_DISTANCE + 1;
778 in_args = findArg(ty, valGenerics, false, typeFilter);
779 returned = checkReturned(ty, valGenerics, false, typeFilter);
782 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
783 if (val.length < 6) {
789 if (in_args <= MAX_LEV_DISTANCE) {
790 if (results_in_args[fullId] === undefined) {
791 results_in_args[fullId] = {
797 results_in_args[fullId].lev =
798 Math.min(results_in_args[fullId].lev, in_args);
800 if (returned <= MAX_LEV_DISTANCE) {
801 if (results_returned[fullId] === undefined) {
802 results_returned[fullId] = {
808 results_returned[fullId].lev =
809 Math.min(results_returned[fullId].lev, returned);
811 if (typePassesFilter(typeFilter, ty.ty) &&
812 (index !== -1 || lev <= MAX_LEV_DISTANCE)) {
813 if (index !== -1 && paths.length < 2) {
816 if (results[fullId] === undefined) {
823 results[fullId].lev = Math.min(results[fullId].lev, lev);
829 "in_args": sortResults(results_in_args, true),
830 "returned": sortResults(results_returned, true),
831 "others": sortResults(results, false),
833 handleAliases(ret, query, filterCrates);
838 * Validate performs the following boolean logic. For example:
839 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
840 * exists in (name || path || parent) OR => ("file" && "open") exists in
843 * This could be written functionally, but I wanted to minimise
844 * functions on stack.
846 * @param {[string]} name [The name of the result]
847 * @param {[string]} path [The path of the result]
848 * @param {[string]} keys [The keys to be used (["file", "open"])]
849 * @param {[object]} parent [The parent of the result]
850 * @return {boolean} [Whether the result is valid or not]
852 function validateResult(name, path, keys, parent) {
853 for (var i = 0, len = keys.length; i < len; ++i) {
854 // each check is for validation so we negate the conditions and invalidate
856 // check for an exact name match
857 name.indexOf(keys[i]) > -1 ||
858 // then an exact path match
859 path.indexOf(keys[i]) > -1 ||
860 // next if there is a parent, check for exact parent match
861 (parent !== undefined && parent.name !== undefined &&
862 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
863 // lastly check to see if the name was a levenshtein match
864 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
871 function getQuery(raw) {
872 var matches, type, query;
875 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
877 type = matches[1].replace(/^const$/, "constant");
878 query = query.substring(matches[0].length);
889 function nextTab(direction) {
890 var next = (searchState.currentTab + direction + 3) % searchState.focusedByTab.length;
891 searchState.focusedByTab[searchState.currentTab] = document.activeElement;
896 // Focus the first search result on the active tab, or the result that
897 // was focused last time this tab was active.
898 function focusSearchResult() {
899 var target = searchState.focusedByTab[searchState.currentTab] ||
900 document.querySelectorAll(".search-results.active a").item(0) ||
901 document.querySelectorAll("#titles > button").item(searchState.currentTab);
907 function buildHrefAndPath(item) {
910 var type = itemTypes[item.ty];
911 var name = item.name;
912 var path = item.path;
914 if (type === "mod") {
915 displayPath = path + "::";
916 href = window.rootPath + path.replace(/::/g, "/") + "/" +
917 name + "/index.html";
918 } else if (type === "primitive" || type === "keyword") {
920 href = window.rootPath + path.replace(/::/g, "/") +
921 "/" + type + "." + name + ".html";
922 } else if (type === "externcrate") {
924 href = window.rootPath + name + "/index.html";
925 } else if (item.parent !== undefined) {
926 var myparent = item.parent;
927 var anchor = "#" + type + "." + name;
928 var parentType = itemTypes[myparent.ty];
929 var pageType = parentType;
930 var pageName = myparent.name;
932 if (parentType === "primitive") {
933 displayPath = myparent.name + "::";
934 } else if (type === "structfield" && parentType === "variant") {
935 // Structfields belonging to variants are special: the
936 // final path element is the enum name.
937 var enumNameIdx = item.path.lastIndexOf("::");
938 var enumName = item.path.substr(enumNameIdx + 2);
939 path = item.path.substr(0, enumNameIdx);
940 displayPath = path + "::" + enumName + "::" + myparent.name + "::";
941 anchor = "#variant." + myparent.name + ".field." + name;
945 displayPath = path + "::" + myparent.name + "::";
947 href = window.rootPath + path.replace(/::/g, "/") +
952 displayPath = item.path + "::";
953 href = window.rootPath + item.path.replace(/::/g, "/") +
954 "/" + type + "." + name + ".html";
956 return [displayPath, href];
959 function escape(content) {
960 var h1 = document.createElement("h1");
961 h1.textContent = content;
965 function pathSplitter(path) {
966 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
967 if (tmp.endsWith("<span>")) {
968 return tmp.slice(0, tmp.length - 6);
973 function addTab(array, query, display) {
975 if (display === true) {
976 extraClass = " active";
979 var output = document.createElement("div");
982 if (array.length > 0) {
983 output.className = "search-results " + extraClass;
985 array.forEach(function(item) {
986 if (item.is_alias !== true) {
987 if (duplicates[item.fullPath]) {
990 duplicates[item.fullPath] = true;
993 var name = item.name;
994 var type = itemTypes[item.ty];
999 if (type === "primitive") {
1000 extra = " <i>(primitive type)</i>";
1001 } else if (type === "keyword") {
1002 extra = " <i>(keyword)</i>";
1005 var link = document.createElement("a");
1006 link.className = "result-" + type;
1007 link.href = item.href;
1009 var wrapper = document.createElement("div");
1010 var resultName = document.createElement("div");
1011 resultName.className = "result-name";
1013 if (item.is_alias) {
1014 var alias = document.createElement("span");
1015 alias.className = "alias";
1017 var bold = document.createElement("b");
1018 bold.innerText = item.alias;
1019 alias.appendChild(bold);
1021 alias.insertAdjacentHTML(
1023 "<span class=\"grey\"><i> - see </i></span>");
1025 resultName.appendChild(alias);
1027 resultName.insertAdjacentHTML(
1029 item.displayPath + "<span class=\"" + type + "\">" + name + extra + "</span>");
1030 wrapper.appendChild(resultName);
1032 var description = document.createElement("div");
1033 description.className = "desc";
1034 var spanDesc = document.createElement("span");
1035 spanDesc.insertAdjacentHTML("beforeend", item.desc);
1037 description.appendChild(spanDesc);
1038 wrapper.appendChild(description);
1039 link.appendChild(wrapper);
1040 output.appendChild(link);
1043 output.className = "search-failed" + extraClass;
1044 output.innerHTML = "No results :(<br/>" +
1045 "Try on <a href=\"https://duckduckgo.com/?q=" +
1046 encodeURIComponent("rust " + query.query) +
1047 "\">DuckDuckGo</a>?<br/><br/>" +
1048 "Or try looking in one of these:<ul><li>The <a " +
1049 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1050 " for technical details about the language.</li><li><a " +
1051 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1052 "Example</a> for expository code examples.</a></li><li>The <a " +
1053 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1054 "introductions to language features and the language itself.</li><li><a " +
1055 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1056 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul>";
1058 return [output, length];
1061 function makeTabHeader(tabNb, text, nbElems) {
1062 if (searchState.currentTab === tabNb) {
1063 return "<button class=\"selected\">" + text +
1064 " <div class=\"count\">(" + nbElems + ")</div></button>";
1066 return "<button>" + text + " <div class=\"count\">(" + nbElems + ")</div></button>";
1069 function showResults(results, go_to_first) {
1070 var search = searchState.outputElement();
1071 if (go_to_first || (results.others.length === 1
1072 && getSettingValue("go-to-only-result") === "true"
1073 // By default, the search DOM element is "empty" (meaning it has no children not
1074 // text content). Once a search has been run, it won't be empty, even if you press
1075 // ESC or empty the search input (which also "cancels" the search).
1076 && (!search.firstChild || search.firstChild.innerText !== searchState.loadingText)))
1078 var elem = document.createElement("a");
1079 elem.href = results.others[0].href;
1080 removeClass(elem, "active");
1081 // For firefox, we need the element to be in the DOM so it can be clicked.
1082 document.body.appendChild(elem);
1086 var query = getQuery(searchState.input.value);
1088 currentResults = query.id;
1090 var ret_others = addTab(results.others, query);
1091 var ret_in_args = addTab(results.in_args, query, false);
1092 var ret_returned = addTab(results.returned, query, false);
1094 // Navigate to the relevant tab if the current tab is empty, like in case users search
1095 // for "-> String". If they had selected another tab previously, they have to click on
1097 var currentTab = searchState.currentTab;
1098 if ((currentTab === 0 && ret_others[1] === 0) ||
1099 (currentTab === 1 && ret_in_args[1] === 0) ||
1100 (currentTab === 2 && ret_returned[1] === 0)) {
1101 if (ret_others[1] !== 0) {
1103 } else if (ret_in_args[1] !== 0) {
1105 } else if (ret_returned[1] !== 0) {
1110 var output = "<h1>Results for " + escape(query.query) +
1111 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1112 "<div id=\"titles\">" +
1113 makeTabHeader(0, "In Names", ret_others[1]) +
1114 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1115 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1118 var resultsElem = document.createElement("div");
1119 resultsElem.id = "results";
1120 resultsElem.appendChild(ret_others[0]);
1121 resultsElem.appendChild(ret_in_args[0]);
1122 resultsElem.appendChild(ret_returned[0]);
1124 search.innerHTML = output;
1125 search.appendChild(resultsElem);
1126 // Reset focused elements.
1127 searchState.focusedByTab = [null, null, null];
1128 searchState.showResults(search);
1129 var elems = document.getElementById("titles").childNodes;
1130 elems[0].onclick = function() { printTab(0); };
1131 elems[1].onclick = function() { printTab(1); };
1132 elems[2].onclick = function() { printTab(2); };
1133 printTab(currentTab);
1136 function execSearch(query, searchWords, filterCrates) {
1137 function getSmallest(arrays, positions, notDuplicates) {
1140 for (var it = 0, len = positions.length; it < len; ++it) {
1141 if (arrays[it].length > positions[it] &&
1142 (start === null || start > arrays[it][positions[it]].lev) &&
1143 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1144 start = arrays[it][positions[it]].lev;
1150 function mergeArrays(arrays) {
1153 var notDuplicates = {};
1155 for (var x = 0, arrays_len = arrays.length; x < arrays_len; ++x) {
1158 while (ret.length < MAX_RESULTS) {
1159 var smallest = getSmallest(arrays, positions, notDuplicates);
1161 if (smallest === null) {
1164 for (x = 0; x < arrays_len && ret.length < MAX_RESULTS; ++x) {
1165 if (arrays[x].length > positions[x] &&
1166 arrays[x][positions[x]].lev === smallest &&
1167 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1168 ret.push(arrays[x][positions[x]]);
1169 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1177 // Split search query by ",", while respecting angle bracket nesting.
1178 // Since "<" is an alias for the Ord family of traits, it also uses
1179 // lookahead to distinguish "<"-as-less-than from "<"-as-angle-bracket.
1181 // tokenizeQuery("A<B, C>, D") == ["A<B, C>", "D"]
1182 // tokenizeQuery("A<B, C, D") == ["A<B", "C", "D"]
1183 function tokenizeQuery(raw) {
1187 var nextAngle = /(<|>)/g;
1190 for (i = 0; i < l; ++i) {
1193 nextAngle.lastIndex = i + 1;
1194 matched = nextAngle.exec(raw);
1195 if (matched && matched[1] === '>') {
1206 ret.push(raw.substring(start, i));
1213 ret.push(raw.substring(start, i));
1218 var queries = tokenizeQuery(query.raw);
1225 for (var i = 0, len = queries.length; i < len; ++i) {
1226 query = queries[i].trim();
1227 if (query.length !== 0) {
1228 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1230 results.in_args.push(tmp.in_args);
1231 results.returned.push(tmp.returned);
1232 results.others.push(tmp.others);
1235 if (queries.length > 1) {
1237 "in_args": mergeArrays(results.in_args),
1238 "returned": mergeArrays(results.returned),
1239 "others": mergeArrays(results.others),
1243 "in_args": results.in_args[0],
1244 "returned": results.returned[0],
1245 "others": results.others[0],
1249 function getFilterCrates() {
1250 var elem = document.getElementById("crate-search");
1252 if (elem && elem.value !== "All crates" &&
1253 hasOwnPropertyRustdoc(rawSearchIndex, elem.value))
1260 function search(e, forced) {
1261 var params = searchState.getQueryStringParams();
1262 var query = getQuery(searchState.input.value.trim());
1268 if (query.query.length === 0) {
1271 if (!forced && query.id === currentResults) {
1272 if (query.query.length > 0) {
1273 searchState.putBackSearch(searchState.input);
1278 // Update document title to maintain a meaningful browser history
1279 searchState.title = "Results for " + query.query + " - Rust";
1281 // Because searching is incremental by character, only the most
1282 // recent search query is added to the browser history.
1283 if (searchState.browserSupportsHistoryApi()) {
1284 var newURL = getNakedUrl() + "?search=" + encodeURIComponent(query.raw) +
1285 window.location.hash;
1286 if (!history.state && !params.search) {
1287 history.pushState(query, "", newURL);
1289 history.replaceState(query, "", newURL);
1293 var filterCrates = getFilterCrates();
1294 showResults(execSearch(query, index, filterCrates), params.go_to_first);
1297 function buildIndex(rawSearchIndex) {
1299 var searchWords = [];
1301 var currentIndex = 0;
1304 for (var crate in rawSearchIndex) {
1305 if (!hasOwnPropertyRustdoc(rawSearchIndex, crate)) {
1311 searchWords.push(crate);
1312 // This object should have exactly the same set of fields as the "row"
1313 // object defined below. Your JavaScript runtime will thank you.
1314 // https://mathiasbynens.be/notes/shapes-ics
1317 ty: 1, // == ExternCrate
1320 desc: rawSearchIndex[crate].doc,
1324 normalizedName: crate.indexOf("_") === -1 ? crate : crate.replace(/_/g, ""),
1327 searchIndex.push(crateRow);
1330 // an array of (Number) item types
1331 var itemTypes = rawSearchIndex[crate].t;
1332 // an array of (String) item names
1333 var itemNames = rawSearchIndex[crate].n;
1334 // an array of (String) full paths (or empty string for previous path)
1335 var itemPaths = rawSearchIndex[crate].q;
1336 // an array of (String) descriptions
1337 var itemDescs = rawSearchIndex[crate].d;
1338 // an array of (Number) the parent path index + 1 to `paths`, or 0 if none
1339 var itemParentIdxs = rawSearchIndex[crate].i;
1340 // an array of (Object | null) the type of the function, if any
1341 var itemFunctionSearchTypes = rawSearchIndex[crate].f;
1342 // an array of [(Number) item type,
1344 var paths = rawSearchIndex[crate].p;
1345 // an array of [(String) alias name
1346 // [Number] index to items]
1347 var aliases = rawSearchIndex[crate].a;
1349 // convert `rawPaths` entries into object form
1350 var len = paths.length;
1351 for (i = 0; i < len; ++i) {
1352 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1355 // convert `item*` into an object form, and construct word indices.
1357 // before any analysis is performed lets gather the search terms to
1358 // search against apart from the rest of the data. This is a quick
1359 // operation that is cached for the life of the page state so that
1360 // all other search operations have access to this cached data for
1361 // faster analysis operations
1362 len = itemTypes.length;
1364 for (i = 0; i < len; ++i) {
1365 // This object should have exactly the same set of fields as the "crateRow"
1366 // object defined above.
1367 if (typeof itemNames[i] === "string") {
1368 word = itemNames[i].toLowerCase();
1369 searchWords.push(word);
1372 searchWords.push("");
1378 path: itemPaths[i] ? itemPaths[i] : lastPath,
1380 parent: itemParentIdxs[i] > 0 ? paths[itemParentIdxs[i] - 1] : undefined,
1381 type: itemFunctionSearchTypes[i],
1383 normalizedName: word.indexOf("_") === -1 ? word : word.replace(/_/g, ""),
1386 searchIndex.push(row);
1387 lastPath = row.path;
1392 ALIASES[crate] = {};
1393 var j, local_aliases;
1394 for (var alias_name in aliases) {
1395 if (!hasOwnPropertyRustdoc(aliases, alias_name)) {
1399 if (!hasOwnPropertyRustdoc(ALIASES[crate], alias_name)) {
1400 ALIASES[crate][alias_name] = [];
1402 local_aliases = aliases[alias_name];
1403 for (j = 0, len = local_aliases.length; j < len; ++j) {
1404 ALIASES[crate][alias_name].push(local_aliases[j] + currentIndex);
1408 currentIndex += crateSize;
1413 function registerSearchEvents() {
1414 var searchAfter500ms = function() {
1415 searchState.clearInputTimeout();
1416 if (searchState.input.value.length === 0) {
1417 if (searchState.browserSupportsHistoryApi()) {
1418 history.replaceState("", window.currentCrate + " - Rust",
1419 getNakedUrl() + window.location.hash);
1421 searchState.hideResults();
1423 searchState.timeout = setTimeout(search, 500);
1426 searchState.input.onkeyup = searchAfter500ms;
1427 searchState.input.oninput = searchAfter500ms;
1428 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1430 searchState.clearInputTimeout();
1433 searchState.input.onchange = function(e) {
1434 if (e.target !== document.activeElement) {
1435 // To prevent doing anything when it's from a blur event.
1438 // Do NOT e.preventDefault() here. It will prevent pasting.
1439 searchState.clearInputTimeout();
1440 // zero-timeout necessary here because at the time of event handler execution the
1441 // pasted content is not in the input field yet. Shouldn’t make any difference for
1443 setTimeout(search, 0);
1445 searchState.input.onpaste = searchState.input.onchange;
1447 searchState.outputElement().addEventListener("keydown", function(e) {
1448 // We only handle unmodified keystrokes here. We don't want to interfere with,
1449 // for instance, alt-left and alt-right for history navigation.
1450 if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
1453 // up and down arrow select next/previous search result, or the
1454 // search box if we're already at the top.
1455 if (e.which === 38) { // up
1456 var previous = document.activeElement.previousElementSibling;
1460 searchState.focus();
1463 } else if (e.which === 40) { // down
1464 var next = document.activeElement.nextElementSibling;
1468 var rect = document.activeElement.getBoundingClientRect();
1469 if (window.innerHeight - rect.bottom < rect.height) {
1470 window.scrollBy(0, rect.height);
1473 } else if (e.which === 37) { // left
1476 } else if (e.which === 39) { // right
1482 searchState.input.addEventListener("keydown", function(e) {
1483 if (e.which === 40) { // down
1484 focusSearchResult();
1490 var selectCrate = document.getElementById("crate-search");
1492 selectCrate.onchange = function() {
1493 updateLocalStorage("rustdoc-saved-filter-crate", selectCrate.value);
1494 // In case you "cut" the entry from the search input, then change the crate filter
1495 // before paste back the previous search, you get the old search results without
1496 // the filter. To prevent this, we need to remove the previous results.
1497 currentResults = null;
1498 search(undefined, true);
1502 // Push and pop states are used to add search results to the browser
1504 if (searchState.browserSupportsHistoryApi()) {
1505 // Store the previous <title> so we can revert back to it later.
1506 var previousTitle = document.title;
1508 window.addEventListener("popstate", function(e) {
1509 var params = searchState.getQueryStringParams();
1510 // Revert to the previous title manually since the History
1511 // API ignores the title parameter.
1512 document.title = previousTitle;
1513 // When browsing forward to search results the previous
1514 // search will be repeated, so the currentResults are
1515 // cleared to ensure the search is successful.
1516 currentResults = null;
1517 // Synchronize search bar with query string state and
1518 // perform the search. This will empty the bar if there's
1519 // nothing there, which lets you really go back to a
1520 // previous state with nothing in the bar.
1521 if (params.search && params.search.length > 0) {
1522 searchState.input.value = params.search;
1523 // Some browsers fire "onpopstate" for every page load
1524 // (Chrome), while others fire the event only when actually
1525 // popping a state (Firefox), which is why search() is
1526 // called both here and at the end of the startSearch()
1530 searchState.input.value = "";
1531 // When browsing back from search results the main page
1532 // visibility must be reset.
1533 searchState.hideResults();
1538 // This is required in firefox to avoid this problem: Navigating to a search result
1539 // with the keyboard, hitting enter, and then hitting back would take you back to
1540 // the doc page, rather than the search that should overlay it.
1541 // This was an interaction between the back-forward cache and our handlers
1542 // that try to sync state between the URL and the search input. To work around it,
1543 // do a small amount of re-init on page show.
1544 window.onpageshow = function(){
1545 var qSearch = searchState.getQueryStringParams().search;
1546 if (searchState.input.value === "" && qSearch) {
1547 searchState.input.value = qSearch;
1553 index = buildIndex(rawSearchIndex);
1554 registerSearchEvents();
1555 // If there's a search term in the URL, execute the search now.
1556 if (searchState.getQueryStringParams().search) {
1561 if (window.searchIndex !== undefined) {
1562 initSearch(window.searchIndex);