From edfe2a893e2ca1330c4fe422d61214f6cb2144f0 Mon Sep 17 00:00:00 2001
From: Guillaume Gomez <guillaume1.gomez@gmail.com>
Date: Fri, 16 Nov 2018 16:31:07 +0100
Subject: [PATCH 1/5] Greatly improve rustdoc rendering speed issues

---
 src/librustdoc/html/render.rs          |    5 +-
 src/librustdoc/html/static/main.js     | 1084 +++++++++++++-----------
 src/librustdoc/html/static/rustdoc.css |    4 +
 src/librustdoc/html/static/storage.js  |   47 +-
 4 files changed, 611 insertions(+), 529 deletions(-)

diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs
index 6158815fb9a51..0d2d6082174ed 100644
--- a/src/librustdoc/html/render.rs
+++ b/src/librustdoc/html/render.rs
@@ -868,9 +868,8 @@ themePicker.onblur = handleThemeButtonsBlur;
     }
 
     {
-        let mut data = format!("var resourcesSuffix = \"{}\";\n",
-                               cx.shared.resource_suffix);
-        data.push_str(static_files::STORAGE_JS);
+        let mut data = static_files::STORAGE_JS.to_owned();
+        data.push_str(&format!("var resourcesSuffix = \"{}\";", cx.shared.resource_suffix));
         write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
                      &data,
                      options.enable_minification)?;
diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js
index 1869969a53069..76ef47e10976d 100644
--- a/src/librustdoc/html/static/main.js
+++ b/src/librustdoc/html/static/main.js
@@ -30,6 +30,27 @@ if (!String.prototype.endsWith) {
     };
 }
 
