2 // This mapping table should match the discriminants of
3 // `rustdoc::html::item_type::ItemType` type in Rust.
4 var itemTypes = ["mod",
31 // used for special search precedence
32 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
33 var TY_KEYWORD = itemTypes.indexOf("keyword");
35 // In the search display, allows to switch between tabs.
36 function printTab(nb) {
37 if (nb === 0 || nb === 1 || nb === 2) {
38 searchState.currentTab = nb;
41 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
43 addClass(elem, "selected");
45 removeClass(elem, "selected");
49 onEachLazy(document.getElementById("results").childNodes, function(elem) {
51 elem.style.display = "";
53 elem.style.display = "none";
59 function removeEmptyStringsFromArray(x) {
60 for (var i = 0, len = x.length; i < len; ++i) {
69 * A function to compute the Levenshtein distance between two strings
70 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
71 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
72 * This code is an unmodified version of the code written by Marco de Wit
73 * and was found at http://stackoverflow.com/a/18514751/745719
75 var levenshtein_row2 = [];
76 function levenshtein(s1, s2) {
80 var s1_len = s1.length, s2_len = s2.length;
81 if (s1_len && s2_len) {
82 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
87 c2 = s2.charCodeAt(i2);
91 for (i1 = 0; i1 < s1_len; ++i1) {
92 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
94 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
100 return s1_len + s2_len;
103 window.initSearch = function(rawSearchIndex) {
104 var MAX_LEV_DISTANCE = 3;
105 var MAX_RESULTS = 200;
106 var GENERICS_DATA = 1;
110 var NO_TYPE_FILTER = -1;
111 var currentResults, index, searchIndex;
113 var params = searchState.getQueryStringParams();
115 // Populate search bar with query string search term when provided,
116 // but only if the input bar is empty. This avoid the obnoxious issue
117 // where you start trying to do a search, and the index loads, and
118 // suddenly your search is gone!
119 if (searchState.input.value === "") {
120 searchState.input.value = params.search || "";
124 * Executes the query and builds an index of results
125 * @param {[Object]} query [The user query]
126 * @param {[type]} searchWords [The list of search words to query
128 * @param {[type]} filterCrates [Crate to search in if defined]
129 * @return {[type]} [A search index of results]
131 function execQuery(query, searchWords, filterCrates) {
132 function itemTypeFromName(typename) {
133 for (var i = 0, len = itemTypes.length; i < len; ++i) {
134 if (itemTypes[i] === typename) {
138 return NO_TYPE_FILTER;
141 var valLower = query.query.toLowerCase(),
143 typeFilter = itemTypeFromName(query.type),
144 results = {}, results_in_args = {}, results_returned = {},
145 split = valLower.split("::");
147 removeEmptyStringsFromArray(split);
149 function transformResults(results) {
151 for (var i = 0, len = results.length; i < len; ++i) {
152 if (results[i].id > -1) {
153 var obj = searchIndex[results[i].id];
154 obj.lev = results[i].lev;
155 var res = buildHrefAndPath(obj);
156 obj.displayPath = pathSplitter(res[0]);
157 obj.fullPath = obj.displayPath + obj.name;
158 // To be sure than it some items aren't considered as duplicate.
159 obj.fullPath += "|" + obj.ty;
162 if (out.length >= MAX_RESULTS) {
170 function sortResults(results, isType) {
172 for (var entry in results) {
173 if (hasOwnProperty(results, entry)) {
174 ar.push(results[entry]);
179 for (i = 0, len = results.length; i < len; ++i) {
181 result.word = searchWords[result.id];
182 result.item = searchIndex[result.id] || {};
184 // if there are no results then return to default and fail
185 if (results.length === 0) {
189 results.sort(function(aaa, bbb) {
192 // sort by exact match with regard to the last word (mismatch goes later)
193 a = (aaa.word !== val);
194 b = (bbb.word !== val);
195 if (a !== b) { return a - b; }
197 // Sort by non levenshtein results and then levenshtein results by the distance
198 // (less changes required to match means higher rankings)
201 if (a !== b) { return a - b; }
203 // sort by crate (non-current crate goes later)
204 a = (aaa.item.crate !== window.currentCrate);
205 b = (bbb.item.crate !== window.currentCrate);
206 if (a !== b) { return a - b; }
208 // sort by item name length (longer goes later)
211 if (a !== b) { return a - b; }
213 // sort by item name (lexicographically larger goes later)
216 if (a !== b) { return (a > b ? +1 : -1); }
218 // sort by index of keyword in item name (no literal occurrence goes later)
221 if (a !== b) { return a - b; }
222 // (later literal occurrence, if any, goes later)
225 if (a !== b) { return a - b; }
227 // special precedence for primitive and keyword pages
228 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
229 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
232 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
233 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
237 // sort by description (no description goes later)
238 a = (aaa.item.desc === "");
239 b = (bbb.item.desc === "");
240 if (a !== b) { return a - b; }
242 // sort by type (later occurrence in `itemTypes` goes later)
245 if (a !== b) { return a - b; }
247 // sort by path (lexicographically larger goes later)
250 if (a !== b) { return (a > b ? +1 : -1); }
256 for (i = 0, len = results.length; i < len; ++i) {
257 var result = results[i];
259 // this validation does not make sense when searching by types
260 if (result.dontValidate) {
263 var name = result.item.name.toLowerCase(),
264 path = result.item.path.toLowerCase(),
265 parent = result.item.parent;
267 if (!isType && !validateResult(name, path, split, parent)) {
271 return transformResults(results);
274 function extractGenerics(val) {
275 val = val.toLowerCase();
276 if (val.indexOf("<") !== -1) {
277 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
279 name: val.substring(0, val.indexOf("<")),
280 generics: values.split(/\s*,\s*/),
289 function getObjectNameFromId(id) {
290 if (typeof id === "number") {
291 return searchIndex[id].name;
296 function checkGenerics(obj, val) {
297 // The names match, but we need to be sure that all generics kinda
299 var tmp_lev, elem_name;
300 if (val.generics.length > 0) {
301 if (obj.length > GENERICS_DATA &&
302 obj[GENERICS_DATA].length >= val.generics.length) {
303 var elems = Object.create(null);
304 var elength = object[GENERICS_DATA].length;
305 for (var x = 0; x < elength; ++x) {
306 elems[getObjectNameFromId(obj[GENERICS_DATA][x])] += 1;
310 // We need to find the type that matches the most to remove it in order
312 var vlength = val.generics.length;
313 for (x = 0; x < vlength; ++x) {
314 var lev = MAX_LEV_DISTANCE + 1;
315 var firstGeneric = getObjectNameFromId(val.generics[x]);
317 if (elems[firstGeneric]) {
318 match = firstGeneric;
321 for (elem_name in elems) {
322 tmp_lev = levenshtein(elem_name, firstGeneric);
329 if (match !== null) {
331 if (elems[match] == 0) {
337 return MAX_LEV_DISTANCE + 1;
340 return Math.ceil(total / done);
343 return MAX_LEV_DISTANCE + 1;
346 // Check for type name and type generics (if any).
347 function checkType(obj, val, literalSearch) {
348 var lev_distance = 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 >= val.generics.length) {
355 var elems = Object.create(null);
356 len = obj[GENERICS_DATA].length;
357 for (x = 0; x < len; ++x) {
358 elems[getObjectNameFromId(obj[GENERICS_DATA][x])] += 1;
362 len = val.generics.length;
363 for (x = 0; x < len; ++x) {
364 firstGeneric = getObjectNameFromId(val.generics[x]);
365 if (elems[firstGeneric]) {
366 elems[firstGeneric] -= 1;
381 // If the type has generics but don't match, then it won't return at this point.
382 // Otherwise, `checkGenerics` will return 0 and it'll return.
383 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
384 var tmp_lev = checkGenerics(obj, val);
385 if (tmp_lev <= MAX_LEV_DISTANCE) {
392 // Names didn't match so let's check if one of the generic types could.
394 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
395 return obj[GENERICS_DATA].some(
397 return 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);
408 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
409 // We can check if the type we're looking for is inside the generics!
410 var olength = obj[GENERICS_DATA].length;
411 for (x = 0; x < olength; ++x) {
412 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
416 // Now whatever happens, the returned distance is "less good" so we should mark it
417 // as such, and so we add 1 to the distance to make it "less good".
418 return lev_distance + 1;
421 function findArg(obj, val, literalSearch, typeFilter) {
422 var lev_distance = MAX_LEV_DISTANCE + 1;
424 if (obj && obj.type && obj.type[INPUTS_DATA] && obj.type[INPUTS_DATA].length > 0) {
425 var length = obj.type[INPUTS_DATA].length;
426 for (var i = 0; i < length; i++) {
427 var tmp = obj.type[INPUTS_DATA][i];
428 if (!typePassesFilter(typeFilter, tmp[1])) {
431 tmp = checkType(tmp, val, literalSearch);
438 lev_distance = Math.min(tmp, lev_distance);
439 if (lev_distance === 0) {
444 return literalSearch ? false : lev_distance;
447 function checkReturned(obj, val, literalSearch, typeFilter) {
448 var lev_distance = MAX_LEV_DISTANCE + 1;
450 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
451 var ret = obj.type[OUTPUT_DATA];
452 if (typeof ret[0] === "string") {
455 for (var x = 0, len = ret.length; x < len; ++x) {
457 if (!typePassesFilter(typeFilter, tmp[1])) {
460 tmp = checkType(tmp, val, literalSearch);
467 lev_distance = Math.min(tmp, lev_distance);
468 if (lev_distance === 0) {
473 return literalSearch ? false : lev_distance;
476 function checkPath(contains, lastElem, ty) {
477 if (contains.length === 0) {
480 var ret_lev = MAX_LEV_DISTANCE + 1;
481 var path = ty.path.split("::");
483 if (ty.parent && ty.parent.name) {
484 path.push(ty.parent.name.toLowerCase());
487 var length = path.length;
488 var clength = contains.length;
489 if (clength > length) {
490 return MAX_LEV_DISTANCE + 1;
492 for (var i = 0; i < length; ++i) {
493 if (i + clength > length) {
498 for (var x = 0; x < clength; ++x) {
499 var lev = levenshtein(path[i + x], contains[x]);
500 if (lev > MAX_LEV_DISTANCE) {
507 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
513 function typePassesFilter(filter, type) {
515 if (filter <= NO_TYPE_FILTER) return true;
518 if (filter === type) return true;
520 // Match related items
521 var name = itemTypes[type];
522 switch (itemTypes[filter]) {
524 return name === "associatedconstant";
526 return name === "method" || name === "tymethod";
528 return name === "primitive" || name === "associatedtype";
530 return name === "traitalias";
537 function createAliasFromItem(item) {
550 function handleAliases(ret, query, filterCrates) {
551 // We separate aliases and crate aliases because we want to have current crate
552 // aliases to be before the others in the displayed results.
554 var crateAliases = [];
555 if (filterCrates !== undefined) {
556 if (ALIASES[filterCrates] && ALIASES[filterCrates][query.search]) {
557 var query_aliases = ALIASES[filterCrates][query.search];
558 var len = query_aliases.length;
559 for (var i = 0; i < len; ++i) {
560 aliases.push(createAliasFromItem(searchIndex[query_aliases[i]]));
564 Object.keys(ALIASES).forEach(function(crate) {
565 if (ALIASES[crate][query.search]) {
566 var pushTo = crate === window.currentCrate ? crateAliases : aliases;
567 var query_aliases = ALIASES[crate][query.search];
568 var len = query_aliases.length;
569 for (var i = 0; i < len; ++i) {
570 pushTo.push(createAliasFromItem(searchIndex[query_aliases[i]]));
576 var sortFunc = function(aaa, bbb) {
577 if (aaa.path < bbb.path) {
579 } else if (aaa.path === bbb.path) {
584 crateAliases.sort(sortFunc);
585 aliases.sort(sortFunc);
587 var pushFunc = function(alias) {
588 alias.alias = query.raw;
589 var res = buildHrefAndPath(alias);
590 alias.displayPath = pathSplitter(res[0]);
591 alias.fullPath = alias.displayPath + alias.name;
594 ret.others.unshift(alias);
595 if (ret.others.length > MAX_RESULTS) {
599 onEach(aliases, pushFunc);
600 onEach(crateAliases, pushFunc);
603 // quoted values mean literal search
604 var nSearchWords = searchWords.length;
611 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
612 val.charAt(val.length - 1) === val.charAt(0))
614 val = extractGenerics(val.substr(1, val.length - 2));
615 for (i = 0; i < nSearchWords; ++i) {
616 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
619 in_args = findArg(searchIndex[i], val, true, typeFilter);
620 returned = checkReturned(searchIndex[i], val, true, typeFilter);
624 if (searchWords[i] === val.name
625 && typePassesFilter(typeFilter, searchIndex[i].ty)
626 && results[fullId] === undefined) {
633 if (in_args && results_in_args[fullId] === undefined) {
634 results_in_args[fullId] = {
640 if (returned && results_returned[fullId] === undefined) {
641 results_returned[fullId] = {
648 query.inputs = [val];
652 } else if (val.search("->") > -1) {
653 var trimmer = function(s) { return s.trim(); };
654 var parts = val.split("->").map(trimmer);
655 var input = parts[0];
656 // sort inputs so that order does not matter
657 var inputs = input.split(",").map(trimmer).sort();
658 for (i = 0, len = inputs.length; i < len; ++i) {
659 inputs[i] = extractGenerics(inputs[i]);
661 var output = extractGenerics(parts[1]);
663 for (i = 0; i < nSearchWords; ++i) {
664 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
667 var type = searchIndex[i].type;
674 returned = checkReturned(ty, output, true, NO_TYPE_FILTER);
675 if (output.name === "*" || returned) {
677 var is_module = false;
683 for (it = 0, len = inputs.length; allFound && it < len; it++) {
684 allFound = checkType(type, inputs[it], true);
689 results_in_args[fullId] = {
696 results_returned[fullId] = {
711 query.inputs = inputs.map(function(input) {
714 query.output = output.name;
716 query.inputs = [val];
719 // gather matching search results up to a certain maximum
720 val = val.replace(/\_/g, "");
722 var valGenerics = extractGenerics(val);
724 var paths = valLower.split("::");
725 removeEmptyStringsFromArray(paths);
726 val = paths[paths.length - 1];
727 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
730 for (j = 0; j < nSearchWords; ++j) {
732 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
736 if (paths.length > 1) {
737 lev = checkPath(contains, paths[paths.length - 1], ty);
738 if (lev > MAX_LEV_DISTANCE) {
740 } else if (lev > 0) {
745 returned = MAX_LEV_DISTANCE + 1;
746 in_args = MAX_LEV_DISTANCE + 1;
748 // we want lev results to go lower than others
749 lev = MAX_LEV_DISTANCE + 1;
752 if (searchWords[j].indexOf(split[i]) > -1 ||
753 searchWords[j].indexOf(val) > -1 ||
754 ty.normalizedName.indexOf(val) > -1)
756 // filter type: ... queries
757 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
758 index = ty.normalizedName.indexOf(val);
761 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
762 if (typePassesFilter(typeFilter, ty.ty)) {
765 lev = MAX_LEV_DISTANCE + 1;
768 in_args = findArg(ty, valGenerics, false, typeFilter);
769 returned = checkReturned(ty, valGenerics, false, typeFilter);
772 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
773 if (val.length < 6) {
779 if (in_args <= MAX_LEV_DISTANCE) {
780 if (results_in_args[fullId] === undefined) {
781 results_in_args[fullId] = {
787 results_in_args[fullId].lev =
788 Math.min(results_in_args[fullId].lev, in_args);
790 if (returned <= MAX_LEV_DISTANCE) {
791 if (results_returned[fullId] === undefined) {
792 results_returned[fullId] = {
798 results_returned[fullId].lev =
799 Math.min(results_returned[fullId].lev, returned);
801 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
802 if (index !== -1 && paths.length < 2) {
805 if (results[fullId] === undefined) {
812 results[fullId].lev = Math.min(results[fullId].lev, lev);
818 "in_args": sortResults(results_in_args, true),
819 "returned": sortResults(results_returned, true),
820 "others": sortResults(results, false),
822 handleAliases(ret, query, filterCrates);
827 * Validate performs the following boolean logic. For example:
828 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
829 * exists in (name || path || parent) OR => ("file" && "open") exists in
832 * This could be written functionally, but I wanted to minimise
833 * functions on stack.
835 * @param {[string]} name [The name of the result]
836 * @param {[string]} path [The path of the result]
837 * @param {[string]} keys [The keys to be used (["file", "open"])]
838 * @param {[object]} parent [The parent of the result]
839 * @return {boolean} [Whether the result is valid or not]
841 function validateResult(name, path, keys, parent) {
842 for (var i = 0, len = keys.length; i < len; ++i) {
843 // each check is for validation so we negate the conditions and invalidate
845 // check for an exact name match
846 name.indexOf(keys[i]) > -1 ||
847 // then an exact path match
848 path.indexOf(keys[i]) > -1 ||
849 // next if there is a parent, check for exact parent match
850 (parent !== undefined && parent.name !== undefined &&
851 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
852 // lastly check to see if the name was a levenshtein match
853 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
860 function getQuery(raw) {
861 var matches, type, query;
864 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
866 type = matches[1].replace(/^const$/, "constant");
867 query = query.substring(matches[0].length);
878 function initSearchNav() {
881 var click_func = function(e) {
883 // to retrieve the real "owner" of the event.
884 while (el.tagName !== "TR") {
887 var dst = e.target.getElementsByTagName("a");
888 if (dst.length < 1) {
892 if (window.location.pathname === dst.pathname) {
893 searchState.hideResults();
894 document.location.href = dst.href;
897 var mouseover_func = function(e) {
898 if (searchState.mouseMovedAfterSearch) {
900 // to retrieve the real "owner" of the event.
901 while (el.tagName !== "TR") {
904 clearTimeout(hoverTimeout);
905 hoverTimeout = setTimeout(function() {
906 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
907 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
908 removeClass(i_e, "highlighted");
911 addClass(el, "highlighted");
915 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
916 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
917 i_e.onclick = click_func;
918 i_e.onmouseover = mouseover_func;
922 searchState.input.onkeydown = function(e) {
923 // "actives" references the currently highlighted item in each search tab.
924 // Each array in "actives" represents a tab.
925 var actives = [[], [], []];
926 // "current" is used to know which tab we're looking into.
928 onEachLazy(document.getElementById("results").childNodes, function(e) {
929 onEachLazy(e.getElementsByClassName("highlighted"), function(h_e) {
930 actives[current].push(h_e);
938 var currentTab = searchState.currentTab;
939 if (e.which === 38) { // up
940 if (e.ctrlKey) { // Going through result tabs.
941 printTab(currentTab > 0 ? currentTab - 1 : 2);
943 if (!actives[currentTab].length ||
944 !actives[currentTab][0].previousElementSibling) {
947 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
948 removeClass(actives[currentTab][0], "highlighted");
951 } else if (e.which === 40) { // down
952 if (e.ctrlKey) { // Going through result tabs.
953 printTab(currentTab > 1 ? 0 : currentTab + 1);
954 } else if (!actives[currentTab].length) {
955 var results = document.getElementById("results").childNodes;
956 if (results.length > 0) {
957 var res = results[currentTab].getElementsByClassName("result");
958 if (res.length > 0) {
959 addClass(res[0], "highlighted");
962 } else if (actives[currentTab][0].nextElementSibling) {
963 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
964 removeClass(actives[currentTab][0], "highlighted");
967 } else if (e.which === 13) { // return
968 if (actives[currentTab].length) {
969 var elem = actives[currentTab][0].getElementsByTagName("a")[0];
970 document.location.href = elem.href;
972 } else if ([SHIFT, CTRL, ALT].indexOf(e.which) !== -1) {
973 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
974 } else if (actives[currentTab].length > 0) {
975 removeClass(actives[currentTab][0], "highlighted");
980 function buildHrefAndPath(item) {
983 var type = itemTypes[item.ty];
984 var name = item.name;
985 var path = item.path;
987 if (type === "mod") {
988 displayPath = path + "::";
989 href = window.rootPath + path.replace(/::/g, "/") + "/" +
990 name + "/index.html";
991 } else if (type === "primitive" || type === "keyword") {
993 href = window.rootPath + path.replace(/::/g, "/") +
994 "/" + type + "." + name + ".html";
995 } else if (type === "externcrate") {
997 href = window.rootPath + name + "/index.html";
998 } else if (item.parent !== undefined) {
999 var myparent = item.parent;
1000 var anchor = "#" + type + "." + name;
1001 var parentType = itemTypes[myparent.ty];
1002 var pageType = parentType;
1003 var pageName = myparent.name;
1005 if (parentType === "primitive") {
1006 displayPath = myparent.name + "::";
1007 } else if (type === "structfield" && parentType === "variant") {
1008 // Structfields belonging to variants are special: the
1009 // final path element is the enum name.
1010 var enumNameIdx = item.path.lastIndexOf("::");
1011 var enumName = item.path.substr(enumNameIdx + 2);
1012 path = item.path.substr(0, enumNameIdx);
1013 displayPath = path + "::" + enumName + "::" + myparent.name + "::";
1014 anchor = "#variant." + myparent.name + ".field." + name;
1016 pageName = enumName;
1018 displayPath = path + "::" + myparent.name + "::";
1020 href = window.rootPath + path.replace(/::/g, "/") +
1025 displayPath = item.path + "::";
1026 href = window.rootPath + item.path.replace(/::/g, "/") +
1027 "/" + type + "." + name + ".html";
1029 return [displayPath, href];
1032 function escape(content) {
1033 var h1 = document.createElement("h1");
1034 h1.textContent = content;
1035 return h1.innerHTML;
1038 function pathSplitter(path) {
1039 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1040 if (tmp.endsWith("<span>")) {
1041 return tmp.slice(0, tmp.length - 6);
1046 function addTab(array, query, display) {
1047 var extraStyle = "";
1048 if (display === false) {
1049 extraStyle = " style=\"display: none;\"";
1053 var duplicates = {};
1055 if (array.length > 0) {
1056 output = "<table class=\"search-results\"" + extraStyle + ">";
1058 array.forEach(function(item) {
1062 type = itemTypes[item.ty];
1064 if (item.is_alias !== true) {
1065 if (duplicates[item.fullPath]) {
1068 duplicates[item.fullPath] = true;
1072 output += "<tr class=\"" + type + " result\"><td>" +
1073 "<a href=\"" + item.href + "\">" +
1074 (item.is_alias === true ?
1075 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1076 "class=\"grey\"><i> - see </i></span>") : "") +
1077 item.displayPath + "<span class=\"" + type + "\">" +
1078 name + "</span></a></td><td>" +
1079 "<a href=\"" + item.href + "\">" +
1080 "<span class=\"desc\">" + item.desc +
1081 " </span></a></td></tr>";
1083 output += "</table>";
1085 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1086 "Try on <a href=\"https://duckduckgo.com/?q=" +
1087 encodeURIComponent("rust " + query.query) +
1088 "\">DuckDuckGo</a>?<br/><br/>" +
1089 "Or try looking in one of these:<ul><li>The <a " +
1090 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1091 " for technical details about the language.</li><li><a " +
1092 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1093 "Example</a> for expository code examples.</a></li><li>The <a " +
1094 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1095 "introductions to language features and the language itself.</li><li><a " +
1096 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1097 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1099 return [output, length];
1102 function makeTabHeader(tabNb, text, nbElems) {
1103 if (searchState.currentTab === tabNb) {
1104 return "<button class=\"selected\">" + text +
1105 " <div class=\"count\">(" + nbElems + ")</div></button>";
1107 return "<button>" + text + " <div class=\"count\">(" + nbElems + ")</div></button>";
1110 function showResults(results) {
1111 var search = searchState.outputElement();
1112 if (results.others.length === 1
1113 && getSettingValue("go-to-only-result") === "true"
1114 // By default, the search DOM element is "empty" (meaning it has no children not
1115 // text content). Once a search has been run, it won't be empty, even if you press
1116 // ESC or empty the search input (which also "cancels" the search).
1117 && (!search.firstChild || search.firstChild.innerText !== searchState.loadingText))
1119 var elem = document.createElement("a");
1120 elem.href = results.others[0].href;
1121 elem.style.display = "none";
1122 // For firefox, we need the element to be in the DOM so it can be clicked.
1123 document.body.appendChild(elem);
1127 var query = getQuery(searchState.input.value);
1129 currentResults = query.id;
1131 var ret_others = addTab(results.others, query);
1132 var ret_in_args = addTab(results.in_args, query, false);
1133 var ret_returned = addTab(results.returned, query, false);
1135 // Navigate to the relevant tab if the current tab is empty, like in case users search
1136 // for "-> String". If they had selected another tab previously, they have to click on
1138 var currentTab = searchState.currentTab;
1139 if ((currentTab === 0 && ret_others[1] === 0) ||
1140 (currentTab === 1 && ret_in_args[1] === 0) ||
1141 (currentTab === 2 && ret_returned[1] === 0)) {
1142 if (ret_others[1] !== 0) {
1144 } else if (ret_in_args[1] !== 0) {
1146 } else if (ret_returned[1] !== 0) {
1151 var output = "<h1>Results for " + escape(query.query) +
1152 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1153 "<div id=\"titles\">" +
1154 makeTabHeader(0, "In Names", ret_others[1]) +
1155 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1156 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1157 "</div><div id=\"results\">" +
1158 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1160 search.innerHTML = output;
1161 searchState.showResults(search);
1163 var elems = document.getElementById("titles").childNodes;
1164 elems[0].onclick = function() { printTab(0); };
1165 elems[1].onclick = function() { printTab(1); };
1166 elems[2].onclick = function() { printTab(2); };
1167 printTab(currentTab);
1170 function execSearch(query, searchWords, filterCrates) {
1171 function getSmallest(arrays, positions, notDuplicates) {
1174 for (var it = 0, len = positions.length; it < len; ++it) {
1175 if (arrays[it].length > positions[it] &&
1176 (start === null || start > arrays[it][positions[it]].lev) &&
1177 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1178 start = arrays[it][positions[it]].lev;
1184 function mergeArrays(arrays) {
1187 var notDuplicates = {};
1189 for (var x = 0, arrays_len = arrays.length; x < arrays_len; ++x) {
1192 while (ret.length < MAX_RESULTS) {
1193 var smallest = getSmallest(arrays, positions, notDuplicates);
1195 if (smallest === null) {
1198 for (x = 0; x < arrays_len && ret.length < MAX_RESULTS; ++x) {
1199 if (arrays[x].length > positions[x] &&
1200 arrays[x][positions[x]].lev === smallest &&
1201 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1202 ret.push(arrays[x][positions[x]]);
1203 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1211 var queries = query.raw.split(",");
1218 for (var i = 0, len = queries.length; i < len; ++i) {
1219 query = queries[i].trim();
1220 if (query.length !== 0) {
1221 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1223 results.in_args.push(tmp.in_args);
1224 results.returned.push(tmp.returned);
1225 results.others.push(tmp.others);
1228 if (queries.length > 1) {
1230 "in_args": mergeArrays(results.in_args),
1231 "returned": mergeArrays(results.returned),
1232 "others": mergeArrays(results.others),
1236 "in_args": results.in_args[0],
1237 "returned": results.returned[0],
1238 "others": results.others[0],
1242 function getFilterCrates() {
1243 var elem = document.getElementById("crate-search");
1245 if (elem && elem.value !== "All crates" && hasOwnProperty(rawSearchIndex, elem.value)) {
1251 function search(e, forced) {
1252 var params = searchState.getQueryStringParams();
1253 var query = getQuery(searchState.input.value.trim());
1259 if (query.query.length === 0) {
1262 if (!forced && query.id === currentResults) {
1263 if (query.query.length > 0) {
1264 searchState.putBackSearch(searchState.input);
1269 // Update document title to maintain a meaningful browser history
1270 searchState.title = "Results for " + query.query + " - Rust";
1272 // Because searching is incremental by character, only the most
1273 // recent search query is added to the browser history.
1274 if (searchState.browserSupportsHistoryApi()) {
1275 var newURL = getNakedUrl() + "?search=" + encodeURIComponent(query.raw) +
1276 window.location.hash;
1277 if (!history.state && !params.search) {
1278 history.pushState(query, "", newURL);
1280 history.replaceState(query, "", newURL);
1284 var filterCrates = getFilterCrates();
1285 showResults(execSearch(query, index, filterCrates));
1288 function buildIndex(rawSearchIndex) {
1290 var searchWords = [];
1292 var currentIndex = 0;
1295 for (var crate in rawSearchIndex) {
1296 if (!hasOwnProperty(rawSearchIndex, crate)) { continue; }
1300 searchWords.push(crate);
1301 var normalizedName = crate.indexOf("_") === -1
1303 : crate.replace(/_/g, "");
1304 // This object should have exactly the same set of fields as the "row"
1305 // object defined below. Your JavaScript runtime will thank you.
1306 // https://mathiasbynens.be/notes/shapes-ics
1309 ty: 1, // == ExternCrate
1312 desc: rawSearchIndex[crate].doc,
1316 normalizedName: normalizedName,
1319 searchIndex.push(crateRow);
1322 // an array of (Number) item types
1323 var itemTypes = rawSearchIndex[crate].t;
1324 // an array of (String) item names
1325 var itemNames = rawSearchIndex[crate].n;
1326 // an array of (String) full paths (or empty string for previous path)
1327 var itemPaths = rawSearchIndex[crate].q;
1328 // an array of (String) descriptions
1329 var itemDescs = rawSearchIndex[crate].d;
1330 // an array of (Number) the parent path index + 1 to `paths`, or 0 if none
1331 var itemParentIdxs = rawSearchIndex[crate].i;
1332 // an array of (Object | null) the type of the function, if any
1333 var itemFunctionSearchTypes = rawSearchIndex[crate].f;
1334 // an array of [(Number) item type,
1336 var paths = rawSearchIndex[crate].p;
1337 // a array of [(String) alias name
1338 // [Number] index to items]
1339 var aliases = rawSearchIndex[crate].a;
1341 // convert `rawPaths` entries into object form
1342 var len = paths.length;
1343 for (i = 0; i < len; ++i) {
1344 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1347 // convert `item*` into an object form, and construct word indices.
1349 // before any analysis is performed lets gather the search terms to
1350 // search against apart from the rest of the data. This is a quick
1351 // operation that is cached for the life of the page state so that
1352 // all other search operations have access to this cached data for
1353 // faster analysis operations
1354 len = itemTypes.length;
1356 for (i = 0; i < len; ++i) {
1357 // This object should have exactly the same set of fields as the "crateRow"
1358 // object defined above.
1359 if (typeof itemNames[i] === "string") {
1360 word = itemNames[i].toLowerCase();
1361 searchWords.push(word);
1364 searchWords.push("");
1366 var normalizedName = word.indexOf("_") === -1
1368 : word.replace(/_/g, "");
1373 path: itemPaths[i] ? itemPaths[i] : lastPath,
1375 parent: itemParentIdxs[i] > 0 ? paths[itemParentIdxs[i] - 1] : undefined,
1376 type: itemFunctionSearchTypes[i],
1378 normalizedName: normalizedName,
1381 searchIndex.push(row);
1382 lastPath = row.path;
1387 ALIASES[crate] = {};
1388 var j, local_aliases;
1389 for (var alias_name in aliases) {
1390 if (!aliases.hasOwnProperty(alias_name)) { continue; }
1392 if (!ALIASES[crate].hasOwnProperty(alias_name)) {
1393 ALIASES[crate][alias_name] = [];
1395 local_aliases = aliases[alias_name];
1396 for (j = 0, len = local_aliases.length; j < len; ++j) {
1397 ALIASES[crate][alias_name].push(local_aliases[j] + currentIndex);
1401 currentIndex += crateSize;
1406 function registerSearchEvents() {
1407 var searchAfter500ms = function() {
1408 searchState.clearInputTimeout();
1409 if (searchState.input.value.length === 0) {
1410 if (searchState.browserSupportsHistoryApi()) {
1411 history.replaceState("", window.currentCrate + " - Rust",
1412 getNakedUrl() + window.location.hash);
1414 searchState.hideResults();
1416 searchState.timeout = setTimeout(search, 500);
1419 searchState.input.onkeyup = searchAfter500ms;
1420 searchState.input.oninput = searchAfter500ms;
1421 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1423 searchState.clearInputTimeout();
1426 searchState.input.onchange = function(e) {
1427 if (e.target !== document.activeElement) {
1428 // To prevent doing anything when it's from a blur event.
1431 // Do NOT e.preventDefault() here. It will prevent pasting.
1432 searchState.clearInputTimeout();
1433 // zero-timeout necessary here because at the time of event handler execution the
1434 // pasted content is not in the input field yet. Shouldn’t make any difference for
1436 setTimeout(search, 0);
1438 searchState.input.onpaste = searchState.input.onchange;
1440 var selectCrate = document.getElementById("crate-search");
1442 selectCrate.onchange = function() {
1443 updateLocalStorage("rustdoc-saved-filter-crate", selectCrate.value);
1444 search(undefined, true);
1448 // Push and pop states are used to add search results to the browser
1450 if (searchState.browserSupportsHistoryApi()) {
1451 // Store the previous <title> so we can revert back to it later.
1452 var previousTitle = document.title;
1454 window.addEventListener("popstate", function(e) {
1455 var params = searchState.getQueryStringParams();
1456 // Revert to the previous title manually since the History
1457 // API ignores the title parameter.
1458 document.title = previousTitle;
1459 // When browsing forward to search results the previous
1460 // search will be repeated, so the currentResults are
1461 // cleared to ensure the search is successful.
1462 currentResults = null;
1463 // Synchronize search bar with query string state and
1464 // perform the search. This will empty the bar if there's
1465 // nothing there, which lets you really go back to a
1466 // previous state with nothing in the bar.
1467 if (params.search && params.search.length > 0) {
1468 searchState.input.value = params.search;
1469 // Some browsers fire "onpopstate" for every page load
1470 // (Chrome), while others fire the event only when actually
1471 // popping a state (Firefox), which is why search() is
1472 // called both here and at the end of the startSearch()
1476 searchState.input.value = "";
1477 // When browsing back from search results the main page
1478 // visibility must be reset.
1479 searchState.hideResults();
1484 // This is required in firefox to avoid this problem: Navigating to a search result
1485 // with the keyboard, hitting enter, and then hitting back would take you back to
1486 // the doc page, rather than the search that should overlay it.
1487 // This was an interaction between the back-forward cache and our handlers
1488 // that try to sync state between the URL and the search input. To work around it,
1489 // do a small amount of re-init on page show.
1490 window.onpageshow = function(){
1491 var qSearch = searchState.getQueryStringParams().search;
1492 if (searchState.input.value === "" && qSearch) {
1493 searchState.input.value = qSearch;
1499 index = buildIndex(rawSearchIndex);
1500 registerSearchEvents();
1501 // If there's a search term in the URL, execute the search now.
1502 if (searchState.getQueryStringParams().search) {
1507 if (window.searchIndex !== undefined) {
1508 initSearch(window.searchIndex);