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