+if (!DOMTokenList.prototype.add) {
+    DOMTokenList.prototype.add = function(className) {
+        if (className && !hasClass(this, className)) {
+            if (this.className && this.className.length > 0) {
+                this.className += " " + className;
+            } else {
+                this.className = className;
+            }
+        }
+    };
+}
+
+if (!DOMTokenList.prototype.remove) {
+    DOMTokenList.prototype.remove = function(className) {
+        if (className && this.className) {
+            this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
+                                                         .trim();
+        }
+    };
+}
+
 (function() {
     "use strict";
 
@@ -61,7 +82,9 @@ if (!String.prototype.endsWith) {
                      "attr",
                      "derive"];
 
-    var search_input = document.getElementsByClassName('search-input')[0];
+    var start = Date.now();
+
+    var search_input = document.getElementsByClassName("search-input")[0];
 
     // On the search screen, so you remain on the last tab you opened.
     //
@@ -75,9 +98,9 @@ if (!String.prototype.endsWith) {
     var titleBeforeSearch = document.title;
 
     function getPageId() {
-        var id = document.location.href.split('#')[1];
+        var id = document.location.href.split("#")[1];
         if (id) {
-            return id.split('?')[0].split('&')[0];
+            return id.split("?")[0].split("&")[0];
         }
         return null;
     }
@@ -87,9 +110,9 @@ if (!String.prototype.endsWith) {
         if (elems) {
             addClass(elems, "show-it");
         }
-        var sidebar = document.getElementsByClassName('sidebar')[0];
+        var sidebar = document.getElementsByClassName("sidebar")[0];
         if (sidebar) {
-            addClass(sidebar, 'mobile');
+            addClass(sidebar, "mobile");
             var filler = document.getElementById("sidebar-filler");
             if (!filler) {
                 var div = document.createElement("div");
@@ -108,13 +131,13 @@ if (!String.prototype.endsWith) {
         if (elems) {
             removeClass(elems, "show-it");
         }
-        var sidebar = document.getElementsByClassName('sidebar')[0];
-        removeClass(sidebar, 'mobile');
+        var sidebar = document.getElementsByClassName("sidebar")[0];
+        removeClass(sidebar, "mobile");
         var filler = document.getElementById("sidebar-filler");
         if (filler) {
             filler.remove();
         }
-        document.getElementsByTagName("body")[0].style.marginTop = '';
+        document.getElementsByTagName("body")[0].style.marginTop = "";
         var themePicker = document.getElementsByClassName("theme-picker");
         if (themePicker && themePicker.length > 0) {
             themePicker[0].style.display = null;
@@ -125,10 +148,12 @@ if (!String.prototype.endsWith) {
     var TY_PRIMITIVE = itemTypes.indexOf("primitive");
     var TY_KEYWORD = itemTypes.indexOf("keyword");
 
-    onEach(document.getElementsByClassName('js-only'), function(e) {
-        removeClass(e, 'js-only');
+    onEach(document.getElementsByClassName("js-only"), function(e) {
+        removeClass(e, "js-only");
     });
 
+    console.log('1', Date.now() - start);
+
     function getQueryStringParams() {
         var params = {};
         window.location.search.substring(1).split("&").
@@ -148,13 +173,14 @@ if (!String.prototype.endsWith) {
     function highlightSourceLines(ev) {
         // If we're in mobile mode, we should add the sidebar in any case.
         hideSidebar();
+        var elem;
         var search = document.getElementById("search");
         var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
         if (match) {
             from = parseInt(match[1], 10);
             to = Math.min(50000, parseInt(match[2] || match[1], 10));
             from = Math.min(from, to);
-            var elem = document.getElementById(from);
+            elem = document.getElementById(from);
             if (!elem) {
                 return;
             }
@@ -164,22 +190,22 @@ if (!String.prototype.endsWith) {
                     x.scrollIntoView();
                 }
             }
-            onEach(document.getElementsByClassName('line-numbers'), function(e) {
-                onEach(e.getElementsByTagName('span'), function(i_e) {
-                    removeClass(i_e, 'line-highlighted');
+            onEach(document.getElementsByClassName("line-numbers"), function(e) {
+                onEach(e.getElementsByTagName("span"), function(i_e) {
+                    removeClass(i_e, "line-highlighted");
                 });
             });
             for (i = from; i <= to; ++i) {
-                addClass(document.getElementById(i), 'line-highlighted');
+                addClass(document.getElementById(i), "line-highlighted");
             }
         } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
             addClass(search, "hidden");
             removeClass(document.getElementById("main"), "hidden");
-            var hash = ev.newURL.slice(ev.newURL.indexOf('#') + 1);
+            var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
             if (browserSupportsHistoryApi()) {
                 history.replaceState(hash, "", "?search=#" + hash);
             }
-            var elem = document.getElementById(hash);
+            elem = document.getElementById(hash);
             if (elem) {
                 elem.scrollIntoView();
             }
@@ -190,7 +216,7 @@ if (!String.prototype.endsWith) {
         var elem = document.getElementById(id);
         if (elem && isHidden(elem)) {
             var h3 = elem.parentNode.previousSibling;
-            if (h3 && h3.tagName !== 'H3') {
+            if (h3 && h3.tagName !== "H3") {
                 h3 = h3.previousSibling; // skip div.docblock
             }
 
@@ -207,6 +233,8 @@ if (!String.prototype.endsWith) {
     highlightSourceLines(null);
     window.onhashchange = highlightSourceLines;
 
+    console.log('2', Date.now() - start);
+
     // Gets the human-readable string for the virtual-key code of the
     // given KeyboardEvent, ev.
     //
@@ -236,7 +264,7 @@ if (!String.prototype.endsWith) {
                 removeClass(help, "hidden");
                 addClass(document.body, "blur");
             }
-        } else if (!hasClass(help, "hidden")) {
+        } else if (hasClass(help, "hidden") === false) {
             ev.preventDefault();
             addClass(help, "hidden");
             removeClass(document.body, "blur");
@@ -246,9 +274,9 @@ if (!String.prototype.endsWith) {
     function handleEscape(ev, help) {
         hideModal();
         var search = document.getElementById("search");
-        if (!hasClass(help, "hidden")) {
+        if (hasClass(help, "hidden") === false) {
             displayHelp(false, ev);
-        } else if (!hasClass(search, "hidden")) {
+        } else if (hasClass(search, "hidden") === false) {
             ev.preventDefault();
             addClass(search, "hidden");
             removeClass(document.getElementById("main"), "hidden");
@@ -305,26 +333,27 @@ if (!String.prototype.endsWith) {
             if (elem && elem.tagName === tagName) {
                 return elem;
             }
-        } while (elem = elem.parentNode);
+            elem = elem.parentNode;
+        } while (elem);
         return null;
     }
 
     document.onkeypress = handleShortcut;
     document.onkeydown = handleShortcut;
     document.onclick = function(ev) {
-        if (hasClass(ev.target, 'collapse-toggle')) {
+        if (hasClass(ev.target, "collapse-toggle")) {
             collapseDocs(ev.target, "toggle");
-        } else if (hasClass(ev.target.parentNode, 'collapse-toggle')) {
+        } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
             collapseDocs(ev.target.parentNode, "toggle");
-        } else if (ev.target.tagName === 'SPAN' && hasClass(ev.target.parentNode, 'line-numbers')) {
+        } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
             var prev_id = 0;
 
             var set_fragment = function(name) {
                 if (browserSupportsHistoryApi()) {
-                    history.replaceState(null, null, '#' + name);
+                    history.replaceState(null, null, "#" + name);
                     window.hashchange();
                 } else {
-                    location.replace('#' + name);
+                    location.replace("#" + name);
                 }
             };
 
@@ -337,31 +366,31 @@ if (!String.prototype.endsWith) {
                     cur_id = tmp;
                 }
 
-                set_fragment(prev_id + '-' + cur_id);
+                set_fragment(prev_id + "-" + cur_id);
             } else {
                 prev_id = cur_id;
 
                 set_fragment(cur_id);
             }
-        } else if (!hasClass(document.getElementById("help"), "hidden")) {
+        } else if (hasClass(document.getElementById("help"), "hidden") === false) {
             addClass(document.getElementById("help"), "hidden");
             removeClass(document.body, "blur");
         } else {
             // Making a collapsed element visible on onhashchange seems
             // too late
-            var a = findParentElement(ev.target, 'A');
+            var a = findParentElement(ev.target, "A");
             if (a && a.hash) {
-                expandSection(a.hash.replace(/^#/, ''));
+                expandSection(a.hash.replace(/^#/, ""));
             }
         }
     };
 
-    var x = document.getElementsByClassName('version-selector');
+    var x = document.getElementsByClassName("version-selector");
     if (x.length > 0) {
         x[0].onchange = function() {
             var i, match,
                 url = document.location.href,
-                stripped = '',
+                stripped = "",
                 len = rootPath.match(/\.\.\//g).length + 1;
 
             for (i = 0; i < len; ++i) {
@@ -372,12 +401,14 @@ if (!String.prototype.endsWith) {
                 url = url.substring(0, url.length - match[0].length);
             }
 
-            url += '/' + document.getElementsByClassName('version-selector')[0].value + stripped;
+            url += "/" + document.getElementsByClassName("version-selector")[0].value + stripped;
 
             document.location.href = url;
         };
     }
 
+    console.log('3', Date.now() - start);
+
     /**
      * A function to compute the Levenshtein distance between two strings
      * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
@@ -428,7 +459,7 @@ if (!String.prototype.endsWith) {
         // where you start trying to do a search, and the index loads, and
         // suddenly your search is gone!
         if (search_input.value === "") {
-            search_input.value = params.search || '';
+            search_input.value = params.search || "";
         }
 
         /**
@@ -441,7 +472,8 @@ if (!String.prototype.endsWith) {
          */
         function execQuery(query, searchWords, filterCrates) {
             function itemTypeFromName(typename) {
-                for (var i = 0; i < itemTypes.length; ++i) {
+                var length = itemTypes.length;
+                for (var i = 0; i < length; ++i) {
                     if (itemTypes[i] === typename) {
                         return i;
                     }
@@ -455,7 +487,8 @@ if (!String.prototype.endsWith) {
                 results = {}, results_in_args = {}, results_returned = {},
                 split = valLower.split("::");
 
-            for (var z = 0; z < split.length; ++z) {
+            var length = split.length;
+            for (var z = 0; z < length; ++z) {
                 if (split[z] === "") {
                     split.splice(z, 1);
                     z -= 1;
@@ -464,7 +497,8 @@ if (!String.prototype.endsWith) {
 
             function transformResults(results, isType) {
                 var out = [];
-                for (i = 0; i < results.length; ++i) {
+                var length = results.length;
+                for (var i = 0; i < length; ++i) {
                     if (results[i].id > -1) {
                         var obj = searchIndex[results[i].id];
                         obj.lev = results[i].lev;
@@ -473,7 +507,7 @@ if (!String.prototype.endsWith) {
                             obj.displayPath = pathSplitter(res[0]);
                             obj.fullPath = obj.displayPath + obj.name;
                             // To be sure than it some items aren't considered as duplicate.
-                            obj.fullPath += '|' + obj.ty;
+                            obj.fullPath += "|" + obj.ty;
                             obj.href = res[1];
                             out.push(obj);
                             if (out.length >= MAX_RESULTS) {
@@ -493,8 +527,9 @@ if (!String.prototype.endsWith) {
                     }
                 }
                 results = ar;
+                var i;
                 var nresults = results.length;
-                for (var i = 0; i < nresults; ++i) {
+                for (i = 0; i < nresults; ++i) {
                     results[i].word = searchWords[results[i].id];
                     results[i].item = searchIndex[results[i].id] || {};
                 }
@@ -552,8 +587,8 @@ if (!String.prototype.endsWith) {
                     }
 
                     // sort by description (no description goes later)
-                    a = (aaa.item.desc === '');
-                    b = (bbb.item.desc === '');
+                    a = (aaa.item.desc === "");
+                    b = (bbb.item.desc === "");
                     if (a !== b) { return a - b; }
 
                     // sort by type (later occurrence in `itemTypes` goes later)
@@ -570,7 +605,8 @@ if (!String.prototype.endsWith) {
                     return 0;
                 });
 
-                for (var i = 0; i < results.length; ++i) {
+                var length = results.length;
+                for (i = 0; i < length; ++i) {
                     var result = results[i];
 
                     // this validation does not make sense when searching by types
@@ -592,10 +628,10 @@ if (!String.prototype.endsWith) {
 
             function extractGenerics(val) {
                 val = val.toLowerCase();
-                if (val.indexOf('<') !== -1) {
-                    var values = val.substring(val.indexOf('<') + 1, val.lastIndexOf('>'));
+                if (val.indexOf("<") !== -1) {
+                    var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
                     return {
-                        name: val.substring(0, val.indexOf('<')),
+                        name: val.substring(0, val.indexOf("<")),
                         generics: values.split(/\s*,\s*/),
                     };
                 }
@@ -617,9 +653,11 @@ if (!String.prototype.endsWith) {
                         var done = 0;
                         // We need to find the type that matches the most to remove it in order
                         // to move forward.
-                        for (var y = 0; y < val.generics.length; ++y) {
+                        var vlength = val.generics.length;
+                        for (var y = 0; y < vlength; ++y) {
                             var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
-                            for (var x = 0; x < elems.length; ++x) {
+                            var elength = elems.length;
+                            for (var x = 0; x < elength; ++x) {
                                 var tmp_lev = levenshtein(elems[x], val.generics[y]);
                                 if (tmp_lev < lev.lev) {
                                     lev.lev = tmp_lev;
@@ -644,6 +682,7 @@ if (!String.prototype.endsWith) {
             // Check for type name and type generics (if any).
             function checkType(obj, val, literalSearch) {
                 var lev_distance = MAX_LEV_DISTANCE + 1;
+                var x;
                 if (obj[NAME] === val.name) {
                     if (literalSearch === true) {
                         if (val.generics && val.generics.length !== 0) {
@@ -651,7 +690,6 @@ if (!String.prototype.endsWith) {
                                   obj[GENERICS_DATA].length >= val.generics.length) {
                                 var elems = obj[GENERICS_DATA].slice(0);
                                 var allFound = true;
-                                var x;
 
                                 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
                                     allFound = false;
@@ -685,7 +723,8 @@ if (!String.prototype.endsWith) {
                 // Names didn't match so let's check if one of the generic types could.
                 if (literalSearch === true) {
                      if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
-                        for (var x = 0; x < obj[GENERICS_DATA].length; ++x) {
+                        var length = obj[GENERICS_DATA].length;
+                        for (x = 0; x < length; ++x) {
                             if (obj[GENERICS_DATA][x] === val.name) {
                                 return true;
                             }
@@ -693,13 +732,13 @@ if (!String.prototype.endsWith) {
                     }
                     return false;
                 }
-                var lev_distance = Math.min(levenshtein(obj[NAME], val.name),
-                                            lev_distance);
+                lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
                 if (lev_distance <= MAX_LEV_DISTANCE) {
                     lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
                 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
                     // We can check if the type we're looking for is inside the generics!
-                    for (var x = 0; x < obj[GENERICS_DATA].length; ++x) {
+                    var olength = obj[GENERICS_DATA].length;
+                    for (x = 0; x < olength; ++x) {
                         lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
                                                 lev_distance);
                     }
@@ -714,7 +753,8 @@ if (!String.prototype.endsWith) {
 
                 if (obj && obj.type && obj.type[INPUTS_DATA] &&
                       obj.type[INPUTS_DATA].length > 0) {
-                    for (var i = 0; i < obj.type[INPUTS_DATA].length; i++) {
+                    var length = obj.type[INPUTS_DATA].length;
+                    for (var i = 0; i < length; i++) {
                         var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
                         if (literalSearch === true && tmp === true) {
                             return true;
@@ -755,16 +795,18 @@ if (!String.prototype.endsWith) {
                     path.push(ty.parent.name.toLowerCase());
                 }
 
-                if (contains.length > path.length) {
+                var length = path.length;
+                var clength = contains.length;
+                if (clength > length) {
                     return MAX_LEV_DISTANCE + 1;
                 }
-                for (var i = 0; i < path.length; ++i) {
-                    if (i + contains.length > path.length) {
+                for (var i = 0; i < length; ++i) {
+                    if (i + clength > length) {
                         break;
                     }
                     var lev_total = 0;
                     var aborted = false;
-                    for (var x = 0; x < contains.length; ++x) {
+                    for (var x = 0; x < clength; ++x) {
                         var lev = levenshtein(path[i + x], contains[x]);
                         if (lev > MAX_LEV_DISTANCE) {
                             aborted = true;
@@ -773,7 +815,7 @@ if (!String.prototype.endsWith) {
                         lev_total += lev;
                     }
                     if (aborted === false) {
-                        ret_lev = Math.min(ret_lev, Math.round(lev_total / contains.length));
+                        ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
                     }
                 }
                 return ret_lev;
@@ -810,18 +852,23 @@ if (!String.prototype.endsWith) {
 
             // quoted values mean literal search
             var nSearchWords = searchWords.length;
+            var i;
+            var ty;
+            var fullId;
+            var returned;
+            var in_args;
             if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
                 val.charAt(val.length - 1) === val.charAt(0))
             {
                 val = extractGenerics(val.substr(1, val.length - 2));
-                for (var i = 0; i < nSearchWords; ++i) {
+                for (i = 0; i < nSearchWords; ++i) {
                     if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
                         continue;
                     }
-                    var in_args = findArg(searchIndex[i], val, true);
-                    var returned = checkReturned(searchIndex[i], val, true);
-                    var ty = searchIndex[i];
-                    var fullId = generateId(ty);
+                    in_args = findArg(searchIndex[i], val, true);
+                    returned = checkReturned(searchIndex[i], val, true);
+                    ty = searchIndex[i];
+                    fullId = generateId(ty);
 
                     if (searchWords[i] === val.name) {
                         // filter type: ... queries
@@ -866,27 +913,27 @@ if (!String.prototype.endsWith) {
                 var input = parts[0];
                 // sort inputs so that order does not matter
                 var inputs = input.split(",").map(trimmer).sort();
-                for (var i = 0; i < inputs.length; ++i) {
+                for (i = 0; i < inputs.length; ++i) {
                     inputs[i] = extractGenerics(inputs[i]);
                 }
                 var output = extractGenerics(parts[1]);
 
-                for (var i = 0; i < nSearchWords; ++i) {
+                for (i = 0; i < nSearchWords; ++i) {
                     if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
                         continue;
                     }
                     var type = searchIndex[i].type;
-                    var ty = searchIndex[i];
+                    ty = searchIndex[i];
                     if (!type) {
                         continue;
                     }
-                    var fullId = generateId(ty);
+                    fullId = generateId(ty);
 
                     // allow searching for void (no output) functions as well
                     var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
-                    var returned = checkReturned(ty, output, true);
+                    returned = checkReturned(ty, output, true);
                     if (output.name === "*" || returned === true) {
-                        var in_args = false;
+                        in_args = false;
                         var module = false;
 
                         if (input === "*") {
@@ -946,14 +993,16 @@ if (!String.prototype.endsWith) {
                 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
 
                 for (j = 0; j < nSearchWords; ++j) {
-                    var ty = searchIndex[j];
+                    var lev;
+                    var lev_distance;
+                    ty = searchIndex[j];
                     if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
                         continue;
                     }
                     var lev_distance;
                     var lev_add = 0;
                     if (paths.length > 1) {
-                        var lev = checkPath(contains, paths[paths.length - 1], ty);
+                        lev = checkPath(contains, paths[paths.length - 1], ty);
                         if (lev > MAX_LEV_DISTANCE) {
                             continue;
                         } else if (lev > 0) {
@@ -961,12 +1010,12 @@ if (!String.prototype.endsWith) {
                         }
                     }
 
-                    var returned = MAX_LEV_DISTANCE + 1;
-                    var in_args = MAX_LEV_DISTANCE + 1;
+                    returned = MAX_LEV_DISTANCE + 1;
+                    in_args = MAX_LEV_DISTANCE + 1;
                     var index = -1;
                     // we want lev results to go lower than others
-                    var lev = MAX_LEV_DISTANCE + 1;
-                    var fullId = generateId(ty);
+                    lev = MAX_LEV_DISTANCE + 1;
+                    fullId = generateId(ty);
 
                     if (searchWords[j].indexOf(split[i]) > -1 ||
                         searchWords[j].indexOf(val) > -1 ||
@@ -1042,14 +1091,14 @@ if (!String.prototype.endsWith) {
             }
 
             var ret = {
-                'in_args': sortResults(results_in_args, true),
-                'returned': sortResults(results_returned, true),
-                'others': sortResults(results),
+                "in_args": sortResults(results_in_args, true),
+                "returned": sortResults(results_returned, true),
+                "others": sortResults(results),
             };
             if (ALIASES && ALIASES[window.currentCrate] &&
                     ALIASES[window.currentCrate][query.raw]) {
                 var aliases = ALIASES[window.currentCrate][query.raw];
-                for (var i = 0; i < aliases.length; ++i) {
+                for (i = 0; i < aliases.length; ++i) {
                     aliases[i].is_alias = true;
                     aliases[i].alias = query.raw;
                     aliases[i].path = aliases[i].p;
@@ -1057,9 +1106,9 @@ if (!String.prototype.endsWith) {
                     aliases[i].displayPath = pathSplitter(res[0]);
                     aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
                     aliases[i].href = res[1];
-                    ret['others'].unshift(aliases[i]);
-                    if (ret['others'].length > MAX_RESULTS) {
-                        ret['others'].pop();
+                    retothers.unshift(aliases[i]);
+                    if (ret.others.length > MAX_RESULTS) {
+                        ret.others.pop();
                     }
                 }
             }
@@ -1106,7 +1155,7 @@ if (!String.prototype.endsWith) {
 
             matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
             if (matches) {
-                type = matches[1].replace(/^const$/, 'constant');
+                type = matches[1].replace(/^const$/, "constant");
                 query = query.substring(matches[0].length);
             }
 
@@ -1124,38 +1173,38 @@ if (!String.prototype.endsWith) {
             var click_func = function(e) {
                 var el = e.target;
                 // to retrieve the real "owner" of the event.
-                while (el.tagName !== 'TR') {
+                while (el.tagName !== "TR") {
                     el = el.parentNode;
                 }
-                var dst = e.target.getElementsByTagName('a');
+                var dst = e.target.getElementsByTagName("a");
                 if (dst.length < 1) {
                     return;
                 }
                 dst = dst[0];
                 if (window.location.pathname === dst.pathname) {
-                    addClass(document.getElementById('search'), 'hidden');
-                    removeClass(document.getElementById('main'), 'hidden');
+                    addClass(document.getElementById("search"), "hidden");
+                    removeClass(document.getElementById("main"), "hidden");
                     document.location.href = dst.href;
                 }
             };
             var mouseover_func = function(e) {
                 var el = e.target;
                 // to retrieve the real "owner" of the event.
-                while (el.tagName !== 'TR') {
+                while (el.tagName !== "TR") {
                     el = el.parentNode;
                 }
                 clearTimeout(hoverTimeout);
                 hoverTimeout = setTimeout(function() {
-                    onEach(document.getElementsByClassName('search-results'), function(e) {
-                        onEach(e.getElementsByClassName('result'), function(i_e) {
-                            removeClass(i_e, 'highlighted');
+                    onEach(document.getElementsByClassName("search-results"), function(e) {
+                        onEach(e.getElementsByClassName("result"), function(i_e) {
+                            removeClass(i_e, "highlighted");
                         });
                     });
-                    addClass(el, 'highlighted');
+                    addClass(el, "highlighted");
                 }, 20);
             };
-            onEach(document.getElementsByClassName('search-results'), function(e) {
-                onEach(e.getElementsByClassName('result'), function(i_e) {
+            onEach(document.getElementsByClassName("search-results"), function(e) {
+                onEach(e.getElementsByClassName("result"), function(i_e) {
                     i_e.onclick = click_func;
                     i_e.onmouseover = mouseover_func;
                 });
@@ -1167,8 +1216,8 @@ if (!String.prototype.endsWith) {
                 var actives = [[], [], []];
                 // "current" is used to know which tab we're looking into.
                 var current = 0;
-                onEach(document.getElementsByClassName('search-results'), function(e) {
-                    onEach(e.getElementsByClassName('highlighted'), function(e) {
+                onEach(document.getElementsByClassName("search-results"), function(e) {
+                    onEach(e.getElementsByClassName("highlighted"), function(e) {
                         actives[current].push(e);
                     });
                     current += 1;
@@ -1180,25 +1229,25 @@ if (!String.prototype.endsWith) {
                         return;
                     }
 
-                    addClass(actives[currentTab][0].previousElementSibling, 'highlighted');
-                    removeClass(actives[currentTab][0], 'highlighted');
+                    addClass(actives[currentTab][0].previousElementSibling, "highlighted");
+                    removeClass(actives[currentTab][0], "highlighted");
                 } else if (e.which === 40) { // down
                     if (!actives[currentTab].length) {
-                        var results = document.getElementsByClassName('search-results');
+                        var results = document.getElementsByClassName("search-results");
                         if (results.length > 0) {
-                            var res = results[currentTab].getElementsByClassName('result');
+                            var res = results[currentTab].getElementsByClassName("result");
                             if (res.length > 0) {
-                                addClass(res[0], 'highlighted');
+                                addClass(res[0], "highlighted");
                             }
                         }
                     } else if (actives[currentTab][0].nextElementSibling) {
-                        addClass(actives[currentTab][0].nextElementSibling, 'highlighted');
-                        removeClass(actives[currentTab][0], 'highlighted');
+                        addClass(actives[currentTab][0].nextElementSibling, "highlighted");
+                        removeClass(actives[currentTab][0], "highlighted");
                     }
                 } else if (e.which === 13) { // return
                     if (actives[currentTab].length) {
                         document.location.href =
-                            actives[currentTab][0].getElementsByTagName('a')[0].href;
+                            actives[currentTab][0].getElementsByTagName("a")[0].href;
                     }
                 } else if (e.which === 9) { // tab
                     if (e.shiftKey) {
@@ -1210,11 +1259,11 @@ if (!String.prototype.endsWith) {
                 } else if (e.which === 16) { // shift
                     // Does nothing, it's just to avoid losing "focus" on the highlighted element.
                 } else if (e.which === 27) { // escape
-                    removeClass(actives[currentTab][0], 'highlighted');
-                    search_input.value = '';
+                    removeClass(actives[currentTab][0], "highlighted");
+                    search_input.value = "";
                     defocusSearchBar();
                 } else if (actives[currentTab].length > 0) {
-                    removeClass(actives[currentTab][0], 'highlighted');
+                    removeClass(actives[currentTab][0], "highlighted");
                 }
             };
         }
@@ -1225,46 +1274,46 @@ if (!String.prototype.endsWith) {
             var type = itemTypes[item.ty];
             var name = item.name;
 
-            if (type === 'mod') {
-                displayPath = item.path + '::';
-                href = rootPath + item.path.replace(/::/g, '/') + '/' +
-                       name + '/index.html';
+            if (type === "mod") {
+                displayPath = item.path + "::";
+                href = rootPath + item.path.replace(/::/g, "/") + "/" +
+                       name + "/index.html";
             } else if (type === "primitive" || type === "keyword") {
                 displayPath = "";
-                href = rootPath + item.path.replace(/::/g, '/') +
-                       '/' + type + '.' + name + '.html';
+                href = rootPath + item.path.replace(/::/g, "/") +
+                       "/" + type + "." + name + ".html";
             } else if (type === "externcrate") {
                 displayPath = "";
-                href = rootPath + name + '/index.html';
+                href = rootPath + name + "/index.html";
             } else if (item.parent !== undefined) {
                 var myparent = item.parent;
-                var anchor = '#' + type + '.' + name;
+                var anchor = "#" + type + "." + name;
                 var parentType = itemTypes[myparent.ty];
                 if (parentType === "primitive") {
-                    displayPath = myparent.name + '::';
+                    displayPath = myparent.name + "::";
                 } else {
-                    displayPath = item.path + '::' + myparent.name + '::';
+                    displayPath = item.path + "::" + myparent.name + "::";
                 }
-                href = rootPath + item.path.replace(/::/g, '/') +
-                       '/' + parentType +
-                       '.' + myparent.name +
-                       '.html' + anchor;
+                href = rootPath + item.path.replace(/::/g, "/") +
+                       "/" + parentType +
+                       "." + myparent.name +
+                       ".html" + anchor;
             } else {
-                displayPath = item.path + '::';
-                href = rootPath + item.path.replace(/::/g, '/') +
-                       '/' + type + '.' + name + '.html';
+                displayPath = item.path + "::";
+                href = rootPath + item.path.replace(/::/g, "/") +
+                       "/" + type + "." + name + ".html";
             }
             return [displayPath, href];
         }
 
         function escape(content) {
-            var h1 = document.createElement('h1');
+            var h1 = document.createElement("h1");
             h1.textContent = content;
             return h1.innerHTML;
         }
 
         function pathSplitter(path) {
-            var tmp = '<span>' + path.replace(/::/g, '::</span><span>');
+            var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
             if (tmp.endsWith("<span>")) {
                 return tmp.slice(0, tmp.length - 6);
             }
@@ -1272,16 +1321,16 @@ if (!String.prototype.endsWith) {
         }
 
         function addTab(array, query, display) {
-            var extraStyle = '';
+            var extraStyle = "";
             if (display === false) {
-                extraStyle = ' style="display: none;"';
+                extraStyle = " style=\"display: none;\"";
             }
 
-            var output = '';
+            var output = "";
             var duplicates = {};
             var length = 0;
             if (array.length > 0) {
-                output = '<table class="search-results"' + extraStyle + '>';
+                output = "<table class=\"search-results\"" + extraStyle + ">";
 
                 array.forEach(function(item) {
                     var name, type;
@@ -1297,50 +1346,50 @@ if (!String.prototype.endsWith) {
                     }
                     length += 1;
 
-                    output += '<tr class="' + type + ' result"><td>' +
-                              '<a href="' + item.href + '">' +
+                    output += "<tr class=\"" + type + " result\"><td>" +
+                              "<a href=\"" + item.href + "\">" +
                               (item.is_alias === true ?
-                               ('<span class="alias"><b>' + item.alias + ' </b></span><span ' +
-                                  'class="grey"><i>&nbsp;- see&nbsp;</i></span>') : '') +
-                              item.displayPath + '<span class="' + type + '">' +
-                              name + '</span></a></td><td>' +
-                              '<a href="' + item.href + '">' +
-                              '<span class="desc">' + escape(item.desc) +
-                              '&nbsp;</span></a></td></tr>';
+                               ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
+                                  "class=\"grey\"><i>&nbsp;- see&nbsp;</i></span>") : "") +
+                              item.displayPath + "<span class=\"" + type + "\">" +
+                              name + "</span></a></td><td>" +
+                              "<a href=\"" + item.href + "\">" +
+                              "<span class=\"desc\">" + escape(item.desc) +
+                              "&nbsp;</span></a></td></tr>";
                 });
-                output += '</table>';
+                output += "</table>";
             } else {
-                output = '<div class="search-failed"' + extraStyle + '>No results :(<br/>' +
-                    'Try on <a href="https://duckduckgo.com/?q=' +
-                    encodeURIComponent('rust ' + query.query) +
-                    '">DuckDuckGo</a>?<br/><br/>' +
-                    'Or try looking in one of these:<ul><li>The <a ' +
-                    'href="https://doc.rust-lang.org/reference/index.html">Rust Reference</a> for' +
-                    ' technical details about the language.</li><li><a ' +
-                    'href="https://doc.rust-lang.org/rust-by-example/index.html">Rust By Example' +
-                    '</a> for expository code examples.</a></li><li>The <a ' +
-                    'href="https://doc.rust-lang.org/book/index.html">Rust Book</a> for ' +
-                    'introductions to language features and the language itself.</li><li><a ' +
-                    'href="https://docs.rs">Docs.rs</a> for documentation of crates released on ' +
-                    '<a href="https://crates.io/">crates.io</a>.</li></ul></div>';
+                output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
+                    "Try on <a href=\"https://duckduckgo.com/?q=" +
+                    encodeURIComponent("rust " + query.query) +
+                    "\">DuckDuckGo</a>?<br/><br/>" +
+                    "Or try looking in one of these:<ul><li>The <a " +
+                    "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
+                    " for technical details about the language.</li><li><a " +
+                    "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
+                    "Example</a> for expository code examples.</a></li><li>The <a " +
+                    "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
+                    "introductions to language features and the language itself.</li><li><a " +
+                    "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
+                    " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
             }
             return [output, length];
         }
 
         function makeTabHeader(tabNb, text, nbElems) {
             if (currentTab === tabNb) {
-                return '<div class="selected">' + text +
-                       ' <div class="count">(' + nbElems + ')</div></div>';
+                return "<div class=\"selected\">" + text +
+                       " <div class=\"count\">(" + nbElems + ")</div></div>";
             }
-            return '<div>' + text + ' <div class="count">(' + nbElems + ')</div></div>';
+            return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
         }
 
-        function showResults(results, filterCrates) {
-            if (results['others'].length === 1 &&
-                getCurrentValue('rustdoc-go-to-only-result') === "true") {
-                var elem = document.createElement('a');
-                elem.href = results['others'][0].href;
-                elem.style.display = 'none';
+        function showResults(results) {
+            if (results.others.length === 1 &&
+                getCurrentValue("rustdoc-go-to-only-result") === "true") {
+                var elem = document.createElement("a");
+                elem.href = results.others[0].href;
+                elem.style.display = "none";
                 // For firefox, we need the element to be in the DOM so it can be clicked.
                 document.body.appendChild(elem);
                 elem.click();
@@ -1349,39 +1398,34 @@ if (!String.prototype.endsWith) {
 
             currentResults = query.id;
 
-            var ret_others = addTab(results['others'], query);
-            var ret_in_args = addTab(results['in_args'], query, false);
-            var ret_returned = addTab(results['returned'], query, false);
+            var ret_others = addTab(results.others, query);
+            var ret_in_args = addTab(results.in_args, query, false);
+            var ret_returned = addTab(results.returned, query, false);
 
-            var filter = "";
-            if (filterCrates !== undefined) {
-                filter = " (in <b>" + filterCrates + "</b> crate)";
-            }
-
-            var output = '<h1>Results for ' + escape(query.query) +
-                (query.type ? ' (type: ' + escape(query.type) + ')' : '') + filter + '</h1>' +
-                '<div id="titles">' +
+            var output = "<h1>Results for " + escape(query.query) +
+                (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
+                "<div id=\"titles\">" +
                 makeTabHeader(0, "In Names", ret_others[1]) +
                 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
                 makeTabHeader(2, "In Return Types", ret_returned[1]) +
-                '</div><div id="results">' +
-                ret_others[0] + ret_in_args[0] + ret_returned[0] + '</div>';
+                "</div><div id=\"results\">" +
+                ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
 
-            addClass(document.getElementById('main'), 'hidden');
-            var search = document.getElementById('search');
-            removeClass(search, 'hidden');
+            addClass(document.getElementById("main"), "hidden");
+            var search = document.getElementById("search");
+            removeClass(search, "hidden");
             search.innerHTML = output;
-            var tds = search.getElementsByTagName('td');
+            var tds = search.getElementsByTagName("td");
             var td_width = 0;
             if (tds.length > 0) {
                 td_width = tds[0].offsetWidth;
             }
             var width = search.offsetWidth - 40 - td_width;
-            onEach(search.getElementsByClassName('desc'), function(e) {
-                e.style.width = width + 'px';
+            onEach(search.getElementsByClassName("desc"), function(e) {
+                e.style.width = width + "px";
             });
             initSearchNav();
-            var elems = document.getElementById('titles').childNodes;
+            var elems = document.getElementById("titles").childNodes;
             elems[0].onclick = function() { printTab(0); };
             elems[1].onclick = function() { printTab(1); };
             elems[2].onclick = function() { printTab(2); };
@@ -1389,74 +1433,74 @@ if (!String.prototype.endsWith) {
         }
 
         function execSearch(query, searchWords, filterCrates) {
+            function getSmallest(arrays, positions, notDuplicates) {
+                var start = null;
+
+                for (var it = 0; it < positions.length; ++it) {
+                    if (arrays[it].length > positions[it] &&
+                        (start === null || start > arrays[it][positions[it]].lev) &&
+                        !notDuplicates[arrays[it][positions[it]].fullPath]) {
+                        start = arrays[it][positions[it]].lev;
+                    }
+                }
+                return start;
+            }
+
+            function mergeArrays(arrays) {
+                var ret = [];
+                var positions = [];
+                var notDuplicates = {};
+
+                for (var x = 0; x < arrays.length; ++x) {
+                    positions.push(0);
+                }
+                while (ret.length < MAX_RESULTS) {
+                    var smallest = getSmallest(arrays, positions, notDuplicates);
+
+                    if (smallest === null) {
+                        break;
+                    }
+                    for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
+                        if (arrays[x].length > positions[x] &&
+                                arrays[x][positions[x]].lev === smallest &&
+                                !notDuplicates[arrays[x][positions[x]].fullPath]) {
+                            ret.push(arrays[x][positions[x]]);
+                            notDuplicates[arrays[x][positions[x]].fullPath] = true;
+                            positions[x] += 1;
+                        }
+                    }
+                }
+                return ret;
+            }
+
             var queries = query.raw.split(",");
             var results = {
-                'in_args': [],
-                'returned': [],
-                'others': [],
+                "in_args": [],
+                "returned": [],
+                "others": [],
             };
 
             for (var i = 0; i < queries.length; ++i) {
-                var query = queries[i].trim();
+                query = queries[i].trim();
                 if (query.length !== 0) {
                     var tmp = execQuery(getQuery(query), searchWords, filterCrates);
 
-                    results['in_args'].push(tmp['in_args']);
-                    results['returned'].push(tmp['returned']);
-                    results['others'].push(tmp['others']);
+                    results.in_args.push(tmp.in_args);
+                    results.returned.push(tmp.returned);
+                    results.others.push(tmp.others);
                 }
             }
             if (queries.length > 1) {
-                function getSmallest(arrays, positions, notDuplicates) {
-                    var start = null;
-
-                    for (var it = 0; it < positions.length; ++it) {
-                        if (arrays[it].length > positions[it] &&
-                            (start === null || start > arrays[it][positions[it]].lev) &&
-                            !notDuplicates[arrays[it][positions[it]].fullPath]) {
-                            start = arrays[it][positions[it]].lev;
-                        }
-                    }
-                    return start;
-                }
-
-                function mergeArrays(arrays) {
-                    var ret = [];
-                    var positions = [];
-                    var notDuplicates = {};
-
-                    for (var x = 0; x < arrays.length; ++x) {
-                        positions.push(0);
-                    }
-                    while (ret.length < MAX_RESULTS) {
-                        var smallest = getSmallest(arrays, positions, notDuplicates);
-
-                        if (smallest === null) {
-                            break;
-                        }
-                        for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
-                            if (arrays[x].length > positions[x] &&
-                                    arrays[x][positions[x]].lev === smallest &&
-                                    !notDuplicates[arrays[x][positions[x]].fullPath]) {
-                                ret.push(arrays[x][positions[x]]);
-                                notDuplicates[arrays[x][positions[x]].fullPath] = true;
-                                positions[x] += 1;
-                            }
-                        }
-                    }
-                    return ret;
-                }
-
                 return {
-                    'in_args': mergeArrays(results['in_args']),
-                    'returned': mergeArrays(results['returned']),
-                    'others': mergeArrays(results['others']),
+                    "in_args": mergeArrays(results.in_args),
+                    "returned": mergeArrays(results.returned),
+                    "others": mergeArrays(results.others),
                 };
             } else {
                 return {
-                    'in_args': results['in_args'][0],
-                    'returned': results['returned'][0],
-                    'others': results['others'][0],
+                    "in_args": results.in_args[0],
+                    "returned": results.returned[0],
+                    "others": results.others[0],
                 };
             }
         }
@@ -1508,6 +1552,8 @@ if (!String.prototype.endsWith) {
         function buildIndex(rawSearchIndex) {
             searchIndex = [];
             var searchWords = [];
+            var i;
+
             for (var crate in rawSearchIndex) {
                 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
 
@@ -1534,7 +1580,7 @@ if (!String.prototype.endsWith) {
 
                 // convert `paths` into an object form
                 var len = paths.length;
-                for (var i = 0; i < len; ++i) {
+                for (i = 0; i < len; ++i) {
                     paths[i] = {ty: paths[i][0], name: paths[i][1]};
                 }
 
@@ -1545,9 +1591,9 @@ if (!String.prototype.endsWith) {
                 // operation that is cached for the life of the page state so that
                 // all other search operations have access to this cached data for
                 // faster analysis operations
-                var len = items.length;
+                len = items.length;
                 var lastPath = "";
-                for (var i = 0; i < len; ++i) {
+                for (i = 0; i < len; ++i) {
                     var rawRow = items[i];
                     var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
                                path: rawRow[2] || lastPath, desc: rawRow[3],
@@ -1573,13 +1619,13 @@ if (!String.prototype.endsWith) {
                     if (browserSupportsHistoryApi()) {
                         history.replaceState("", "std - Rust", "?search=");
                     }
-                    var main = document.getElementById('main');
-                    if (hasClass(main, 'content')) {
-                        removeClass(main, 'hidden');
+                    var main = document.getElementById("main");
+                    if (hasClass(main, "content")) {
+                        removeClass(main, "hidden");
                     }
-                    var search_c = document.getElementById('search');
-                    if (hasClass(search_c, 'content')) {
-                        addClass(search_c, 'hidden');
+                    var search_c = document.getElementById("search");
+                    if (hasClass(search_c, "content")) {
+                        addClass(search_c, "hidden");
                     }
                 } else {
                     searchTimeout = setTimeout(search, 500);
@@ -1620,13 +1666,13 @@ if (!String.prototype.endsWith) {
                     // When browsing back from search results the main page
                     // visibility must be reset.
                     if (!params.search) {
-                        var main = document.getElementById('main');
-                        if (hasClass(main, 'content')) {
-                            removeClass(main, 'hidden');
+                        var main = document.getElementById("main");
+                        if (hasClass(main, "content")) {
+                            removeClass(main, "hidden");
                         }
-                        var search_c = document.getElementById('search');
-                        if (hasClass(search_c, 'content')) {
-                            addClass(search_c, 'hidden');
+                        var search_c = document.getElementById("search");
+                        if (hasClass(search_c, "content")) {
+                            addClass(search_c, "hidden");
                         }
                     }
                     // Revert to the previous title manually since the History
@@ -1643,9 +1689,9 @@ if (!String.prototype.endsWith) {
                     if (params.search) {
                         search_input.value = params.search;
                     } else {
-                        search_input.value = '';
+                        search_input.value = "";
                     }
-                    // Some browsers fire 'onpopstate' for every page load
+                    // Some browsers fire "onpopstate" for every page load
                     // (Chrome), while others fire the event only when actually
                     // popping a state (Firefox), which is why search() is
                     // called both here and at the end of the startSearch()
@@ -1660,13 +1706,13 @@ if (!String.prototype.endsWith) {
         startSearch();
 
         // Draw a convenient sidebar of known crates if we have a listing
-        if (rootPath === '../' || rootPath === "./") {
-            var sidebar = document.getElementsByClassName('sidebar-elems')[0];
+        if (rootPath === "../" || rootPath === "./") {
+            var sidebar = document.getElementsByClassName("sidebar-elems")[0];
             if (sidebar) {
-                var div = document.createElement('div');
-                div.className = 'block crate';
-                div.innerHTML = '<h3>Crates</h3>';
-                var ul = document.createElement('ul');
+                var div = document.createElement("div");
+                div.className = "block crate";
+                div.innerHTML = "<h3>Crates</h3>";
+                var ul = document.createElement("ul");
                 div.appendChild(ul);
 
                 var crates = [];
@@ -1678,17 +1724,17 @@ if (!String.prototype.endsWith) {
                 }
                 crates.sort();
                 for (var i = 0; i < crates.length; ++i) {
-                    var klass = 'crate';
+                    var klass = "crate";
                     if (rootPath !== "./" && crates[i] === window.currentCrate) {
-                        klass += ' current';
+                        klass += " current";
                     }
-                    var link = document.createElement('a');
-                    link.href = rootPath + crates[i] + '/index.html';
+                    var link = document.createElement("a");
+                    link.href = rootPath + crates[i] + "/index.html";
                     link.title = rawSearchIndex[crates[i]].doc;
                     link.className = klass;
                     link.textContent = crates[i];
 
-                    var li = document.createElement('li');
+                    var li = document.createElement("li");
                     li.appendChild(link);
                     ul.appendChild(li);
                 }
@@ -1701,41 +1747,44 @@ if (!String.prototype.endsWith) {
 
     // delayed sidebar rendering.
     function initSidebarItems(items) {
-        var sidebar = document.getElementsByClassName('sidebar-elems')[0];
+        var sidebar = document.getElementsByClassName("sidebar-elems")[0];
         var current = window.sidebarCurrent;
 
         function block(shortty, longty) {
             var filtered = items[shortty];
-            if (!filtered) { return; }
+            if (!filtered) {
+                return;
+            }
 
-            var div = document.createElement('div');
-            div.className = 'block ' + shortty;
-            var h3 = document.createElement('h3');
+            var div = document.createElement("div");
+            div.className = "block " + shortty;
+            var h3 = document.createElement("h3");
             h3.textContent = longty;
             div.appendChild(h3);
-            var ul = document.createElement('ul');
+            var ul = document.createElement("ul");
 
-            for (var i = 0; i < filtered.length; ++i) {
+            var length = filtered.length;
+            for (var i = 0; i < length; ++i) {
                 var item = filtered[i];
                 var name = item[0];
                 var desc = item[1]; // can be null
 
                 var klass = shortty;
                 if (name === current.name && shortty === current.ty) {
-                    klass += ' current';
+                    klass += " current";
                 }
                 var path;
-                if (shortty === 'mod') {
-                    path = name + '/index.html';
+                if (shortty === "mod") {
+                    path = name + "/index.html";
                 } else {
-                    path = shortty + '.' + name + '.html';
+                    path = shortty + "." + name + ".html";
                 }
-                var link = document.createElement('a');
+                var link = document.createElement("a");
                 link.href = current.relpath + path;
                 link.title = desc;
                 link.className = klass;
                 link.textContent = name;
-                var li = document.createElement('li');
+                var li = document.createElement("li");
                 li.appendChild(link);
                 ul.appendChild(li);
             }
@@ -1763,22 +1812,25 @@ if (!String.prototype.endsWith) {
     window.initSidebarItems = initSidebarItems;
 
     window.register_implementors = function(imp) {
-        var implementors = document.getElementById('implementors-list');
-        var synthetic_implementors = document.getElementById('synthetic-implementors-list');
+        var implementors = document.getElementById("implementors-list");
+        var synthetic_implementors = document.getElementById("synthetic-implementors-list");
 
         var libs = Object.getOwnPropertyNames(imp);
-        for (var i = 0; i < libs.length; ++i) {
+        var llength = libs.length;
+        for (var i = 0; i < llength; ++i) {
             if (libs[i] === currentCrate) { continue; }
             var structs = imp[libs[i]];
 
+            var slength = structs.length;
             struct_loop:
-            for (var j = 0; j < structs.length; ++j) {
+            for (var j = 0; j < slength; ++j) {
                 var struct = structs[j];
 
                 var list = struct.synthetic ? synthetic_implementors : implementors;
 
                 if (struct.synthetic) {
-                    for (var k = 0; k < struct.types.length; k++) {
+                    var stlength = struct.types.length;
+                    for (var k = 0; k < stlength; k++) {
                         if (window.inlined_types.has(struct.types[k])) {
                             continue struct_loop;
                         }
@@ -1786,21 +1838,22 @@ if (!String.prototype.endsWith) {
                     }
                 }
 
-                var code = document.createElement('code');
+                var code = document.createElement("code");
                 code.innerHTML = struct.text;
 
-                var x = code.getElementsByTagName('a');
-                for (var k = 0; k < x.length; k++) {
-                    var href = x[k].getAttribute('href');
-                    if (href && href.indexOf('http') !== 0) {
-                        x[k].setAttribute('href', rootPath + href);
+                var x = code.getElementsByTagName("a");
+                var xlength = x.length;
+                for (var it = 0; it < xlength; it++) {
+                    var href = x[it].getAttribute("href");
+                    if (href && href.indexOf("http") !== 0) {
+                        x[it].setAttribute("href", rootPath + href);
                     }
                 }
-                var display = document.createElement('h3');
+                var display = document.createElement("h3");
                 addClass(display, "impl");
-                display.innerHTML = '<span class="in-band"><table class="table-display"><tbody>\
-                    <tr><td><code>' + code.outerHTML + '</code></td><td></td></tr></tbody></table>\
-                    </span>';
+                display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
+                    "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
+                    "</tbody></table></span>";
                 list.appendChild(display);
             }
         }
@@ -1809,6 +1862,8 @@ if (!String.prototype.endsWith) {
         window.register_implementors(window.pending_implementors);
     }
 
+    console.log('4', Date.now() - start);
+
     function labelForToggleButton(sectionIsCollapsed) {
         if (sectionIsCollapsed) {
             // button will expand the section
@@ -1816,16 +1871,18 @@ if (!String.prototype.endsWith) {
         }
         // button will collapse the section
         // note that this text is also set in the HTML template in render.rs
-        return "\u2212"; // "\u2212" is '−' minus sign
+        return "\u2212"; // "\u2212" is "−" minus sign
     }
 
     function onEveryMatchingChild(elem, className, func) {
         if (elem && className && func) {
-            for (var i = 0; i < elem.childNodes.length; i++) {
-                if (hasClass(elem.childNodes[i], className)) {
-                    func(elem.childNodes[i]);
+            var length = elem.childNodes.length;
+            var nodes = elem.childNodes;
+            for (var i = 0; i < length; ++i) {
+                if (hasClass(nodes[i], className)) {
+                    func(nodes[i]);
                 } else {
-                    onEveryMatchingChild(elem.childNodes[i], className, func);
+                    onEveryMatchingChild(nodes[i], className, func);
                 }
             }
         }
@@ -1870,27 +1927,58 @@ if (!String.prototype.endsWith) {
 
         function adjustToggle(arg) {
             return function(e) {
-                if (hasClass(e, 'toggle-label')) {
+                if (hasClass(e, "toggle-label")) {
                     if (arg) {
-                        e.style.display = 'inline-block';
+                        e.style.display = "inline-block";
                     } else {
-                        e.style.display = 'none';
+                        e.style.display = "none";
                     }
                 }
-                if (hasClass(e, 'inner')) {
+                if (hasClass(e, "inner")) {
                     e.innerHTML = labelForToggleButton(arg);
                 }
             };
-        };
+        }
 
-        if (!hasClass(toggle.parentNode, "impl")) {
-            var relatedDoc = toggle.parentNode.nextElementSibling;
+        function implHider(addOrRemove) {
+            return function(n) {
+                var is_method = hasClass(n, "method");
+                if (is_method || hasClass(n, "type")) {
+                    if (is_method === true) {
+                        if (addOrRemove) {
+                            addClass(n, "hidden-by-impl-hider");
+                        } else {
+                            removeClass(n, "hidden-by-impl-hider");
+                        }
+                    }
+                    var ns = n.nextElementSibling;
+                    while (true) {
+                        if (ns && (
+                                hasClass(ns, "docblock") ||
+                                hasClass(ns, "stability"))) {
+                            if (addOrRemove) {
+                                addClass(ns, "hidden-by-impl-hider");
+                            } else {
+                                removeClass(ns, "hidden-by-impl-hider");
+                            }
+                            ns = ns.nextElementSibling;
+                            continue;
+                        }
+                        break;
+                    }
+                }
+            };
+        }
+
+        var relatedDoc;
+        var action;
+        if (hasClass(toggle.parentNode, "impl") === false) {
+            relatedDoc = toggle.parentNode.nextElementSibling;
             if (hasClass(relatedDoc, "stability")) {
                 relatedDoc = relatedDoc.nextElementSibling;
             }
             if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
-                var action = mode;
-                if (action === "toggle") {
+                if (mode === "toggle") {
                     if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
                         action = "show";
                     } else {
@@ -1900,66 +1988,34 @@ if (!String.prototype.endsWith) {
                 if (action === "hide") {
                     addClass(relatedDoc, "hidden-by-usual-hider");
                     onEach(toggle.childNodes, adjustToggle(true));
-                    addClass(toggle.parentNode, 'collapsed');
+                    addClass(toggle.parentNode, "collapsed");
                 } else if (action === "show") {
                     removeClass(relatedDoc, "hidden-by-usual-hider");
-                    removeClass(toggle.parentNode, 'collapsed');
+                    removeClass(toggle.parentNode, "collapsed");
                     onEach(toggle.childNodes, adjustToggle(false));
                 }
             }
         } else {
             // we are collapsing the impl block
-            function implHider(addOrRemove) {
-                return function(n) {
-                    var is_method = hasClass(n, "method");
-                    if (is_method || hasClass(n, "type")) {
-                        if (is_method === true) {
-                            if (addOrRemove) {
-                                addClass(n, "hidden-by-impl-hider");
-                            } else {
-                                removeClass(n, "hidden-by-impl-hider");
-                            }
-                        }
-                        var ns = n.nextElementSibling;
-                        while (true) {
-                            if (ns && (
-                                    hasClass(ns, "docblock") ||
-                                    hasClass(ns, "stability"))) {
-                                if (addOrRemove) {
-                                    addClass(ns, "hidden-by-impl-hider");
-                                } else {
-                                    removeClass(ns, "hidden-by-impl-hider");
-                                }
-                                ns = ns.nextElementSibling;
-                                continue;
-                            }
-                            break;
-                        }
-                    }
-                }
-            }
 
             var parentElem = toggle.parentNode;
-            var relatedDoc = parentElem;
+            relatedDoc = parentElem;
             var docblock = relatedDoc.nextElementSibling;
 
-            while (!hasClass(relatedDoc, "impl-items")) {
+            while (hasClass(relatedDoc, "impl-items") === false) {
                 relatedDoc = relatedDoc.nextElementSibling;
             }
 
-            if ((!relatedDoc && !hasClass(docblock, "docblock")) ||
-                (pageId && onEach(relatedDoc.childNodes, function(e) {
-                    return e.id === pageId;
-                }) === true)) {
+            if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
+                (pageId && relatedDoc.getElementById(pageId))) {
                 return;
             }
 
             // Hide all functions, but not associated types/consts
 
-            var action = mode;
-            if (action === "toggle") {
+            if (mode === "toggle") {
                 if (hasClass(relatedDoc, "fns-now-collapsed") ||
-                    hasClass(docblock,  "hidden-by-impl-hider")) {
+                    hasClass(docblock, "hidden-by-impl-hider")) {
                     action = "show";
                 } else {
                     action = "hide";
@@ -1980,91 +2036,129 @@ if (!String.prototype.endsWith) {
         }
     }
 
+    function collapser(e) {
+        // inherent impl ids are like "impl" or impl-<number>'.
+        // they will never be hidden by default.
+        var n = e.parentElement;
+        if (n.id.match(/^impl(?:-\d+)?$/) === null) {
+            // Automatically minimize all non-inherent impls
+            if (collapse || hasClass(n, "impl")) {
+                collapseDocs(e, "hide", pageId);
+            }
+        }
+    }
+
     function autoCollapse(pageId, collapse) {
         if (collapse) {
             toggleAllDocs(pageId, true);
-        }
-        var collapser = function(e) {
-                // inherent impl ids are like 'impl' or impl-<number>'.
-                // they will never be hidden by default.
-                var n = e.parentElement;
-                if (n.id.match(/^impl(?:-\d+)?$/) === null) {
-                    // Automatically minimize all non-inherent impls
-                    if (collapse || hasClass(n, 'impl')) {
-                        collapseDocs(e, "hide", pageId);
-                    }
-                }
-        };
-        if (getCurrentValue('rustdoc-trait-implementations') !== "false") {
-            var impl_list = document.getElementById('implementations-list');
+        } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
+            var impl_list = document.getElementById("implementations-list");
 
             if (impl_list !== null) {
                 onEach(impl_list.getElementsByClassName("collapse-toggle"), collapser);
             }
         }
-        if (getCurrentValue('rustdoc-method-docs') !== "false") {
-            var implItems = document.getElementsByClassName('impl-items');
-
-            if (implItems && implItems.length > 0) {
-                onEach(implItems, function(elem) {
-                    onEach(elem.getElementsByClassName("collapse-toggle"), collapser);
-                });
-            }
-        }
     }
 
-    var x = document.getElementById('toggle-all-docs');
-    if (x) {
-        x.onclick = toggleAllDocs;
+    var toggles = document.getElementById("toggle-all-docs");
+    if (toggles) {
+        toggles.onclick = toggleAllDocs;
     }
 
     function insertAfter(newNode, referenceNode) {
         referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
     }
 
-    function checkIfThereAreMethods(elems) {
-        var areThereMethods = false;
-
-        onEach(elems, function(e) {
-            if (hasClass(e, "method")) {
-                areThereMethods = true;
-                return true;
-            }
-        });
-        return areThereMethods;
-    }
-
-    var toggle = document.createElement('a');
-    toggle.href = 'javascript:void(0)';
-    toggle.className = 'collapse-toggle';
-    toggle.innerHTML = "[<span class='inner'>" + labelForToggleButton(false) + "</span>]";
+    var toggle = document.createElement("a");
+    toggle.href = "javascript:void(0)";
+    toggle.className = "collapse-toggle";
+    toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) + "</span>]";
 
     var func = function(e) {
         var next = e.nextElementSibling;
-        if (hasClass(e, 'impl') && next && hasClass(next, 'docblock')) {
+        if (next && hasClass(e, "impl") && hasClass(next, "docblock")) {
             next = next.nextElementSibling;
         }
         if (!next) {
             return;
         }
-        if ((hasClass(e, 'method') || hasClass(e, 'associatedconstant') ||
-             checkIfThereAreMethods(next.childNodes)) &&
-            (hasClass(next, 'docblock') ||
-             hasClass(e, 'impl') ||
-             (hasClass(next, 'stability') &&
-              hasClass(next.nextElementSibling, 'docblock')))) {
+        if ((hasClass(e, "method") || hasClass(e, "associatedconstant") ||
+             next.getElementsByClassName("method").length > 0) &&
+            (hasClass(next, "docblock") ||
+             hasClass(e, "impl") ||
+             (hasClass(next, "stability") &&
+              hasClass(next.nextElementSibling, "docblock")))) {
             insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
         }
     };
-    onEach(document.getElementsByClassName('method'), func);
-    onEach(document.getElementsByClassName('associatedconstant'), func);
-    onEach(document.getElementsByClassName('impl'), func);
-    onEach(document.getElementsByClassName('impl-items'), function(e) {
-        onEach(e.getElementsByClassName('associatedconstant'), func);
-        var hiddenElems = e.getElementsByClassName('hidden');
+
+    var func2 = function(e) {
+        var next = e.nextElementSibling;
+        if (next && hasClass(next, "docblock")) {
+            next = next.nextElementSibling;
+        }
+        if (!next) {
+            return;
+        }
+        if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
+            insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
+        }
+    };
+
+    console.log('5', Date.now() - start);
+    onEach(document.getElementsByClassName("method"), func);
+    console.log('6', Date.now() - start);
+    onEach(document.getElementsByClassName("associatedconstant"), func);
+    console.log('7', Date.now() - start);
+    onEach(document.getElementsByClassName("impl"), func2   );
+    console.log('8', Date.now() - start);
+    var impl_call = function() {};
+    if (getCurrentValue("rustdoc-method-docs") !== "false") {
+        impl_call = function(e, newToggle, pageId) {
+            if (e.id.match(/^impl(?:-\d+)?$/) === null) {
+                // Automatically minimize all non-inherent impls
+                if (hasClass(e, "impl")) {
+                    collapseDocs(newToggle, "hide", pageId);
+                }
+            }
+        };
+    }
+    var pageId = getPageId();
+    var newToggle = document.createElement("a");
+    newToggle.href = "javascript:void(0)";
+    newToggle.className = "collapse-toggle hidden-default collapsed";
+    newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
+                          "</span>] Show hidden undocumented items";
+    function toggleClicked() {
+        if (hasClass(this, "collapsed")) {
+            removeClass(this, "collapsed");
+            onEach(this.parentNode.getElementsByClassName("hidden"), function(x) {
+                if (hasClass(x, "content") === false) {
+                    removeClass(x, "hidden");
+                    addClass(x, "x");
+                }
+            }, true);
+            this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
+                             "</span>] Hide undocumented items";
+        } else {
+            addClass(this, "collapsed");
+            onEach(this.parentNode.getElementsByClassName("x"), function(x) {
+                if (hasClass(x, "content") === false) {
+                    addClass(x, "hidden");
+                    removeClass(x, "x");
+                }
+            }, true);
+            this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
+                             "</span>] Show hidden undocumented items";
+        }
+    }
+    onEach(document.getElementsByClassName("impl-items"), function(e) {
+        onEach(e.getElementsByClassName("associatedconstant"), func);
+        var hiddenElems = e.getElementsByClassName("hidden");
         var needToggle = false;
 
-        for (var i = 0; i < hiddenElems.length; ++i) {
+        var hlength = hiddenElems.length;
+        for (var i = 0; i < hlength; ++i) {
             if (hasClass(hiddenElems[i], "content") === false &&
                 hasClass(hiddenElems[i], "docblock") === false) {
                 needToggle = true;
@@ -2072,46 +2166,22 @@ if (!String.prototype.endsWith) {
             }
         }
         if (needToggle === true) {
-            var newToggle = document.createElement('a');
-            newToggle.href = 'javascript:void(0)';
-            newToggle.className = 'collapse-toggle hidden-default collapsed';
-            newToggle.innerHTML = "[<span class='inner'>" + labelForToggleButton(true) + "</span>" +
-                                  "] Show hidden undocumented items";
-            newToggle.onclick = function() {
-                if (hasClass(this, "collapsed")) {
-                    removeClass(this, "collapsed");
-                    onEach(this.parentNode.getElementsByClassName("hidden"), function(x) {
-                        if (hasClass(x, "content") === false) {
-                            removeClass(x, "hidden");
-                            addClass(x, "x");
-                        }
-                    }, true);
-                    this.innerHTML = "[<span class='inner'>" + labelForToggleButton(false) +
-                                     "</span>] Hide undocumented items"
-                } else {
-                    addClass(this, "collapsed");
-                    onEach(this.parentNode.getElementsByClassName("x"), function(x) {
-                        if (hasClass(x, "content") === false) {
-                            addClass(x, "hidden");
-                            removeClass(x, "x");
-                        }
-                    }, true);
-                    this.innerHTML = "[<span class='inner'>" + labelForToggleButton(true) +
-                                     "</span>] Show hidden undocumented items";
-                }
-            };
-            e.insertBefore(newToggle, e.firstChild);
+            var toggle = newToggle.cloneNode(true);
+            toggle.onclick = toggleClicked;
+            e.insertBefore(toggle, e.firstChild);
+            impl_call(e, toggle, pageId);
         }
     });
+    console.log('9', Date.now() - start);
 
     function createToggle(otherMessage, fontSize, extraClass, show) {
-        var span = document.createElement('span');
-        span.className = 'toggle-label';
+        var span = document.createElement("span");
+        span.className = "toggle-label";
         if (show) {
-            span.style.display = 'none';
+            span.style.display = "none";
         }
         if (!otherMessage) {
-            span.innerHTML = '&nbsp;Expand&nbsp;description';
+            span.innerHTML = "&nbsp;Expand&nbsp;description";
         } else {
             span.innerHTML = otherMessage;
         }
@@ -2123,13 +2193,13 @@ if (!String.prototype.endsWith) {
         var mainToggle = toggle.cloneNode(true);
         mainToggle.appendChild(span);
 
-        var wrapper = document.createElement('div');
-        wrapper.className = 'toggle-wrapper';
+        var wrapper = document.createElement("div");
+        wrapper.className = "toggle-wrapper";
         if (!show) {
-            addClass(wrapper, 'collapsed');
-            var inner = mainToggle.getElementsByClassName('inner');
+            addClass(wrapper, "collapsed");
+            var inner = mainToggle.getElementsByClassName("inner");
             if (inner && inner.length > 0) {
-                inner[0].innerHTML = '+';
+                inner[0].innerHTML = "+";
             }
         }
         if (extraClass) {
@@ -2139,21 +2209,21 @@ if (!String.prototype.endsWith) {
         return wrapper;
     }
 
-    var showItemDeclarations = getCurrentValue('rustdoc-item-declarations') === "false";
+    var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
     function buildToggleWrapper(e) {
-        if (hasClass(e, 'autohide')) {
+        if (hasClass(e, "autohide")) {
             var wrap = e.previousElementSibling;
-            if (wrap && hasClass(wrap, 'toggle-wrapper')) {
+            if (wrap && hasClass(wrap, "toggle-wrapper")) {
                 var toggle = wrap.childNodes[0];
-                var extra = e.childNodes[0].tagName === 'H3';
+                var extra = e.childNodes[0].tagName === "H3";
 
-                e.style.display = 'none';
-                addClass(wrap, 'collapsed');
-                onEach(toggle.getElementsByClassName('inner'), function(e) {
+                e.style.display = "none";
+                addClass(wrap, "collapsed");
+                onEach(toggle.getElementsByClassName("inner"), function(e) {
                     e.innerHTML = labelForToggleButton(true);
                 });
-                onEach(toggle.getElementsByClassName('toggle-label'), function(e) {
-                    e.style.display = 'inline-block';
+                onEach(toggle.getElementsByClassName("toggle-label"), function(e) {
+                    e.style.display = "inline-block";
                     if (extra === true) {
                         i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
                     }
@@ -2161,28 +2231,28 @@ if (!String.prototype.endsWith) {
             }
         }
         if (e.parentNode.id === "main") {
-            var otherMessage = '';
+            var otherMessage = "";
             var fontSize;
             var extraClass;
 
             if (hasClass(e, "type-decl")) {
                 fontSize = "20px";
-                otherMessage = '&nbsp;Show&nbsp;declaration';
+                otherMessage = "&nbsp;Show&nbsp;declaration";
                 if (showItemDeclarations === false) {
-                    extraClass = 'collapsed';
+                    extraClass = "collapsed";
                 }
             } else if (hasClass(e, "sub-variant")) {
-                otherMessage = '&nbsp;Show&nbsp;fields';
+                otherMessage = "&nbsp;Show&nbsp;fields";
             } else if (hasClass(e, "non-exhaustive")) {
-                otherMessage = '&nbsp;This&nbsp;';
+                otherMessage = "&nbsp;This&nbsp;";
                 if (hasClass(e, "non-exhaustive-struct")) {
-                    otherMessage += 'struct';
+                    otherMessage += "struct";
                 } else if (hasClass(e, "non-exhaustive-enum")) {
-                    otherMessage += 'enum';
+                    otherMessage += "enum";
                 } else if (hasClass(e, "non-exhaustive-type")) {
-                    otherMessage += 'type';
+                    otherMessage += "type";
                 }
-                otherMessage += '&nbsp;is&nbsp;marked&nbsp;as&nbsp;non-exhaustive';
+                otherMessage += "&nbsp;is&nbsp;marked&nbsp;as&nbsp;non-exhaustive";
             } else if (hasClass(e.childNodes[0], "impl-items")) {
                 extraClass = "marg-left";
             }
@@ -2199,18 +2269,21 @@ if (!String.prototype.endsWith) {
         }
     }
 
-    onEach(document.getElementsByClassName('docblock'), buildToggleWrapper);
-    onEach(document.getElementsByClassName('sub-variant'), buildToggleWrapper);
+    console.log('10', Date.now() - start);
+    onEach(document.getElementsByClassName("docblock"), buildToggleWrapper);
+    console.log('11', Date.now() - start);
+    onEach(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
+    console.log('12', Date.now() - start);
 
     function createToggleWrapper(tog) {
-        var span = document.createElement('span');
-        span.className = 'toggle-label';
-        span.style.display = 'none';
-        span.innerHTML = '&nbsp;Expand&nbsp;attributes';
+        var span = document.createElement("span");
+        span.className = "toggle-label";
+        span.style.display = "none";
+        span.innerHTML = "&nbsp;Expand&nbsp;attributes";
         tog.appendChild(span);
 
-        var wrapper = document.createElement('div');
-        wrapper.className = 'toggle-wrapper toggle-attributes';
+        var wrapper = document.createElement("div");
+        wrapper.className = "toggle-wrapper toggle-attributes";
         wrapper.appendChild(tog);
         return wrapper;
     }
@@ -2221,19 +2294,19 @@ if (!String.prototype.endsWith) {
             currentTab = nb;
         }
         var nb_copy = nb;
-        onEach(document.getElementById('titles').childNodes, function(elem) {
+        onEach(document.getElementById("titles").childNodes, function(elem) {
             if (nb_copy === 0) {
-                addClass(elem, 'selected');
+                addClass(elem, "selected");
             } else {
-                removeClass(elem, 'selected');
+                removeClass(elem, "selected");
             }
             nb_copy -= 1;
         });
-        onEach(document.getElementById('results').childNodes, function(elem) {
+        onEach(document.getElementById("results").childNodes, function(elem) {
             if (nb === 0) {
-                elem.style.display = '';
+                elem.style.display = "";
             } else {
-                elem.style.display = 'none';
+                elem.style.display = "none";
             }
             nb -= 1;
         });
@@ -2246,54 +2319,57 @@ if (!String.prototype.endsWith) {
             collapseDocs(x.previousSibling.childNodes[0], "toggle");
         };
     }
-    onEach(document.getElementById('main').getElementsByClassName('attributes'), function(i_e) {
+    onEach(document.getElementById("main").getElementsByClassName("attributes"), function(i_e) {
         i_e.parentNode.insertBefore(createToggleWrapper(toggle.cloneNode(true)), i_e);
         itemAttributesFunc(i_e);
     });
+    console.log('12a', Date.now() - start);
 
     // To avoid checking on "rustdoc-line-numbers" value on every loop...
     var lineNumbersFunc = function() {};
     if (getCurrentValue("rustdoc-line-numbers") === "true") {
         lineNumbersFunc = function(x) {
-            var count = x.textContent.split('\n').length;
+            var count = x.textContent.split("\n").length;
             var elems = [];
             for (var i = 0; i < count; ++i) {
                 elems.push(i + 1);
             }
-            var node = document.createElement('pre');
-            addClass(node, 'line-number');
-            node.innerHTML = elems.join('\n');
+            var node = document.createElement("pre");
+            addClass(node, "line-number");
+            node.innerHTML = elems.join("\n");
             x.parentNode.insertBefore(node, x);
         };
     }
-    onEach(document.getElementsByClassName('rust-example-rendered'), function(e) {
-        if (hasClass(e, 'compile_fail')) {
+    console.log('13', Date.now() - start);
+    onEach(document.getElementsByClassName("rust-example-rendered"), function(e) {
+        if (hasClass(e, "compile_fail")) {
             e.addEventListener("mouseover", function(event) {
-                this.parentElement.previousElementSibling.childNodes[0].style.color = '#f00';
+                this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
             });
             e.addEventListener("mouseout", function(event) {
-                this.parentElement.previousElementSibling.childNodes[0].style.color = '';
+                this.parentElement.previousElementSibling.childNodes[0].style.color = "";
             });
-        } else if (hasClass(e, 'ignore')) {
+        } else if (hasClass(e, "ignore")) {
             e.addEventListener("mouseover", function(event) {
-                this.parentElement.previousElementSibling.childNodes[0].style.color = '#ff9200';
+                this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
             });
             e.addEventListener("mouseout", function(event) {
-                this.parentElement.previousElementSibling.childNodes[0].style.color = '';
+                this.parentElement.previousElementSibling.childNodes[0].style.color = "";
             });
         }
         lineNumbersFunc(e);
     });
+    console.log('14', Date.now() - start);
 
     function showModal(content) {
-        var modal = document.createElement('div');
+        var modal = document.createElement("div");
         modal.id = "important";
-        addClass(modal, 'modal');
-        modal.innerHTML = '<div class="modal-content"><div class="close" id="modal-close">✕</div>' +
-                          '<div class="whiter"></div><span class="docblock">' + content +
-                          '</span></div>';
-        document.getElementsByTagName('body')[0].appendChild(modal);
-        document.getElementById('modal-close').onclick = hideModal;
+        addClass(modal, "modal");
+        modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
+                          "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
+                          "</span></div>";
+        document.getElementsByTagName("body")[0].appendChild(modal);
+        document.getElementById("modal-close").onclick = hideModal;
         modal.onclick = hideModal;
     }
 
@@ -2304,11 +2380,12 @@ if (!String.prototype.endsWith) {
         }
     }
 
-    onEach(document.getElementsByClassName('important-traits'), function(e) {
+    onEach(document.getElementsByClassName("important-traits"), function(e) {
         e.onclick = function() {
             showModal(e.lastElementChild.innerHTML);
         };
     });
+    console.log('15', Date.now() - start);
 
     function putBackSearch(search_input) {
         if (search_input.value !== "") {
@@ -2333,13 +2410,13 @@ if (!String.prototype.endsWith) {
         addClass(document.getElementById("main"), "hidden");
         var search = document.getElementById("search");
         removeClass(search, "hidden");
-        search.innerHTML = '<h3 style="text-align: center;">Loading search results...</h3>';
+        search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
     }
 
     var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
     if (sidebar_menu) {
         sidebar_menu.onclick = function() {
-            var sidebar = document.getElementsByClassName('sidebar')[0];
+            var sidebar = document.getElementsByClassName("sidebar")[0];
             if (hasClass(sidebar, "mobile") === true) {
                 hideSidebar();
             } else {
@@ -2352,10 +2429,23 @@ if (!String.prototype.endsWith) {
         hideSidebar();
     };
 
+    console.log('16', Date.now() - start);
     autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
+    console.log('17', Date.now() - start);
 
     if (window.location.hash && window.location.hash.length > 0) {
-        expandSection(window.location.hash.replace(/^#/, ''));
+        expandSection(window.location.hash.replace(/^#/, ""));
+    }
+
+    var main = document.getElementById("main");
+    if (main) {
+        console.log('18', Date.now() - start);
+        onEach(main.childNodes, function(e) {
+            if (e.tagName === "H2" || e.tagName === "H3") {
+                e.nextElementSibling.style.display = "block";
+            }
+        });
+        console.log('19', Date.now() - start);
     }
 
     function addSearchOptions(crates) {
@@ -2394,10 +2484,10 @@ if (!String.prototype.endsWith) {
 
 // Sets the focus on the search bar at the top of the page
 function focusSearchBar() {
-    document.getElementsByClassName('search-input')[0].focus();
+    document.getElementsByClassName("search-input")[0].focus();
 }
 
 // Removes the focus from the search bar
 function defocusSearchBar() {
-    document.getElementsByClassName('search-input')[0].blur();
+    document.getElementsByClassName("search-input")[0].blur();
 }
diff --git a/src/librustdoc/html/static/rustdoc.css b/src/librustdoc/html/static/rustdoc.css
index 37d26a4cadc57..3e2e6d6eb4caa 100644
--- a/src/librustdoc/html/static/rustdoc.css
+++ b/src/librustdoc/html/static/rustdoc.css
@@ -368,6 +368,10 @@ body:not(.source) .example-wrap > pre {
 #main > .docblock h2 { font-size: 1.15em; }
 #main > .docblock h3, #main > .docblock h4, #main > .docblock h5 { font-size: 1em; }
 
+#main > h2 + div, #main > h2 + h3, #main > h3 + div {
+	display: none;
+}
+
 .docblock h1 { font-size: 1em; }
 .docblock h2 { font-size: 0.95em; }
 .docblock h3, .docblock h4, .docblock h5 { font-size: 0.9em; }
diff --git a/src/librustdoc/html/static/storage.js b/src/librustdoc/html/static/storage.js
index e8f0c03d91aa6..1b2732a51c150 100644
--- a/src/librustdoc/html/static/storage.js
+++ b/src/librustdoc/html/static/storage.js
@@ -19,55 +19,44 @@ var mainTheme = document.getElementById("mainThemeStyle");
 var savedHref = [];
 
 function hasClass(elem, className) {
-    if (elem && className && elem.className) {
-        var elemClass = elem.className;
-        var start = elemClass.indexOf(className);
-        if (start === -1) {
-            return false;
-        } else if (elemClass.length === className.length) {
-            return true;
-        } else {
-            if (start > 0 && elemClass[start - 1] !== ' ') {
-                return false;
-            }
-            var end = start + className.length;
-            return !(end < elemClass.length && elemClass[end] !== ' ');
-        }
+    if (!elem || !elem.classList) {
+        return false;
     }
-    return false;
+    return elem.classList.contains(className);
 }
 
 function addClass(elem, className) {
-    if (elem && className && !hasClass(elem, className)) {
-        if (elem.className && elem.className.length > 0) {
-            elem.className += ' ' + className;
-        } else {
-            elem.className = className;
-        }
+    if (!elem || !elem.classList) {
+        return;
     }
+    elem.classList.add(className);
 }
 
 function removeClass(elem, className) {
-    if (elem && className && elem.className) {
-        elem.className = (" " + elem.className + " ").replace(" " + className + " ", " ")
-                                                     .trim();
+    if (!elem || !elem.classList) {
+        return;
     }
+    elem.classList.remove(className);
 }
 
 function isHidden(elem) {
-    return (elem.offsetParent === null)
+    return (elem.offsetParent === null);
 }
 
+var allcallers = {};
+var resourcesSuffix="";
+
 function onEach(arr, func, reversed) {
     if (arr && arr.length > 0 && func) {
+        var length = arr.length;
         if (reversed !== true) {
-            for (var i = 0; i < arr.length; ++i) {
+            for (var i = 0; i < length; ++i) {
                 if (func(arr[i]) === true) {
                     return true;
                 }
             }
         } else {
-            for (var i = arr.length - 1; i >= 0; --i) {
+            for (var i = length - 1; i >= 0; --i) {
                 if (func(arr[i]) === true) {
                     return true;
                 }
@@ -133,8 +122,8 @@ function switchTheme(styleElem, mainStyleElem, newTheme) {
     });
     if (found === true) {
         styleElem.href = newHref;
-        updateLocalStorage('rustdoc-theme', newTheme);
+        updateLocalStorage("rustdoc-theme", newTheme);
     }
 }
 
-switchTheme(currentTheme, mainTheme, getCurrentValue('rustdoc-theme') || 'light');
+switchTheme(currentTheme, mainTheme, getCurrentValue("rustdoc-theme") || "light");

From 34e31830c0da20a7ccc1a83a423437fb2ee073d3 Mon Sep 17 00:00:00 2001
From: Guillaume Gomez <guillaume1.gomez@gmail.com>
Date: Mon, 26 Nov 2018 17:17:38 +0100
Subject: [PATCH 2/5] Prevent lazy iterations over DOM

---
 src/librustdoc/html/static/main.js | 204 ++++++++++++++---------------
 1 file changed, 99 insertions(+), 105 deletions(-)

diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js
index 76ef47e10976d..adc49da61da13 100644
--- a/src/librustdoc/html/static/main.js
+++ b/src/librustdoc/html/static/main.js
@@ -148,12 +148,10 @@ if (!DOMTokenList.prototype.remove) {
     var TY_PRIMITIVE = itemTypes.indexOf("primitive");
     var TY_KEYWORD = itemTypes.indexOf("keyword");
 
-    onEach(document.getElementsByClassName("js-only"), function(e) {
+    onEach(Array.prototype.slice.call(document.getElementsByClassName("js-only")), function(e) {
         removeClass(e, "js-only");
     });
 
-    console.log('1', Date.now() - start);
-
     function getQueryStringParams() {
         var params = {};
         window.location.search.substring(1).split("&").
@@ -170,6 +168,8 @@ if (!DOMTokenList.prototype.remove) {
           window.history && typeof window.history.pushState === "function";
     }
 
+    var main = document.getElementById("main");
+
     function highlightSourceLines(ev) {
         // If we're in mobile mode, we should add the sidebar in any case.
         hideSidebar();
@@ -190,8 +190,9 @@ if (!DOMTokenList.prototype.remove) {
                     x.scrollIntoView();
                 }
             }
-            onEach(document.getElementsByClassName("line-numbers"), function(e) {
-                onEach(e.getElementsByTagName("span"), function(i_e) {
+            onEach(Array.prototype.slice.call(document.getElementsByClassName("line-numbers")),
+                   function(e) {
+                onEach(Array.prototype.slice.call(e.getElementsByTagName("span")), function(i_e) {
                     removeClass(i_e, "line-highlighted");
                 });
             });
@@ -200,7 +201,7 @@ if (!DOMTokenList.prototype.remove) {
             }
         } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
             addClass(search, "hidden");
-            removeClass(document.getElementById("main"), "hidden");
+            removeClass(main, "hidden");
             var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
             if (browserSupportsHistoryApi()) {
                 history.replaceState(hash, "", "?search=#" + hash);
@@ -233,8 +234,6 @@ if (!DOMTokenList.prototype.remove) {
     highlightSourceLines(null);
     window.onhashchange = highlightSourceLines;
 
-    console.log('2', Date.now() - start);
-
     // Gets the human-readable string for the virtual-key code of the
     // given KeyboardEvent, ev.
     //
@@ -279,7 +278,7 @@ if (!DOMTokenList.prototype.remove) {
         } else if (hasClass(search, "hidden") === false) {
             ev.preventDefault();
             addClass(search, "hidden");
-            removeClass(document.getElementById("main"), "hidden");
+            removeClass(main, "hidden");
             document.title = titleBeforeSearch;
         }
         defocusSearchBar();
@@ -407,8 +406,6 @@ if (!DOMTokenList.prototype.remove) {
         };
     }
 
-    console.log('3', Date.now() - start);
-
     /**
      * A function to compute the Levenshtein distance between two strings
      * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
@@ -1183,7 +1180,7 @@ if (!DOMTokenList.prototype.remove) {
                 dst = dst[0];
                 if (window.location.pathname === dst.pathname) {
                     addClass(document.getElementById("search"), "hidden");
-                    removeClass(document.getElementById("main"), "hidden");
+                    removeClass(main, "hidden");
                     document.location.href = dst.href;
                 }
             };
@@ -1411,7 +1408,7 @@ if (!DOMTokenList.prototype.remove) {
                 "</div><div id=\"results\">" +
                 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
 
-            addClass(document.getElementById("main"), "hidden");
+            addClass(main, "hidden");
             var search = document.getElementById("search");
             removeClass(search, "hidden");
             search.innerHTML = output;
@@ -1421,7 +1418,7 @@ if (!DOMTokenList.prototype.remove) {
                 td_width = tds[0].offsetWidth;
             }
             var width = search.offsetWidth - 40 - td_width;
-            onEach(search.getElementsByClassName("desc"), function(e) {
+            onEach(Array.prototype.slice.call(search.getElementsByClassName("desc")), function(e) {
                 e.style.width = width + "px";
             });
             initSearchNav();
@@ -1619,7 +1616,6 @@ if (!DOMTokenList.prototype.remove) {
                     if (browserSupportsHistoryApi()) {
                         history.replaceState("", "std - Rust", "?search=");
                     }
-                    var main = document.getElementById("main");
                     if (hasClass(main, "content")) {
                         removeClass(main, "hidden");
                     }
@@ -1666,7 +1662,6 @@ if (!DOMTokenList.prototype.remove) {
                     // When browsing back from search results the main page
                     // visibility must be reset.
                     if (!params.search) {
-                        var main = document.getElementById("main");
                         if (hasClass(main, "content")) {
                             removeClass(main, "hidden");
                         }
@@ -1862,8 +1857,6 @@ if (!DOMTokenList.prototype.remove) {
         window.register_implementors(window.pending_implementors);
     }
 
-    console.log('4', Date.now() - start);
-
     function labelForToggleButton(sectionIsCollapsed) {
         if (sectionIsCollapsed) {
             // button will expand the section
@@ -1889,31 +1882,35 @@ if (!DOMTokenList.prototype.remove) {
     }
 
     function toggleAllDocs(pageId, fromAutoCollapse) {
-        var toggle = document.getElementById("toggle-all-docs");
-        if (!toggle) {
+        var innerToggle = document.getElementById("toggle-all-docs");
+        if (!innerToggle) {
             return;
         }
-        if (hasClass(toggle, "will-expand")) {
+        if (hasClass(innerToggle, "will-expand")) {
             updateLocalStorage("rustdoc-collapse", "false");
-            removeClass(toggle, "will-expand");
-            onEveryMatchingChild(toggle, "inner", function(e) {
+            removeClass(innerToggle, "will-expand");
+            onEveryMatchingChild(innerToggle, "inner", function(e) {
                 e.innerHTML = labelForToggleButton(false);
             });
-            toggle.title = "collapse all docs";
+            innerToggle.title = "collapse all docs";
             if (fromAutoCollapse !== true) {
-                onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
+                onEach(Array.prototype.slice.call(
+                           document.getElementsByClassName("collapse-toggle")),
+                       function(e) {
                     collapseDocs(e, "show");
                 });
             }
         } else {
             updateLocalStorage("rustdoc-collapse", "true");
-            addClass(toggle, "will-expand");
-            onEveryMatchingChild(toggle, "inner", function(e) {
+            addClass(innerToggle, "will-expand");
+            onEveryMatchingChild(innerToggle, "inner", function(e) {
                 e.innerHTML = labelForToggleButton(true);
             });
-            toggle.title = "expand all docs";
+            innerToggle.title = "expand all docs";
             if (fromAutoCollapse !== true) {
-                onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
+                onEach(Array.prototype.slice.call(
+                           document.getElementsByClassName("collapse-toggle")),
+                       function(e) {
                     collapseDocs(e, "hide", pageId);
                 });
             }
@@ -1987,12 +1984,12 @@ if (!DOMTokenList.prototype.remove) {
                 }
                 if (action === "hide") {
                     addClass(relatedDoc, "hidden-by-usual-hider");
-                    onEach(toggle.childNodes, adjustToggle(true));
+                    onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(true));
                     addClass(toggle.parentNode, "collapsed");
                 } else if (action === "show") {
                     removeClass(relatedDoc, "hidden-by-usual-hider");
                     removeClass(toggle.parentNode, "collapsed");
-                    onEach(toggle.childNodes, adjustToggle(false));
+                    onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(false));
                 }
             }
         } else {
@@ -2025,13 +2022,13 @@ if (!DOMTokenList.prototype.remove) {
             if (action === "show") {
                 removeClass(relatedDoc, "fns-now-collapsed");
                 removeClass(docblock, "hidden-by-usual-hider");
-                onEach(toggle.childNodes, adjustToggle(false));
-                onEach(relatedDoc.childNodes, implHider(false));
+                onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(false));
+                onEach(Array.prototype.slice.call(relatedDoc.childNodes), implHider(false));
             } else if (action === "hide") {
                 addClass(relatedDoc, "fns-now-collapsed");
                 addClass(docblock, "hidden-by-usual-hider");
-                onEach(toggle.childNodes, adjustToggle(true));
-                onEach(relatedDoc.childNodes, implHider(true));
+                onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(true));
+                onEach(Array.prototype.slice.call(relatedDoc.childNodes), implHider(true));
             }
         }
     }
@@ -2055,7 +2052,9 @@ if (!DOMTokenList.prototype.remove) {
             var impl_list = document.getElementById("implementations-list");
 
             if (impl_list !== null) {
-                onEach(impl_list.getElementsByClassName("collapse-toggle"), collapser);
+                onEach(Array.prototype.slice.call(
+                           impl_list.getElementsByClassName("collapse-toggle")),
+                       collapser);
             }
         }
     }
@@ -2069,30 +2068,30 @@ if (!DOMTokenList.prototype.remove) {
         referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
     }
 
-    var toggle = document.createElement("a");
-    toggle.href = "javascript:void(0)";
-    toggle.className = "collapse-toggle";
-    toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) + "</span>]";
+    function createSimpleToggle(sectionIsCollapsed) {
+        var toggle = document.createElement("a");
+        toggle.href = "javascript:void(0)";
+        toggle.className = "collapse-toggle";
+        toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
+                           "</span>]";
+        return toggle;
+    }
+
+    var toggle = createSimpleToggle(false);
 
     var func = function(e) {
         var next = e.nextElementSibling;
-        if (next && hasClass(e, "impl") && hasClass(next, "docblock")) {
-            next = next.nextElementSibling;
-        }
         if (!next) {
             return;
         }
-        if ((hasClass(e, "method") || hasClass(e, "associatedconstant") ||
-             next.getElementsByClassName("method").length > 0) &&
-            (hasClass(next, "docblock") ||
-             hasClass(e, "impl") ||
-             (hasClass(next, "stability") &&
-              hasClass(next.nextElementSibling, "docblock")))) {
+        if (hasClass(next, "docblock") ||
+            (hasClass(next, "stability") &&
+             hasClass(next.nextElementSibling, "docblock"))) {
             insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
         }
     };
 
-    var func2 = function(e) {
+    var funcImpl = function(e) {
         var next = e.nextElementSibling;
         if (next && hasClass(next, "docblock")) {
             next = next.nextElementSibling;
@@ -2105,13 +2104,9 @@ if (!DOMTokenList.prototype.remove) {
         }
     };
 
-    console.log('5', Date.now() - start);
-    onEach(document.getElementsByClassName("method"), func);
-    console.log('6', Date.now() - start);
-    onEach(document.getElementsByClassName("associatedconstant"), func);
-    console.log('7', Date.now() - start);
-    onEach(document.getElementsByClassName("impl"), func2   );
-    console.log('8', Date.now() - start);
+    onEach(Array.prototype.slice.call(document.getElementsByClassName("method")), func);
+    onEach(Array.prototype.slice.call(document.getElementsByClassName("associatedconstant")), func);
+    onEach(Array.prototype.slice.call(document.getElementsByClassName("impl")), funcImpl);
     var impl_call = function() {};
     if (getCurrentValue("rustdoc-method-docs") !== "false") {
         impl_call = function(e, newToggle, pageId) {
@@ -2132,7 +2127,8 @@ if (!DOMTokenList.prototype.remove) {
     function toggleClicked() {
         if (hasClass(this, "collapsed")) {
             removeClass(this, "collapsed");
-            onEach(this.parentNode.getElementsByClassName("hidden"), function(x) {
+            onEach(Array.prototype.slice.call(this.parentNode.getElementsByClassName("hidden")),
+                   function(x) {
                 if (hasClass(x, "content") === false) {
                     removeClass(x, "hidden");
                     addClass(x, "x");
@@ -2142,7 +2138,8 @@ if (!DOMTokenList.prototype.remove) {
                              "</span>] Hide undocumented items";
         } else {
             addClass(this, "collapsed");
-            onEach(this.parentNode.getElementsByClassName("x"), function(x) {
+            onEach(Array.prototype.slice.call(this.parentNode.getElementsByClassName("x")),
+                   function(x) {
                 if (hasClass(x, "content") === false) {
                     addClass(x, "hidden");
                     removeClass(x, "x");
@@ -2152,8 +2149,8 @@ if (!DOMTokenList.prototype.remove) {
                              "</span>] Show hidden undocumented items";
         }
     }
-    onEach(document.getElementsByClassName("impl-items"), function(e) {
-        onEach(e.getElementsByClassName("associatedconstant"), func);
+    onEach(Array.prototype.slice.call(document.getElementsByClassName("impl-items")), function(e) {
+        onEach(Array.prototype.slice.call(e.getElementsByClassName("associatedconstant")), func);
         var hiddenElems = e.getElementsByClassName("hidden");
         var needToggle = false;
 
@@ -2166,13 +2163,12 @@ if (!DOMTokenList.prototype.remove) {
             }
         }
         if (needToggle === true) {
-            var toggle = newToggle.cloneNode(true);
-            toggle.onclick = toggleClicked;
-            e.insertBefore(toggle, e.firstChild);
-            impl_call(e, toggle, pageId);
+            var inner_toggle = newToggle.cloneNode(true);
+            inner_toggle.onclick = toggleClicked;
+            e.insertBefore(inner_toggle, e.firstChild);
+            impl_call(e, inner_toggle, pageId);
         }
     });
-    console.log('9', Date.now() - start);
 
     function createToggle(otherMessage, fontSize, extraClass, show) {
         var span = document.createElement("span");
@@ -2214,15 +2210,18 @@ if (!DOMTokenList.prototype.remove) {
         if (hasClass(e, "autohide")) {
             var wrap = e.previousElementSibling;
             if (wrap && hasClass(wrap, "toggle-wrapper")) {
-                var toggle = wrap.childNodes[0];
+                var inner_toggle = wrap.childNodes[0];
                 var extra = e.childNodes[0].tagName === "H3";
 
                 e.style.display = "none";
                 addClass(wrap, "collapsed");
-                onEach(toggle.getElementsByClassName("inner"), function(e) {
+                onEach(Array.prototype.slice.call(inner_toggle.getElementsByClassName("inner")),
+                       function(e) {
                     e.innerHTML = labelForToggleButton(true);
                 });
-                onEach(toggle.getElementsByClassName("toggle-label"), function(e) {
+                onEach(Array.prototype.slice.call(
+                           inner_toggle.getElementsByClassName("toggle-label")),
+                       function(e) {
                     e.style.display = "inline-block";
                     if (extra === true) {
                         i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
@@ -2269,24 +2268,10 @@ if (!DOMTokenList.prototype.remove) {
         }
     }
 
-    console.log('10', Date.now() - start);
-    onEach(document.getElementsByClassName("docblock"), buildToggleWrapper);
-    console.log('11', Date.now() - start);
-    onEach(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
-    console.log('12', Date.now() - start);
-
-    function createToggleWrapper(tog) {
-        var span = document.createElement("span");
-        span.className = "toggle-label";
-        span.style.display = "none";
-        span.innerHTML = "&nbsp;Expand&nbsp;attributes";
-        tog.appendChild(span);
-
-        var wrapper = document.createElement("div");
-        wrapper.className = "toggle-wrapper toggle-attributes";
-        wrapper.appendChild(tog);
-        return wrapper;
-    }
+    onEach(Array.prototype.slice.call(document.getElementsByClassName("docblock")),
+           buildToggleWrapper);
+    onEach(Array.prototype.slice.call(document.getElementsByClassName("sub-variant")),
+           buildToggleWrapper);
 
     // In the search display, allows to switch between tabs.
     function printTab(nb) {
@@ -2294,7 +2279,8 @@ if (!DOMTokenList.prototype.remove) {
             currentTab = nb;
         }
         var nb_copy = nb;
-        onEach(document.getElementById("titles").childNodes, function(elem) {
+        onEach(Array.prototype.slice.call(document.getElementById("titles").childNodes),
+               function(elem) {
             if (nb_copy === 0) {
                 addClass(elem, "selected");
             } else {
@@ -2302,7 +2288,8 @@ if (!DOMTokenList.prototype.remove) {
             }
             nb_copy -= 1;
         });
-        onEach(document.getElementById("results").childNodes, function(elem) {
+        onEach(Array.prototype.slice.call(document.getElementById("results").childNodes),
+               function(elem) {
             if (nb === 0) {
                 elem.style.display = "";
             } else {
@@ -2312,6 +2299,19 @@ if (!DOMTokenList.prototype.remove) {
         });
     }
 
+    function createToggleWrapper(tog) {
+        var span = document.createElement("span");
+        span.className = "toggle-label";
+        span.style.display = "none";
+        span.innerHTML = "&nbsp;Expand&nbsp;attributes";
+        tog.appendChild(span);
+
+        var wrapper = document.createElement("div");
+        wrapper.className = "toggle-wrapper toggle-attributes";
+        wrapper.appendChild(tog);
+        return wrapper;
+    }
+
     // To avoid checking on "rustdoc-item-attributes" value on every loop...
     var itemAttributesFunc = function() {};
     if (getCurrentValue("rustdoc-item-attributes") !== "false") {
@@ -2319,11 +2319,11 @@ if (!DOMTokenList.prototype.remove) {
             collapseDocs(x.previousSibling.childNodes[0], "toggle");
         };
     }
-    onEach(document.getElementById("main").getElementsByClassName("attributes"), function(i_e) {
-        i_e.parentNode.insertBefore(createToggleWrapper(toggle.cloneNode(true)), i_e);
+    var attributesToggle = createToggleWrapper(createSimpleToggle(false));
+    onEach(Array.prototype.slice.call(main.getElementsByClassName("attributes")), function(i_e) {
+        i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
         itemAttributesFunc(i_e);
     });
-    console.log('12a', Date.now() - start);
 
     // To avoid checking on "rustdoc-line-numbers" value on every loop...
     var lineNumbersFunc = function() {};
@@ -2340,8 +2340,8 @@ if (!DOMTokenList.prototype.remove) {
             x.parentNode.insertBefore(node, x);
         };
     }
-    console.log('13', Date.now() - start);
-    onEach(document.getElementsByClassName("rust-example-rendered"), function(e) {
+    onEach(Array.prototype.slice.call(document.getElementsByClassName("rust-example-rendered")),
+           function(e) {
         if (hasClass(e, "compile_fail")) {
             e.addEventListener("mouseover", function(event) {
                 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
@@ -2359,7 +2359,6 @@ if (!DOMTokenList.prototype.remove) {
         }
         lineNumbersFunc(e);
     });
-    console.log('14', Date.now() - start);
 
     function showModal(content) {
         var modal = document.createElement("div");
@@ -2380,16 +2379,16 @@ if (!DOMTokenList.prototype.remove) {
         }
     }
 
-    onEach(document.getElementsByClassName("important-traits"), function(e) {
+    onEach(Array.prototype.slice.call(document.getElementsByClassName("important-traits")),
+           function(e) {
         e.onclick = function() {
             showModal(e.lastElementChild.innerHTML);
         };
     });
-    console.log('15', Date.now() - start);
 
     function putBackSearch(search_input) {
         if (search_input.value !== "") {
-            addClass(document.getElementById("main"), "hidden");
+            addClass(main, "hidden");
             removeClass(document.getElementById("search"), "hidden");
             if (browserSupportsHistoryApi()) {
                 history.replaceState(search_input.value,
@@ -2407,7 +2406,7 @@ if (!DOMTokenList.prototype.remove) {
 
     var params = getQueryStringParams();
     if (params && params.search) {
-        addClass(document.getElementById("main"), "hidden");
+        addClass(main, "hidden");
         var search = document.getElementById("search");
         removeClass(search, "hidden");
         search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
@@ -2429,23 +2428,18 @@ if (!DOMTokenList.prototype.remove) {
         hideSidebar();
     };
 
-    console.log('16', Date.now() - start);
     autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
-    console.log('17', Date.now() - start);
 
     if (window.location.hash && window.location.hash.length > 0) {
         expandSection(window.location.hash.replace(/^#/, ""));
     }
 
-    var main = document.getElementById("main");
     if (main) {
-        console.log('18', Date.now() - start);
-        onEach(main.childNodes, function(e) {
+        onEach(Array.prototype.slice.call(main.childNodes), function(e) {
             if (e.tagName === "H2" || e.tagName === "H3") {
                 e.nextElementSibling.style.display = "block";
             }
         });
-        console.log('19', Date.now() - start);
     }
 
     function addSearchOptions(crates) {

From a68988719cf0b1c2a367096ee3df03b92d14757c Mon Sep 17 00:00:00 2001
From: Guillaume Gomez <guillaume1.gomez@gmail.com>
Date: Sun, 2 Dec 2018 01:22:44 +0100
Subject: [PATCH 3/5] cleanup

---
 src/librustdoc/html/static/main.js    | 94 +++++++++++----------------
 src/librustdoc/html/static/storage.js | 17 ++---
 2 files changed, 46 insertions(+), 65 deletions(-)

diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js
index adc49da61da13..1348cd72b9d57 100644
--- a/src/librustdoc/html/static/main.js
+++ b/src/librustdoc/html/static/main.js
@@ -82,8 +82,6 @@ if (!DOMTokenList.prototype.remove) {
                      "attr",
                      "derive"];
 
-    var start = Date.now();
-
     var search_input = document.getElementsByClassName("search-input")[0];
 
     // On the search screen, so you remain on the last tab you opened.
@@ -148,7 +146,7 @@ if (!DOMTokenList.prototype.remove) {
     var TY_PRIMITIVE = itemTypes.indexOf("primitive");
     var TY_KEYWORD = itemTypes.indexOf("keyword");
 
-    onEach(Array.prototype.slice.call(document.getElementsByClassName("js-only")), function(e) {
+    onEachLazy(document.getElementsByClassName("js-only"), function(e) {
         removeClass(e, "js-only");
     });
 
@@ -190,9 +188,8 @@ if (!DOMTokenList.prototype.remove) {
                     x.scrollIntoView();
                 }
             }
-            onEach(Array.prototype.slice.call(document.getElementsByClassName("line-numbers")),
-                   function(e) {
-                onEach(Array.prototype.slice.call(e.getElementsByTagName("span")), function(i_e) {
+            onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
+                onEachLazy(e.getElementsByTagName("span"), function(i_e) {
                     removeClass(i_e, "line-highlighted");
                 });
             });
@@ -1103,7 +1100,7 @@ if (!DOMTokenList.prototype.remove) {
                     aliases[i].displayPath = pathSplitter(res[0]);
                     aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
                     aliases[i].href = res[1];
-                    retothers.unshift(aliases[i]);
+                    ret.others.unshift(aliases[i]);
                     if (ret.others.length > MAX_RESULTS) {
                         ret.others.pop();
                     }
@@ -1192,16 +1189,16 @@ if (!DOMTokenList.prototype.remove) {
                 }
                 clearTimeout(hoverTimeout);
                 hoverTimeout = setTimeout(function() {
-                    onEach(document.getElementsByClassName("search-results"), function(e) {
-                        onEach(e.getElementsByClassName("result"), function(i_e) {
+                    onEachLazy(document.getElementsByClassName("search-results"), function(e) {
+                        onEachLazy(e.getElementsByClassName("result"), function(i_e) {
                             removeClass(i_e, "highlighted");
                         });
                     });
                     addClass(el, "highlighted");
                 }, 20);
             };
-            onEach(document.getElementsByClassName("search-results"), function(e) {
-                onEach(e.getElementsByClassName("result"), function(i_e) {
+            onEachLazy(document.getElementsByClassName("search-results"), function(e) {
+                onEachLazy(e.getElementsByClassName("result"), function(i_e) {
                     i_e.onclick = click_func;
                     i_e.onmouseover = mouseover_func;
                 });
@@ -1213,8 +1210,8 @@ if (!DOMTokenList.prototype.remove) {
                 var actives = [[], [], []];
                 // "current" is used to know which tab we're looking into.
                 var current = 0;
-                onEach(document.getElementsByClassName("search-results"), function(e) {
-                    onEach(e.getElementsByClassName("highlighted"), function(e) {
+                onEachLazy(document.getElementsByClassName("search-results"), function(e) {
+                    onEachLazy(e.getElementsByClassName("highlighted"), function(e) {
                         actives[current].push(e);
                     });
                     current += 1;
@@ -1418,7 +1415,7 @@ if (!DOMTokenList.prototype.remove) {
                 td_width = tds[0].offsetWidth;
             }
             var width = search.offsetWidth - 40 - td_width;
-            onEach(Array.prototype.slice.call(search.getElementsByClassName("desc")), function(e) {
+            onEachLazy(search.getElementsByClassName("desc"), function(e) {
                 e.style.width = width + "px";
             });
             initSearchNav();
@@ -1894,9 +1891,7 @@ if (!DOMTokenList.prototype.remove) {
             });
             innerToggle.title = "collapse all docs";
             if (fromAutoCollapse !== true) {
-                onEach(Array.prototype.slice.call(
-                           document.getElementsByClassName("collapse-toggle")),
-                       function(e) {
+                onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
                     collapseDocs(e, "show");
                 });
             }
@@ -1908,9 +1903,7 @@ if (!DOMTokenList.prototype.remove) {
             });
             innerToggle.title = "expand all docs";
             if (fromAutoCollapse !== true) {
-                onEach(Array.prototype.slice.call(
-                           document.getElementsByClassName("collapse-toggle")),
-                       function(e) {
+                onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
                     collapseDocs(e, "hide", pageId);
                 });
             }
@@ -1984,12 +1977,12 @@ if (!DOMTokenList.prototype.remove) {
                 }
                 if (action === "hide") {
                     addClass(relatedDoc, "hidden-by-usual-hider");
-                    onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(true));
+                    onEachLazy(toggle.childNodes, adjustToggle(true));
                     addClass(toggle.parentNode, "collapsed");
                 } else if (action === "show") {
                     removeClass(relatedDoc, "hidden-by-usual-hider");
                     removeClass(toggle.parentNode, "collapsed");
-                    onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(false));
+                    onEachLazy(toggle.childNodes, adjustToggle(false));
                 }
             }
         } else {
@@ -2022,13 +2015,13 @@ if (!DOMTokenList.prototype.remove) {
             if (action === "show") {
                 removeClass(relatedDoc, "fns-now-collapsed");
                 removeClass(docblock, "hidden-by-usual-hider");
-                onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(false));
-                onEach(Array.prototype.slice.call(relatedDoc.childNodes), implHider(false));
+                onEachLazy(toggle.childNodes, adjustToggle(false));
+                onEachLazy(relatedDoc.childNodes, implHider(false));
             } else if (action === "hide") {
                 addClass(relatedDoc, "fns-now-collapsed");
                 addClass(docblock, "hidden-by-usual-hider");
-                onEach(Array.prototype.slice.call(toggle.childNodes), adjustToggle(true));
-                onEach(Array.prototype.slice.call(relatedDoc.childNodes), implHider(true));
+                onEachLazy(toggle.childNodes, adjustToggle(true));
+                onEachLazy(relatedDoc.childNodes, implHider(true));
             }
         }
     }
@@ -2052,9 +2045,7 @@ if (!DOMTokenList.prototype.remove) {
             var impl_list = document.getElementById("implementations-list");
 
             if (impl_list !== null) {
-                onEach(Array.prototype.slice.call(
-                           impl_list.getElementsByClassName("collapse-toggle")),
-                       collapser);
+                onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), collapser);
             }
         }
     }
@@ -2104,9 +2095,9 @@ if (!DOMTokenList.prototype.remove) {
         }
     };
 
-    onEach(Array.prototype.slice.call(document.getElementsByClassName("method")), func);
-    onEach(Array.prototype.slice.call(document.getElementsByClassName("associatedconstant")), func);
-    onEach(Array.prototype.slice.call(document.getElementsByClassName("impl")), funcImpl);
+    onEachLazy(document.getElementsByClassName("method"), func);
+    onEachLazy(document.getElementsByClassName("associatedconstant"), func);
+    onEachLazy(document.getElementsByClassName("impl"), funcImpl);
     var impl_call = function() {};
     if (getCurrentValue("rustdoc-method-docs") !== "false") {
         impl_call = function(e, newToggle, pageId) {
@@ -2127,8 +2118,7 @@ if (!DOMTokenList.prototype.remove) {
     function toggleClicked() {
         if (hasClass(this, "collapsed")) {
             removeClass(this, "collapsed");
-            onEach(Array.prototype.slice.call(this.parentNode.getElementsByClassName("hidden")),
-                   function(x) {
+            onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
                 if (hasClass(x, "content") === false) {
                     removeClass(x, "hidden");
                     addClass(x, "x");
@@ -2138,8 +2128,7 @@ if (!DOMTokenList.prototype.remove) {
                              "</span>] Hide undocumented items";
         } else {
             addClass(this, "collapsed");
-            onEach(Array.prototype.slice.call(this.parentNode.getElementsByClassName("x")),
-                   function(x) {
+            onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
                 if (hasClass(x, "content") === false) {
                     addClass(x, "hidden");
                     removeClass(x, "x");
@@ -2149,8 +2138,8 @@ if (!DOMTokenList.prototype.remove) {
                              "</span>] Show hidden undocumented items";
         }
     }
-    onEach(Array.prototype.slice.call(document.getElementsByClassName("impl-items")), function(e) {
-        onEach(Array.prototype.slice.call(e.getElementsByClassName("associatedconstant")), func);
+    onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
+        onEachLazy(e.getElementsByClassName("associatedconstant"), func);
         var hiddenElems = e.getElementsByClassName("hidden");
         var needToggle = false;
 
@@ -2215,13 +2204,10 @@ if (!DOMTokenList.prototype.remove) {
 
                 e.style.display = "none";
                 addClass(wrap, "collapsed");
-                onEach(Array.prototype.slice.call(inner_toggle.getElementsByClassName("inner")),
-                       function(e) {
+                onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
                     e.innerHTML = labelForToggleButton(true);
                 });
-                onEach(Array.prototype.slice.call(
-                           inner_toggle.getElementsByClassName("toggle-label")),
-                       function(e) {
+                onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
                     e.style.display = "inline-block";
                     if (extra === true) {
                         i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
@@ -2268,10 +2254,8 @@ if (!DOMTokenList.prototype.remove) {
         }
     }
 
-    onEach(Array.prototype.slice.call(document.getElementsByClassName("docblock")),
-           buildToggleWrapper);
-    onEach(Array.prototype.slice.call(document.getElementsByClassName("sub-variant")),
-           buildToggleWrapper);
+    onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
+    onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
 
     // In the search display, allows to switch between tabs.
     function printTab(nb) {
@@ -2279,8 +2263,7 @@ if (!DOMTokenList.prototype.remove) {
             currentTab = nb;
         }
         var nb_copy = nb;
-        onEach(Array.prototype.slice.call(document.getElementById("titles").childNodes),
-               function(elem) {
+        onEachLazy(document.getElementById("titles").childNodes, function(elem) {
             if (nb_copy === 0) {
                 addClass(elem, "selected");
             } else {
@@ -2288,8 +2271,7 @@ if (!DOMTokenList.prototype.remove) {
             }
             nb_copy -= 1;
         });
-        onEach(Array.prototype.slice.call(document.getElementById("results").childNodes),
-               function(elem) {
+        onEachLazy(document.getElementById("results").childNodes, function(elem) {
             if (nb === 0) {
                 elem.style.display = "";
             } else {
@@ -2320,7 +2302,7 @@ if (!DOMTokenList.prototype.remove) {
         };
     }
     var attributesToggle = createToggleWrapper(createSimpleToggle(false));
-    onEach(Array.prototype.slice.call(main.getElementsByClassName("attributes")), function(i_e) {
+    onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
         i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
         itemAttributesFunc(i_e);
     });
@@ -2340,8 +2322,7 @@ if (!DOMTokenList.prototype.remove) {
             x.parentNode.insertBefore(node, x);
         };
     }
-    onEach(Array.prototype.slice.call(document.getElementsByClassName("rust-example-rendered")),
-           function(e) {
+    onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
         if (hasClass(e, "compile_fail")) {
             e.addEventListener("mouseover", function(event) {
                 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
@@ -2379,8 +2360,7 @@ if (!DOMTokenList.prototype.remove) {
         }
     }
 
-    onEach(Array.prototype.slice.call(document.getElementsByClassName("important-traits")),
-           function(e) {
+    onEachLazy(document.getElementsByClassName("important-traits"), function(e) {
         e.onclick = function() {
             showModal(e.lastElementChild.innerHTML);
         };
@@ -2435,7 +2415,7 @@ if (!DOMTokenList.prototype.remove) {
     }
 
     if (main) {
-        onEach(Array.prototype.slice.call(main.childNodes), function(e) {
+        onEachLazy(main.childNodes, function(e) {
             if (e.tagName === "H2" || e.tagName === "H3") {
                 e.nextElementSibling.style.display = "block";
             }
diff --git a/src/librustdoc/html/static/storage.js b/src/librustdoc/html/static/storage.js
index 1b2732a51c150..d1c377bf95ac8 100644
--- a/src/librustdoc/html/static/storage.js
+++ b/src/librustdoc/html/static/storage.js
@@ -19,10 +19,7 @@ var mainTheme = document.getElementById("mainThemeStyle");
 var savedHref = [];
 
 function hasClass(elem, className) {
-    if (!elem || !elem.classList) {
-        return false;
-    }
-    return elem.classList.contains(className);
+    return elem && elem.classList && elem.classList.contains(className);
 }
 
 function addClass(elem, className) {
@@ -40,12 +37,9 @@ function removeClass(elem, className) {
 }
 
 function isHidden(elem) {
-    return (elem.offsetParent === null);
+    return elem.offsetParent === null;
 }
 
-var allcallers = {};
-var resourcesSuffix="";
-
 function onEach(arr, func, reversed) {
     if (arr && arr.length > 0 && func) {
         var length = arr.length;
@@ -66,6 +60,13 @@ function onEach(arr, func, reversed) {
     return false;
 }
 
+function onEachLazy(lazyArray, func, reversed) {
+    return onEach(
+        Array.prototype.slice.call(lazyArray),
+        func,
+        reversed);
+}
+
 function usableLocalStorage() {
     // Check if the browser supports localStorage at all:
     if (typeof(Storage) === "undefined") {

From e17518f65ea7b9af90e91f15784a485a3f4a6598 Mon Sep 17 00:00:00 2001
From: Guillaume Gomez <guillaume1.gomez@gmail.com>
Date: Sun, 2 Dec 2018 18:00:50 +0100
Subject: [PATCH 4/5] Show everything when noscript is on

---
 src/librustdoc/html/layout.rs           |  1 +
 src/librustdoc/html/render.rs           |  3 +++
 src/librustdoc/html/static/noscript.css | 19 +++++++++++++++++++
 src/librustdoc/html/static_files.rs     |  3 +++
 4 files changed, 26 insertions(+)
 create mode 100644 src/librustdoc/html/static/noscript.css

diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs
index fa5d015e5b72d..3e69db3f899af 100644
--- a/src/librustdoc/html/layout.rs
+++ b/src/librustdoc/html/layout.rs
@@ -54,6 +54,7 @@ pub fn render<T: fmt::Display, S: fmt::Display>(
     <link rel=\"stylesheet\" type=\"text/css\" href=\"{root_path}light{suffix}.css\" \
           id=\"themeStyle\">\
     <script src=\"{root_path}storage{suffix}.js\"></script>\
+    <noscript><link rel=\"stylesheet\" href=\"{root_path}noscript{suffix}.css\"></noscript>\
     {css_extension}\
     {favicon}\
     {in_header}\
diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs
index 0d2d6082174ed..2ffd4dd7e5780 100644
--- a/src/librustdoc/html/render.rs
+++ b/src/librustdoc/html/render.rs
@@ -772,6 +772,9 @@ fn write_shared(
     write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
                  static_files::SETTINGS_CSS,
                  options.enable_minification)?;
+    write_minify(cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
+                 static_files::NOSCRIPT_CSS,
+                 options.enable_minification)?;
 
     // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
     // then we'll run over the "official" styles.
diff --git a/src/librustdoc/html/static/noscript.css b/src/librustdoc/html/static/noscript.css
new file mode 100644
index 0000000000000..f4de75f2140bd
--- /dev/null
+++ b/src/librustdoc/html/static/noscript.css
@@ -0,0 +1,19 @@
+/**
+ * Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+ * file at the top-level directory of this distribution and at
+ * http://rust-lang.org/COPYRIGHT.
+ *
+ * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+ * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+ * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+ * option. This file may not be copied, modified, or distributed
+ * except according to those terms.
+ */
+
+#main > h2 + div, #main > h2 + h3, #main > h3 + div {
+	display: block;
+}
+
+.loading-content {
+	display: none;
+}
diff --git a/src/librustdoc/html/static_files.rs b/src/librustdoc/html/static_files.rs
index a485facfac2dc..f71b2a8728422 100644
--- a/src/librustdoc/html/static_files.rs
+++ b/src/librustdoc/html/static_files.rs
@@ -23,6 +23,9 @@ pub static RUSTDOC_CSS: &'static str = include_str!("static/rustdoc.css");
 /// The file contents of `settings.css`, responsible for the items on the settings page.
 pub static SETTINGS_CSS: &'static str = include_str!("static/settings.css");
 
+/// The file contents of the `noscript.css` file, used in case JS isn't supported or is disabled.
+pub static NOSCRIPT_CSS: &'static str = include_str!("static/noscript.css");
+
 /// The file contents of `normalize.css`, included to even out standard elements between browser
 /// implementations.
 pub static NORMALIZE_CSS: &'static str = include_str!("static/normalize.css");

From b8c1726f267ce24b773f04c7d161c62f6fbc05fb Mon Sep 17 00:00:00 2001
From: Guillaume Gomez <guillaume1.gomez@gmail.com>
Date: Sun, 2 Dec 2018 19:11:32 +0100
Subject: [PATCH 5/5] Show 'loading content' when loading content

---
 src/librustdoc/html/render.rs      | 96 +++++++++++++-----------------
 src/librustdoc/html/static/main.js | 13 ++--
 2 files changed, 51 insertions(+), 58 deletions(-)

diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs
index 2ffd4dd7e5780..b84fa7d581f48 100644
--- a/src/librustdoc/html/render.rs
+++ b/src/librustdoc/html/render.rs
@@ -3016,6 +3016,22 @@ fn item_trait(
     // Trait documentation
     document(w, cx, it)?;
 
+    fn write_small_section_header(
+        w: &mut fmt::Formatter,
+        id: &str,
+        title: &str,
+        extra_content: &str,
+    ) -> fmt::Result {
+        write!(w, "
+            <h2 id='{0}' class='small-section-header'>\
+              {1}<a href='#{0}' class='anchor'></a>\
+            </h2>{2}", id, title, extra_content)
+    }
+
+    fn write_loading_content(w: &mut fmt::Formatter, extra_content: &str) -> fmt::Result {
+        write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
+    }
+
     fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
                   -> fmt::Result {
         let name = m.name.as_ref().unwrap();
@@ -3036,74 +3052,45 @@ fn item_trait(
     }
 
     if !types.is_empty() {
-        write!(w, "
-            <h2 id='associated-types' class='small-section-header'>
-              Associated Types<a href='#associated-types' class='anchor'></a>
-            </h2>
-            <div class='methods'>
-        ")?;
+        write_small_section_header(w, "associated-types", "Associated Types",
+                                   "<div class='methods'>")?;
         for t in &types {
             trait_item(w, cx, *t, it)?;
         }
-        write!(w, "</div>")?;
+        write_loading_content(w, "</div>")?;
     }
 
     if !consts.is_empty() {
-        write!(w, "
-            <h2 id='associated-const' class='small-section-header'>
-              Associated Constants<a href='#associated-const' class='anchor'></a>
-            </h2>
-            <div class='methods'>
-        ")?;
+        write_small_section_header(w, "associated-const", "Associated Constants",
+                                   "<div class='methods'>")?;
         for t in &consts {
             trait_item(w, cx, *t, it)?;
         }
-        write!(w, "</div>")?;
+        write_loading_content(w, "</div>")?;
     }
 
     // Output the documentation for each function individually
     if !required.is_empty() {
-        write!(w, "
-            <h2 id='required-methods' class='small-section-header'>
-              Required Methods<a href='#required-methods' class='anchor'></a>
-            </h2>
-            <div class='methods'>
-        ")?;
+        write_small_section_header(w, "required-methods", "Required methods",
+                                   "<div class='methods'>")?;
         for m in &required {
             trait_item(w, cx, *m, it)?;
         }
-        write!(w, "</div>")?;
+        write_loading_content(w, "</div>")?;
     }
     if !provided.is_empty() {
-        write!(w, "
-            <h2 id='provided-methods' class='small-section-header'>
-              Provided Methods<a href='#provided-methods' class='anchor'></a>
-            </h2>
-            <div class='methods'>
-        ")?;
+        write_small_section_header(w, "provided-methods", "Provided methods",
+                                   "<div class='methods'>")?;
         for m in &provided {
             trait_item(w, cx, *m, it)?;
         }
-        write!(w, "</div>")?;
+        write_loading_content(w, "</div>")?;
     }
 
     // If there are methods directly on this trait object, render them here.
     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
 
     let cache = cache();
-    let impl_header = "\
-        <h2 id='implementors' class='small-section-header'>\
-          Implementors<a href='#implementors' class='anchor'></a>\
-        </h2>\
-        <div class='item-list' id='implementors-list'>\
-    ";
-
-    let synthetic_impl_header = "\
-        <h2 id='synthetic-implementors' class='small-section-header'>\
-          Auto implementors<a href='#synthetic-implementors' class='anchor'></a>\
-        </h2>\
-        <div class='item-list' id='synthetic-implementors-list'>\
-    ";
 
     let mut synthetic_types = Vec::new();
 
@@ -3140,11 +3127,7 @@ fn item_trait(
         concrete.sort_by(compare_impl);
 
         if !foreign.is_empty() {
-            write!(w, "
-                <h2 id='foreign-impls' class='small-section-header'>
-                  Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
-                </h2>
-            ")?;
+            write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
 
             for implementor in foreign {
                 let assoc_link = AssocItemLink::GotoSource(
@@ -3155,33 +3138,38 @@ fn item_trait(
                             RenderMode::Normal, implementor.impl_item.stable_since(), false,
                             None)?;
             }
+            write_loading_content(w, "")?;
         }
 
-        write!(w, "{}", impl_header)?;
+        write_small_section_header(w, "implementors", "Implementors",
+                                   "<div class='item-list' id='implementors-list'>")?;
         for implementor in concrete {
             render_implementor(cx, implementor, w, &implementor_dups)?;
         }
-        write!(w, "</div>")?;
+        write_loading_content(w, "</div>")?;
 
         if t.auto {
-            write!(w, "{}", synthetic_impl_header)?;
+            write_small_section_header(w, "synthetic-implementors", "Auto implementors",
+                                       "<div class='item-list' id='synthetic-implementors-list'>")?;
             for implementor in synthetic {
                 synthetic_types.extend(
                     collect_paths_for_type(implementor.inner_impl().for_.clone())
                 );
                 render_implementor(cx, implementor, w, &implementor_dups)?;
             }
-            write!(w, "</div>")?;
+            write_loading_content(w, "</div>")?;
         }
     } else {
         // even without any implementations to write in, we still want the heading and list, so the
         // implementors javascript file pulled in below has somewhere to write the impls into
-        write!(w, "{}", impl_header)?;
-        write!(w, "</div>")?;
+        write_small_section_header(w, "implementors", "Implementors",
+                                   "<div class='item-list' id='implementors-list'>")?;
+        write_loading_content(w, "</div>")?;
 
         if t.auto {
-            write!(w, "{}", synthetic_impl_header)?;
-            write!(w, "</div>")?;
+            write_small_section_header(w, "synthetic-implementors", "Auto implementors",
+                                       "<div class='item-list' id='synthetic-implementors-list'>")?;
+            write_loading_content(w, "</div>")?;
         }
     }
     write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js
index 1348cd72b9d57..51714c35d6faa 100644
--- a/src/librustdoc/html/static/main.js
+++ b/src/librustdoc/html/static/main.js
@@ -1961,7 +1961,7 @@ if (!DOMTokenList.prototype.remove) {
         }
 
         var relatedDoc;
-        var action;
+        var action = mode;
         if (hasClass(toggle.parentNode, "impl") === false) {
             relatedDoc = toggle.parentNode.nextElementSibling;
             if (hasClass(relatedDoc, "stability")) {
@@ -1997,7 +1997,7 @@ if (!DOMTokenList.prototype.remove) {
             }
 
             if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
-                (pageId && relatedDoc.getElementById(pageId))) {
+                (pageId && document.getElementById(pageId))) {
                 return;
             }
 
@@ -2026,7 +2026,7 @@ if (!DOMTokenList.prototype.remove) {
         }
     }
 
-    function collapser(e) {
+    function collapser(e, collapse) {
         // inherent impl ids are like "impl" or impl-<number>'.
         // they will never be hidden by default.
         var n = e.parentElement;
@@ -2045,7 +2045,9 @@ if (!DOMTokenList.prototype.remove) {
             var impl_list = document.getElementById("implementations-list");
 
             if (impl_list !== null) {
-                onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), collapser);
+                onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
+                    collapser(e, collapse);
+                });
             }
         }
     }
@@ -2415,6 +2417,9 @@ if (!DOMTokenList.prototype.remove) {
     }
 
     if (main) {
+        onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
+            e.remove();
+        });
         onEachLazy(main.childNodes, function(e) {
             if (e.tagName === "H2" || e.tagName === "H3") {
                 e.nextElementSibling.style.display = "block";