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]]) {
303 elems[obj[GENERICS_DATA][x]] = 0;
305 elems[obj[GENERICS_DATA][x]] += 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 len, x, firstGeneric;
349 if (obj[NAME] === val.name) {
351 if (val.generics && val.generics.length !== 0) {
352 if (obj.length > GENERICS_DATA &&
353 obj[GENERICS_DATA].length > 0) {
354 var elems = Object.create(null);
355 len = obj[GENERICS_DATA].length;
356 for (x = 0; x < len; ++x) {
357 if (!elems[obj[GENERICS_DATA][x]]) {
358 elems[obj[GENERICS_DATA][x]] = 0;
360 elems[obj[GENERICS_DATA][x]] += 1;
364 len = val.generics.length;
365 for (x = 0; x < len; ++x) {
366 firstGeneric = val.generics[x];
367 if (elems[firstGeneric]) {
368 elems[firstGeneric] -= 1;
382 // If the type has generics but don't match, then it won't return at this point.
383 // Otherwise, `checkGenerics` will return 0 and it'll return.
384 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
385 var tmp_lev = checkGenerics(obj, val);
386 if (tmp_lev <= MAX_LEV_DISTANCE) {
391 } else if (literalSearch) {
392 if ((!val.generics || val.generics.length === 0) &&
393 obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
394 return obj[GENERICS_DATA].some(
396 return name === val.name;
401 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
402 if (lev_distance <= MAX_LEV_DISTANCE) {
403 // The generics didn't match but the name kinda did so we give it
404 // a levenshtein distance value that isn't *this* good so it goes
405 // into the search results but not too high.
406 lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2);
407 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
408 // We can check if the type we're looking for is inside the generics!
409 var olength = obj[GENERICS_DATA].length;
410 for (x = 0; x < olength; ++x) {
411 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
415 // Now whatever happens, the returned distance is "less good" so we should mark it
416 // as such, and so we add 1 to the distance to make it "less good".
417 return lev_distance + 1;
420 function findArg(obj, val, literalSearch, typeFilter) {
421 var lev_distance = MAX_LEV_DISTANCE + 1;
423 if (obj && obj.type && obj.type[INPUTS_DATA] && obj.type[INPUTS_DATA].length > 0) {
424 var length = obj.type[INPUTS_DATA].length;
425 for (var i = 0; i < length; i++) {
426 var tmp = obj.type[INPUTS_DATA][i];
427 if (!typePassesFilter(typeFilter, tmp[1])) {
430 tmp = checkType(tmp, val, literalSearch);
437 lev_distance = Math.min(tmp, lev_distance);
438 if (lev_distance === 0) {
443 return literalSearch ? false : lev_distance;
446 function checkReturned(obj, val, literalSearch, typeFilter) {
447 var lev_distance = MAX_LEV_DISTANCE + 1;
449 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
450 var ret = obj.type[OUTPUT_DATA];
451 if (typeof ret[0] === "string") {
454 for (var x = 0, len = ret.length; x < len; ++x) {
456 if (!typePassesFilter(typeFilter, tmp[1])) {
459 tmp = checkType(tmp, val, literalSearch);
466 lev_distance = Math.min(tmp, lev_distance);
467 if (lev_distance === 0) {
472 return literalSearch ? false : lev_distance;
475 function checkPath(contains, lastElem, ty) {
476 if (contains.length === 0) {
479 var ret_lev = MAX_LEV_DISTANCE + 1;
480 var path = ty.path.split("::");
482 if (ty.parent && ty.parent.name) {
483 path.push(ty.parent.name.toLowerCase());
486 var length = path.length;
487 var clength = contains.length;
488 if (clength > length) {
489 return MAX_LEV_DISTANCE + 1;
491 for (var i = 0; i < length; ++i) {
492 if (i + clength > length) {
497 for (var x = 0; x < clength; ++x) {
498 var lev = levenshtein(path[i + x], contains[x]);
499 if (lev > MAX_LEV_DISTANCE) {
506 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
512 function typePassesFilter(filter, type) {
514 if (filter <= NO_TYPE_FILTER) return true;
517 if (filter === type) return true;
519 // Match related items
520 var name = itemTypes[type];
521 switch (itemTypes[filter]) {
523 return name === "associatedconstant";
525 return name === "method" || name === "tymethod";
527 return name === "primitive" || name === "associatedtype";
529 return name === "traitalias";
536 function createAliasFromItem(item) {
549 function handleAliases(ret, query, filterCrates) {
550 // We separate aliases and crate aliases because we want to have current crate
551 // aliases to be before the others in the displayed results.
553 var crateAliases = [];
554 if (filterCrates !== undefined) {
555 if (ALIASES[filterCrates] && ALIASES[filterCrates][query.search]) {
556 var query_aliases = ALIASES[filterCrates][query.search];
557 var len = query_aliases.length;
558 for (var i = 0; i < len; ++i) {
559 aliases.push(createAliasFromItem(searchIndex[query_aliases[i]]));
563 Object.keys(ALIASES).forEach(function(crate) {
564 if (ALIASES[crate][query.search]) {
565 var pushTo = crate === window.currentCrate ? crateAliases : aliases;
566 var query_aliases = ALIASES[crate][query.search];
567 var len = query_aliases.length;
568 for (var i = 0; i < len; ++i) {
569 pushTo.push(createAliasFromItem(searchIndex[query_aliases[i]]));
575 var sortFunc = function(aaa, bbb) {
576 if (aaa.path < bbb.path) {
578 } else if (aaa.path === bbb.path) {
583 crateAliases.sort(sortFunc);
584 aliases.sort(sortFunc);
586 var pushFunc = function(alias) {
587 alias.alias = query.raw;
588 var res = buildHrefAndPath(alias);
589 alias.displayPath = pathSplitter(res[0]);
590 alias.fullPath = alias.displayPath + alias.name;
593 ret.others.unshift(alias);
594 if (ret.others.length > MAX_RESULTS) {
598 onEach(aliases, pushFunc);
599 onEach(crateAliases, pushFunc);
602 // quoted values mean literal search
603 var nSearchWords = searchWords.length;
610 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
611 val.charAt(val.length - 1) === val.charAt(0))
613 val = extractGenerics(val.substr(1, val.length - 2));
614 for (i = 0; i < nSearchWords; ++i) {
615 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
618 in_args = findArg(searchIndex[i], val, true, typeFilter);
619 returned = checkReturned(searchIndex[i], val, true, typeFilter);
623 if (searchWords[i] === val.name
624 && typePassesFilter(typeFilter, searchIndex[i].ty)
625 && results[fullId] === undefined) {
632 if (in_args && results_in_args[fullId] === undefined) {
633 results_in_args[fullId] = {
639 if (returned && results_returned[fullId] === undefined) {
640 results_returned[fullId] = {
647 query.inputs = [val];
651 } else if (val.search("->") > -1) {
652 var trimmer = function(s) { return s.trim(); };
653 var parts = val.split("->").map(trimmer);
654 var input = parts[0];
655 // sort inputs so that order does not matter
656 var inputs = input.split(",").map(trimmer).sort();
657 for (i = 0, len = inputs.length; i < len; ++i) {
658 inputs[i] = extractGenerics(inputs[i]);
660 var output = extractGenerics(parts[1]);
662 for (i = 0; i < nSearchWords; ++i) {
663 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
666 var type = searchIndex[i].type;
673 returned = checkReturned(ty, output, true, NO_TYPE_FILTER);
674 if (output.name === "*" || returned) {
676 var is_module = false;
682 for (it = 0, len = inputs.length; allFound && it < len; it++) {
683 allFound = checkType(type, inputs[it], true);
688 results_in_args[fullId] = {
695 results_returned[fullId] = {
710 query.inputs = inputs.map(function(input) {
713 query.output = output.name;
715 query.inputs = [val];
718 // gather matching search results up to a certain maximum
719 val = val.replace(/_/g, "");
721 var valGenerics = extractGenerics(val);
723 var paths = valLower.split("::");
724 removeEmptyStringsFromArray(paths);
725 val = paths[paths.length - 1];
726 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
729 for (j = 0; j < nSearchWords; ++j) {
731 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
735 if (paths.length > 1) {
736 lev = checkPath(contains, paths[paths.length - 1], ty);
737 if (lev > MAX_LEV_DISTANCE) {
739 } else if (lev > 0) {
744 returned = MAX_LEV_DISTANCE + 1;
745 in_args = MAX_LEV_DISTANCE + 1;
747 // we want lev results to go lower than others
748 lev = MAX_LEV_DISTANCE + 1;
751 if (searchWords[j].indexOf(split[i]) > -1 ||
752 searchWords[j].indexOf(val) > -1 ||
753 ty.normalizedName.indexOf(val) > -1)
755 // filter type: ... queries
756 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
757 index = ty.normalizedName.indexOf(val);
760 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
761 if (typePassesFilter(typeFilter, ty.ty)) {
764 lev = MAX_LEV_DISTANCE + 1;
767 in_args = findArg(ty, valGenerics, false, typeFilter);
768 returned = checkReturned(ty, valGenerics, false, typeFilter);
771 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
772 if (val.length < 6) {
778 if (in_args <= MAX_LEV_DISTANCE) {
779 if (results_in_args[fullId] === undefined) {
780 results_in_args[fullId] = {
786 results_in_args[fullId].lev =
787 Math.min(results_in_args[fullId].lev, in_args);
789 if (returned <= MAX_LEV_DISTANCE) {
790 if (results_returned[fullId] === undefined) {
791 results_returned[fullId] = {
797 results_returned[fullId].lev =
798 Math.min(results_returned[fullId].lev, returned);
800 if (typePassesFilter(typeFilter, ty.ty) &&
801 (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 nextTab(direction) {
879 var next = (searchState.currentTab + direction + 3) % searchState.focusedByTab.length;
880 searchState.focusedByTab[searchState.currentTab] = document.activeElement;
885 // Focus the first search result on the active tab, or the result that
886 // was focused last time this tab was active.
887 function focusSearchResult() {
888 var target = searchState.focusedByTab[searchState.currentTab] ||
889 document.querySelectorAll(".search-results.active a").item(0) ||
890 document.querySelectorAll("#titles > button").item(searchState.currentTab);
896 function buildHrefAndPath(item) {
899 var type = itemTypes[item.ty];
900 var name = item.name;
901 var path = item.path;
903 if (type === "mod") {
904 displayPath = path + "::";
905 href = window.rootPath + path.replace(/::/g, "/") + "/" +
906 name + "/index.html";
907 } else if (type === "primitive" || type === "keyword") {
909 href = window.rootPath + path.replace(/::/g, "/") +
910 "/" + type + "." + name + ".html";
911 } else if (type === "externcrate") {
913 href = window.rootPath + name + "/index.html";
914 } else if (item.parent !== undefined) {
915 var myparent = item.parent;
916 var anchor = "#" + type + "." + name;
917 var parentType = itemTypes[myparent.ty];
918 var pageType = parentType;
919 var pageName = myparent.name;
921 if (parentType === "primitive") {
922 displayPath = myparent.name + "::";
923 } else if (type === "structfield" && parentType === "variant") {
924 // Structfields belonging to variants are special: the
925 // final path element is the enum name.
926 var enumNameIdx = item.path.lastIndexOf("::");
927 var enumName = item.path.substr(enumNameIdx + 2);
928 path = item.path.substr(0, enumNameIdx);
929 displayPath = path + "::" + enumName + "::" + myparent.name + "::";
930 anchor = "#variant." + myparent.name + ".field." + name;
934 displayPath = path + "::" + myparent.name + "::";
936 href = window.rootPath + path.replace(/::/g, "/") +
941 displayPath = item.path + "::";
942 href = window.rootPath + item.path.replace(/::/g, "/") +
943 "/" + type + "." + name + ".html";
945 return [displayPath, href];
948 function escape(content) {
949 var h1 = document.createElement("h1");
950 h1.textContent = content;
954 function pathSplitter(path) {
955 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
956 if (tmp.endsWith("<span>")) {
957 return tmp.slice(0, tmp.length - 6);
962 function addTab(array, query, display) {
964 if (display === true) {
965 extraClass = " active";
968 var output = document.createElement("div");
971 if (array.length > 0) {
972 output.className = "search-results " + extraClass;
974 array.forEach(function(item) {
975 if (item.is_alias !== true) {
976 if (duplicates[item.fullPath]) {
979 duplicates[item.fullPath] = true;
982 var name = item.name;
983 var type = itemTypes[item.ty];
988 if (type === "primitive") {
989 extra = " <i>(primitive type)</i>";
990 } else if (type === "keyword") {
991 extra = " <i>(keyword)</i>";
994 var link = document.createElement("a");
995 link.className = "result-" + type;
996 link.href = item.href;
998 var wrapper = document.createElement("div");
999 var resultName = document.createElement("div");
1000 resultName.className = "result-name";
1002 if (item.is_alias) {
1003 var alias = document.createElement("span");
1004 alias.className = "alias";
1006 var bold = document.createElement("b");
1007 bold.innerText = item.alias;
1008 alias.appendChild(bold);
1010 alias.insertAdjacentHTML(
1012 "<span class=\"grey\"><i> - see </i></span>");
1014 resultName.appendChild(alias);
1016 resultName.insertAdjacentHTML(
1018 item.displayPath + "<span class=\"" + type + "\">" + name + extra + "</span>");
1019 wrapper.appendChild(resultName);
1021 var description = document.createElement("div");
1022 description.className = "desc";
1023 var spanDesc = document.createElement("span");
1024 spanDesc.insertAdjacentHTML("beforeend", item.desc);
1026 description.appendChild(spanDesc);
1027 wrapper.appendChild(description);
1028 link.appendChild(wrapper);
1029 output.appendChild(link);
1032 output.className = "search-failed" + extraClass;
1033 output.innerHTML = "No results :(<br/>" +
1034 "Try on <a href=\"https://duckduckgo.com/?q=" +
1035 encodeURIComponent("rust " + query.query) +
1036 "\">DuckDuckGo</a>?<br/><br/>" +
1037 "Or try looking in one of these:<ul><li>The <a " +
1038 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1039 " for technical details about the language.</li><li><a " +
1040 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1041 "Example</a> for expository code examples.</a></li><li>The <a " +
1042 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1043 "introductions to language features and the language itself.</li><li><a " +
1044 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1045 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul>";
1047 return [output, length];
1050 function makeTabHeader(tabNb, text, nbElems) {
1051 if (searchState.currentTab === tabNb) {
1052 return "<button class=\"selected\">" + text +
1053 " <div class=\"count\">(" + nbElems + ")</div></button>";
1055 return "<button>" + text + " <div class=\"count\">(" + nbElems + ")</div></button>";
1058 function showResults(results, go_to_first) {
1059 var search = searchState.outputElement();
1060 if (go_to_first || (results.others.length === 1
1061 && getSettingValue("go-to-only-result") === "true"
1062 // By default, the search DOM element is "empty" (meaning it has no children not
1063 // text content). Once a search has been run, it won't be empty, even if you press
1064 // ESC or empty the search input (which also "cancels" the search).
1065 && (!search.firstChild || search.firstChild.innerText !== searchState.loadingText)))
1067 var elem = document.createElement("a");
1068 elem.href = results.others[0].href;
1069 removeClass(elem, "active");
1070 // For firefox, we need the element to be in the DOM so it can be clicked.
1071 document.body.appendChild(elem);
1075 var query = getQuery(searchState.input.value);
1077 currentResults = query.id;
1079 var ret_others = addTab(results.others, query);
1080 var ret_in_args = addTab(results.in_args, query, false);
1081 var ret_returned = addTab(results.returned, query, false);
1083 // Navigate to the relevant tab if the current tab is empty, like in case users search
1084 // for "-> String". If they had selected another tab previously, they have to click on
1086 var currentTab = searchState.currentTab;
1087 if ((currentTab === 0 && ret_others[1] === 0) ||
1088 (currentTab === 1 && ret_in_args[1] === 0) ||
1089 (currentTab === 2 && ret_returned[1] === 0)) {
1090 if (ret_others[1] !== 0) {
1092 } else if (ret_in_args[1] !== 0) {
1094 } else if (ret_returned[1] !== 0) {
1099 var output = "<h1>Results for " + escape(query.query) +
1100 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1101 "<div id=\"titles\">" +
1102 makeTabHeader(0, "In Names", ret_others[1]) +
1103 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1104 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1107 var resultsElem = document.createElement("div");
1108 resultsElem.id = "results";
1109 resultsElem.appendChild(ret_others[0]);
1110 resultsElem.appendChild(ret_in_args[0]);
1111 resultsElem.appendChild(ret_returned[0]);
1113 search.innerHTML = output;
1114 search.appendChild(resultsElem);
1115 // Reset focused elements.
1116 searchState.focusedByTab = [null, null, null];
1117 searchState.showResults(search);
1118 var elems = document.getElementById("titles").childNodes;
1119 elems[0].onclick = function() { printTab(0); };
1120 elems[1].onclick = function() { printTab(1); };
1121 elems[2].onclick = function() { printTab(2); };
1122 printTab(currentTab);
1125 function execSearch(query, searchWords, filterCrates) {
1126 function getSmallest(arrays, positions, notDuplicates) {
1129 for (var it = 0, len = positions.length; it < len; ++it) {
1130 if (arrays[it].length > positions[it] &&
1131 (start === null || start > arrays[it][positions[it]].lev) &&
1132 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1133 start = arrays[it][positions[it]].lev;
1139 function mergeArrays(arrays) {
1142 var notDuplicates = {};
1144 for (var x = 0, arrays_len = arrays.length; x < arrays_len; ++x) {
1147 while (ret.length < MAX_RESULTS) {
1148 var smallest = getSmallest(arrays, positions, notDuplicates);
1150 if (smallest === null) {
1153 for (x = 0; x < arrays_len && ret.length < MAX_RESULTS; ++x) {
1154 if (arrays[x].length > positions[x] &&
1155 arrays[x][positions[x]].lev === smallest &&
1156 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1157 ret.push(arrays[x][positions[x]]);
1158 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1166 // Split search query by ",", while respecting angle bracket nesting.
1167 // Since "<" is an alias for the Ord family of traits, it also uses
1168 // lookahead to distinguish "<"-as-less-than from "<"-as-angle-bracket.
1170 // tokenizeQuery("A<B, C>, D") == ["A<B, C>", "D"]
1171 // tokenizeQuery("A<B, C, D") == ["A<B", "C", "D"]
1172 function tokenizeQuery(raw) {
1176 var nextAngle = /(<|>)/g;
1179 for (i = 0; i < l; ++i) {
1182 nextAngle.lastIndex = i + 1;
1183 matched = nextAngle.exec(raw);
1184 if (matched && matched[1] === '>') {
1195 ret.push(raw.substring(start, i));
1202 ret.push(raw.substring(start, i));
1207 var queries = tokenizeQuery(query.raw);
1214 for (var i = 0, len = queries.length; i < len; ++i) {
1215 query = queries[i].trim();
1216 if (query.length !== 0) {
1217 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1219 results.in_args.push(tmp.in_args);
1220 results.returned.push(tmp.returned);
1221 results.others.push(tmp.others);
1224 if (queries.length > 1) {
1226 "in_args": mergeArrays(results.in_args),
1227 "returned": mergeArrays(results.returned),
1228 "others": mergeArrays(results.others),
1232 "in_args": results.in_args[0],
1233 "returned": results.returned[0],
1234 "others": results.others[0],
1238 function getFilterCrates() {
1239 var elem = document.getElementById("crate-search");
1241 if (elem && elem.value !== "All crates" &&
1242 hasOwnPropertyRustdoc(rawSearchIndex, elem.value))
1249 function search(e, forced) {
1250 var params = searchState.getQueryStringParams();
1251 var query = getQuery(searchState.input.value.trim());
1257 if (query.query.length === 0) {
1260 if (!forced && query.id === currentResults) {
1261 if (query.query.length > 0) {
1262 searchState.putBackSearch(searchState.input);
1267 // Update document title to maintain a meaningful browser history
1268 searchState.title = "Results for " + query.query + " - Rust";
1270 // Because searching is incremental by character, only the most
1271 // recent search query is added to the browser history.
1272 if (searchState.browserSupportsHistoryApi()) {
1273 var newURL = getNakedUrl() + "?search=" + encodeURIComponent(query.raw) +
1274 window.location.hash;
1275 if (!history.state && !params.search) {
1276 history.pushState(query, "", newURL);
1278 history.replaceState(query, "", newURL);
1282 var filterCrates = getFilterCrates();
1283 showResults(execSearch(query, index, filterCrates), params.go_to_first);
1286 function buildIndex(rawSearchIndex) {
1288 var searchWords = [];
1290 var currentIndex = 0;
1293 for (var crate in rawSearchIndex) {
1294 if (!hasOwnPropertyRustdoc(rawSearchIndex, crate)) {
1300 searchWords.push(crate);
1301 // This object should have exactly the same set of fields as the "row"
1302 // object defined below. Your JavaScript runtime will thank you.
1303 // https://mathiasbynens.be/notes/shapes-ics
1306 ty: 1, // == ExternCrate
1309 desc: rawSearchIndex[crate].doc,
1313 normalizedName: crate.indexOf("_") === -1 ? crate : crate.replace(/_/g, ""),
1316 searchIndex.push(crateRow);
1319 // an array of (Number) item types
1320 var itemTypes = rawSearchIndex[crate].t;
1321 // an array of (String) item names
1322 var itemNames = rawSearchIndex[crate].n;
1323 // an array of (String) full paths (or empty string for previous path)
1324 var itemPaths = rawSearchIndex[crate].q;
1325 // an array of (String) descriptions
1326 var itemDescs = rawSearchIndex[crate].d;
1327 // an array of (Number) the parent path index + 1 to `paths`, or 0 if none
1328 var itemParentIdxs = rawSearchIndex[crate].i;
1329 // an array of (Object | null) the type of the function, if any
1330 var itemFunctionSearchTypes = rawSearchIndex[crate].f;
1331 // an array of [(Number) item type,
1333 var paths = rawSearchIndex[crate].p;
1334 // an array of [(String) alias name
1335 // [Number] index to items]
1336 var aliases = rawSearchIndex[crate].a;
1338 // convert `rawPaths` entries into object form
1339 var len = paths.length;
1340 for (i = 0; i < len; ++i) {
1341 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1344 // convert `item*` into an object form, and construct word indices.
1346 // before any analysis is performed lets gather the search terms to
1347 // search against apart from the rest of the data. This is a quick
1348 // operation that is cached for the life of the page state so that
1349 // all other search operations have access to this cached data for
1350 // faster analysis operations
1351 len = itemTypes.length;
1353 for (i = 0; i < len; ++i) {
1354 // This object should have exactly the same set of fields as the "crateRow"
1355 // object defined above.
1356 if (typeof itemNames[i] === "string") {
1357 word = itemNames[i].toLowerCase();
1358 searchWords.push(word);
1361 searchWords.push("");
1367 path: itemPaths[i] ? itemPaths[i] : lastPath,
1369 parent: itemParentIdxs[i] > 0 ? paths[itemParentIdxs[i] - 1] : undefined,
1370 type: itemFunctionSearchTypes[i],
1372 normalizedName: word.indexOf("_") === -1 ? word : word.replace(/_/g, ""),
1375 searchIndex.push(row);
1376 lastPath = row.path;
1381 ALIASES[crate] = {};
1382 var j, local_aliases;
1383 for (var alias_name in aliases) {
1384 if (!hasOwnPropertyRustdoc(aliases, alias_name)) {
1388 if (!hasOwnPropertyRustdoc(ALIASES[crate], alias_name)) {
1389 ALIASES[crate][alias_name] = [];
1391 local_aliases = aliases[alias_name];
1392 for (j = 0, len = local_aliases.length; j < len; ++j) {
1393 ALIASES[crate][alias_name].push(local_aliases[j] + currentIndex);
1397 currentIndex += crateSize;
1402 function registerSearchEvents() {
1403 var searchAfter500ms = function() {
1404 searchState.clearInputTimeout();
1405 if (searchState.input.value.length === 0) {
1406 if (searchState.browserSupportsHistoryApi()) {
1407 history.replaceState("", window.currentCrate + " - Rust",
1408 getNakedUrl() + window.location.hash);
1410 searchState.hideResults();
1412 searchState.timeout = setTimeout(search, 500);
1415 searchState.input.onkeyup = searchAfter500ms;
1416 searchState.input.oninput = searchAfter500ms;
1417 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1419 searchState.clearInputTimeout();
1422 searchState.input.onchange = function(e) {
1423 if (e.target !== document.activeElement) {
1424 // To prevent doing anything when it's from a blur event.
1427 // Do NOT e.preventDefault() here. It will prevent pasting.
1428 searchState.clearInputTimeout();
1429 // zero-timeout necessary here because at the time of event handler execution the
1430 // pasted content is not in the input field yet. Shouldn’t make any difference for
1432 setTimeout(search, 0);
1434 searchState.input.onpaste = searchState.input.onchange;
1436 searchState.outputElement().addEventListener("keydown", function(e) {
1437 // We only handle unmodified keystrokes here. We don't want to interfere with,
1438 // for instance, alt-left and alt-right for history navigation.
1439 if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
1442 // up and down arrow select next/previous search result, or the
1443 // search box if we're already at the top.
1444 if (e.which === 38) { // up
1445 var previous = document.activeElement.previousElementSibling;
1449 searchState.focus();
1452 } else if (e.which === 40) { // down
1453 var next = document.activeElement.nextElementSibling;
1457 var rect = document.activeElement.getBoundingClientRect();
1458 if (window.innerHeight - rect.bottom < rect.height) {
1459 window.scrollBy(0, rect.height);
1462 } else if (e.which === 37) { // left
1465 } else if (e.which === 39) { // right
1471 searchState.input.addEventListener("keydown", function(e) {
1472 if (e.which === 40) { // down
1473 focusSearchResult();
1479 var selectCrate = document.getElementById("crate-search");
1481 selectCrate.onchange = function() {
1482 updateLocalStorage("rustdoc-saved-filter-crate", selectCrate.value);
1483 // In case you "cut" the entry from the search input, then change the crate filter
1484 // before paste back the previous search, you get the old search results without
1485 // the filter. To prevent this, we need to remove the previous results.
1486 currentResults = null;
1487 search(undefined, true);
1491 // Push and pop states are used to add search results to the browser
1493 if (searchState.browserSupportsHistoryApi()) {
1494 // Store the previous <title> so we can revert back to it later.
1495 var previousTitle = document.title;
1497 window.addEventListener("popstate", function(e) {
1498 var params = searchState.getQueryStringParams();
1499 // Revert to the previous title manually since the History
1500 // API ignores the title parameter.
1501 document.title = previousTitle;
1502 // When browsing forward to search results the previous
1503 // search will be repeated, so the currentResults are
1504 // cleared to ensure the search is successful.
1505 currentResults = null;
1506 // Synchronize search bar with query string state and
1507 // perform the search. This will empty the bar if there's
1508 // nothing there, which lets you really go back to a
1509 // previous state with nothing in the bar.
1510 if (params.search && params.search.length > 0) {
1511 searchState.input.value = params.search;
1512 // Some browsers fire "onpopstate" for every page load
1513 // (Chrome), while others fire the event only when actually
1514 // popping a state (Firefox), which is why search() is
1515 // called both here and at the end of the startSearch()
1519 searchState.input.value = "";
1520 // When browsing back from search results the main page
1521 // visibility must be reset.
1522 searchState.hideResults();
1527 // This is required in firefox to avoid this problem: Navigating to a search result
1528 // with the keyboard, hitting enter, and then hitting back would take you back to
1529 // the doc page, rather than the search that should overlay it.
1530 // This was an interaction between the back-forward cache and our handlers
1531 // that try to sync state between the URL and the search input. To work around it,
1532 // do a small amount of re-init on page show.
1533 window.onpageshow = function(){
1534 var qSearch = searchState.getQueryStringParams().search;
1535 if (searchState.input.value === "" && qSearch) {
1536 searchState.input.value = qSearch;
1542 index = buildIndex(rawSearchIndex);
1543 registerSearchEvents();
1544 // If there's a search term in the URL, execute the search now.
1545 if (searchState.getQueryStringParams().search) {
1550 if (window.searchIndex !== undefined) {
1551 initSearch(window.searchIndex);