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