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