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