]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/static/main.js
Rollup merge of #78716 - est31:array_traits, r=Dylan-DPC
[rust.git] / src / librustdoc / html / static / main.js
1 // From rust:
2 /* global ALIASES, currentCrate, rootPath */
3
4 // Local js definitions:
5 /* global addClass, getCurrentValue, hasClass */
6 /* global onEachLazy, hasOwnProperty, removeClass, updateLocalStorage */
7 /* global hideThemeButtonState, showThemeButtonState */
8
9 if (!String.prototype.startsWith) {
10     String.prototype.startsWith = function(searchString, position) {
11         position = position || 0;
12         return this.indexOf(searchString, position) === position;
13     };
14 }
15 if (!String.prototype.endsWith) {
16     String.prototype.endsWith = function(suffix, length) {
17         var l = length || this.length;
18         return this.indexOf(suffix, l - suffix.length) !== -1;
19     };
20 }
21
22 if (!DOMTokenList.prototype.add) {
23     DOMTokenList.prototype.add = function(className) {
24         if (className && !hasClass(this, className)) {
25             if (this.className && this.className.length > 0) {
26                 this.className += " " + className;
27             } else {
28                 this.className = className;
29             }
30         }
31     };
32 }
33
34 if (!DOMTokenList.prototype.remove) {
35     DOMTokenList.prototype.remove = function(className) {
36         if (className && this.className) {
37             this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
38                                                          .trim();
39         }
40     };
41 }
42
43 function getSearchInput() {
44     return document.getElementsByClassName("search-input")[0];
45 }
46
47 function getSearchElement() {
48     return document.getElementById("search");
49 }
50
51 function getThemesElement() {
52     return document.getElementById("theme-choices");
53 }
54
55 function getThemePickerElement() {
56     return document.getElementById("theme-picker");
57 }
58
59 // Sets the focus on the search bar at the top of the page
60 function focusSearchBar() {
61     getSearchInput().focus();
62 }
63
64 // Removes the focus from the search bar
65 function defocusSearchBar() {
66     getSearchInput().blur();
67 }
68
69 (function() {
70     "use strict";
71
72     // This mapping table should match the discriminants of
73     // `rustdoc::html::item_type::ItemType` type in Rust.
74     var itemTypes = ["mod",
75                      "externcrate",
76                      "import",
77                      "struct",
78                      "enum",
79                      "fn",
80                      "type",
81                      "static",
82                      "trait",
83                      "impl",
84                      "tymethod",
85                      "method",
86                      "structfield",
87                      "variant",
88                      "macro",
89                      "primitive",
90                      "associatedtype",
91                      "constant",
92                      "associatedconstant",
93                      "union",
94                      "foreigntype",
95                      "keyword",
96                      "existential",
97                      "attr",
98                      "derive",
99                      "traitalias"];
100
101     var disableShortcuts = getSettingValue("disable-shortcuts") === "true";
102     var search_input = getSearchInput();
103     var searchTimeout = null;
104     var toggleAllDocsId = "toggle-all-docs";
105
106     // On the search screen, so you remain on the last tab you opened.
107     //
108     // 0 for "In Names"
109     // 1 for "In Parameters"
110     // 2 for "In Return Types"
111     var currentTab = 0;
112
113     var mouseMovedAfterSearch = true;
114
115     var titleBeforeSearch = document.title;
116
117     function clearInputTimeout() {
118         if (searchTimeout !== null) {
119             clearTimeout(searchTimeout);
120             searchTimeout = null;
121         }
122     }
123
124     function getPageId() {
125         if (window.location.hash) {
126             var tmp = window.location.hash.replace(/^#/, "");
127             if (tmp.length > 0) {
128                 return tmp;
129             }
130         }
131         return null;
132     }
133
134     function showSidebar() {
135         var elems = document.getElementsByClassName("sidebar-elems")[0];
136         if (elems) {
137             addClass(elems, "show-it");
138         }
139         var sidebar = document.getElementsByClassName("sidebar")[0];
140         if (sidebar) {
141             addClass(sidebar, "mobile");
142             var filler = document.getElementById("sidebar-filler");
143             if (!filler) {
144                 var div = document.createElement("div");
145                 div.id = "sidebar-filler";
146                 sidebar.appendChild(div);
147             }
148         }
149     }
150
151     function hideSidebar() {
152         var elems = document.getElementsByClassName("sidebar-elems")[0];
153         if (elems) {
154             removeClass(elems, "show-it");
155         }
156         var sidebar = document.getElementsByClassName("sidebar")[0];
157         removeClass(sidebar, "mobile");
158         var filler = document.getElementById("sidebar-filler");
159         if (filler) {
160             filler.remove();
161         }
162         document.getElementsByTagName("body")[0].style.marginTop = "";
163     }
164
165     function showSearchResults(search) {
166         if (search === null || typeof search === 'undefined') {
167             search = getSearchElement();
168         }
169         addClass(main, "hidden");
170         removeClass(search, "hidden");
171         mouseMovedAfterSearch = false;
172     }
173
174     function hideSearchResults(search) {
175         if (search === null || typeof search === 'undefined') {
176             search = getSearchElement();
177         }
178         addClass(search, "hidden");
179         removeClass(main, "hidden");
180     }
181
182     // used for special search precedence
183     var TY_PRIMITIVE = itemTypes.indexOf("primitive");
184     var TY_KEYWORD = itemTypes.indexOf("keyword");
185
186     function getQueryStringParams() {
187         var params = {};
188         window.location.search.substring(1).split("&").
189             map(function(s) {
190                 var pair = s.split("=");
191                 params[decodeURIComponent(pair[0])] =
192                     typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
193             });
194         return params;
195     }
196
197     function browserSupportsHistoryApi() {
198         return window.history && typeof window.history.pushState === "function";
199     }
200
201     function isHidden(elem) {
202         return elem.offsetHeight === 0;
203     }
204
205     var main = document.getElementById("main");
206     var savedHash = "";
207
208     function handleHashes(ev) {
209         var elem;
210         var search = getSearchElement();
211         if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
212             // This block occurs when clicking on an element in the navbar while
213             // in a search.
214             hideSearchResults(search);
215             var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
216             if (browserSupportsHistoryApi()) {
217                 history.replaceState(hash, "", "?search=#" + hash);
218             }
219             elem = document.getElementById(hash);
220             if (elem) {
221                 elem.scrollIntoView();
222             }
223         }
224         // This part is used in case an element is not visible.
225         if (savedHash !== window.location.hash) {
226             savedHash = window.location.hash;
227             if (savedHash.length === 0) {
228                 return;
229             }
230             elem = document.getElementById(savedHash.slice(1)); // we remove the '#'
231             if (!elem || !isHidden(elem)) {
232                 return;
233             }
234             var parent = elem.parentNode;
235             if (parent && hasClass(parent, "impl-items")) {
236                 // In case this is a trait implementation item, we first need to toggle
237                 // the "Show hidden undocumented items".
238                 onEachLazy(parent.getElementsByClassName("collapsed"), function(e) {
239                     if (e.parentNode === parent) {
240                         // Only click on the toggle we're looking for.
241                         e.click();
242                         return true;
243                     }
244                 });
245                 if (isHidden(elem)) {
246                     // The whole parent is collapsed. We need to click on its toggle as well!
247                     if (hasClass(parent.lastElementChild, "collapse-toggle")) {
248                         parent.lastElementChild.click();
249                     }
250                 }
251             }
252         }
253     }
254
255     function highlightSourceLines(match, ev) {
256         if (typeof match === "undefined") {
257             // If we're in mobile mode, we should hide the sidebar in any case.
258             hideSidebar();
259             match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
260         }
261         if (!match) {
262             return;
263         }
264         var from = parseInt(match[1], 10);
265         var to = from;
266         if (typeof match[2] !== "undefined") {
267             to = parseInt(match[2], 10);
268         }
269         if (to < from) {
270             var tmp = to;
271             to = from;
272             from = tmp;
273         }
274         var elem = document.getElementById(from);
275         if (!elem) {
276             return;
277         }
278         if (!ev) {
279             var x = document.getElementById(from);
280             if (x) {
281                 x.scrollIntoView();
282             }
283         }
284         onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
285             onEachLazy(e.getElementsByTagName("span"), function(i_e) {
286                 removeClass(i_e, "line-highlighted");
287             });
288         });
289         for (var i = from; i <= to; ++i) {
290             elem = document.getElementById(i);
291             if (!elem) {
292                 break;
293             }
294             addClass(elem, "line-highlighted");
295         }
296     }
297
298     function onHashChange(ev) {
299         // If we're in mobile mode, we should hide the sidebar in any case.
300         hideSidebar();
301         var match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
302         if (match) {
303             return highlightSourceLines(match, ev);
304         }
305         handleHashes(ev);
306     }
307
308     function expandSection(id) {
309         var elem = document.getElementById(id);
310         if (elem && isHidden(elem)) {
311             var h3 = elem.parentNode.previousElementSibling;
312             if (h3 && h3.tagName !== "H3") {
313                 h3 = h3.previousElementSibling; // skip div.docblock
314             }
315
316             if (h3) {
317                 var collapses = h3.getElementsByClassName("collapse-toggle");
318                 if (collapses.length > 0) {
319                     // The element is not visible, we need to make it appear!
320                     collapseDocs(collapses[0], "show");
321                 }
322             }
323         }
324     }
325
326     // Gets the human-readable string for the virtual-key code of the
327     // given KeyboardEvent, ev.
328     //
329     // This function is meant as a polyfill for KeyboardEvent#key,
330     // since it is not supported in Trident.  We also test for
331     // KeyboardEvent#keyCode because the handleShortcut handler is
332     // also registered for the keydown event, because Blink doesn't fire
333     // keypress on hitting the Escape key.
334     //
335     // So I guess you could say things are getting pretty interoperable.
336     function getVirtualKey(ev) {
337         if ("key" in ev && typeof ev.key != "undefined") {
338             return ev.key;
339         }
340
341         var c = ev.charCode || ev.keyCode;
342         if (c == 27) {
343             return "Escape";
344         }
345         return String.fromCharCode(c);
346     }
347
348     function getHelpElement() {
349         buildHelperPopup();
350         return document.getElementById("help");
351     }
352
353     function displayHelp(display, ev, help) {
354         help = help ? help : getHelpElement();
355         if (display === true) {
356             if (hasClass(help, "hidden")) {
357                 ev.preventDefault();
358                 removeClass(help, "hidden");
359                 addClass(document.body, "blur");
360             }
361         } else if (hasClass(help, "hidden") === false) {
362             ev.preventDefault();
363             addClass(help, "hidden");
364             removeClass(document.body, "blur");
365         }
366     }
367
368     function handleEscape(ev) {
369         var help = getHelpElement();
370         var search = getSearchElement();
371         if (hasClass(help, "hidden") === false) {
372             displayHelp(false, ev, help);
373         } else if (hasClass(search, "hidden") === false) {
374             clearInputTimeout();
375             ev.preventDefault();
376             hideSearchResults(search);
377             document.title = titleBeforeSearch;
378         }
379         defocusSearchBar();
380         hideThemeButtonState();
381     }
382
383     function handleShortcut(ev) {
384         // Don't interfere with browser shortcuts
385         if (ev.ctrlKey || ev.altKey || ev.metaKey || disableShortcuts === true) {
386             return;
387         }
388
389         if (document.activeElement.tagName === "INPUT") {
390             switch (getVirtualKey(ev)) {
391             case "Escape":
392                 handleEscape(ev);
393                 break;
394             }
395         } else {
396             switch (getVirtualKey(ev)) {
397             case "Escape":
398                 handleEscape(ev);
399                 break;
400
401             case "s":
402             case "S":
403                 displayHelp(false, ev);
404                 ev.preventDefault();
405                 focusSearchBar();
406                 break;
407
408             case "+":
409             case "-":
410                 ev.preventDefault();
411                 toggleAllDocs();
412                 break;
413
414             case "?":
415                 displayHelp(true, ev);
416                 break;
417
418             default:
419                 var themePicker = getThemePickerElement();
420                 if (themePicker.parentNode.contains(ev.target)) {
421                     handleThemeKeyDown(ev);
422                 }
423             }
424         }
425     }
426
427     function handleThemeKeyDown(ev) {
428         var active = document.activeElement;
429         var themes = getThemesElement();
430         switch (getVirtualKey(ev)) {
431         case "ArrowUp":
432             ev.preventDefault();
433             if (active.previousElementSibling && ev.target.id !== "theme-picker") {
434                 active.previousElementSibling.focus();
435             } else {
436                 showThemeButtonState();
437                 themes.lastElementChild.focus();
438             }
439             break;
440         case "ArrowDown":
441             ev.preventDefault();
442             if (active.nextElementSibling && ev.target.id !== "theme-picker") {
443                 active.nextElementSibling.focus();
444             } else {
445                 showThemeButtonState();
446                 themes.firstElementChild.focus();
447             }
448             break;
449         case "Enter":
450         case "Return":
451         case "Space":
452             if (ev.target.id === "theme-picker" && themes.style.display === "none") {
453                 ev.preventDefault();
454                 showThemeButtonState();
455                 themes.firstElementChild.focus();
456             }
457             break;
458         case "Home":
459             ev.preventDefault();
460             themes.firstElementChild.focus();
461             break;
462         case "End":
463             ev.preventDefault();
464             themes.lastElementChild.focus();
465             break;
466         // The escape key is handled in handleEscape, not here,
467         // so that pressing escape will close the menu even if it isn't focused
468         }
469     }
470
471     function findParentElement(elem, tagName) {
472         do {
473             if (elem && elem.tagName === tagName) {
474                 return elem;
475             }
476             elem = elem.parentNode;
477         } while (elem);
478         return null;
479     }
480
481     document.addEventListener("keypress", handleShortcut);
482     document.addEventListener("keydown", handleShortcut);
483
484     function resetMouseMoved(ev) {
485         mouseMovedAfterSearch = true;
486     }
487
488     document.addEventListener("mousemove", resetMouseMoved);
489
490     var handleSourceHighlight = (function() {
491         var prev_line_id = 0;
492
493         var set_fragment = function(name) {
494             var x = window.scrollX,
495                 y = window.scrollY;
496             if (browserSupportsHistoryApi()) {
497                 history.replaceState(null, null, "#" + name);
498                 highlightSourceLines();
499             } else {
500                 location.replace("#" + name);
501             }
502             // Prevent jumps when selecting one or many lines
503             window.scrollTo(x, y);
504         };
505
506         return function(ev) {
507             var cur_line_id = parseInt(ev.target.id, 10);
508             ev.preventDefault();
509
510             if (ev.shiftKey && prev_line_id) {
511                 // Swap selection if needed
512                 if (prev_line_id > cur_line_id) {
513                     var tmp = prev_line_id;
514                     prev_line_id = cur_line_id;
515                     cur_line_id = tmp;
516                 }
517
518                 set_fragment(prev_line_id + "-" + cur_line_id);
519             } else {
520                 prev_line_id = cur_line_id;
521
522                 set_fragment(cur_line_id);
523             }
524         };
525     }());
526
527     document.addEventListener("click", function(ev) {
528         if (hasClass(ev.target, "help-button")) {
529             displayHelp(true, ev);
530         } else if (hasClass(ev.target, "collapse-toggle")) {
531             collapseDocs(ev.target, "toggle");
532         } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
533             collapseDocs(ev.target.parentNode, "toggle");
534         } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
535             handleSourceHighlight(ev);
536         } else if (hasClass(getHelpElement(), "hidden") === false) {
537             var help = getHelpElement();
538             var is_inside_help_popup = ev.target !== help && help.contains(ev.target);
539             if (is_inside_help_popup === false) {
540                 addClass(help, "hidden");
541                 removeClass(document.body, "blur");
542             }
543         } else {
544             // Making a collapsed element visible on onhashchange seems
545             // too late
546             var a = findParentElement(ev.target, "A");
547             if (a && a.hash) {
548                 expandSection(a.hash.replace(/^#/, ""));
549             }
550         }
551     });
552
553     (function() {
554         var x = document.getElementsByClassName("version-selector");
555         if (x.length > 0) {
556             x[0].onchange = function() {
557                 var i, match,
558                     url = document.location.href,
559                     stripped = "",
560                     len = rootPath.match(/\.\.\//g).length + 1;
561
562                 for (i = 0; i < len; ++i) {
563                     match = url.match(/\/[^\/]*$/);
564                     if (i < len - 1) {
565                         stripped = match[0] + stripped;
566                     }
567                     url = url.substring(0, url.length - match[0].length);
568                 }
569
570                 var selectedVersion = document.getElementsByClassName("version-selector")[0].value;
571                 url += "/" + selectedVersion + stripped;
572
573                 document.location.href = url;
574             };
575         }
576     }());
577
578     /**
579      * A function to compute the Levenshtein distance between two strings
580      * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
581      * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
582      * This code is an unmodified version of the code written by Marco de Wit
583      * and was found at http://stackoverflow.com/a/18514751/745719
584      */
585     var levenshtein_row2 = [];
586     function levenshtein(s1, s2) {
587         if (s1 === s2) {
588             return 0;
589         }
590         var s1_len = s1.length, s2_len = s2.length;
591         if (s1_len && s2_len) {
592             var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
593             while (i1 < s1_len) {
594                 row[i1] = ++i1;
595             }
596             while (i2 < s2_len) {
597                 c2 = s2.charCodeAt(i2);
598                 a = i2;
599                 ++i2;
600                 b = i2;
601                 for (i1 = 0; i1 < s1_len; ++i1) {
602                     c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
603                     a = row[i1];
604                     b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
605                     row[i1] = b;
606                 }
607             }
608             return b;
609         }
610         return s1_len + s2_len;
611     }
612
613     window.initSearch = function(rawSearchIndex) {
614         var MAX_LEV_DISTANCE = 3;
615         var MAX_RESULTS = 200;
616         var GENERICS_DATA = 1;
617         var NAME = 0;
618         var INPUTS_DATA = 0;
619         var OUTPUT_DATA = 1;
620         var NO_TYPE_FILTER = -1;
621         var currentResults, index, searchIndex;
622         var ALIASES = {};
623         var params = getQueryStringParams();
624
625         // Populate search bar with query string search term when provided,
626         // but only if the input bar is empty. This avoid the obnoxious issue
627         // where you start trying to do a search, and the index loads, and
628         // suddenly your search is gone!
629         if (search_input.value === "") {
630             search_input.value = params.search || "";
631         }
632
633         /**
634          * Executes the query and builds an index of results
635          * @param  {[Object]} query      [The user query]
636          * @param  {[type]} searchWords  [The list of search words to query
637          *                                against]
638          * @param  {[type]} filterCrates [Crate to search in if defined]
639          * @return {[type]}              [A search index of results]
640          */
641         function execQuery(query, searchWords, filterCrates) {
642             function itemTypeFromName(typename) {
643                 var length = itemTypes.length;
644                 for (var i = 0; i < length; ++i) {
645                     if (itemTypes[i] === typename) {
646                         return i;
647                     }
648                 }
649                 return NO_TYPE_FILTER;
650             }
651
652             var valLower = query.query.toLowerCase(),
653                 val = valLower,
654                 typeFilter = itemTypeFromName(query.type),
655                 results = {}, results_in_args = {}, results_returned = {},
656                 split = valLower.split("::");
657
658             var length = split.length;
659             for (var z = 0; z < length; ++z) {
660                 if (split[z] === "") {
661                     split.splice(z, 1);
662                     z -= 1;
663                 }
664             }
665
666             function transformResults(results, isType) {
667                 var out = [];
668                 var length = results.length;
669                 for (var i = 0; i < length; ++i) {
670                     if (results[i].id > -1) {
671                         var obj = searchIndex[results[i].id];
672                         obj.lev = results[i].lev;
673                         if (isType !== true || obj.type) {
674                             var res = buildHrefAndPath(obj);
675                             obj.displayPath = pathSplitter(res[0]);
676                             obj.fullPath = obj.displayPath + obj.name;
677                             // To be sure than it some items aren't considered as duplicate.
678                             obj.fullPath += "|" + obj.ty;
679                             obj.href = res[1];
680                             out.push(obj);
681                             if (out.length >= MAX_RESULTS) {
682                                 break;
683                             }
684                         }
685                     }
686                 }
687                 return out;
688             }
689
690             function sortResults(results, isType) {
691                 var ar = [];
692                 for (var entry in results) {
693                     if (hasOwnProperty(results, entry)) {
694                         ar.push(results[entry]);
695                     }
696                 }
697                 results = ar;
698                 var i;
699                 var nresults = results.length;
700                 for (i = 0; i < nresults; ++i) {
701                     results[i].word = searchWords[results[i].id];
702                     results[i].item = searchIndex[results[i].id] || {};
703                 }
704                 // if there are no results then return to default and fail
705                 if (results.length === 0) {
706                     return [];
707                 }
708
709                 results.sort(function(aaa, bbb) {
710                     var a, b;
711
712                     // sort by exact match with regard to the last word (mismatch goes later)
713                     a = (aaa.word !== val);
714                     b = (bbb.word !== val);
715                     if (a !== b) { return a - b; }
716
717                     // Sort by non levenshtein results and then levenshtein results by the distance
718                     // (less changes required to match means higher rankings)
719                     a = (aaa.lev);
720                     b = (bbb.lev);
721                     if (a !== b) { return a - b; }
722
723                     // sort by crate (non-current crate goes later)
724                     a = (aaa.item.crate !== window.currentCrate);
725                     b = (bbb.item.crate !== window.currentCrate);
726                     if (a !== b) { return a - b; }
727
728                     // sort by item name length (longer goes later)
729                     a = aaa.word.length;
730                     b = bbb.word.length;
731                     if (a !== b) { return a - b; }
732
733                     // sort by item name (lexicographically larger goes later)
734                     a = aaa.word;
735                     b = bbb.word;
736                     if (a !== b) { return (a > b ? +1 : -1); }
737
738                     // sort by index of keyword in item name (no literal occurrence goes later)
739                     a = (aaa.index < 0);
740                     b = (bbb.index < 0);
741                     if (a !== b) { return a - b; }
742                     // (later literal occurrence, if any, goes later)
743                     a = aaa.index;
744                     b = bbb.index;
745                     if (a !== b) { return a - b; }
746
747                     // special precedence for primitive and keyword pages
748                     if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
749                         (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
750                         return -1;
751                     }
752                     if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
753                         (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
754                         return 1;
755                     }
756
757                     // sort by description (no description goes later)
758                     a = (aaa.item.desc === "");
759                     b = (bbb.item.desc === "");
760                     if (a !== b) { return a - b; }
761
762                     // sort by type (later occurrence in `itemTypes` goes later)
763                     a = aaa.item.ty;
764                     b = bbb.item.ty;
765                     if (a !== b) { return a - b; }
766
767                     // sort by path (lexicographically larger goes later)
768                     a = aaa.item.path;
769                     b = bbb.item.path;
770                     if (a !== b) { return (a > b ? +1 : -1); }
771
772                     // que sera, sera
773                     return 0;
774                 });
775
776                 var length = results.length;
777                 for (i = 0; i < length; ++i) {
778                     var result = results[i];
779
780                     // this validation does not make sense when searching by types
781                     if (result.dontValidate) {
782                         continue;
783                     }
784                     var name = result.item.name.toLowerCase(),
785                         path = result.item.path.toLowerCase(),
786                         parent = result.item.parent;
787
788                     if (isType !== true &&
789                         validateResult(name, path, split, parent) === false)
790                     {
791                         result.id = -1;
792                     }
793                 }
794                 return transformResults(results);
795             }
796
797             function extractGenerics(val) {
798                 val = val.toLowerCase();
799                 if (val.indexOf("<") !== -1) {
800                     var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
801                     return {
802                         name: val.substring(0, val.indexOf("<")),
803                         generics: values.split(/\s*,\s*/),
804                     };
805                 }
806                 return {
807                     name: val,
808                     generics: [],
809                 };
810             }
811
812             function getObjectFromId(id) {
813                 if (typeof id === "number") {
814                     return searchIndex[id];
815                 }
816                 return {'name': id};
817             }
818
819             function checkGenerics(obj, val) {
820                 // The names match, but we need to be sure that all generics kinda
821                 // match as well.
822                 var lev_distance = MAX_LEV_DISTANCE + 1;
823                 if (val.generics.length > 0) {
824                     if (obj.length > GENERICS_DATA &&
825                           obj[GENERICS_DATA].length >= val.generics.length) {
826                         var elems = obj[GENERICS_DATA].slice(0);
827                         var total = 0;
828                         var done = 0;
829                         // We need to find the type that matches the most to remove it in order
830                         // to move forward.
831                         var vlength = val.generics.length;
832                         for (var y = 0; y < vlength; ++y) {
833                             var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
834                             var elength = elems.length;
835                             var firstGeneric = getObjectFromId(val.generics[y]).name;
836                             for (var x = 0; x < elength; ++x) {
837                                 var tmp_lev = levenshtein(getObjectFromId(elems[x]).name,
838                                                           firstGeneric);
839                                 if (tmp_lev < lev.lev) {
840                                     lev.lev = tmp_lev;
841                                     lev.pos = x;
842                                 }
843                             }
844                             if (lev.pos !== -1) {
845                                 elems.splice(lev.pos, 1);
846                                 lev_distance = Math.min(lev.lev, lev_distance);
847                                 total += lev.lev;
848                                 done += 1;
849                             } else {
850                                 return MAX_LEV_DISTANCE + 1;
851                             }
852                         }
853                         return Math.ceil(total / done);
854                     }
855                 }
856                 return MAX_LEV_DISTANCE + 1;
857             }
858
859             // Check for type name and type generics (if any).
860             function checkType(obj, val, literalSearch) {
861                 var lev_distance = MAX_LEV_DISTANCE + 1;
862                 var x;
863                 if (obj[NAME] === val.name) {
864                     if (literalSearch === true) {
865                         if (val.generics && val.generics.length !== 0) {
866                             if (obj.length > GENERICS_DATA &&
867                                   obj[GENERICS_DATA].length >= val.generics.length) {
868                                 var elems = obj[GENERICS_DATA].slice(0);
869                                 var allFound = true;
870
871                                 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
872                                     allFound = false;
873                                     var firstGeneric = getObjectFromId(val.generics[y]).name;
874                                     for (x = 0; allFound === false && x < elems.length; ++x) {
875                                         allFound = getObjectFromId(elems[x]).name === firstGeneric;
876                                     }
877                                     if (allFound === true) {
878                                         elems.splice(x - 1, 1);
879                                     }
880                                 }
881                                 if (allFound === true) {
882                                     return true;
883                                 }
884                             } else {
885                                 return false;
886                             }
887                         }
888                         return true;
889                     }
890                     // If the type has generics but don't match, then it won't return at this point.
891                     // Otherwise, `checkGenerics` will return 0 and it'll return.
892                     if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
893                         var tmp_lev = checkGenerics(obj, val);
894                         if (tmp_lev <= MAX_LEV_DISTANCE) {
895                             return tmp_lev;
896                         }
897                     } else {
898                         return 0;
899                     }
900                 }
901                 // Names didn't match so let's check if one of the generic types could.
902                 if (literalSearch === true) {
903                      if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
904                         var length = obj[GENERICS_DATA].length;
905                         for (x = 0; x < length; ++x) {
906                             if (obj[GENERICS_DATA][x] === val.name) {
907                                 return true;
908                             }
909                         }
910                     }
911                     return false;
912                 }
913                 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
914                 if (lev_distance <= MAX_LEV_DISTANCE) {
915                     // The generics didn't match but the name kinda did so we give it
916                     // a levenshtein distance value that isn't *this* good so it goes
917                     // into the search results but not too high.
918                     lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2);
919                 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
920                     // We can check if the type we're looking for is inside the generics!
921                     var olength = obj[GENERICS_DATA].length;
922                     for (x = 0; x < olength; ++x) {
923                         lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
924                                                 lev_distance);
925                     }
926                 }
927                 // Now whatever happens, the returned distance is "less good" so we should mark it
928                 // as such, and so we add 1 to the distance to make it "less good".
929                 return lev_distance + 1;
930             }
931
932             function findArg(obj, val, literalSearch, typeFilter) {
933                 var lev_distance = MAX_LEV_DISTANCE + 1;
934
935                 if (obj && obj.type && obj.type[INPUTS_DATA] && obj.type[INPUTS_DATA].length > 0) {
936                     var length = obj.type[INPUTS_DATA].length;
937                     for (var i = 0; i < length; i++) {
938                         var tmp = obj.type[INPUTS_DATA][i];
939                         if (typePassesFilter(typeFilter, tmp[1]) === false) {
940                             continue;
941                         }
942                         tmp = checkType(tmp, val, literalSearch);
943                         if (literalSearch === true) {
944                             if (tmp === true) {
945                                 return true;
946                             }
947                             continue;
948                         }
949                         lev_distance = Math.min(tmp, lev_distance);
950                         if (lev_distance === 0) {
951                             return 0;
952                         }
953                     }
954                 }
955                 return literalSearch === true ? false : lev_distance;
956             }
957
958             function checkReturned(obj, val, literalSearch, typeFilter) {
959                 var lev_distance = MAX_LEV_DISTANCE + 1;
960
961                 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
962                     var ret = obj.type[OUTPUT_DATA];
963                     if (typeof ret[0] === "string") {
964                         ret = [ret];
965                     }
966                     for (var x = 0; x < ret.length; ++x) {
967                         var tmp = ret[x];
968                         if (typePassesFilter(typeFilter, tmp[1]) === false) {
969                             continue;
970                         }
971                         tmp = checkType(tmp, val, literalSearch);
972                         if (literalSearch === true) {
973                             if (tmp === true) {
974                                 return true;
975                             }
976                             continue;
977                         }
978                         lev_distance = Math.min(tmp, lev_distance);
979                         if (lev_distance === 0) {
980                             return 0;
981                         }
982                     }
983                 }
984                 return literalSearch === true ? false : lev_distance;
985             }
986
987             function checkPath(contains, lastElem, ty) {
988                 if (contains.length === 0) {
989                     return 0;
990                 }
991                 var ret_lev = MAX_LEV_DISTANCE + 1;
992                 var path = ty.path.split("::");
993
994                 if (ty.parent && ty.parent.name) {
995                     path.push(ty.parent.name.toLowerCase());
996                 }
997
998                 var length = path.length;
999                 var clength = contains.length;
1000                 if (clength > length) {
1001                     return MAX_LEV_DISTANCE + 1;
1002                 }
1003                 for (var i = 0; i < length; ++i) {
1004                     if (i + clength > length) {
1005                         break;
1006                     }
1007                     var lev_total = 0;
1008                     var aborted = false;
1009                     for (var x = 0; x < clength; ++x) {
1010                         var lev = levenshtein(path[i + x], contains[x]);
1011                         if (lev > MAX_LEV_DISTANCE) {
1012                             aborted = true;
1013                             break;
1014                         }
1015                         lev_total += lev;
1016                     }
1017                     if (aborted === false) {
1018                         ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
1019                     }
1020                 }
1021                 return ret_lev;
1022             }
1023
1024             function typePassesFilter(filter, type) {
1025                 // No filter
1026                 if (filter <= NO_TYPE_FILTER) return true;
1027
1028                 // Exact match
1029                 if (filter === type) return true;
1030
1031                 // Match related items
1032                 var name = itemTypes[type];
1033                 switch (itemTypes[filter]) {
1034                     case "constant":
1035                         return name === "associatedconstant";
1036                     case "fn":
1037                         return name === "method" || name === "tymethod";
1038                     case "type":
1039                         return name === "primitive" || name === "associatedtype";
1040                     case "trait":
1041                         return name === "traitalias";
1042                 }
1043
1044                 // No match
1045                 return false;
1046             }
1047
1048             function generateId(ty) {
1049                 if (ty.parent && ty.parent.name) {
1050                     return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
1051                 }
1052                 return itemTypes[ty.ty] + ty.path + ty.name;
1053             }
1054
1055             function createAliasFromItem(item) {
1056                 return {
1057                     crate: item.crate,
1058                     name: item.name,
1059                     path: item.path,
1060                     desc: item.desc,
1061                     ty: item.ty,
1062                     parent: item.parent,
1063                     type: item.type,
1064                     is_alias: true,
1065                 };
1066             }
1067
1068             function handleAliases(ret, query, filterCrates) {
1069                 // We separate aliases and crate aliases because we want to have current crate
1070                 // aliases to be before the others in the displayed results.
1071                 var aliases = [];
1072                 var crateAliases = [];
1073                 var i;
1074                 if (filterCrates !== undefined) {
1075                     if (ALIASES[filterCrates] && ALIASES[filterCrates][query.search]) {
1076                         for (i = 0; i < ALIASES[filterCrates][query.search].length; ++i) {
1077                             aliases.push(
1078                                 createAliasFromItem(
1079                                     searchIndex[ALIASES[filterCrates][query.search][i]]));
1080                         }
1081                     }
1082                 } else {
1083                     Object.keys(ALIASES).forEach(function(crate) {
1084                         if (ALIASES[crate][query.search]) {
1085                             var pushTo = crate === window.currentCrate ? crateAliases : aliases;
1086                             for (i = 0; i < ALIASES[crate][query.search].length; ++i) {
1087                                 pushTo.push(
1088                                     createAliasFromItem(
1089                                         searchIndex[ALIASES[crate][query.search][i]]));
1090                             }
1091                         }
1092                     });
1093                 }
1094
1095                 var sortFunc = function(aaa, bbb) {
1096                     if (aaa.path < bbb.path) {
1097                         return 1;
1098                     } else if (aaa.path === bbb.path) {
1099                         return 0;
1100                     }
1101                     return -1;
1102                 };
1103                 crateAliases.sort(sortFunc);
1104                 aliases.sort(sortFunc);
1105
1106                 var pushFunc = function(alias) {
1107                     alias.alias = query.raw;
1108                     var res = buildHrefAndPath(alias);
1109                     alias.displayPath = pathSplitter(res[0]);
1110                     alias.fullPath = alias.displayPath + alias.name;
1111                     alias.href = res[1];
1112
1113                     ret.others.unshift(alias);
1114                     if (ret.others.length > MAX_RESULTS) {
1115                         ret.others.pop();
1116                     }
1117                 };
1118                 onEach(aliases, pushFunc);
1119                 onEach(crateAliases, pushFunc);
1120             }
1121
1122             // quoted values mean literal search
1123             var nSearchWords = searchWords.length;
1124             var i;
1125             var ty;
1126             var fullId;
1127             var returned;
1128             var in_args;
1129             if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
1130                 val.charAt(val.length - 1) === val.charAt(0))
1131             {
1132                 val = extractGenerics(val.substr(1, val.length - 2));
1133                 for (i = 0; i < nSearchWords; ++i) {
1134                     if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
1135                         continue;
1136                     }
1137                     in_args = findArg(searchIndex[i], val, true, typeFilter);
1138                     returned = checkReturned(searchIndex[i], val, true, typeFilter);
1139                     ty = searchIndex[i];
1140                     fullId = generateId(ty);
1141
1142                     if (searchWords[i] === val.name
1143                         && typePassesFilter(typeFilter, searchIndex[i].ty)
1144                         && results[fullId] === undefined) {
1145                         results[fullId] = {
1146                             id: i,
1147                             index: -1,
1148                             dontValidate: true,
1149                         };
1150                     }
1151                     if (in_args === true && results_in_args[fullId] === undefined) {
1152                         results_in_args[fullId] = {
1153                             id: i,
1154                             index: -1,
1155                             dontValidate: true,
1156                         };
1157                     }
1158                     if (returned === true && results_returned[fullId] === undefined) {
1159                         results_returned[fullId] = {
1160                             id: i,
1161                             index: -1,
1162                             dontValidate: true,
1163                         };
1164                     }
1165                 }
1166                 query.inputs = [val];
1167                 query.output = val;
1168                 query.search = val;
1169             // searching by type
1170             } else if (val.search("->") > -1) {
1171                 var trimmer = function(s) { return s.trim(); };
1172                 var parts = val.split("->").map(trimmer);
1173                 var input = parts[0];
1174                 // sort inputs so that order does not matter
1175                 var inputs = input.split(",").map(trimmer).sort();
1176                 for (i = 0; i < inputs.length; ++i) {
1177                     inputs[i] = extractGenerics(inputs[i]);
1178                 }
1179                 var output = extractGenerics(parts[1]);
1180
1181                 for (i = 0; i < nSearchWords; ++i) {
1182                     if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
1183                         continue;
1184                     }
1185                     var type = searchIndex[i].type;
1186                     ty = searchIndex[i];
1187                     if (!type) {
1188                         continue;
1189                     }
1190                     fullId = generateId(ty);
1191
1192                     returned = checkReturned(ty, output, true, NO_TYPE_FILTER);
1193                     if (output.name === "*" || returned === true) {
1194                         in_args = false;
1195                         var is_module = false;
1196
1197                         if (input === "*") {
1198                             is_module = true;
1199                         } else {
1200                             var allFound = true;
1201                             for (var it = 0; allFound === true && it < inputs.length; it++) {
1202                                 allFound = checkType(type, inputs[it], true);
1203                             }
1204                             in_args = allFound;
1205                         }
1206                         if (in_args === true) {
1207                             results_in_args[fullId] = {
1208                                 id: i,
1209                                 index: -1,
1210                                 dontValidate: true,
1211                             };
1212                         }
1213                         if (returned === true) {
1214                             results_returned[fullId] = {
1215                                 id: i,
1216                                 index: -1,
1217                                 dontValidate: true,
1218                             };
1219                         }
1220                         if (is_module === true) {
1221                             results[fullId] = {
1222                                 id: i,
1223                                 index: -1,
1224                                 dontValidate: true,
1225                             };
1226                         }
1227                     }
1228                 }
1229                 query.inputs = inputs.map(function(input) {
1230                     return input.name;
1231                 });
1232                 query.output = output.name;
1233             } else {
1234                 query.inputs = [val];
1235                 query.output = val;
1236                 query.search = val;
1237                 // gather matching search results up to a certain maximum
1238                 val = val.replace(/\_/g, "");
1239
1240                 var valGenerics = extractGenerics(val);
1241
1242                 var paths = valLower.split("::");
1243                 var j;
1244                 for (j = 0; j < paths.length; ++j) {
1245                     if (paths[j] === "") {
1246                         paths.splice(j, 1);
1247                         j -= 1;
1248                     }
1249                 }
1250                 val = paths[paths.length - 1];
1251                 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
1252
1253                 var lev;
1254                 for (j = 0; j < nSearchWords; ++j) {
1255                     ty = searchIndex[j];
1256                     if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
1257                         continue;
1258                     }
1259                     var lev_add = 0;
1260                     if (paths.length > 1) {
1261                         lev = checkPath(contains, paths[paths.length - 1], ty);
1262                         if (lev > MAX_LEV_DISTANCE) {
1263                             continue;
1264                         } else if (lev > 0) {
1265                             lev_add = lev / 10;
1266                         }
1267                     }
1268
1269                     returned = MAX_LEV_DISTANCE + 1;
1270                     in_args = MAX_LEV_DISTANCE + 1;
1271                     var index = -1;
1272                     // we want lev results to go lower than others
1273                     lev = MAX_LEV_DISTANCE + 1;
1274                     fullId = generateId(ty);
1275
1276                     if (searchWords[j].indexOf(split[i]) > -1 ||
1277                         searchWords[j].indexOf(val) > -1 ||
1278                         searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1279                     {
1280                         // filter type: ... queries
1281                         if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1282                             index = searchWords[j].replace(/_/g, "").indexOf(val);
1283                         }
1284                     }
1285                     if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1286                         if (typePassesFilter(typeFilter, ty.ty) === false) {
1287                             lev = MAX_LEV_DISTANCE + 1;
1288                         } else {
1289                             lev += 1;
1290                         }
1291                     }
1292                     in_args = findArg(ty, valGenerics, false, typeFilter);
1293                     returned = checkReturned(ty, valGenerics, false, typeFilter);
1294
1295                     lev += lev_add;
1296                     if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1297                         if (val.length < 6) {
1298                             lev -= 1;
1299                         } else {
1300                             lev = 0;
1301                         }
1302                     }
1303                     if (in_args <= MAX_LEV_DISTANCE) {
1304                         if (results_in_args[fullId] === undefined) {
1305                             results_in_args[fullId] = {
1306                                 id: j,
1307                                 index: index,
1308                                 lev: in_args,
1309                             };
1310                         }
1311                         results_in_args[fullId].lev =
1312                             Math.min(results_in_args[fullId].lev, in_args);
1313                     }
1314                     if (returned <= MAX_LEV_DISTANCE) {
1315                         if (results_returned[fullId] === undefined) {
1316                             results_returned[fullId] = {
1317                                 id: j,
1318                                 index: index,
1319                                 lev: returned,
1320                             };
1321                         }
1322                         results_returned[fullId].lev =
1323                             Math.min(results_returned[fullId].lev, returned);
1324                     }
1325                     if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1326                         if (index !== -1 && paths.length < 2) {
1327                             lev = 0;
1328                         }
1329                         if (results[fullId] === undefined) {
1330                             results[fullId] = {
1331                                 id: j,
1332                                 index: index,
1333                                 lev: lev,
1334                             };
1335                         }
1336                         results[fullId].lev = Math.min(results[fullId].lev, lev);
1337                     }
1338                 }
1339             }
1340
1341             var ret = {
1342                 "in_args": sortResults(results_in_args, true),
1343                 "returned": sortResults(results_returned, true),
1344                 "others": sortResults(results),
1345             };
1346             handleAliases(ret, query, filterCrates);
1347             return ret;
1348         }
1349
1350         /**
1351          * Validate performs the following boolean logic. For example:
1352          * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1353          * exists in (name || path || parent) OR => ("file" && "open") exists in
1354          * (name || path )
1355          *
1356          * This could be written functionally, but I wanted to minimise
1357          * functions on stack.
1358          *
1359          * @param  {[string]} name   [The name of the result]
1360          * @param  {[string]} path   [The path of the result]
1361          * @param  {[string]} keys   [The keys to be used (["file", "open"])]
1362          * @param  {[object]} parent [The parent of the result]
1363          * @return {[boolean]}       [Whether the result is valid or not]
1364          */
1365         function validateResult(name, path, keys, parent) {
1366             for (var i = 0; i < keys.length; ++i) {
1367                 // each check is for validation so we negate the conditions and invalidate
1368                 if (!(
1369                     // check for an exact name match
1370                     name.indexOf(keys[i]) > -1 ||
1371                     // then an exact path match
1372                     path.indexOf(keys[i]) > -1 ||
1373                     // next if there is a parent, check for exact parent match
1374                     (parent !== undefined && parent.name !== undefined &&
1375                         parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1376                     // lastly check to see if the name was a levenshtein match
1377                     levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1378                     return false;
1379                 }
1380             }
1381             return true;
1382         }
1383
1384         function getQuery(raw) {
1385             var matches, type, query;
1386             query = raw;
1387
1388             matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1389             if (matches) {
1390                 type = matches[1].replace(/^const$/, "constant");
1391                 query = query.substring(matches[0].length);
1392             }
1393
1394             return {
1395                 raw: raw,
1396                 query: query,
1397                 type: type,
1398                 id: query + type
1399             };
1400         }
1401
1402         function initSearchNav() {
1403             var hoverTimeout;
1404
1405             var click_func = function(e) {
1406                 var el = e.target;
1407                 // to retrieve the real "owner" of the event.
1408                 while (el.tagName !== "TR") {
1409                     el = el.parentNode;
1410                 }
1411                 var dst = e.target.getElementsByTagName("a");
1412                 if (dst.length < 1) {
1413                     return;
1414                 }
1415                 dst = dst[0];
1416                 if (window.location.pathname === dst.pathname) {
1417                     hideSearchResults();
1418                     document.location.href = dst.href;
1419                 }
1420             };
1421             var mouseover_func = function(e) {
1422                 if (mouseMovedAfterSearch) {
1423                     var el = e.target;
1424                     // to retrieve the real "owner" of the event.
1425                     while (el.tagName !== "TR") {
1426                         el = el.parentNode;
1427                     }
1428                     clearTimeout(hoverTimeout);
1429                     hoverTimeout = setTimeout(function() {
1430                         onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1431                             onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1432                                 removeClass(i_e, "highlighted");
1433                             });
1434                         });
1435                         addClass(el, "highlighted");
1436                     }, 20);
1437                 }
1438             };
1439             onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1440                 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1441                     i_e.onclick = click_func;
1442                     i_e.onmouseover = mouseover_func;
1443                 });
1444             });
1445
1446             search_input.onkeydown = function(e) {
1447                 // "actives" references the currently highlighted item in each search tab.
1448                 // Each array in "actives" represents a tab.
1449                 var actives = [[], [], []];
1450                 // "current" is used to know which tab we're looking into.
1451                 var current = 0;
1452                 onEachLazy(document.getElementById("results").childNodes, function(e) {
1453                     onEachLazy(e.getElementsByClassName("highlighted"), function(h_e) {
1454                         actives[current].push(h_e);
1455                     });
1456                     current += 1;
1457                 });
1458
1459                 if (e.which === 38) { // up
1460                     if (!actives[currentTab].length ||
1461                         !actives[currentTab][0].previousElementSibling) {
1462                         return;
1463                     }
1464
1465                     addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1466                     removeClass(actives[currentTab][0], "highlighted");
1467                     e.preventDefault();
1468                 } else if (e.which === 40) { // down
1469                     if (!actives[currentTab].length) {
1470                         var results = document.getElementById("results").childNodes;
1471                         if (results.length > 0) {
1472                             var res = results[currentTab].getElementsByClassName("result");
1473                             if (res.length > 0) {
1474                                 addClass(res[0], "highlighted");
1475                             }
1476                         }
1477                     } else if (actives[currentTab][0].nextElementSibling) {
1478                         addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1479                         removeClass(actives[currentTab][0], "highlighted");
1480                     }
1481                     e.preventDefault();
1482                 } else if (e.which === 13) { // return
1483                     if (actives[currentTab].length) {
1484                         document.location.href =
1485                             actives[currentTab][0].getElementsByTagName("a")[0].href;
1486                     }
1487                 } else if (e.which === 9) { // tab
1488                     if (e.shiftKey) {
1489                         printTab(currentTab > 0 ? currentTab - 1 : 2);
1490                     } else {
1491                         printTab(currentTab > 1 ? 0 : currentTab + 1);
1492                     }
1493                     e.preventDefault();
1494                 } else if (e.which === 16) { // shift
1495                     // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1496                 } else if (actives[currentTab].length > 0) {
1497                     removeClass(actives[currentTab][0], "highlighted");
1498                 }
1499             };
1500         }
1501
1502         function buildHrefAndPath(item) {
1503             var displayPath;
1504             var href;
1505             var type = itemTypes[item.ty];
1506             var name = item.name;
1507             var path = item.path;
1508
1509             if (type === "mod") {
1510                 displayPath = path + "::";
1511                 href = rootPath + path.replace(/::/g, "/") + "/" +
1512                        name + "/index.html";
1513             } else if (type === "primitive" || type === "keyword") {
1514                 displayPath = "";
1515                 href = rootPath + path.replace(/::/g, "/") +
1516                        "/" + type + "." + name + ".html";
1517             } else if (type === "externcrate") {
1518                 displayPath = "";
1519                 href = rootPath + name + "/index.html";
1520             } else if (item.parent !== undefined) {
1521                 var myparent = item.parent;
1522                 var anchor = "#" + type + "." + name;
1523                 var parentType = itemTypes[myparent.ty];
1524                 var pageType = parentType;
1525                 var pageName = myparent.name;
1526
1527                 if (parentType === "primitive") {
1528                     displayPath = myparent.name + "::";
1529                 } else if (type === "structfield" && parentType === "variant") {
1530                     // Structfields belonging to variants are special: the
1531                     // final path element is the enum name.
1532                     var splitPath = item.path.split("::");
1533                     var enumName = splitPath.pop();
1534                     path = splitPath.join("::");
1535                     displayPath = path + "::" + enumName + "::" + myparent.name + "::";
1536                     anchor = "#variant." + myparent.name + ".field." + name;
1537                     pageType = "enum";
1538                     pageName = enumName;
1539                 } else {
1540                     displayPath = path + "::" + myparent.name + "::";
1541                 }
1542                 href = rootPath + path.replace(/::/g, "/") +
1543                        "/" + pageType +
1544                        "." + pageName +
1545                        ".html" + anchor;
1546             } else {
1547                 displayPath = item.path + "::";
1548                 href = rootPath + item.path.replace(/::/g, "/") +
1549                        "/" + type + "." + name + ".html";
1550             }
1551             return [displayPath, href];
1552         }
1553
1554         function escape(content) {
1555             var h1 = document.createElement("h1");
1556             h1.textContent = content;
1557             return h1.innerHTML;
1558         }
1559
1560         function pathSplitter(path) {
1561             var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1562             if (tmp.endsWith("<span>")) {
1563                 return tmp.slice(0, tmp.length - 6);
1564             }
1565             return tmp;
1566         }
1567
1568         function addTab(array, query, display) {
1569             var extraStyle = "";
1570             if (display === false) {
1571                 extraStyle = " style=\"display: none;\"";
1572             }
1573
1574             var output = "";
1575             var duplicates = {};
1576             var length = 0;
1577             if (array.length > 0) {
1578                 output = "<table class=\"search-results\"" + extraStyle + ">";
1579
1580                 array.forEach(function(item) {
1581                     var name, type;
1582
1583                     name = item.name;
1584                     type = itemTypes[item.ty];
1585
1586                     if (item.is_alias !== true) {
1587                         if (duplicates[item.fullPath]) {
1588                             return;
1589                         }
1590                         duplicates[item.fullPath] = true;
1591                     }
1592                     length += 1;
1593
1594                     output += "<tr class=\"" + type + " result\"><td>" +
1595                               "<a href=\"" + item.href + "\">" +
1596                               (item.is_alias === true ?
1597                                ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1598                                   "class=\"grey\"><i>&nbsp;- see&nbsp;</i></span>") : "") +
1599                               item.displayPath + "<span class=\"" + type + "\">" +
1600                               name + "</span></a></td><td>" +
1601                               "<a href=\"" + item.href + "\">" +
1602                               "<span class=\"desc\">" + escape(item.desc) +
1603                               "&nbsp;</span></a></td></tr>";
1604                 });
1605                 output += "</table>";
1606             } else {
1607                 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1608                     "Try on <a href=\"https://duckduckgo.com/?q=" +
1609                     encodeURIComponent("rust " + query.query) +
1610                     "\">DuckDuckGo</a>?<br/><br/>" +
1611                     "Or try looking in one of these:<ul><li>The <a " +
1612                     "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1613                     " for technical details about the language.</li><li><a " +
1614                     "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1615                     "Example</a> for expository code examples.</a></li><li>The <a " +
1616                     "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1617                     "introductions to language features and the language itself.</li><li><a " +
1618                     "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1619                     " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1620             }
1621             return [output, length];
1622         }
1623
1624         function makeTabHeader(tabNb, text, nbElems) {
1625             if (currentTab === tabNb) {
1626                 return "<div class=\"selected\">" + text +
1627                        " <div class=\"count\">(" + nbElems + ")</div></div>";
1628             }
1629             return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1630         }
1631
1632         function showResults(results) {
1633             var search = getSearchElement();
1634             if (results.others.length === 1
1635                 && getSettingValue("go-to-only-result") === "true"
1636                 // By default, the search DOM element is "empty" (meaning it has no children not
1637                 // text content). Once a search has been run, it won't be empty, even if you press
1638                 // ESC or empty the search input (which also "cancels" the search).
1639                 && (!search.firstChild || search.firstChild.innerText !== getSearchLoadingText()))
1640             {
1641                 var elem = document.createElement("a");
1642                 elem.href = results.others[0].href;
1643                 elem.style.display = "none";
1644                 // For firefox, we need the element to be in the DOM so it can be clicked.
1645                 document.body.appendChild(elem);
1646                 elem.click();
1647                 return;
1648             }
1649             var query = getQuery(search_input.value);
1650
1651             currentResults = query.id;
1652
1653             var ret_others = addTab(results.others, query);
1654             var ret_in_args = addTab(results.in_args, query, false);
1655             var ret_returned = addTab(results.returned, query, false);
1656
1657             var output = "<h1>Results for " + escape(query.query) +
1658                 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1659                 "<div id=\"titles\">" +
1660                 makeTabHeader(0, "In Names", ret_others[1]) +
1661                 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1662                 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1663                 "</div><div id=\"results\">" +
1664                 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1665
1666             search.innerHTML = output;
1667             showSearchResults(search);
1668             var tds = search.getElementsByTagName("td");
1669             var td_width = 0;
1670             if (tds.length > 0) {
1671                 td_width = tds[0].offsetWidth;
1672             }
1673             var width = search.offsetWidth - 40 - td_width;
1674             onEachLazy(search.getElementsByClassName("desc"), function(e) {
1675                 e.style.width = width + "px";
1676             });
1677             initSearchNav();
1678             var elems = document.getElementById("titles").childNodes;
1679             elems[0].onclick = function() { printTab(0); };
1680             elems[1].onclick = function() { printTab(1); };
1681             elems[2].onclick = function() { printTab(2); };
1682             printTab(currentTab);
1683         }
1684
1685         function execSearch(query, searchWords, filterCrates) {
1686             function getSmallest(arrays, positions, notDuplicates) {
1687                 var start = null;
1688
1689                 for (var it = 0; it < positions.length; ++it) {
1690                     if (arrays[it].length > positions[it] &&
1691                         (start === null || start > arrays[it][positions[it]].lev) &&
1692                         !notDuplicates[arrays[it][positions[it]].fullPath]) {
1693                         start = arrays[it][positions[it]].lev;
1694                     }
1695                 }
1696                 return start;
1697             }
1698
1699             function mergeArrays(arrays) {
1700                 var ret = [];
1701                 var positions = [];
1702                 var notDuplicates = {};
1703
1704                 for (var x = 0; x < arrays.length; ++x) {
1705                     positions.push(0);
1706                 }
1707                 while (ret.length < MAX_RESULTS) {
1708                     var smallest = getSmallest(arrays, positions, notDuplicates);
1709
1710                     if (smallest === null) {
1711                         break;
1712                     }
1713                     for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1714                         if (arrays[x].length > positions[x] &&
1715                                 arrays[x][positions[x]].lev === smallest &&
1716                                 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1717                             ret.push(arrays[x][positions[x]]);
1718                             notDuplicates[arrays[x][positions[x]].fullPath] = true;
1719                             positions[x] += 1;
1720                         }
1721                     }
1722                 }
1723                 return ret;
1724             }
1725
1726             var queries = query.raw.split(",");
1727             var results = {
1728                 "in_args": [],
1729                 "returned": [],
1730                 "others": [],
1731             };
1732
1733             for (var i = 0; i < queries.length; ++i) {
1734                 query = queries[i].trim();
1735                 if (query.length !== 0) {
1736                     var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1737
1738                     results.in_args.push(tmp.in_args);
1739                     results.returned.push(tmp.returned);
1740                     results.others.push(tmp.others);
1741                 }
1742             }
1743             if (queries.length > 1) {
1744                 return {
1745                     "in_args": mergeArrays(results.in_args),
1746                     "returned": mergeArrays(results.returned),
1747                     "others": mergeArrays(results.others),
1748                 };
1749             }
1750             return {
1751                 "in_args": results.in_args[0],
1752                 "returned": results.returned[0],
1753                 "others": results.others[0],
1754             };
1755         }
1756
1757         function getFilterCrates() {
1758             var elem = document.getElementById("crate-search");
1759
1760             if (elem && elem.value !== "All crates" && hasOwnProperty(rawSearchIndex, elem.value)) {
1761                 return elem.value;
1762             }
1763             return undefined;
1764         }
1765
1766         function search(e, forced) {
1767             var params = getQueryStringParams();
1768             var query = getQuery(search_input.value.trim());
1769
1770             if (e) {
1771                 e.preventDefault();
1772             }
1773
1774             if (query.query.length === 0) {
1775                 return;
1776             }
1777             if (forced !== true && query.id === currentResults) {
1778                 if (query.query.length > 0) {
1779                     putBackSearch(search_input);
1780                 }
1781                 return;
1782             }
1783
1784             // Update document title to maintain a meaningful browser history
1785             document.title = "Results for " + query.query + " - Rust";
1786
1787             // Because searching is incremental by character, only the most
1788             // recent search query is added to the browser history.
1789             if (browserSupportsHistoryApi()) {
1790                 if (!history.state && !params.search) {
1791                     history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1792                 } else {
1793                     history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1794                 }
1795             }
1796
1797             var filterCrates = getFilterCrates();
1798             showResults(execSearch(query, index, filterCrates));
1799         }
1800
1801         function buildIndex(rawSearchIndex) {
1802             searchIndex = [];
1803             var searchWords = [];
1804             var i;
1805             var currentIndex = 0;
1806
1807             for (var crate in rawSearchIndex) {
1808                 if (!hasOwnProperty(rawSearchIndex, crate)) { continue; }
1809
1810                 var crateSize = 0;
1811
1812                 searchWords.push(crate);
1813                 searchIndex.push({
1814                     crate: crate,
1815                     ty: 1, // == ExternCrate
1816                     name: crate,
1817                     path: "",
1818                     desc: rawSearchIndex[crate].doc,
1819                     type: null,
1820                 });
1821                 currentIndex += 1;
1822
1823                 // an array of [(Number) item type,
1824                 //              (String) name,
1825                 //              (String) full path or empty string for previous path,
1826                 //              (String) description,
1827                 //              (Number | null) the parent path index to `paths`]
1828                 //              (Object | null) the type of the function (if any)
1829                 var items = rawSearchIndex[crate].i;
1830                 // an array of [(Number) item type,
1831                 //              (String) name]
1832                 var paths = rawSearchIndex[crate].p;
1833                 // a array of [(String) alias name
1834                 //             [Number] index to items]
1835                 var aliases = rawSearchIndex[crate].a;
1836
1837                 // convert `rawPaths` entries into object form
1838                 var len = paths.length;
1839                 for (i = 0; i < len; ++i) {
1840                     paths[i] = {ty: paths[i][0], name: paths[i][1]};
1841                 }
1842
1843                 // convert `items` into an object form, and construct word indices.
1844                 //
1845                 // before any analysis is performed lets gather the search terms to
1846                 // search against apart from the rest of the data.  This is a quick
1847                 // operation that is cached for the life of the page state so that
1848                 // all other search operations have access to this cached data for
1849                 // faster analysis operations
1850                 len = items.length;
1851                 var lastPath = "";
1852                 for (i = 0; i < len; ++i) {
1853                     var rawRow = items[i];
1854                     if (!rawRow[2]) {
1855                         rawRow[2] = lastPath;
1856                     }
1857                     var row = {
1858                         crate: crate,
1859                         ty: rawRow[0],
1860                         name: rawRow[1],
1861                         path: rawRow[2],
1862                         desc: rawRow[3],
1863                         parent: paths[rawRow[4]],
1864                         type: rawRow[5],
1865                     };
1866                     searchIndex.push(row);
1867                     if (typeof row.name === "string") {
1868                         var word = row.name.toLowerCase();
1869                         searchWords.push(word);
1870                     } else {
1871                         searchWords.push("");
1872                     }
1873                     lastPath = row.path;
1874                     crateSize += 1;
1875                 }
1876
1877                 if (aliases) {
1878                     ALIASES[crate] = {};
1879                     var j, local_aliases;
1880                     for (var alias_name in aliases) {
1881                         if (!aliases.hasOwnProperty(alias_name)) { continue; }
1882
1883                         if (!ALIASES[crate].hasOwnProperty(alias_name)) {
1884                             ALIASES[crate][alias_name] = [];
1885                         }
1886                         local_aliases = aliases[alias_name];
1887                         for (j = 0; j < local_aliases.length; ++j) {
1888                             ALIASES[crate][alias_name].push(local_aliases[j] + currentIndex);
1889                         }
1890                     }
1891                 }
1892                 currentIndex += crateSize;
1893             }
1894             return searchWords;
1895         }
1896
1897         function startSearch() {
1898             var callback = function() {
1899                 clearInputTimeout();
1900                 if (search_input.value.length === 0) {
1901                     if (browserSupportsHistoryApi()) {
1902                         history.replaceState("", window.currentCrate + " - Rust", "?search=");
1903                     }
1904                     hideSearchResults();
1905                 } else {
1906                     searchTimeout = setTimeout(search, 500);
1907                 }
1908             };
1909             search_input.onkeyup = callback;
1910             search_input.oninput = callback;
1911             document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1912                 e.preventDefault();
1913                 clearInputTimeout();
1914                 search();
1915             };
1916             search_input.onchange = function(e) {
1917                 if (e.target !== document.activeElement) {
1918                     // To prevent doing anything when it's from a blur event.
1919                     return;
1920                 }
1921                 // Do NOT e.preventDefault() here. It will prevent pasting.
1922                 clearInputTimeout();
1923                 // zero-timeout necessary here because at the time of event handler execution the
1924                 // pasted content is not in the input field yet. Shouldn’t make any difference for
1925                 // change, though.
1926                 setTimeout(search, 0);
1927             };
1928             search_input.onpaste = search_input.onchange;
1929
1930             var selectCrate = document.getElementById("crate-search");
1931             if (selectCrate) {
1932                 selectCrate.onchange = function() {
1933                     updateLocalStorage("rustdoc-saved-filter-crate", selectCrate.value);
1934                     search(undefined, true);
1935                 };
1936             }
1937
1938             // Push and pop states are used to add search results to the browser
1939             // history.
1940             if (browserSupportsHistoryApi()) {
1941                 // Store the previous <title> so we can revert back to it later.
1942                 var previousTitle = document.title;
1943
1944                 window.addEventListener("popstate", function(e) {
1945                     var params = getQueryStringParams();
1946                     // Revert to the previous title manually since the History
1947                     // API ignores the title parameter.
1948                     document.title = previousTitle;
1949                     // When browsing forward to search results the previous
1950                     // search will be repeated, so the currentResults are
1951                     // cleared to ensure the search is successful.
1952                     currentResults = null;
1953                     // Synchronize search bar with query string state and
1954                     // perform the search. This will empty the bar if there's
1955                     // nothing there, which lets you really go back to a
1956                     // previous state with nothing in the bar.
1957                     if (params.search && params.search.length > 0) {
1958                         search_input.value = params.search;
1959                         // Some browsers fire "onpopstate" for every page load
1960                         // (Chrome), while others fire the event only when actually
1961                         // popping a state (Firefox), which is why search() is
1962                         // called both here and at the end of the startSearch()
1963                         // function.
1964                         search(e);
1965                     } else {
1966                         search_input.value = "";
1967                         // When browsing back from search results the main page
1968                         // visibility must be reset.
1969                         hideSearchResults();
1970                     }
1971                 });
1972             }
1973             search();
1974         }
1975
1976         index = buildIndex(rawSearchIndex);
1977         startSearch();
1978
1979         // Draw a convenient sidebar of known crates if we have a listing
1980         if (rootPath === "../" || rootPath === "./") {
1981             var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1982             if (sidebar) {
1983                 var div = document.createElement("div");
1984                 div.className = "block crate";
1985                 div.innerHTML = "<h3>Crates</h3>";
1986                 var ul = document.createElement("ul");
1987                 div.appendChild(ul);
1988
1989                 var crates = [];
1990                 for (var crate in rawSearchIndex) {
1991                     if (!hasOwnProperty(rawSearchIndex, crate)) {
1992                         continue;
1993                     }
1994                     crates.push(crate);
1995                 }
1996                 crates.sort();
1997                 for (var i = 0; i < crates.length; ++i) {
1998                     var klass = "crate";
1999                     if (rootPath !== "./" && crates[i] === window.currentCrate) {
2000                         klass += " current";
2001                     }
2002                     var link = document.createElement("a");
2003                     link.href = rootPath + crates[i] + "/index.html";
2004                     link.title = rawSearchIndex[crates[i]].doc;
2005                     link.className = klass;
2006                     link.textContent = crates[i];
2007
2008                     var li = document.createElement("li");
2009                     li.appendChild(link);
2010                     ul.appendChild(li);
2011                 }
2012                 sidebar.appendChild(div);
2013             }
2014         }
2015     };
2016
2017
2018     // delayed sidebar rendering.
2019     window.initSidebarItems = function(items) {
2020         var sidebar = document.getElementsByClassName("sidebar-elems")[0];
2021         var current = window.sidebarCurrent;
2022
2023         function block(shortty, longty) {
2024             var filtered = items[shortty];
2025             if (!filtered) {
2026                 return;
2027             }
2028
2029             var div = document.createElement("div");
2030             div.className = "block " + shortty;
2031             var h3 = document.createElement("h3");
2032             h3.textContent = longty;
2033             div.appendChild(h3);
2034             var ul = document.createElement("ul");
2035
2036             var length = filtered.length;
2037             for (var i = 0; i < length; ++i) {
2038                 var item = filtered[i];
2039                 var name = item[0];
2040                 var desc = item[1]; // can be null
2041
2042                 var klass = shortty;
2043                 if (name === current.name && shortty === current.ty) {
2044                     klass += " current";
2045                 }
2046                 var path;
2047                 if (shortty === "mod") {
2048                     path = name + "/index.html";
2049                 } else {
2050                     path = shortty + "." + name + ".html";
2051                 }
2052                 var link = document.createElement("a");
2053                 link.href = current.relpath + path;
2054                 link.title = desc;
2055                 link.className = klass;
2056                 link.textContent = name;
2057                 var li = document.createElement("li");
2058                 li.appendChild(link);
2059                 ul.appendChild(li);
2060             }
2061             div.appendChild(ul);
2062             if (sidebar) {
2063                 sidebar.appendChild(div);
2064             }
2065         }
2066
2067         block("primitive", "Primitive Types");
2068         block("mod", "Modules");
2069         block("macro", "Macros");
2070         block("struct", "Structs");
2071         block("enum", "Enums");
2072         block("union", "Unions");
2073         block("constant", "Constants");
2074         block("static", "Statics");
2075         block("trait", "Traits");
2076         block("fn", "Functions");
2077         block("type", "Type Definitions");
2078         block("foreigntype", "Foreign Types");
2079         block("keyword", "Keywords");
2080         block("traitalias", "Trait Aliases");
2081     };
2082
2083     window.register_implementors = function(imp) {
2084         var implementors = document.getElementById("implementors-list");
2085         var synthetic_implementors = document.getElementById("synthetic-implementors-list");
2086
2087         if (synthetic_implementors) {
2088             // This `inlined_types` variable is used to avoid having the same implementation
2089             // showing up twice. For example "String" in the "Sync" doc page.
2090             //
2091             // By the way, this is only used by and useful for traits implemented automatically
2092             // (like "Send" and "Sync").
2093             var inlined_types = new Set();
2094             onEachLazy(synthetic_implementors.getElementsByClassName("impl"), function(el) {
2095                 var aliases = el.getAttribute("aliases");
2096                 if (!aliases) {
2097                     return;
2098                 }
2099                 aliases.split(",").forEach(function(alias) {
2100                     inlined_types.add(alias);
2101                 });
2102             });
2103         }
2104
2105         var libs = Object.getOwnPropertyNames(imp);
2106         var llength = libs.length;
2107         for (var i = 0; i < llength; ++i) {
2108             if (libs[i] === currentCrate) { continue; }
2109             var structs = imp[libs[i]];
2110
2111             var slength = structs.length;
2112             struct_loop:
2113             for (var j = 0; j < slength; ++j) {
2114                 var struct = structs[j];
2115
2116                 var list = struct.synthetic ? synthetic_implementors : implementors;
2117
2118                 if (struct.synthetic) {
2119                     var stlength = struct.types.length;
2120                     for (var k = 0; k < stlength; k++) {
2121                         if (inlined_types.has(struct.types[k])) {
2122                             continue struct_loop;
2123                         }
2124                         inlined_types.add(struct.types[k]);
2125                     }
2126                 }
2127
2128                 var code = document.createElement("code");
2129                 code.innerHTML = struct.text;
2130
2131                 var x = code.getElementsByTagName("a");
2132                 var xlength = x.length;
2133                 for (var it = 0; it < xlength; it++) {
2134                     var href = x[it].getAttribute("href");
2135                     if (href && href.indexOf("http") !== 0) {
2136                         x[it].setAttribute("href", rootPath + href);
2137                     }
2138                 }
2139                 var display = document.createElement("h3");
2140                 addClass(display, "impl");
2141                 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
2142                     "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
2143                     "</tbody></table></span>";
2144                 list.appendChild(display);
2145             }
2146         }
2147     };
2148     if (window.pending_implementors) {
2149         window.register_implementors(window.pending_implementors);
2150     }
2151
2152     function labelForToggleButton(sectionIsCollapsed) {
2153         if (sectionIsCollapsed) {
2154             // button will expand the section
2155             return "+";
2156         }
2157         // button will collapse the section
2158         // note that this text is also set in the HTML template in render.rs
2159         return "\u2212"; // "\u2212" is "−" minus sign
2160     }
2161
2162     function onEveryMatchingChild(elem, className, func) {
2163         if (elem && className && func) {
2164             var length = elem.childNodes.length;
2165             var nodes = elem.childNodes;
2166             for (var i = 0; i < length; ++i) {
2167                 if (hasClass(nodes[i], className)) {
2168                     func(nodes[i]);
2169                 } else {
2170                     onEveryMatchingChild(nodes[i], className, func);
2171                 }
2172             }
2173         }
2174     }
2175
2176     function toggleAllDocs(pageId, fromAutoCollapse) {
2177         var innerToggle = document.getElementById(toggleAllDocsId);
2178         if (!innerToggle) {
2179             return;
2180         }
2181         if (hasClass(innerToggle, "will-expand")) {
2182             updateLocalStorage("rustdoc-collapse", "false");
2183             removeClass(innerToggle, "will-expand");
2184             onEveryMatchingChild(innerToggle, "inner", function(e) {
2185                 e.innerHTML = labelForToggleButton(false);
2186             });
2187             innerToggle.title = "collapse all docs";
2188             if (fromAutoCollapse !== true) {
2189                 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
2190                     collapseDocs(e, "show");
2191                 });
2192             }
2193         } else {
2194             updateLocalStorage("rustdoc-collapse", "true");
2195             addClass(innerToggle, "will-expand");
2196             onEveryMatchingChild(innerToggle, "inner", function(e) {
2197                 var parent = e.parentNode;
2198                 var superParent = null;
2199
2200                 if (parent) {
2201                     superParent = parent.parentNode;
2202                 }
2203                 if (!parent || !superParent || superParent.id !== "main" ||
2204                     hasClass(parent, "impl") === false) {
2205                     e.innerHTML = labelForToggleButton(true);
2206                 }
2207             });
2208             innerToggle.title = "expand all docs";
2209             if (fromAutoCollapse !== true) {
2210                 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
2211                     var parent = e.parentNode;
2212                     var superParent = null;
2213
2214                     if (parent) {
2215                         superParent = parent.parentNode;
2216                     }
2217                     if (!parent || !superParent || superParent.id !== "main" ||
2218                         hasClass(parent, "impl") === false) {
2219                         collapseDocs(e, "hide", pageId);
2220                     }
2221                 });
2222             }
2223         }
2224     }
2225
2226     function collapseDocs(toggle, mode, pageId) {
2227         if (!toggle || !toggle.parentNode) {
2228             return;
2229         }
2230
2231         function adjustToggle(arg) {
2232             return function(e) {
2233                 if (hasClass(e, "toggle-label")) {
2234                     if (arg) {
2235                         e.style.display = "inline-block";
2236                     } else {
2237                         e.style.display = "none";
2238                     }
2239                 }
2240                 if (hasClass(e, "inner")) {
2241                     e.innerHTML = labelForToggleButton(arg);
2242                 }
2243             };
2244         }
2245
2246         function implHider(addOrRemove, fullHide) {
2247             return function(n) {
2248                 var is_method = hasClass(n, "method") || fullHide;
2249                 if (is_method || hasClass(n, "type")) {
2250                     if (is_method === true) {
2251                         if (addOrRemove) {
2252                             addClass(n, "hidden-by-impl-hider");
2253                         } else {
2254                             removeClass(n, "hidden-by-impl-hider");
2255                         }
2256                     }
2257                     var ns = n.nextElementSibling;
2258                     while (ns && (hasClass(ns, "docblock") || hasClass(ns, "stability"))) {
2259                         if (addOrRemove) {
2260                             addClass(ns, "hidden-by-impl-hider");
2261                         } else {
2262                             removeClass(ns, "hidden-by-impl-hider");
2263                         }
2264                         ns = ns.nextElementSibling;
2265                     }
2266                 }
2267             };
2268         }
2269
2270         var relatedDoc;
2271         var action = mode;
2272         if (hasClass(toggle.parentNode, "impl") === false) {
2273             relatedDoc = toggle.parentNode.nextElementSibling;
2274             if (hasClass(relatedDoc, "stability")) {
2275                 relatedDoc = relatedDoc.nextElementSibling;
2276             }
2277             if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
2278                 if (mode === "toggle") {
2279                     if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
2280                         action = "show";
2281                     } else {
2282                         action = "hide";
2283                     }
2284                 }
2285                 if (action === "hide") {
2286                     addClass(relatedDoc, "hidden-by-usual-hider");
2287                     onEachLazy(toggle.childNodes, adjustToggle(true));
2288                     addClass(toggle.parentNode, "collapsed");
2289                 } else if (action === "show") {
2290                     removeClass(relatedDoc, "hidden-by-usual-hider");
2291                     removeClass(toggle.parentNode, "collapsed");
2292                     onEachLazy(toggle.childNodes, adjustToggle(false));
2293                 }
2294             }
2295         } else {
2296             // we are collapsing the impl block(s).
2297
2298             var parentElem = toggle.parentNode;
2299             relatedDoc = parentElem;
2300             var docblock = relatedDoc.nextElementSibling;
2301
2302             while (hasClass(relatedDoc, "impl-items") === false) {
2303                 relatedDoc = relatedDoc.nextElementSibling;
2304             }
2305
2306             if (!relatedDoc && hasClass(docblock, "docblock") === false) {
2307                 return;
2308             }
2309
2310             // Hide all functions, but not associated types/consts.
2311
2312             if (mode === "toggle") {
2313                 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2314                     hasClass(docblock, "hidden-by-impl-hider")) {
2315                     action = "show";
2316                 } else {
2317                     action = "hide";
2318                 }
2319             }
2320
2321             var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
2322             if (action === "show") {
2323                 removeClass(relatedDoc, "fns-now-collapsed");
2324                 removeClass(docblock, "hidden-by-usual-hider");
2325                 onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
2326                 onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
2327             } else if (action === "hide") {
2328                 addClass(relatedDoc, "fns-now-collapsed");
2329                 addClass(docblock, "hidden-by-usual-hider");
2330                 onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule));
2331                 onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
2332             }
2333         }
2334     }
2335
2336     function collapser(pageId, e, collapse) {
2337         // inherent impl ids are like "impl" or impl-<number>'.
2338         // they will never be hidden by default.
2339         var n = e.parentElement;
2340         if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2341             // Automatically minimize all non-inherent impls
2342             if (collapse || hasClass(n, "impl")) {
2343                 collapseDocs(e, "hide", pageId);
2344             }
2345         }
2346     }
2347
2348     function autoCollapse(pageId, collapse) {
2349         if (collapse) {
2350             toggleAllDocs(pageId, true);
2351         } else if (getSettingValue("auto-hide-trait-implementations") !== "false") {
2352             var impl_list = document.getElementById("trait-implementations-list");
2353
2354             if (impl_list !== null) {
2355                 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2356                     collapser(pageId, e, collapse);
2357                 });
2358             }
2359
2360             var blanket_list = document.getElementById("blanket-implementations-list");
2361
2362             if (blanket_list !== null) {
2363                 onEachLazy(blanket_list.getElementsByClassName("collapse-toggle"), function(e) {
2364                     collapser(pageId, e, collapse);
2365                 });
2366             }
2367         }
2368     }
2369
2370     function insertAfter(newNode, referenceNode) {
2371         referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2372     }
2373
2374     function createSimpleToggle(sectionIsCollapsed) {
2375         var toggle = document.createElement("a");
2376         toggle.href = "javascript:void(0)";
2377         toggle.className = "collapse-toggle";
2378         toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2379                            "</span>]";
2380         return toggle;
2381     }
2382
2383     function createToggle(toggle, otherMessage, fontSize, extraClass, show) {
2384         var span = document.createElement("span");
2385         span.className = "toggle-label";
2386         if (show) {
2387             span.style.display = "none";
2388         }
2389         if (!otherMessage) {
2390             span.innerHTML = "&nbsp;Expand&nbsp;description";
2391         } else {
2392             span.innerHTML = otherMessage;
2393         }
2394
2395         if (fontSize) {
2396             span.style.fontSize = fontSize;
2397         }
2398
2399         var mainToggle = toggle.cloneNode(true);
2400         mainToggle.appendChild(span);
2401
2402         var wrapper = document.createElement("div");
2403         wrapper.className = "toggle-wrapper";
2404         if (!show) {
2405             addClass(wrapper, "collapsed");
2406             var inner = mainToggle.getElementsByClassName("inner");
2407             if (inner && inner.length > 0) {
2408                 inner[0].innerHTML = "+";
2409             }
2410         }
2411         if (extraClass) {
2412             addClass(wrapper, extraClass);
2413         }
2414         wrapper.appendChild(mainToggle);
2415         return wrapper;
2416     }
2417
2418     (function() {
2419         var toggles = document.getElementById(toggleAllDocsId);
2420         if (toggles) {
2421             toggles.onclick = toggleAllDocs;
2422         }
2423
2424         var toggle = createSimpleToggle(false);
2425         var hideMethodDocs = getSettingValue("auto-hide-method-docs") === "true";
2426         var hideImplementors = getSettingValue("auto-collapse-implementors") !== "false";
2427         var pageId = getPageId();
2428
2429         var func = function(e) {
2430             var next = e.nextElementSibling;
2431             if (!next) {
2432                 return;
2433             }
2434             if (hasClass(next, "docblock") === true ||
2435                 (hasClass(next, "stability") === true &&
2436                  hasClass(next.nextElementSibling, "docblock") === true)) {
2437                 var newToggle = toggle.cloneNode(true);
2438                 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2439                 if (hideMethodDocs === true && hasClass(e, "method") === true) {
2440                     collapseDocs(newToggle, "hide", pageId);
2441                 }
2442             }
2443         };
2444
2445         var funcImpl = function(e) {
2446             var next = e.nextElementSibling;
2447             if (next && hasClass(next, "docblock")) {
2448                 next = next.nextElementSibling;
2449             }
2450             if (!next) {
2451                 return;
2452             }
2453             if (hasClass(e, "impl") &&
2454                 (next.getElementsByClassName("method").length > 0 ||
2455                  next.getElementsByClassName("associatedconstant").length > 0)) {
2456                 var newToggle = toggle.cloneNode(true);
2457                 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2458                 // In case the option "auto-collapse implementors" is not set to false, we collapse
2459                 // all implementors.
2460                 if (hideImplementors === true && e.parentNode.id === "implementors-list") {
2461                     collapseDocs(newToggle, "hide", pageId);
2462                 }
2463             }
2464         };
2465
2466         onEachLazy(document.getElementsByClassName("method"), func);
2467         onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2468         onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2469         var impl_call = function() {};
2470         if (hideMethodDocs === true) {
2471             impl_call = function(e, newToggle) {
2472                 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2473                     // Automatically minimize all non-inherent impls
2474                     if (hasClass(e, "impl") === true) {
2475                         collapseDocs(newToggle, "hide", pageId);
2476                     }
2477                 }
2478             };
2479         }
2480         var newToggle = document.createElement("a");
2481         newToggle.href = "javascript:void(0)";
2482         newToggle.className = "collapse-toggle hidden-default collapsed";
2483         newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2484                               "</span>] Show hidden undocumented items";
2485         function toggleClicked() {
2486             if (hasClass(this, "collapsed")) {
2487                 removeClass(this, "collapsed");
2488                 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2489                     if (hasClass(x, "content") === false) {
2490                         removeClass(x, "hidden");
2491                         addClass(x, "x");
2492                     }
2493                 }, true);
2494                 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2495                                  "</span>] Hide undocumented items";
2496             } else {
2497                 addClass(this, "collapsed");
2498                 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2499                     if (hasClass(x, "content") === false) {
2500                         addClass(x, "hidden");
2501                         removeClass(x, "x");
2502                     }
2503                 }, true);
2504                 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2505                                  "</span>] Show hidden undocumented items";
2506             }
2507         }
2508         onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2509             onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2510             var hiddenElems = e.getElementsByClassName("hidden");
2511             var needToggle = false;
2512
2513             var hlength = hiddenElems.length;
2514             for (var i = 0; i < hlength; ++i) {
2515                 if (hasClass(hiddenElems[i], "content") === false &&
2516                     hasClass(hiddenElems[i], "docblock") === false) {
2517                     needToggle = true;
2518                     break;
2519                 }
2520             }
2521             if (needToggle === true) {
2522                 var inner_toggle = newToggle.cloneNode(true);
2523                 inner_toggle.onclick = toggleClicked;
2524                 e.insertBefore(inner_toggle, e.firstChild);
2525                 impl_call(e.previousSibling, inner_toggle);
2526             }
2527         });
2528
2529         var currentType = document.getElementsByClassName("type-decl")[0];
2530         var className = null;
2531         if (currentType) {
2532             currentType = currentType.getElementsByClassName("rust")[0];
2533             if (currentType) {
2534                 currentType.classList.forEach(function(item) {
2535                     if (item !== "main") {
2536                         className = item;
2537                         return true;
2538                     }
2539                 });
2540             }
2541         }
2542         var showItemDeclarations = getSettingValue("auto-hide-" + className);
2543         if (showItemDeclarations === null) {
2544             if (className === "enum" || className === "macro") {
2545                 showItemDeclarations = "false";
2546             } else if (className === "struct" || className === "union" || className === "trait") {
2547                 showItemDeclarations = "true";
2548             } else {
2549                 // In case we found an unknown type, we just use the "parent" value.
2550                 showItemDeclarations = getSettingValue("auto-hide-declarations");
2551             }
2552         }
2553         showItemDeclarations = showItemDeclarations === "false";
2554         function buildToggleWrapper(e) {
2555             if (hasClass(e, "autohide")) {
2556                 var wrap = e.previousElementSibling;
2557                 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2558                     var inner_toggle = wrap.childNodes[0];
2559                     var extra = e.childNodes[0].tagName === "H3";
2560
2561                     e.style.display = "none";
2562                     addClass(wrap, "collapsed");
2563                     onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2564                         e.innerHTML = labelForToggleButton(true);
2565                     });
2566                     onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2567                         e.style.display = "inline-block";
2568                         if (extra === true) {
2569                             e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2570                         }
2571                     });
2572                 }
2573             }
2574             if (e.parentNode.id === "main") {
2575                 var otherMessage = "";
2576                 var fontSize;
2577                 var extraClass;
2578
2579                 if (hasClass(e, "type-decl")) {
2580                     fontSize = "20px";
2581                     otherMessage = "&nbsp;Show&nbsp;declaration";
2582                     if (showItemDeclarations === false) {
2583                         extraClass = "collapsed";
2584                     }
2585                 } else if (hasClass(e, "sub-variant")) {
2586                     otherMessage = "&nbsp;Show&nbsp;fields";
2587                 } else if (hasClass(e, "non-exhaustive")) {
2588                     otherMessage = "&nbsp;This&nbsp;";
2589                     if (hasClass(e, "non-exhaustive-struct")) {
2590                         otherMessage += "struct";
2591                     } else if (hasClass(e, "non-exhaustive-enum")) {
2592                         otherMessage += "enum";
2593                     } else if (hasClass(e, "non-exhaustive-variant")) {
2594                         otherMessage += "enum variant";
2595                     } else if (hasClass(e, "non-exhaustive-type")) {
2596                         otherMessage += "type";
2597                     }
2598                     otherMessage += "&nbsp;is&nbsp;marked&nbsp;as&nbsp;non-exhaustive";
2599                 } else if (hasClass(e.childNodes[0], "impl-items")) {
2600                     extraClass = "marg-left";
2601                 }
2602
2603                 e.parentNode.insertBefore(
2604                     createToggle(
2605                         toggle,
2606                         otherMessage,
2607                         fontSize,
2608                         extraClass,
2609                         hasClass(e, "type-decl") === false || showItemDeclarations === true),
2610                     e);
2611                 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2612                     collapseDocs(e.previousSibling.childNodes[0], "toggle");
2613                 }
2614                 if (hasClass(e, "non-exhaustive") === true) {
2615                     collapseDocs(e.previousSibling.childNodes[0], "toggle");
2616                 }
2617             }
2618         }
2619
2620         onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2621         onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2622         var pageId = getPageId();
2623
2624         autoCollapse(pageId, getSettingValue("collapse") === "true");
2625
2626         if (pageId !== null) {
2627             expandSection(pageId);
2628         }
2629     }());
2630
2631     function createToggleWrapper(tog) {
2632         var span = document.createElement("span");
2633         span.className = "toggle-label";
2634         span.style.display = "none";
2635         span.innerHTML = "&nbsp;Expand&nbsp;attributes";
2636         tog.appendChild(span);
2637
2638         var wrapper = document.createElement("div");
2639         wrapper.className = "toggle-wrapper toggle-attributes";
2640         wrapper.appendChild(tog);
2641         return wrapper;
2642     }
2643
2644     (function() {
2645         // To avoid checking on "rustdoc-item-attributes" value on every loop...
2646         var itemAttributesFunc = function() {};
2647         if (getSettingValue("auto-hide-attributes") !== "false") {
2648             itemAttributesFunc = function(x) {
2649                 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2650             };
2651         }
2652         var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2653         onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2654             var attr_tog = attributesToggle.cloneNode(true);
2655             if (hasClass(i_e, "top-attr") === true) {
2656                 addClass(attr_tog, "top-attr");
2657             }
2658             i_e.parentNode.insertBefore(attr_tog, i_e);
2659             itemAttributesFunc(i_e);
2660         });
2661     }());
2662
2663     (function() {
2664         // To avoid checking on "rustdoc-line-numbers" value on every loop...
2665         var lineNumbersFunc = function() {};
2666         if (getSettingValue("line-numbers") === "true") {
2667             lineNumbersFunc = function(x) {
2668                 var count = x.textContent.split("\n").length;
2669                 var elems = [];
2670                 for (var i = 0; i < count; ++i) {
2671                     elems.push(i + 1);
2672                 }
2673                 var node = document.createElement("pre");
2674                 addClass(node, "line-number");
2675                 node.innerHTML = elems.join("\n");
2676                 x.parentNode.insertBefore(node, x);
2677             };
2678         }
2679         onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2680             if (hasClass(e, "compile_fail")) {
2681                 e.addEventListener("mouseover", function() {
2682                     this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2683                 });
2684                 e.addEventListener("mouseout", function() {
2685                     this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2686                 });
2687             } else if (hasClass(e, "ignore")) {
2688                 e.addEventListener("mouseover", function() {
2689                     this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2690                 });
2691                 e.addEventListener("mouseout", function() {
2692                     this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2693                 });
2694             }
2695             lineNumbersFunc(e);
2696         });
2697     }());
2698
2699     onEachLazy(document.getElementsByClassName("notable-traits"), function(e) {
2700         e.onclick = function() {
2701             this.getElementsByClassName('notable-traits-tooltiptext')[0]
2702                 .classList.toggle("force-tooltip");
2703         };
2704     });
2705
2706     // In the search display, allows to switch between tabs.
2707     function printTab(nb) {
2708         if (nb === 0 || nb === 1 || nb === 2) {
2709             currentTab = nb;
2710         }
2711         var nb_copy = nb;
2712         onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2713             if (nb_copy === 0) {
2714                 addClass(elem, "selected");
2715             } else {
2716                 removeClass(elem, "selected");
2717             }
2718             nb_copy -= 1;
2719         });
2720         onEachLazy(document.getElementById("results").childNodes, function(elem) {
2721             if (nb === 0) {
2722                 elem.style.display = "";
2723             } else {
2724                 elem.style.display = "none";
2725             }
2726             nb -= 1;
2727         });
2728     }
2729
2730     function putBackSearch(search_input) {
2731         var search = getSearchElement();
2732         if (search_input.value !== "" && hasClass(search, "hidden")) {
2733             showSearchResults(search);
2734             if (browserSupportsHistoryApi()) {
2735                 history.replaceState(search_input.value,
2736                                      "",
2737                                      "?search=" + encodeURIComponent(search_input.value));
2738             }
2739         }
2740     }
2741
2742     function getSearchLoadingText() {
2743         return "Loading search results...";
2744     }
2745
2746     if (search_input) {
2747         search_input.onfocus = function() {
2748             putBackSearch(this);
2749         };
2750     }
2751
2752     var params = getQueryStringParams();
2753     if (params && params.search) {
2754         var search = getSearchElement();
2755         search.innerHTML = "<h3 style=\"text-align: center;\">" + getSearchLoadingText() + "</h3>";
2756         showSearchResults(search);
2757     }
2758
2759     var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2760     if (sidebar_menu) {
2761         sidebar_menu.onclick = function() {
2762             var sidebar = document.getElementsByClassName("sidebar")[0];
2763             if (hasClass(sidebar, "mobile") === true) {
2764                 hideSidebar();
2765             } else {
2766                 showSidebar();
2767             }
2768         };
2769     }
2770
2771     if (main) {
2772         onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2773             e.remove();
2774         });
2775         onEachLazy(main.childNodes, function(e) {
2776             // Unhide the actual content once loading is complete. Headers get
2777             // flex treatment for their horizontal layout, divs get block treatment
2778             // for vertical layout (column-oriented flex layout for divs caused
2779             // errors in mobile browsers).
2780             if (e.tagName === "H2" || e.tagName === "H3") {
2781                 var nextTagName = e.nextElementSibling.tagName;
2782                 if (nextTagName == "H2" || nextTagName == "H3") {
2783                     e.nextElementSibling.style.display = "flex";
2784                 } else {
2785                     e.nextElementSibling.style.display = "block";
2786                 }
2787             }
2788         });
2789     }
2790
2791     function enableSearchInput() {
2792         if (search_input) {
2793             search_input.removeAttribute('disabled');
2794         }
2795     }
2796
2797     window.addSearchOptions = function(crates) {
2798         var elem = document.getElementById("crate-search");
2799
2800         if (!elem) {
2801             enableSearchInput();
2802             return;
2803         }
2804         var crates_text = [];
2805         if (Object.keys(crates).length > 1) {
2806             for (var crate in crates) {
2807                 if (hasOwnProperty(crates, crate)) {
2808                     crates_text.push(crate);
2809                 }
2810             }
2811         }
2812         crates_text.sort(function(a, b) {
2813             var lower_a = a.toLowerCase();
2814             var lower_b = b.toLowerCase();
2815
2816             if (lower_a < lower_b) {
2817                 return -1;
2818             } else if (lower_a > lower_b) {
2819                 return 1;
2820             }
2821             return 0;
2822         });
2823         var savedCrate = getSettingValue("saved-filter-crate");
2824         for (var i = 0; i < crates_text.length; ++i) {
2825             var option = document.createElement("option");
2826             option.value = crates_text[i];
2827             option.innerText = crates_text[i];
2828             elem.appendChild(option);
2829             // Set the crate filter from saved storage, if the current page has the saved crate
2830             // filter.
2831             //
2832             // If not, ignore the crate filter -- we want to support filtering for crates on sites
2833             // like doc.rust-lang.org where the crates may differ from page to page while on the
2834             // same domain.
2835             if (crates_text[i] === savedCrate) {
2836                 elem.value = savedCrate;
2837             }
2838         }
2839         enableSearchInput();
2840     };
2841
2842     function buildHelperPopup() {
2843         var popup = document.createElement("aside");
2844         addClass(popup, "hidden");
2845         popup.id = "help";
2846
2847         var book_info = document.createElement("span");
2848         book_info.innerHTML = "You can find more information in \
2849             <a href=\"https://doc.rust-lang.org/rustdoc/\">the rustdoc book</a>.";
2850
2851         var container = document.createElement("div");
2852         var shortcuts = [
2853             ["?", "Show this help dialog"],
2854             ["S", "Focus the search field"],
2855             ["↑", "Move up in search results"],
2856             ["↓", "Move down in search results"],
2857             ["↹", "Switch tab"],
2858             ["&#9166;", "Go to active search result"],
2859             ["+", "Expand all sections"],
2860             ["-", "Collapse all sections"],
2861         ].map(x => "<dt><kbd>" + x[0] + "</kbd></dt><dd>" + x[1] + "</dd>").join("");
2862         var div_shortcuts = document.createElement("div");
2863         addClass(div_shortcuts, "shortcuts");
2864         div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>";
2865
2866         var infos = [
2867             "Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to \
2868              restrict the search to a given item kind.",
2869             "Accepted kinds are: <code>fn</code>, <code>mod</code>, <code>struct</code>, \
2870              <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, \
2871              and <code>const</code>.",
2872             "Search functions by type signature (e.g., <code>vec -&gt; usize</code> or \
2873              <code>* -&gt; vec</code>)",
2874             "Search multiple things at once by splitting your query with comma (e.g., \
2875              <code>str,u8</code> or <code>String,struct:Vec,test</code>)",
2876             "You can look for items with an exact name by putting double quotes around \
2877              your request: <code>\"string\"</code>",
2878             "Look for items inside another one by searching for a path: <code>vec::Vec</code>",
2879         ].map(x => "<p>" + x + "</p>").join("");
2880         var div_infos = document.createElement("div");
2881         addClass(div_infos, "infos");
2882         div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos;
2883
2884         container.appendChild(book_info);
2885         container.appendChild(div_shortcuts);
2886         container.appendChild(div_infos);
2887
2888         popup.appendChild(container);
2889         insertAfter(popup, getSearchElement());
2890         // So that it's only built once and then it'll do nothing when called!
2891         buildHelperPopup = function() {};
2892     }
2893
2894     onHashChange(null);
2895     window.onhashchange = onHashChange;
2896 }());
2897
2898 // This is required in firefox. Explanations: when going back in the history, firefox doesn't re-run
2899 // the JS, therefore preventing rustdoc from setting a few things required to be able to reload the
2900 // previous search results (if you navigated to a search result with the keyboard, pressed enter on
2901 // it to navigate to that result, and then came back to this page).
2902 window.onunload = function(){};