]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/static/main.js
Fix default value for setting "Auto-hide item methods' documentation"
[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 is_module = false;
934
935                         if (input === "*") {
936                             is_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 (is_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                         } else if (searchWords[j] === val) {
1077                             // Small trick to fix when you're looking for a one letter type
1078                             // and there are other short named types.
1079                             lev = -1;
1080                         }
1081                         if (results[fullId] === undefined) {
1082                             results[fullId] = {
1083                                 id: j,
1084                                 index: index,
1085                                 lev: lev,
1086                             };
1087                         }
1088                         results[fullId].lev = Math.min(results[fullId].lev, lev);
1089                     }
1090                 }
1091             }
1092
1093             var ret = {
1094                 "in_args": sortResults(results_in_args, true),
1095                 "returned": sortResults(results_returned, true),
1096                 "others": sortResults(results),
1097             };
1098             if (ALIASES && ALIASES[window.currentCrate] &&
1099                     ALIASES[window.currentCrate][query.raw]) {
1100                 var aliases = ALIASES[window.currentCrate][query.raw];
1101                 for (i = 0; i < aliases.length; ++i) {
1102                     aliases[i].is_alias = true;
1103                     aliases[i].alias = query.raw;
1104                     aliases[i].path = aliases[i].p;
1105                     var res = buildHrefAndPath(aliases[i]);
1106                     aliases[i].displayPath = pathSplitter(res[0]);
1107                     aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1108                     aliases[i].href = res[1];
1109                     ret.others.unshift(aliases[i]);
1110                     if (ret.others.length > MAX_RESULTS) {
1111                         ret.others.pop();
1112                     }
1113                 }
1114             }
1115             return ret;
1116         }
1117
1118         /**
1119          * Validate performs the following boolean logic. For example:
1120          * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1121          * exists in (name || path || parent) OR => ("file" && "open") exists in
1122          * (name || path )
1123          *
1124          * This could be written functionally, but I wanted to minimise
1125          * functions on stack.
1126          *
1127          * @param  {[string]} name   [The name of the result]
1128          * @param  {[string]} path   [The path of the result]
1129          * @param  {[string]} keys   [The keys to be used (["file", "open"])]
1130          * @param  {[object]} parent [The parent of the result]
1131          * @return {[boolean]}       [Whether the result is valid or not]
1132          */
1133         function validateResult(name, path, keys, parent) {
1134             for (var i = 0; i < keys.length; ++i) {
1135                 // each check is for validation so we negate the conditions and invalidate
1136                 if (!(
1137                     // check for an exact name match
1138                     name.indexOf(keys[i]) > -1 ||
1139                     // then an exact path match
1140                     path.indexOf(keys[i]) > -1 ||
1141                     // next if there is a parent, check for exact parent match
1142                     (parent !== undefined &&
1143                         parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1144                     // lastly check to see if the name was a levenshtein match
1145                     levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1146                     return false;
1147                 }
1148             }
1149             return true;
1150         }
1151
1152         function getQuery(raw) {
1153             var matches, type, query;
1154             query = raw;
1155
1156             matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1157             if (matches) {
1158                 type = matches[1].replace(/^const$/, "constant");
1159                 query = query.substring(matches[0].length);
1160             }
1161
1162             return {
1163                 raw: raw,
1164                 query: query,
1165                 type: type,
1166                 id: query + type
1167             };
1168         }
1169
1170         function initSearchNav() {
1171             var hoverTimeout;
1172
1173             var click_func = function(e) {
1174                 var el = e.target;
1175                 // to retrieve the real "owner" of the event.
1176                 while (el.tagName !== "TR") {
1177                     el = el.parentNode;
1178                 }
1179                 var dst = e.target.getElementsByTagName("a");
1180                 if (dst.length < 1) {
1181                     return;
1182                 }
1183                 dst = dst[0];
1184                 if (window.location.pathname === dst.pathname) {
1185                     addClass(document.getElementById("search"), "hidden");
1186                     removeClass(main, "hidden");
1187                     document.location.href = dst.href;
1188                 }
1189             };
1190             var mouseover_func = function(e) {
1191                 var el = e.target;
1192                 // to retrieve the real "owner" of the event.
1193                 while (el.tagName !== "TR") {
1194                     el = el.parentNode;
1195                 }
1196                 clearTimeout(hoverTimeout);
1197                 hoverTimeout = setTimeout(function() {
1198                     onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1199                         onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1200                             removeClass(i_e, "highlighted");
1201                         });
1202                     });
1203                     addClass(el, "highlighted");
1204                 }, 20);
1205             };
1206             onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1207                 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1208                     i_e.onclick = click_func;
1209                     i_e.onmouseover = mouseover_func;
1210                 });
1211             });
1212
1213             search_input.onkeydown = function(e) {
1214                 // "actives" references the currently highlighted item in each search tab.
1215                 // Each array in "actives" represents a tab.
1216                 var actives = [[], [], []];
1217                 // "current" is used to know which tab we're looking into.
1218                 var current = 0;
1219                 onEachLazy(document.getElementById("results").childNodes, function(e) {
1220                     onEachLazy(e.getElementsByClassName("highlighted"), function(e) {
1221                         actives[current].push(e);
1222                     });
1223                     current += 1;
1224                 });
1225
1226                 if (e.which === 38) { // up
1227                     if (!actives[currentTab].length ||
1228                         !actives[currentTab][0].previousElementSibling) {
1229                         return;
1230                     }
1231
1232                     addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1233                     removeClass(actives[currentTab][0], "highlighted");
1234                 } else if (e.which === 40) { // down
1235                     if (!actives[currentTab].length) {
1236                         var results = document.getElementById("results").childNodes;
1237                         if (results.length > 0) {
1238                             var res = results[currentTab].getElementsByClassName("result");
1239                             if (res.length > 0) {
1240                                 addClass(res[0], "highlighted");
1241                             }
1242                         }
1243                     } else if (actives[currentTab][0].nextElementSibling) {
1244                         addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1245                         removeClass(actives[currentTab][0], "highlighted");
1246                     }
1247                 } else if (e.which === 13) { // return
1248                     if (actives[currentTab].length) {
1249                         document.location.href =
1250                             actives[currentTab][0].getElementsByTagName("a")[0].href;
1251                     }
1252                 } else if (e.which === 9) { // tab
1253                     if (e.shiftKey) {
1254                         printTab(currentTab > 0 ? currentTab - 1 : 2);
1255                     } else {
1256                         printTab(currentTab > 1 ? 0 : currentTab + 1);
1257                     }
1258                     e.preventDefault();
1259                 } else if (e.which === 16) { // shift
1260                     // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1261                 } else if (e.which === 27) { // escape
1262                     removeClass(actives[currentTab][0], "highlighted");
1263                     search_input.value = "";
1264                     defocusSearchBar();
1265                 } else if (actives[currentTab].length > 0) {
1266                     removeClass(actives[currentTab][0], "highlighted");
1267                 }
1268             };
1269         }
1270
1271         function buildHrefAndPath(item) {
1272             var displayPath;
1273             var href;
1274             var type = itemTypes[item.ty];
1275             var name = item.name;
1276
1277             if (type === "mod") {
1278                 displayPath = item.path + "::";
1279                 href = rootPath + item.path.replace(/::/g, "/") + "/" +
1280                        name + "/index.html";
1281             } else if (type === "primitive" || type === "keyword") {
1282                 displayPath = "";
1283                 href = rootPath + item.path.replace(/::/g, "/") +
1284                        "/" + type + "." + name + ".html";
1285             } else if (type === "externcrate") {
1286                 displayPath = "";
1287                 href = rootPath + name + "/index.html";
1288             } else if (item.parent !== undefined) {
1289                 var myparent = item.parent;
1290                 var anchor = "#" + type + "." + name;
1291                 var parentType = itemTypes[myparent.ty];
1292                 if (parentType === "primitive") {
1293                     displayPath = myparent.name + "::";
1294                 } else {
1295                     displayPath = item.path + "::" + myparent.name + "::";
1296                 }
1297                 href = rootPath + item.path.replace(/::/g, "/") +
1298                        "/" + parentType +
1299                        "." + myparent.name +
1300                        ".html" + anchor;
1301             } else {
1302                 displayPath = item.path + "::";
1303                 href = rootPath + item.path.replace(/::/g, "/") +
1304                        "/" + type + "." + name + ".html";
1305             }
1306             return [displayPath, href];
1307         }
1308
1309         function escape(content) {
1310             var h1 = document.createElement("h1");
1311             h1.textContent = content;
1312             return h1.innerHTML;
1313         }
1314
1315         function pathSplitter(path) {
1316             var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1317             if (tmp.endsWith("<span>")) {
1318                 return tmp.slice(0, tmp.length - 6);
1319             }
1320             return tmp;
1321         }
1322
1323         function addTab(array, query, display) {
1324             var extraStyle = "";
1325             if (display === false) {
1326                 extraStyle = " style=\"display: none;\"";
1327             }
1328
1329             var output = "";
1330             var duplicates = {};
1331             var length = 0;
1332             if (array.length > 0) {
1333                 output = "<table class=\"search-results\"" + extraStyle + ">";
1334
1335                 array.forEach(function(item) {
1336                     var name, type;
1337
1338                     name = item.name;
1339                     type = itemTypes[item.ty];
1340
1341                     if (item.is_alias !== true) {
1342                         if (duplicates[item.fullPath]) {
1343                             return;
1344                         }
1345                         duplicates[item.fullPath] = true;
1346                     }
1347                     length += 1;
1348
1349                     output += "<tr class=\"" + type + " result\"><td>" +
1350                               "<a href=\"" + item.href + "\">" +
1351                               (item.is_alias === true ?
1352                                ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1353                                   "class=\"grey\"><i>&nbsp;- see&nbsp;</i></span>") : "") +
1354                               item.displayPath + "<span class=\"" + type + "\">" +
1355                               name + "</span></a></td><td>" +
1356                               "<a href=\"" + item.href + "\">" +
1357                               "<span class=\"desc\">" + escape(item.desc) +
1358                               "&nbsp;</span></a></td></tr>";
1359                 });
1360                 output += "</table>";
1361             } else {
1362                 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1363                     "Try on <a href=\"https://duckduckgo.com/?q=" +
1364                     encodeURIComponent("rust " + query.query) +
1365                     "\">DuckDuckGo</a>?<br/><br/>" +
1366                     "Or try looking in one of these:<ul><li>The <a " +
1367                     "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1368                     " for technical details about the language.</li><li><a " +
1369                     "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1370                     "Example</a> for expository code examples.</a></li><li>The <a " +
1371                     "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1372                     "introductions to language features and the language itself.</li><li><a " +
1373                     "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1374                     " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1375             }
1376             return [output, length];
1377         }
1378
1379         function makeTabHeader(tabNb, text, nbElems) {
1380             if (currentTab === tabNb) {
1381                 return "<div class=\"selected\">" + text +
1382                        " <div class=\"count\">(" + nbElems + ")</div></div>";
1383             }
1384             return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1385         }
1386
1387         function showResults(results) {
1388             if (results.others.length === 1 &&
1389                 getCurrentValue("rustdoc-go-to-only-result") === "true") {
1390                 var elem = document.createElement("a");
1391                 elem.href = results.others[0].href;
1392                 elem.style.display = "none";
1393                 // For firefox, we need the element to be in the DOM so it can be clicked.
1394                 document.body.appendChild(elem);
1395                 elem.click();
1396             }
1397             var query = getQuery(search_input.value);
1398
1399             currentResults = query.id;
1400
1401             var ret_others = addTab(results.others, query);
1402             var ret_in_args = addTab(results.in_args, query, false);
1403             var ret_returned = addTab(results.returned, query, false);
1404
1405             var output = "<h1>Results for " + escape(query.query) +
1406                 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1407                 "<div id=\"titles\">" +
1408                 makeTabHeader(0, "In Names", ret_others[1]) +
1409                 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1410                 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1411                 "</div><div id=\"results\">" +
1412                 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1413
1414             addClass(main, "hidden");
1415             var search = document.getElementById("search");
1416             removeClass(search, "hidden");
1417             search.innerHTML = output;
1418             var tds = search.getElementsByTagName("td");
1419             var td_width = 0;
1420             if (tds.length > 0) {
1421                 td_width = tds[0].offsetWidth;
1422             }
1423             var width = search.offsetWidth - 40 - td_width;
1424             onEachLazy(search.getElementsByClassName("desc"), function(e) {
1425                 e.style.width = width + "px";
1426             });
1427             initSearchNav();
1428             var elems = document.getElementById("titles").childNodes;
1429             elems[0].onclick = function() { printTab(0); };
1430             elems[1].onclick = function() { printTab(1); };
1431             elems[2].onclick = function() { printTab(2); };
1432             printTab(currentTab);
1433         }
1434
1435         function execSearch(query, searchWords, filterCrates) {
1436             function getSmallest(arrays, positions, notDuplicates) {
1437                 var start = null;
1438
1439                 for (var it = 0; it < positions.length; ++it) {
1440                     if (arrays[it].length > positions[it] &&
1441                         (start === null || start > arrays[it][positions[it]].lev) &&
1442                         !notDuplicates[arrays[it][positions[it]].fullPath]) {
1443                         start = arrays[it][positions[it]].lev;
1444                     }
1445                 }
1446                 return start;
1447             }
1448
1449             function mergeArrays(arrays) {
1450                 var ret = [];
1451                 var positions = [];
1452                 var notDuplicates = {};
1453
1454                 for (var x = 0; x < arrays.length; ++x) {
1455                     positions.push(0);
1456                 }
1457                 while (ret.length < MAX_RESULTS) {
1458                     var smallest = getSmallest(arrays, positions, notDuplicates);
1459
1460                     if (smallest === null) {
1461                         break;
1462                     }
1463                     for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1464                         if (arrays[x].length > positions[x] &&
1465                                 arrays[x][positions[x]].lev === smallest &&
1466                                 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1467                             ret.push(arrays[x][positions[x]]);
1468                             notDuplicates[arrays[x][positions[x]].fullPath] = true;
1469                             positions[x] += 1;
1470                         }
1471                     }
1472                 }
1473                 return ret;
1474             }
1475
1476             var queries = query.raw.split(",");
1477             var results = {
1478                 "in_args": [],
1479                 "returned": [],
1480                 "others": [],
1481             };
1482
1483             for (var i = 0; i < queries.length; ++i) {
1484                 query = queries[i].trim();
1485                 if (query.length !== 0) {
1486                     var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1487
1488                     results.in_args.push(tmp.in_args);
1489                     results.returned.push(tmp.returned);
1490                     results.others.push(tmp.others);
1491                 }
1492             }
1493             if (queries.length > 1) {
1494                 return {
1495                     "in_args": mergeArrays(results.in_args),
1496                     "returned": mergeArrays(results.returned),
1497                     "others": mergeArrays(results.others),
1498                 };
1499             } else {
1500                 return {
1501                     "in_args": results.in_args[0],
1502                     "returned": results.returned[0],
1503                     "others": results.others[0],
1504                 };
1505             }
1506         }
1507
1508         function getFilterCrates() {
1509             var elem = document.getElementById("crate-search");
1510
1511             if (elem && elem.value !== "All crates" && rawSearchIndex.hasOwnProperty(elem.value)) {
1512                 return elem.value;
1513             }
1514             return undefined;
1515         }
1516
1517         function search(e, forced) {
1518             var params = getQueryStringParams();
1519             var query = getQuery(search_input.value.trim());
1520
1521             if (e) {
1522                 e.preventDefault();
1523             }
1524
1525             if (query.query.length === 0) {
1526                 return;
1527             }
1528             if (forced !== true && query.id === currentResults) {
1529                 if (query.query.length > 0) {
1530                     putBackSearch(search_input);
1531                 }
1532                 return;
1533             }
1534
1535             // Update document title to maintain a meaningful browser history
1536             document.title = "Results for " + query.query + " - Rust";
1537
1538             // Because searching is incremental by character, only the most
1539             // recent search query is added to the browser history.
1540             if (browserSupportsHistoryApi()) {
1541                 if (!history.state && !params.search) {
1542                     history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1543                 } else {
1544                     history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1545                 }
1546             }
1547
1548             var filterCrates = getFilterCrates();
1549             showResults(execSearch(query, index, filterCrates), filterCrates);
1550         }
1551
1552         function buildIndex(rawSearchIndex) {
1553             searchIndex = [];
1554             var searchWords = [];
1555             var i;
1556
1557             for (var crate in rawSearchIndex) {
1558                 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1559
1560                 searchWords.push(crate);
1561                 searchIndex.push({
1562                     crate: crate,
1563                     ty: 1, // == ExternCrate
1564                     name: crate,
1565                     path: "",
1566                     desc: rawSearchIndex[crate].doc,
1567                     type: null,
1568                 });
1569
1570                 // an array of [(Number) item type,
1571                 //              (String) name,
1572                 //              (String) full path or empty string for previous path,
1573                 //              (String) description,
1574                 //              (Number | null) the parent path index to `paths`]
1575                 //              (Object | null) the type of the function (if any)
1576                 var items = rawSearchIndex[crate].i;
1577                 // an array of [(Number) item type,
1578                 //              (String) name]
1579                 var paths = rawSearchIndex[crate].p;
1580
1581                 // convert `paths` into an object form
1582                 var len = paths.length;
1583                 for (i = 0; i < len; ++i) {
1584                     paths[i] = {ty: paths[i][0], name: paths[i][1]};
1585                 }
1586
1587                 // convert `items` into an object form, and construct word indices.
1588                 //
1589                 // before any analysis is performed lets gather the search terms to
1590                 // search against apart from the rest of the data.  This is a quick
1591                 // operation that is cached for the life of the page state so that
1592                 // all other search operations have access to this cached data for
1593                 // faster analysis operations
1594                 len = items.length;
1595                 var lastPath = "";
1596                 for (i = 0; i < len; ++i) {
1597                     var rawRow = items[i];
1598                     var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1599                                path: rawRow[2] || lastPath, desc: rawRow[3],
1600                                parent: paths[rawRow[4]], type: rawRow[5]};
1601                     searchIndex.push(row);
1602                     if (typeof row.name === "string") {
1603                         var word = row.name.toLowerCase();
1604                         searchWords.push(word);
1605                     } else {
1606                         searchWords.push("");
1607                     }
1608                     lastPath = row.path;
1609                 }
1610             }
1611             return searchWords;
1612         }
1613
1614         function startSearch() {
1615             var searchTimeout;
1616             var callback = function() {
1617                 clearTimeout(searchTimeout);
1618                 if (search_input.value.length === 0) {
1619                     if (browserSupportsHistoryApi()) {
1620                         history.replaceState("", window.currentCrate + " - Rust", "?search=");
1621                     }
1622                     if (hasClass(main, "content")) {
1623                         removeClass(main, "hidden");
1624                     }
1625                     var search_c = document.getElementById("search");
1626                     if (hasClass(search_c, "content")) {
1627                         addClass(search_c, "hidden");
1628                     }
1629                 } else {
1630                     searchTimeout = setTimeout(search, 500);
1631                 }
1632             };
1633             search_input.onkeyup = callback;
1634             search_input.oninput = callback;
1635             document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1636                 e.preventDefault();
1637                 clearTimeout(searchTimeout);
1638                 search();
1639             };
1640             search_input.onchange = function(e) {
1641                 // Do NOT e.preventDefault() here. It will prevent pasting.
1642                 clearTimeout(searchTimeout);
1643                 // zero-timeout necessary here because at the time of event handler execution the
1644                 // pasted content is not in the input field yet. Shouldn’t make any difference for
1645                 // change, though.
1646                 setTimeout(search, 0);
1647             };
1648             search_input.onpaste = search_input.onchange;
1649
1650             var selectCrate = document.getElementById('crate-search');
1651             if (selectCrate) {
1652                 selectCrate.onchange = function() {
1653                     search(undefined, true);
1654                 };
1655             }
1656
1657             // Push and pop states are used to add search results to the browser
1658             // history.
1659             if (browserSupportsHistoryApi()) {
1660                 // Store the previous <title> so we can revert back to it later.
1661                 var previousTitle = document.title;
1662
1663                 window.onpopstate = function(e) {
1664                     var params = getQueryStringParams();
1665                     // When browsing back from search results the main page
1666                     // visibility must be reset.
1667                     if (!params.search) {
1668                         if (hasClass(main, "content")) {
1669                             removeClass(main, "hidden");
1670                         }
1671                         var search_c = document.getElementById("search");
1672                         if (hasClass(search_c, "content")) {
1673                             addClass(search_c, "hidden");
1674                         }
1675                     }
1676                     // Revert to the previous title manually since the History
1677                     // API ignores the title parameter.
1678                     document.title = previousTitle;
1679                     // When browsing forward to search results the previous
1680                     // search will be repeated, so the currentResults are
1681                     // cleared to ensure the search is successful.
1682                     currentResults = null;
1683                     // Synchronize search bar with query string state and
1684                     // perform the search. This will empty the bar if there's
1685                     // nothing there, which lets you really go back to a
1686                     // previous state with nothing in the bar.
1687                     if (params.search) {
1688                         search_input.value = params.search;
1689                     } else {
1690                         search_input.value = "";
1691                     }
1692                     // Some browsers fire "onpopstate" for every page load
1693                     // (Chrome), while others fire the event only when actually
1694                     // popping a state (Firefox), which is why search() is
1695                     // called both here and at the end of the startSearch()
1696                     // function.
1697                     search();
1698                 };
1699             }
1700             search();
1701         }
1702
1703         index = buildIndex(rawSearchIndex);
1704         startSearch();
1705
1706         // Draw a convenient sidebar of known crates if we have a listing
1707         if (rootPath === "../" || rootPath === "./") {
1708             var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1709             if (sidebar) {
1710                 var div = document.createElement("div");
1711                 div.className = "block crate";
1712                 div.innerHTML = "<h3>Crates</h3>";
1713                 var ul = document.createElement("ul");
1714                 div.appendChild(ul);
1715
1716                 var crates = [];
1717                 for (var crate in rawSearchIndex) {
1718                     if (!rawSearchIndex.hasOwnProperty(crate)) {
1719                         continue;
1720                     }
1721                     crates.push(crate);
1722                 }
1723                 crates.sort();
1724                 for (var i = 0; i < crates.length; ++i) {
1725                     var klass = "crate";
1726                     if (rootPath !== "./" && crates[i] === window.currentCrate) {
1727                         klass += " current";
1728                     }
1729                     var link = document.createElement("a");
1730                     link.href = rootPath + crates[i] + "/index.html";
1731                     link.title = rawSearchIndex[crates[i]].doc;
1732                     link.className = klass;
1733                     link.textContent = crates[i];
1734
1735                     var li = document.createElement("li");
1736                     li.appendChild(link);
1737                     ul.appendChild(li);
1738                 }
1739                 sidebar.appendChild(div);
1740             }
1741         }
1742     }
1743
1744     window.initSearch = initSearch;
1745
1746     // delayed sidebar rendering.
1747     function initSidebarItems(items) {
1748         var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1749         var current = window.sidebarCurrent;
1750
1751         function block(shortty, longty) {
1752             var filtered = items[shortty];
1753             if (!filtered) {
1754                 return;
1755             }
1756
1757             var div = document.createElement("div");
1758             div.className = "block " + shortty;
1759             var h3 = document.createElement("h3");
1760             h3.textContent = longty;
1761             div.appendChild(h3);
1762             var ul = document.createElement("ul");
1763
1764             var length = filtered.length;
1765             for (var i = 0; i < length; ++i) {
1766                 var item = filtered[i];
1767                 var name = item[0];
1768                 var desc = item[1]; // can be null
1769
1770                 var klass = shortty;
1771                 if (name === current.name && shortty === current.ty) {
1772                     klass += " current";
1773                 }
1774                 var path;
1775                 if (shortty === "mod") {
1776                     path = name + "/index.html";
1777                 } else {
1778                     path = shortty + "." + name + ".html";
1779                 }
1780                 var link = document.createElement("a");
1781                 link.href = current.relpath + path;
1782                 link.title = desc;
1783                 link.className = klass;
1784                 link.textContent = name;
1785                 var li = document.createElement("li");
1786                 li.appendChild(link);
1787                 ul.appendChild(li);
1788             }
1789             div.appendChild(ul);
1790             if (sidebar) {
1791                 sidebar.appendChild(div);
1792             }
1793         }
1794
1795         block("primitive", "Primitive Types");
1796         block("mod", "Modules");
1797         block("macro", "Macros");
1798         block("struct", "Structs");
1799         block("enum", "Enums");
1800         block("union", "Unions");
1801         block("constant", "Constants");
1802         block("static", "Statics");
1803         block("trait", "Traits");
1804         block("fn", "Functions");
1805         block("type", "Type Definitions");
1806         block("foreigntype", "Foreign Types");
1807         block("keyword", "Keywords");
1808         block("traitalias", "Trait Aliases");
1809     }
1810
1811     window.initSidebarItems = initSidebarItems;
1812
1813     window.register_implementors = function(imp) {
1814         var implementors = document.getElementById("implementors-list");
1815         var synthetic_implementors = document.getElementById("synthetic-implementors-list");
1816
1817         var libs = Object.getOwnPropertyNames(imp);
1818         var llength = libs.length;
1819         for (var i = 0; i < llength; ++i) {
1820             if (libs[i] === currentCrate) { continue; }
1821             var structs = imp[libs[i]];
1822
1823             var slength = structs.length;
1824             struct_loop:
1825             for (var j = 0; j < slength; ++j) {
1826                 var struct = structs[j];
1827
1828                 var list = struct.synthetic ? synthetic_implementors : implementors;
1829
1830                 if (struct.synthetic) {
1831                     var stlength = struct.types.length;
1832                     for (var k = 0; k < stlength; k++) {
1833                         if (window.inlined_types.has(struct.types[k])) {
1834                             continue struct_loop;
1835                         }
1836                         window.inlined_types.add(struct.types[k]);
1837                     }
1838                 }
1839
1840                 var code = document.createElement("code");
1841                 code.innerHTML = struct.text;
1842
1843                 var x = code.getElementsByTagName("a");
1844                 var xlength = x.length;
1845                 for (var it = 0; it < xlength; it++) {
1846                     var href = x[it].getAttribute("href");
1847                     if (href && href.indexOf("http") !== 0) {
1848                         x[it].setAttribute("href", rootPath + href);
1849                     }
1850                 }
1851                 var display = document.createElement("h3");
1852                 addClass(display, "impl");
1853                 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
1854                     "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
1855                     "</tbody></table></span>";
1856                 list.appendChild(display);
1857             }
1858         }
1859     };
1860     if (window.pending_implementors) {
1861         window.register_implementors(window.pending_implementors);
1862     }
1863
1864     function labelForToggleButton(sectionIsCollapsed) {
1865         if (sectionIsCollapsed) {
1866             // button will expand the section
1867             return "+";
1868         }
1869         // button will collapse the section
1870         // note that this text is also set in the HTML template in render.rs
1871         return "\u2212"; // "\u2212" is "−" minus sign
1872     }
1873
1874     function onEveryMatchingChild(elem, className, func) {
1875         if (elem && className && func) {
1876             var length = elem.childNodes.length;
1877             var nodes = elem.childNodes;
1878             for (var i = 0; i < length; ++i) {
1879                 if (hasClass(nodes[i], className)) {
1880                     func(nodes[i]);
1881                 } else {
1882                     onEveryMatchingChild(nodes[i], className, func);
1883                 }
1884             }
1885         }
1886     }
1887
1888     function toggleAllDocs(pageId, fromAutoCollapse) {
1889         var innerToggle = document.getElementById("toggle-all-docs");
1890         if (!innerToggle) {
1891             return;
1892         }
1893         if (hasClass(innerToggle, "will-expand")) {
1894             updateLocalStorage("rustdoc-collapse", "false");
1895             removeClass(innerToggle, "will-expand");
1896             onEveryMatchingChild(innerToggle, "inner", function(e) {
1897                 e.innerHTML = labelForToggleButton(false);
1898             });
1899             innerToggle.title = "collapse all docs";
1900             if (fromAutoCollapse !== true) {
1901                 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1902                     collapseDocs(e, "show");
1903                 });
1904             }
1905         } else {
1906             updateLocalStorage("rustdoc-collapse", "true");
1907             addClass(innerToggle, "will-expand");
1908             onEveryMatchingChild(innerToggle, "inner", function(e) {
1909                 var parent = e.parentNode;
1910                 var superParent = null;
1911
1912                 if (parent) {
1913                     superParent = parent.parentNode;
1914                 }
1915                 if (!parent || !superParent || superParent.id !== "main" ||
1916                     hasClass(parent, "impl") === false) {
1917                     e.innerHTML = labelForToggleButton(true);
1918                 }
1919             });
1920             innerToggle.title = "expand all docs";
1921             if (fromAutoCollapse !== true) {
1922                 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
1923                     var parent = e.parentNode;
1924                     var superParent = null;
1925
1926                     if (parent) {
1927                         superParent = parent.parentNode;
1928                     }
1929                     if (!parent || !superParent || superParent.id !== "main" ||
1930                         hasClass(parent, "impl") === false) {
1931                         collapseDocs(e, "hide", pageId);
1932                     }
1933                 });
1934             }
1935         }
1936     }
1937
1938     function collapseDocs(toggle, mode, pageId) {
1939         if (!toggle || !toggle.parentNode) {
1940             return;
1941         }
1942
1943         function adjustToggle(arg) {
1944             return function(e) {
1945                 if (hasClass(e, "toggle-label")) {
1946                     if (arg) {
1947                         e.style.display = "inline-block";
1948                     } else {
1949                         e.style.display = "none";
1950                     }
1951                 }
1952                 if (hasClass(e, "inner")) {
1953                     e.innerHTML = labelForToggleButton(arg);
1954                 }
1955             };
1956         }
1957
1958         function implHider(addOrRemove, fullHide) {
1959             return function(n) {
1960                 var is_method = hasClass(n, "method") || fullHide;
1961                 if (is_method || hasClass(n, "type")) {
1962                     if (is_method === true) {
1963                         if (addOrRemove) {
1964                             addClass(n, "hidden-by-impl-hider");
1965                         } else {
1966                             removeClass(n, "hidden-by-impl-hider");
1967                         }
1968                     }
1969                     var ns = n.nextElementSibling;
1970                     while (true) {
1971                         if (ns && (
1972                                 hasClass(ns, "docblock") ||
1973                                 hasClass(ns, "stability"))) {
1974                             if (addOrRemove) {
1975                                 addClass(ns, "hidden-by-impl-hider");
1976                             } else {
1977                                 removeClass(ns, "hidden-by-impl-hider");
1978                             }
1979                             ns = ns.nextElementSibling;
1980                             continue;
1981                         }
1982                         break;
1983                     }
1984                 }
1985             };
1986         }
1987
1988         var relatedDoc;
1989         var action = mode;
1990         if (hasClass(toggle.parentNode, "impl") === false) {
1991             relatedDoc = toggle.parentNode.nextElementSibling;
1992             if (hasClass(relatedDoc, "stability")) {
1993                 relatedDoc = relatedDoc.nextElementSibling;
1994             }
1995             if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1996                 if (mode === "toggle") {
1997                     if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1998                         action = "show";
1999                     } else {
2000                         action = "hide";
2001                     }
2002                 }
2003                 if (action === "hide") {
2004                     addClass(relatedDoc, "hidden-by-usual-hider");
2005                     onEachLazy(toggle.childNodes, adjustToggle(true));
2006                     addClass(toggle.parentNode, "collapsed");
2007                 } else if (action === "show") {
2008                     removeClass(relatedDoc, "hidden-by-usual-hider");
2009                     removeClass(toggle.parentNode, "collapsed");
2010                     onEachLazy(toggle.childNodes, adjustToggle(false));
2011                 }
2012             }
2013         } else {
2014             // we are collapsing the impl block(s).
2015
2016             var parentElem = toggle.parentNode;
2017             relatedDoc = parentElem;
2018             var docblock = relatedDoc.nextElementSibling;
2019
2020             while (hasClass(relatedDoc, "impl-items") === false) {
2021                 relatedDoc = relatedDoc.nextElementSibling;
2022             }
2023
2024             if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
2025                 (pageId && document.getElementById(pageId))) {
2026                 return;
2027             }
2028
2029             // Hide all functions, but not associated types/consts.
2030
2031             if (mode === "toggle") {
2032                 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2033                     hasClass(docblock, "hidden-by-impl-hider")) {
2034                     action = "show";
2035                 } else {
2036                     action = "hide";
2037                 }
2038             }
2039
2040             var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
2041             if (action === "show") {
2042                 removeClass(relatedDoc, "fns-now-collapsed");
2043                 removeClass(docblock, "hidden-by-usual-hider");
2044                 onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
2045                 onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
2046             } else if (action === "hide") {
2047                 addClass(relatedDoc, "fns-now-collapsed");
2048                 addClass(docblock, "hidden-by-usual-hider");
2049                 onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule));
2050                 onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
2051             }
2052         }
2053     }
2054
2055     function collapser(e, collapse) {
2056         // inherent impl ids are like "impl" or impl-<number>'.
2057         // they will never be hidden by default.
2058         var n = e.parentElement;
2059         if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2060             // Automatically minimize all non-inherent impls
2061             if (collapse || hasClass(n, "impl")) {
2062                 collapseDocs(e, "hide", pageId);
2063             }
2064         }
2065     }
2066
2067     function autoCollapse(pageId, collapse) {
2068         if (collapse) {
2069             toggleAllDocs(pageId, true);
2070         } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
2071             var impl_list = document.getElementById("implementations-list");
2072
2073             if (impl_list !== null) {
2074                 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2075                     collapser(e, collapse);
2076                 });
2077             }
2078
2079             var blanket_list = document.getElementById("blanket-implementations-list");
2080
2081             if (blanket_list !== null) {
2082                 onEachLazy(blanket_list.getElementsByClassName("collapse-toggle"), function(e) {
2083                     collapser(e, collapse);
2084                 });
2085             }
2086         }
2087     }
2088
2089     var toggles = document.getElementById("toggle-all-docs");
2090     if (toggles) {
2091         toggles.onclick = toggleAllDocs;
2092     }
2093
2094     function insertAfter(newNode, referenceNode) {
2095         referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2096     }
2097
2098     function createSimpleToggle(sectionIsCollapsed) {
2099         var toggle = document.createElement("a");
2100         toggle.href = "javascript:void(0)";
2101         toggle.className = "collapse-toggle";
2102         toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2103                            "</span>]";
2104         return toggle;
2105     }
2106
2107     var toggle = createSimpleToggle(false);
2108     var hideMethodDocs = getCurrentValue("rustdoc-method-docs") === "true";
2109     var pageId = getPageId();
2110
2111     var func = function(e) {
2112         var next = e.nextElementSibling;
2113         if (!next) {
2114             return;
2115         }
2116         if (hasClass(next, "docblock") === true ||
2117             (hasClass(next, "stability") === true &&
2118              hasClass(next.nextElementSibling, "docblock") === true)) {
2119             var newToggle = toggle.cloneNode(true);
2120             insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2121             if (hideMethodDocs === true && hasClass(e, "method") === true) {
2122                 collapseDocs(newToggle, "hide", pageId);
2123             }
2124         }
2125     };
2126
2127     var funcImpl = function(e) {
2128         var next = e.nextElementSibling;
2129         if (next && hasClass(next, "docblock")) {
2130             next = next.nextElementSibling;
2131         }
2132         if (!next) {
2133             return;
2134         }
2135         if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
2136             insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2137         }
2138     };
2139
2140     onEachLazy(document.getElementsByClassName("method"), func);
2141     onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2142     onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2143     var impl_call = function() {};
2144     if (hideMethodDocs === true) {
2145         impl_call = function(e, newToggle, pageId) {
2146             if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2147                 // Automatically minimize all non-inherent impls
2148                 if (hasClass(e, "impl") === true) {
2149                     collapseDocs(newToggle, "hide", pageId);
2150                 }
2151             }
2152         };
2153     }
2154     var newToggle = document.createElement("a");
2155     newToggle.href = "javascript:void(0)";
2156     newToggle.className = "collapse-toggle hidden-default collapsed";
2157     newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2158                           "</span>] Show hidden undocumented items";
2159     function toggleClicked() {
2160         if (hasClass(this, "collapsed")) {
2161             removeClass(this, "collapsed");
2162             onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2163                 if (hasClass(x, "content") === false) {
2164                     removeClass(x, "hidden");
2165                     addClass(x, "x");
2166                 }
2167             }, true);
2168             this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2169                              "</span>] Hide undocumented items";
2170         } else {
2171             addClass(this, "collapsed");
2172             onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2173                 if (hasClass(x, "content") === false) {
2174                     addClass(x, "hidden");
2175                     removeClass(x, "x");
2176                 }
2177             }, true);
2178             this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2179                              "</span>] Show hidden undocumented items";
2180         }
2181     }
2182     onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2183         onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2184         var hiddenElems = e.getElementsByClassName("hidden");
2185         var needToggle = false;
2186
2187         var hlength = hiddenElems.length;
2188         for (var i = 0; i < hlength; ++i) {
2189             if (hasClass(hiddenElems[i], "content") === false &&
2190                 hasClass(hiddenElems[i], "docblock") === false) {
2191                 needToggle = true;
2192                 break;
2193             }
2194         }
2195         if (needToggle === true) {
2196             var inner_toggle = newToggle.cloneNode(true);
2197             inner_toggle.onclick = toggleClicked;
2198             e.insertBefore(inner_toggle, e.firstChild);
2199             impl_call(e.previousSibling, inner_toggle, pageId);
2200         }
2201     });
2202
2203     function createToggle(otherMessage, fontSize, extraClass, show) {
2204         var span = document.createElement("span");
2205         span.className = "toggle-label";
2206         if (show) {
2207             span.style.display = "none";
2208         }
2209         if (!otherMessage) {
2210             span.innerHTML = "&nbsp;Expand&nbsp;description";
2211         } else {
2212             span.innerHTML = otherMessage;
2213         }
2214
2215         if (fontSize) {
2216             span.style.fontSize = fontSize;
2217         }
2218
2219         var mainToggle = toggle.cloneNode(true);
2220         mainToggle.appendChild(span);
2221
2222         var wrapper = document.createElement("div");
2223         wrapper.className = "toggle-wrapper";
2224         if (!show) {
2225             addClass(wrapper, "collapsed");
2226             var inner = mainToggle.getElementsByClassName("inner");
2227             if (inner && inner.length > 0) {
2228                 inner[0].innerHTML = "+";
2229             }
2230         }
2231         if (extraClass) {
2232             addClass(wrapper, extraClass);
2233         }
2234         wrapper.appendChild(mainToggle);
2235         return wrapper;
2236     }
2237
2238     var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
2239     function buildToggleWrapper(e) {
2240         if (hasClass(e, "autohide")) {
2241             var wrap = e.previousElementSibling;
2242             if (wrap && hasClass(wrap, "toggle-wrapper")) {
2243                 var inner_toggle = wrap.childNodes[0];
2244                 var extra = e.childNodes[0].tagName === "H3";
2245
2246                 e.style.display = "none";
2247                 addClass(wrap, "collapsed");
2248                 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2249                     e.innerHTML = labelForToggleButton(true);
2250                 });
2251                 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2252                     e.style.display = "inline-block";
2253                     if (extra === true) {
2254                         i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2255                     }
2256                 });
2257             }
2258         }
2259         if (e.parentNode.id === "main") {
2260             var otherMessage = "";
2261             var fontSize;
2262             var extraClass;
2263
2264             if (hasClass(e, "type-decl")) {
2265                 fontSize = "20px";
2266                 otherMessage = "&nbsp;Show&nbsp;declaration";
2267                 if (showItemDeclarations === false) {
2268                     extraClass = "collapsed";
2269                 }
2270             } else if (hasClass(e, "sub-variant")) {
2271                 otherMessage = "&nbsp;Show&nbsp;fields";
2272             } else if (hasClass(e, "non-exhaustive")) {
2273                 otherMessage = "&nbsp;This&nbsp;";
2274                 if (hasClass(e, "non-exhaustive-struct")) {
2275                     otherMessage += "struct";
2276                 } else if (hasClass(e, "non-exhaustive-enum")) {
2277                     otherMessage += "enum";
2278                 } else if (hasClass(e, "non-exhaustive-variant")) {
2279                     otherMessage += "enum variant";
2280                 } else if (hasClass(e, "non-exhaustive-type")) {
2281                     otherMessage += "type";
2282                 }
2283                 otherMessage += "&nbsp;is&nbsp;marked&nbsp;as&nbsp;non-exhaustive";
2284             } else if (hasClass(e.childNodes[0], "impl-items")) {
2285                 extraClass = "marg-left";
2286             }
2287
2288             e.parentNode.insertBefore(
2289                 createToggle(otherMessage,
2290                              fontSize,
2291                              extraClass,
2292                              hasClass(e, "type-decl") === false || showItemDeclarations === true),
2293                 e);
2294             if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2295                 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2296             }
2297             if (hasClass(e, "non-exhaustive") === true) {
2298                 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2299             }
2300         }
2301     }
2302
2303     onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2304     onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2305
2306     function createToggleWrapper(tog) {
2307         var span = document.createElement("span");
2308         span.className = "toggle-label";
2309         span.style.display = "none";
2310         span.innerHTML = "&nbsp;Expand&nbsp;attributes";
2311         tog.appendChild(span);
2312
2313         var wrapper = document.createElement("div");
2314         wrapper.className = "toggle-wrapper toggle-attributes";
2315         wrapper.appendChild(tog);
2316         return wrapper;
2317     }
2318
2319     // To avoid checking on "rustdoc-item-attributes" value on every loop...
2320     var itemAttributesFunc = function() {};
2321     if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2322         itemAttributesFunc = function(x) {
2323             collapseDocs(x.previousSibling.childNodes[0], "toggle");
2324         };
2325     }
2326     var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2327     onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2328         i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
2329         itemAttributesFunc(i_e);
2330     });
2331
2332     // To avoid checking on "rustdoc-line-numbers" value on every loop...
2333     var lineNumbersFunc = function() {};
2334     if (getCurrentValue("rustdoc-line-numbers") === "true") {
2335         lineNumbersFunc = function(x) {
2336             var count = x.textContent.split("\n").length;
2337             var elems = [];
2338             for (var i = 0; i < count; ++i) {
2339                 elems.push(i + 1);
2340             }
2341             var node = document.createElement("pre");
2342             addClass(node, "line-number");
2343             node.innerHTML = elems.join("\n");
2344             x.parentNode.insertBefore(node, x);
2345         };
2346     }
2347     onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2348         if (hasClass(e, "compile_fail")) {
2349             e.addEventListener("mouseover", function(event) {
2350                 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2351             });
2352             e.addEventListener("mouseout", function(event) {
2353                 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2354             });
2355         } else if (hasClass(e, "ignore")) {
2356             e.addEventListener("mouseover", function(event) {
2357                 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2358             });
2359             e.addEventListener("mouseout", function(event) {
2360                 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2361             });
2362         }
2363         lineNumbersFunc(e);
2364     });
2365
2366     function showModal(content) {
2367         var modal = document.createElement("div");
2368         modal.id = "important";
2369         addClass(modal, "modal");
2370         modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
2371                           "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
2372                           "</span></div>";
2373         document.getElementsByTagName("body")[0].appendChild(modal);
2374         document.getElementById("modal-close").onclick = hideModal;
2375         modal.onclick = hideModal;
2376     }
2377
2378     function hideModal() {
2379         var modal = document.getElementById("important");
2380         if (modal) {
2381             modal.parentNode.removeChild(modal);
2382         }
2383     }
2384
2385     onEachLazy(document.getElementsByClassName("important-traits"), function(e) {
2386         e.onclick = function() {
2387             showModal(e.lastElementChild.innerHTML);
2388         };
2389     });
2390
2391     // In the search display, allows to switch between tabs.
2392     function printTab(nb) {
2393         if (nb === 0 || nb === 1 || nb === 2) {
2394             currentTab = nb;
2395         }
2396         var nb_copy = nb;
2397         onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2398             if (nb_copy === 0) {
2399                 addClass(elem, "selected");
2400             } else {
2401                 removeClass(elem, "selected");
2402             }
2403             nb_copy -= 1;
2404         });
2405         onEachLazy(document.getElementById("results").childNodes, function(elem) {
2406             if (nb === 0) {
2407                 elem.style.display = "";
2408             } else {
2409                 elem.style.display = "none";
2410             }
2411             nb -= 1;
2412         });
2413     }
2414
2415     function putBackSearch(search_input) {
2416         if (search_input.value !== "") {
2417             addClass(main, "hidden");
2418             removeClass(document.getElementById("search"), "hidden");
2419             if (browserSupportsHistoryApi()) {
2420                 history.replaceState(search_input.value,
2421                                      "",
2422                                      "?search=" + encodeURIComponent(search_input.value));
2423             }
2424         }
2425     }
2426
2427     if (search_input) {
2428         search_input.onfocus = function() {
2429             putBackSearch(this);
2430         };
2431     }
2432
2433     var params = getQueryStringParams();
2434     if (params && params.search) {
2435         addClass(main, "hidden");
2436         var search = document.getElementById("search");
2437         removeClass(search, "hidden");
2438         search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
2439     }
2440
2441     var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2442     if (sidebar_menu) {
2443         sidebar_menu.onclick = function() {
2444             var sidebar = document.getElementsByClassName("sidebar")[0];
2445             if (hasClass(sidebar, "mobile") === true) {
2446                 hideSidebar();
2447             } else {
2448                 showSidebar();
2449             }
2450         };
2451     }
2452
2453     window.onresize = function() {
2454         hideSidebar();
2455     };
2456
2457     autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2458
2459     if (window.location.hash && window.location.hash.length > 0) {
2460         expandSection(window.location.hash.replace(/^#/, ""));
2461     }
2462
2463     if (main) {
2464         onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2465             e.remove();
2466         });
2467         onEachLazy(main.childNodes, function(e) {
2468             // Unhide the actual content once loading is complete. Headers get
2469             // flex treatment for their horizontal layout, divs get block treatment
2470             // for vertical layout (column-oriented flex layout for divs caused
2471             // errors in mobile browsers).
2472             if (e.tagName === "H2" || e.tagName === "H3") {
2473                 var nextTagName = e.nextElementSibling.tagName;
2474                 if (nextTagName == "H2" || nextTagName == "H3") {
2475                     e.nextElementSibling.style.display = "flex";
2476                 } else {
2477                     e.nextElementSibling.style.display = "block";
2478                 }
2479             }
2480         });
2481     }
2482
2483     function addSearchOptions(crates) {
2484         var elem = document.getElementById('crate-search');
2485
2486         if (!elem) {
2487             return;
2488         }
2489         var crates_text = [];
2490         if (Object.keys(crates).length > 1) {
2491             for (var crate in crates) {
2492                 if (crates.hasOwnProperty(crate)) {
2493                     crates_text.push(crate);
2494                 }
2495             }
2496         }
2497         crates_text.sort(function(a, b) {
2498             var lower_a = a.toLowerCase();
2499             var lower_b = b.toLowerCase();
2500
2501             if (lower_a < lower_b) {
2502                 return -1;
2503             } else if (lower_a > lower_b) {
2504                 return 1;
2505             }
2506             return 0;
2507         });
2508         for (var i = 0; i < crates_text.length; ++i) {
2509             var option = document.createElement("option");
2510             option.value = crates_text[i];
2511             option.innerText = crates_text[i];
2512             elem.appendChild(option);
2513         }
2514     }
2515
2516     window.addSearchOptions = addSearchOptions;
2517 }());
2518
2519 // Sets the focus on the search bar at the top of the page
2520 function focusSearchBar() {
2521     document.getElementsByClassName("search-input")[0].focus();
2522 }
2523
2524 // Removes the focus from the search bar
2525 function defocusSearchBar() {
2526     document.getElementsByClassName("search-input")[0].blur();
2527 }