]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/mod.rs
88c5e94c27671c78830d30440842678220b90e89
[rust.git] / src / librustdoc / html / render / mod.rs
1 // ignore-tidy-filelength
2
3 //! Rustdoc's HTML rendering module.
4 //!
5 //! This modules contains the bulk of the logic necessary for rendering a
6 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
7 //! rendering process is largely driven by the `format!` syntax extension to
8 //! perform all I/O into files and streams.
9 //!
10 //! The rendering process is largely driven by the `Context` and `Cache`
11 //! structures. The cache is pre-populated by crawling the crate in question,
12 //! and then it is shared among the various rendering threads. The cache is meant
13 //! to be a fairly large structure not implementing `Clone` (because it's shared
14 //! among threads). The context, however, should be a lightweight structure. This
15 //! is cloned per-thread and contains information about what is currently being
16 //! rendered.
17 //!
18 //! In order to speed up rendering (mostly because of markdown rendering), the
19 //! rendering process has been parallelized. This parallelization is only
20 //! exposed through the `crate` method on the context, and then also from the
21 //! fact that the shared cache is stored in TLS (and must be accessed as such).
22 //!
23 //! In addition to rendering the crate itself, this module is also responsible
24 //! for creating the corresponding search index and source file renderings.
25 //! These threads are not parallelized (they haven't been a bottleneck yet), and
26 //! both occur before the crate is rendered.
27
28 crate mod cache;
29
30 #[cfg(test)]
31 mod tests;
32
33 use std::borrow::Cow;
34 use std::cell::{Cell, RefCell};
35 use std::cmp::Ordering;
36 use std::collections::{BTreeMap, VecDeque};
37 use std::default::Default;
38 use std::ffi::OsStr;
39 use std::fmt::{self, Write};
40 use std::fs::{self, File};
41 use std::io::prelude::*;
42 use std::io::{self, BufReader};
43 use std::path::{Component, Path, PathBuf};
44 use std::rc::Rc;
45 use std::str;
46 use std::string::ToString;
47 use std::sync::mpsc::{channel, Receiver};
48 use std::sync::Arc;
49
50 use itertools::Itertools;
51 use rustc_ast_pretty::pprust;
52 use rustc_attr::{Deprecation, StabilityLevel};
53 use rustc_data_structures::flock;
54 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
55 use rustc_data_structures::sync::Lrc;
56 use rustc_hir as hir;
57 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
58 use rustc_hir::Mutability;
59 use rustc_middle::middle::stability;
60 use rustc_session::Session;
61 use rustc_span::edition::Edition;
62 use rustc_span::hygiene::MacroKind;
63 use rustc_span::source_map::FileName;
64 use rustc_span::symbol::{kw, sym, Symbol};
65 use serde::ser::SerializeSeq;
66 use serde::{Serialize, Serializer};
67
68 use crate::clean::{self, AttributesExt, GetDefId, RenderedLink, SelfTy, TypeKind};
69 use crate::config::{RenderInfo, RenderOptions};
70 use crate::docfs::{DocFS, PathError};
71 use crate::doctree;
72 use crate::error::Error;
73 use crate::formats::cache::{cache, Cache};
74 use crate::formats::item_type::ItemType;
75 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
76 use crate::html::escape::Escape;
77 use crate::html::format::fmt_impl_for_trait_page;
78 use crate::html::format::Function;
79 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
80 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
81 use crate::html::markdown::{
82     self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine,
83 };
84 use crate::html::sources;
85 use crate::html::{highlight, layout, static_files};
86 use cache::{build_index, ExternalLocation};
87
88 /// A pair of name and its optional document.
89 crate type NameDoc = (String, Option<String>);
90
91 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
92     crate::html::format::display_fn(move |f| {
93         if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
94     })
95 }
96
97 /// Major driving force in all rustdoc rendering. This contains information
98 /// about where in the tree-like hierarchy rendering is occurring and controls
99 /// how the current page is being rendered.
100 ///
101 /// It is intended that this context is a lightweight object which can be fairly
102 /// easily cloned because it is cloned per work-job (about once per item in the
103 /// rustdoc tree).
104 #[derive(Clone)]
105 crate struct Context {
106     /// Current hierarchy of components leading down to what's currently being
107     /// rendered
108     crate current: Vec<String>,
109     /// The current destination folder of where HTML artifacts should be placed.
110     /// This changes as the context descends into the module hierarchy.
111     crate dst: PathBuf,
112     /// A flag, which when `true`, will render pages which redirect to the
113     /// real location of an item. This is used to allow external links to
114     /// publicly reused items to redirect to the right location.
115     crate render_redirect_pages: bool,
116     /// The map used to ensure all generated 'id=' attributes are unique.
117     id_map: Rc<RefCell<IdMap>>,
118     crate shared: Arc<SharedContext>,
119     all: Rc<RefCell<AllTypes>>,
120     /// Storage for the errors produced while generating documentation so they
121     /// can be printed together at the end.
122     crate errors: Rc<Receiver<String>>,
123 }
124
125 crate struct SharedContext {
126     crate sess: Lrc<Session>,
127     /// The path to the crate root source minus the file name.
128     /// Used for simplifying paths to the highlighted source code files.
129     crate src_root: PathBuf,
130     /// This describes the layout of each page, and is not modified after
131     /// creation of the context (contains info like the favicon and added html).
132     crate layout: layout::Layout,
133     /// This flag indicates whether `[src]` links should be generated or not. If
134     /// the source files are present in the html rendering, then this will be
135     /// `true`.
136     crate include_sources: bool,
137     /// The local file sources we've emitted and their respective url-paths.
138     crate local_sources: FxHashMap<PathBuf, String>,
139     /// Whether the collapsed pass ran
140     crate collapsed: bool,
141     /// The base-URL of the issue tracker for when an item has been tagged with
142     /// an issue number.
143     crate issue_tracker_base_url: Option<String>,
144     /// The directories that have already been created in this doc run. Used to reduce the number
145     /// of spurious `create_dir_all` calls.
146     crate created_dirs: RefCell<FxHashSet<PathBuf>>,
147     /// This flag indicates whether listings of modules (in the side bar and documentation itself)
148     /// should be ordered alphabetically or in order of appearance (in the source code).
149     crate sort_modules_alphabetically: bool,
150     /// Additional CSS files to be added to the generated docs.
151     crate style_files: Vec<StylePath>,
152     /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
153     /// "light-v2.css").
154     crate resource_suffix: String,
155     /// Optional path string to be used to load static files on output pages. If not set, uses
156     /// combinations of `../` to reach the documentation root.
157     crate static_root_path: Option<String>,
158     /// The fs handle we are working with.
159     crate fs: DocFS,
160     /// The default edition used to parse doctests.
161     crate edition: Edition,
162     crate codes: ErrorCodes,
163     playground: Option<markdown::Playground>,
164 }
165
166 impl Context {
167     fn path(&self, filename: &str) -> PathBuf {
168         // We use splitn vs Path::extension here because we might get a filename
169         // like `style.min.css` and we want to process that into
170         // `style-suffix.min.css`.  Path::extension would just return `css`
171         // which would result in `style.min-suffix.css` which isn't what we
172         // want.
173         let (base, ext) = filename.split_once('.').unwrap();
174         let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext);
175         self.dst.join(&filename)
176     }
177
178     fn sess(&self) -> &Session {
179         &self.shared.sess
180     }
181 }
182
183 impl SharedContext {
184     crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
185         let mut dirs = self.created_dirs.borrow_mut();
186         if !dirs.contains(dst) {
187             try_err!(self.fs.create_dir_all(dst), dst);
188             dirs.insert(dst.to_path_buf());
189         }
190
191         Ok(())
192     }
193
194     /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
195     /// `collapsed_doc_value` of the given item.
196     crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
197         if self.collapsed {
198             item.collapsed_doc_value().map(|s| s.into())
199         } else {
200             item.doc_value().map(|s| s.into())
201         }
202     }
203 }
204
205 // Helper structs for rendering items/sidebars and carrying along contextual
206 // information
207
208 /// Struct representing one entry in the JS search index. These are all emitted
209 /// by hand to a large JS file at the end of cache-creation.
210 #[derive(Debug)]
211 crate struct IndexItem {
212     crate ty: ItemType,
213     crate name: String,
214     crate path: String,
215     crate desc: String,
216     crate parent: Option<DefId>,
217     crate parent_idx: Option<usize>,
218     crate search_type: Option<IndexItemFunctionType>,
219 }
220
221 impl Serialize for IndexItem {
222     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
223     where
224         S: Serializer,
225     {
226         assert_eq!(
227             self.parent.is_some(),
228             self.parent_idx.is_some(),
229             "`{}` is missing idx",
230             self.name
231         );
232
233         (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
234             .serialize(serializer)
235     }
236 }
237
238 /// A type used for the search index.
239 #[derive(Debug)]
240 crate struct RenderType {
241     ty: Option<DefId>,
242     idx: Option<usize>,
243     name: Option<String>,
244     generics: Option<Vec<Generic>>,
245 }
246
247 impl Serialize for RenderType {
248     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
249     where
250         S: Serializer,
251     {
252         if let Some(name) = &self.name {
253             let mut seq = serializer.serialize_seq(None)?;
254             if let Some(id) = self.idx {
255                 seq.serialize_element(&id)?;
256             } else {
257                 seq.serialize_element(&name)?;
258             }
259             if let Some(generics) = &self.generics {
260                 seq.serialize_element(&generics)?;
261             }
262             seq.end()
263         } else {
264             serializer.serialize_none()
265         }
266     }
267 }
268
269 /// A type used for the search index.
270 #[derive(Debug)]
271 crate struct Generic {
272     name: String,
273     defid: Option<DefId>,
274     idx: Option<usize>,
275 }
276
277 impl Serialize for Generic {
278     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
279     where
280         S: Serializer,
281     {
282         if let Some(id) = self.idx {
283             serializer.serialize_some(&id)
284         } else {
285             serializer.serialize_some(&self.name)
286         }
287     }
288 }
289
290 /// Full type of functions/methods in the search index.
291 #[derive(Debug)]
292 crate struct IndexItemFunctionType {
293     inputs: Vec<TypeWithKind>,
294     output: Option<Vec<TypeWithKind>>,
295 }
296
297 impl Serialize for IndexItemFunctionType {
298     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
299     where
300         S: Serializer,
301     {
302         // If we couldn't figure out a type, just write `null`.
303         let mut iter = self.inputs.iter();
304         if match self.output {
305             Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
306             None => iter.any(|ref i| i.ty.name.is_none()),
307         } {
308             serializer.serialize_none()
309         } else {
310             let mut seq = serializer.serialize_seq(None)?;
311             seq.serialize_element(&self.inputs)?;
312             if let Some(output) = &self.output {
313                 if output.len() > 1 {
314                     seq.serialize_element(&output)?;
315                 } else {
316                     seq.serialize_element(&output[0])?;
317                 }
318             }
319             seq.end()
320         }
321     }
322 }
323
324 #[derive(Debug)]
325 crate struct TypeWithKind {
326     ty: RenderType,
327     kind: TypeKind,
328 }
329
330 impl From<(RenderType, TypeKind)> for TypeWithKind {
331     fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
332         TypeWithKind { ty: x.0, kind: x.1 }
333     }
334 }
335
336 impl Serialize for TypeWithKind {
337     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
338     where
339         S: Serializer,
340     {
341         let mut seq = serializer.serialize_seq(None)?;
342         seq.serialize_element(&self.ty.name)?;
343         let x: ItemType = self.kind.into();
344         seq.serialize_element(&x)?;
345         seq.end()
346     }
347 }
348
349 #[derive(Debug, Clone)]
350 crate struct StylePath {
351     /// The path to the theme
352     crate path: PathBuf,
353     /// What the `disabled` attribute should be set to in the HTML tag
354     crate disabled: bool,
355 }
356
357 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
358
359 crate fn initial_ids() -> Vec<String> {
360     [
361         "main",
362         "search",
363         "help",
364         "TOC",
365         "render-detail",
366         "associated-types",
367         "associated-const",
368         "required-methods",
369         "provided-methods",
370         "implementors",
371         "synthetic-implementors",
372         "implementors-list",
373         "synthetic-implementors-list",
374         "methods",
375         "deref-methods",
376         "implementations",
377     ]
378     .iter()
379     .map(|id| (String::from(*id)))
380     .collect()
381 }
382
383 /// Generates the documentation for `crate` into the directory `dst`
384 impl FormatRenderer for Context {
385     fn init(
386         mut krate: clean::Crate,
387         options: RenderOptions,
388         _render_info: RenderInfo,
389         edition: Edition,
390         cache: &mut Cache,
391         sess: Lrc<Session>,
392     ) -> Result<(Context, clean::Crate), Error> {
393         // need to save a copy of the options for rendering the index page
394         let md_opts = options.clone();
395         let RenderOptions {
396             output,
397             external_html,
398             id_map,
399             playground_url,
400             sort_modules_alphabetically,
401             themes: style_files,
402             default_settings,
403             extension_css,
404             resource_suffix,
405             static_root_path,
406             generate_search_filter,
407             unstable_features,
408             ..
409         } = options;
410
411         let src_root = match krate.src {
412             FileName::Real(ref p) => match p.local_path().parent() {
413                 Some(p) => p.to_path_buf(),
414                 None => PathBuf::new(),
415             },
416             _ => PathBuf::new(),
417         };
418         // If user passed in `--playground-url` arg, we fill in crate name here
419         let mut playground = None;
420         if let Some(url) = playground_url {
421             playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url });
422         }
423         let mut layout = layout::Layout {
424             logo: String::new(),
425             favicon: String::new(),
426             external_html,
427             default_settings,
428             krate: krate.name.clone(),
429             css_file_extension: extension_css,
430             generate_search_filter,
431         };
432         let mut issue_tracker_base_url = None;
433         let mut include_sources = true;
434
435         // Crawl the crate attributes looking for attributes which control how we're
436         // going to emit HTML
437         if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
438             for attr in attrs.lists(sym::doc) {
439                 match (attr.name_or_empty(), attr.value_str()) {
440                     (sym::html_favicon_url, Some(s)) => {
441                         layout.favicon = s.to_string();
442                     }
443                     (sym::html_logo_url, Some(s)) => {
444                         layout.logo = s.to_string();
445                     }
446                     (sym::html_playground_url, Some(s)) => {
447                         playground = Some(markdown::Playground {
448                             crate_name: Some(krate.name.clone()),
449                             url: s.to_string(),
450                         });
451                     }
452                     (sym::issue_tracker_base_url, Some(s)) => {
453                         issue_tracker_base_url = Some(s.to_string());
454                     }
455                     (sym::html_no_source, None) if attr.is_word() => {
456                         include_sources = false;
457                     }
458                     _ => {}
459                 }
460             }
461         }
462         let (sender, receiver) = channel();
463         let mut scx = SharedContext {
464             sess,
465             collapsed: krate.collapsed,
466             src_root,
467             include_sources,
468             local_sources: Default::default(),
469             issue_tracker_base_url,
470             layout,
471             created_dirs: Default::default(),
472             sort_modules_alphabetically,
473             style_files,
474             resource_suffix,
475             static_root_path,
476             fs: DocFS::new(sender),
477             edition,
478             codes: ErrorCodes::from(unstable_features.is_nightly_build()),
479             playground,
480         };
481
482         // Add the default themes to the `Vec` of stylepaths
483         //
484         // Note that these must be added before `sources::render` is called
485         // so that the resulting source pages are styled
486         //
487         // `light.css` is not disabled because it is the stylesheet that stays loaded
488         // by the browser as the theme stylesheet. The theme system (hackily) works by
489         // changing the href to this stylesheet. All other themes are disabled to
490         // prevent rule conflicts
491         scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
492         scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
493         scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
494
495         let dst = output;
496         scx.ensure_dir(&dst)?;
497         krate = sources::render(&dst, &mut scx, krate)?;
498
499         // Build our search index
500         let index = build_index(&krate, cache);
501
502         let cache = Arc::new(cache);
503         let mut cx = Context {
504             current: Vec::new(),
505             dst,
506             render_redirect_pages: false,
507             id_map: Rc::new(RefCell::new(id_map)),
508             shared: Arc::new(scx),
509             all: Rc::new(RefCell::new(AllTypes::new())),
510             errors: Rc::new(receiver),
511         };
512
513         CURRENT_DEPTH.with(|s| s.set(0));
514
515         // Write shared runs within a flock; disable thread dispatching of IO temporarily.
516         Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
517         write_shared(&cx, &krate, index, &md_opts, &cache)?;
518         Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
519         Ok((cx, krate))
520     }
521
522     fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
523         Arc::get_mut(&mut self.shared).unwrap().fs.close();
524         let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
525         if nb_errors > 0 {
526             Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
527         } else {
528             Ok(())
529         }
530     }
531
532     fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
533         let final_file = self.dst.join(&krate.name).join("all.html");
534         let settings_file = self.dst.join("settings.html");
535         let crate_name = krate.name.clone();
536
537         let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
538         if !root_path.ends_with('/') {
539             root_path.push('/');
540         }
541         let mut page = layout::Page {
542             title: "List of all items in this crate",
543             css_class: "mod",
544             root_path: "../",
545             static_root_path: self.shared.static_root_path.as_deref(),
546             description: "List of all items in this crate",
547             keywords: BASIC_KEYWORDS,
548             resource_suffix: &self.shared.resource_suffix,
549             extra_scripts: &[],
550             static_extra_scripts: &[],
551         };
552         let sidebar = if let Some(ref version) = cache.crate_version {
553             format!(
554                 "<p class=\"location\">Crate {}</p>\
555                      <div class=\"block version\">\
556                          <p>Version {}</p>\
557                      </div>\
558                      <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
559                 crate_name,
560                 Escape(version),
561             )
562         } else {
563             String::new()
564         };
565         let all = self.all.replace(AllTypes::new());
566         let v = layout::render(
567             &self.shared.layout,
568             &page,
569             sidebar,
570             |buf: &mut Buffer| all.print(buf),
571             &self.shared.style_files,
572         );
573         self.shared.fs.write(&final_file, v.as_bytes())?;
574
575         // Generating settings page.
576         page.title = "Rustdoc settings";
577         page.description = "Settings of Rustdoc";
578         page.root_path = "./";
579
580         let mut style_files = self.shared.style_files.clone();
581         let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
582         style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
583         let v = layout::render(
584             &self.shared.layout,
585             &page,
586             sidebar,
587             settings(
588                 self.shared.static_root_path.as_deref().unwrap_or("./"),
589                 &self.shared.resource_suffix,
590                 &self.shared.style_files,
591             )?,
592             &style_files,
593         );
594         self.shared.fs.write(&settings_file, v.as_bytes())?;
595         Ok(())
596     }
597
598     fn mod_item_in(
599         &mut self,
600         item: &clean::Item,
601         item_name: &str,
602         cache: &Cache,
603     ) -> Result<(), Error> {
604         // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
605         // if they contain impls for public types. These modules can also
606         // contain items such as publicly re-exported structures.
607         //
608         // External crates will provide links to these structures, so
609         // these modules are recursed into, but not rendered normally
610         // (a flag on the context).
611         if !self.render_redirect_pages {
612             self.render_redirect_pages = item.is_stripped();
613         }
614         let scx = &self.shared;
615         self.dst.push(item_name);
616         self.current.push(item_name.to_owned());
617
618         info!("Recursing into {}", self.dst.display());
619
620         let buf = self.render_item(item, false, cache);
621         // buf will be empty if the module is stripped and there is no redirect for it
622         if !buf.is_empty() {
623             self.shared.ensure_dir(&self.dst)?;
624             let joint_dst = self.dst.join("index.html");
625             scx.fs.write(&joint_dst, buf.as_bytes())?;
626         }
627
628         // Render sidebar-items.js used throughout this module.
629         if !self.render_redirect_pages {
630             let module = match item.kind {
631                 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
632                 _ => unreachable!(),
633             };
634             let items = self.build_sidebar_items(module);
635             let js_dst = self.dst.join("sidebar-items.js");
636             let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
637             scx.fs.write(&js_dst, &v)?;
638         }
639         Ok(())
640     }
641
642     fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
643         info!("Recursed; leaving {}", self.dst.display());
644
645         // Go back to where we were at
646         self.dst.pop();
647         self.current.pop();
648         Ok(())
649     }
650
651     fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
652         // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
653         // if they contain impls for public types. These modules can also
654         // contain items such as publicly re-exported structures.
655         //
656         // External crates will provide links to these structures, so
657         // these modules are recursed into, but not rendered normally
658         // (a flag on the context).
659         if !self.render_redirect_pages {
660             self.render_redirect_pages = item.is_stripped();
661         }
662
663         let buf = self.render_item(&item, true, cache);
664         // buf will be empty if the item is stripped and there is no redirect for it
665         if !buf.is_empty() {
666             let name = item.name.as_ref().unwrap();
667             let item_type = item.type_();
668             let file_name = &item_path(item_type, &name.as_str());
669             self.shared.ensure_dir(&self.dst)?;
670             let joint_dst = self.dst.join(file_name);
671             self.shared.fs.write(&joint_dst, buf.as_bytes())?;
672
673             if !self.render_redirect_pages {
674                 self.all.borrow_mut().append(full_path(self, &item), &item_type);
675             }
676             // If the item is a macro, redirect from the old macro URL (with !)
677             // to the new one (without).
678             if item_type == ItemType::Macro {
679                 let redir_name = format!("{}.{}!.html", item_type, name);
680                 let redir_dst = self.dst.join(redir_name);
681                 let v = layout::redirect(file_name);
682                 self.shared.fs.write(&redir_dst, v.as_bytes())?;
683             }
684         }
685         Ok(())
686     }
687 }
688
689 fn write_shared(
690     cx: &Context,
691     krate: &clean::Crate,
692     search_index: String,
693     options: &RenderOptions,
694     cache: &Cache,
695 ) -> Result<(), Error> {
696     // Write out the shared files. Note that these are shared among all rustdoc
697     // docs placed in the output directory, so this needs to be a synchronized
698     // operation with respect to all other rustdocs running around.
699     let lock_file = cx.dst.join(".lock");
700     let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
701
702     // Add all the static files. These may already exist, but we just
703     // overwrite them anyway to make sure that they're fresh and up-to-date.
704
705     write_minify(
706         &cx.shared.fs,
707         cx.path("rustdoc.css"),
708         static_files::RUSTDOC_CSS,
709         options.enable_minification,
710     )?;
711     write_minify(
712         &cx.shared.fs,
713         cx.path("settings.css"),
714         static_files::SETTINGS_CSS,
715         options.enable_minification,
716     )?;
717     write_minify(
718         &cx.shared.fs,
719         cx.path("noscript.css"),
720         static_files::NOSCRIPT_CSS,
721         options.enable_minification,
722     )?;
723
724     // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
725     // then we'll run over the "official" styles.
726     let mut themes: FxHashSet<String> = FxHashSet::default();
727
728     for entry in &cx.shared.style_files {
729         let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
730         let extension =
731             try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
732
733         // Handle the official themes
734         match theme {
735             "light" => write_minify(
736                 &cx.shared.fs,
737                 cx.path("light.css"),
738                 static_files::themes::LIGHT,
739                 options.enable_minification,
740             )?,
741             "dark" => write_minify(
742                 &cx.shared.fs,
743                 cx.path("dark.css"),
744                 static_files::themes::DARK,
745                 options.enable_minification,
746             )?,
747             "ayu" => write_minify(
748                 &cx.shared.fs,
749                 cx.path("ayu.css"),
750                 static_files::themes::AYU,
751                 options.enable_minification,
752             )?,
753             _ => {
754                 // Handle added third-party themes
755                 let content = try_err!(fs::read(&entry.path), &entry.path);
756                 cx.shared
757                     .fs
758                     .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
759             }
760         };
761
762         themes.insert(theme.to_owned());
763     }
764
765     let write = |p, c| cx.shared.fs.write(p, c);
766     if (*cx.shared).layout.logo.is_empty() {
767         write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
768     }
769     if (*cx.shared).layout.favicon.is_empty() {
770         write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
771         write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
772         write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
773     }
774     write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
775     write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
776     write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
777
778     let mut themes: Vec<&String> = themes.iter().collect();
779     themes.sort();
780     // To avoid theme switch latencies as much as possible, we put everything theme related
781     // at the beginning of the html files into another js file.
782     let theme_js = format!(
783         r#"var themes = document.getElementById("theme-choices");
784 var themePicker = document.getElementById("theme-picker");
785
786 function showThemeButtonState() {{
787     themes.style.display = "block";
788     themePicker.style.borderBottomRightRadius = "0";
789     themePicker.style.borderBottomLeftRadius = "0";
790 }}
791
792 function hideThemeButtonState() {{
793     themes.style.display = "none";
794     themePicker.style.borderBottomRightRadius = "3px";
795     themePicker.style.borderBottomLeftRadius = "3px";
796 }}
797
798 function switchThemeButtonState() {{
799     if (themes.style.display === "block") {{
800         hideThemeButtonState();
801     }} else {{
802         showThemeButtonState();
803     }}
804 }};
805
806 function handleThemeButtonsBlur(e) {{
807     var active = document.activeElement;
808     var related = e.relatedTarget;
809
810     if (active.id !== "theme-picker" &&
811         (!active.parentNode || active.parentNode.id !== "theme-choices") &&
812         (!related ||
813          (related.id !== "theme-picker" &&
814           (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
815         hideThemeButtonState();
816     }}
817 }}
818
819 themePicker.onclick = switchThemeButtonState;
820 themePicker.onblur = handleThemeButtonsBlur;
821 {}.forEach(function(item) {{
822     var but = document.createElement("button");
823     but.textContent = item;
824     but.onclick = function(el) {{
825         switchTheme(currentTheme, mainTheme, item, true);
826         useSystemTheme(false);
827     }};
828     but.onblur = handleThemeButtonsBlur;
829     themes.appendChild(but);
830 }});"#,
831         serde_json::to_string(&themes).unwrap()
832     );
833
834     write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
835     write_minify(
836         &cx.shared.fs,
837         cx.path("main.js"),
838         static_files::MAIN_JS,
839         options.enable_minification,
840     )?;
841     write_minify(
842         &cx.shared.fs,
843         cx.path("settings.js"),
844         static_files::SETTINGS_JS,
845         options.enable_minification,
846     )?;
847     if cx.shared.include_sources {
848         write_minify(
849             &cx.shared.fs,
850             cx.path("source-script.js"),
851             static_files::sidebar::SOURCE_SCRIPT,
852             options.enable_minification,
853         )?;
854     }
855
856     {
857         write_minify(
858             &cx.shared.fs,
859             cx.path("storage.js"),
860             &format!(
861                 "var resourcesSuffix = \"{}\";{}",
862                 cx.shared.resource_suffix,
863                 static_files::STORAGE_JS
864             ),
865             options.enable_minification,
866         )?;
867     }
868
869     if let Some(ref css) = cx.shared.layout.css_file_extension {
870         let out = cx.path("theme.css");
871         let buffer = try_err!(fs::read_to_string(css), css);
872         if !options.enable_minification {
873             cx.shared.fs.write(&out, &buffer)?;
874         } else {
875             write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
876         }
877     }
878     write_minify(
879         &cx.shared.fs,
880         cx.path("normalize.css"),
881         static_files::NORMALIZE_CSS,
882         options.enable_minification,
883     )?;
884     write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
885     write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
886     write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
887     write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
888     write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
889     write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
890     write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
891     write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
892     write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
893     write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
894     write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
895     write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
896     write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
897
898     fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
899         let mut ret = Vec::new();
900         let mut krates = Vec::new();
901
902         if path.exists() {
903             for line in BufReader::new(File::open(path)?).lines() {
904                 let line = line?;
905                 if !line.starts_with(key) {
906                     continue;
907                 }
908                 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
909                     continue;
910                 }
911                 ret.push(line.to_string());
912                 krates.push(
913                     line[key.len() + 2..]
914                         .split('"')
915                         .next()
916                         .map(|s| s.to_owned())
917                         .unwrap_or_else(String::new),
918                 );
919             }
920         }
921         Ok((ret, krates))
922     }
923
924     fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
925         let mut ret = Vec::new();
926         let mut krates = Vec::new();
927
928         if path.exists() {
929             for line in BufReader::new(File::open(path)?).lines() {
930                 let line = line?;
931                 if !line.starts_with('"') {
932                     continue;
933                 }
934                 if line.starts_with(&format!("\"{}\"", krate)) {
935                     continue;
936                 }
937                 if line.ends_with(",\\") {
938                     ret.push(line[..line.len() - 2].to_string());
939                 } else {
940                     // Ends with "\\" (it's the case for the last added crate line)
941                     ret.push(line[..line.len() - 1].to_string());
942                 }
943                 krates.push(
944                     line.split('"')
945                         .find(|s| !s.is_empty())
946                         .map(|s| s.to_owned())
947                         .unwrap_or_else(String::new),
948                 );
949             }
950         }
951         Ok((ret, krates))
952     }
953
954     use std::ffi::OsString;
955
956     #[derive(Debug)]
957     struct Hierarchy {
958         elem: OsString,
959         children: FxHashMap<OsString, Hierarchy>,
960         elems: FxHashSet<OsString>,
961     }
962
963     impl Hierarchy {
964         fn new(elem: OsString) -> Hierarchy {
965             Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
966         }
967
968         fn to_json_string(&self) -> String {
969             let mut subs: Vec<&Hierarchy> = self.children.values().collect();
970             subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
971             let mut files = self
972                 .elems
973                 .iter()
974                 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
975                 .collect::<Vec<_>>();
976             files.sort_unstable_by(|a, b| a.cmp(b));
977             let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
978             let dirs =
979                 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
980             let files = files.join(",");
981             let files =
982                 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
983             format!(
984                 "{{\"name\":\"{name}\"{dirs}{files}}}",
985                 name = self.elem.to_str().expect("invalid osstring conversion"),
986                 dirs = dirs,
987                 files = files
988             )
989         }
990     }
991
992     if cx.shared.include_sources {
993         let mut hierarchy = Hierarchy::new(OsString::new());
994         for source in cx
995             .shared
996             .local_sources
997             .iter()
998             .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
999         {
1000             let mut h = &mut hierarchy;
1001             let mut elems = source
1002                 .components()
1003                 .filter_map(|s| match s {
1004                     Component::Normal(s) => Some(s.to_owned()),
1005                     _ => None,
1006                 })
1007                 .peekable();
1008             loop {
1009                 let cur_elem = elems.next().expect("empty file path");
1010                 if elems.peek().is_none() {
1011                     h.elems.insert(cur_elem);
1012                     break;
1013                 } else {
1014                     let e = cur_elem.clone();
1015                     h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1016                     h = h.children.get_mut(&cur_elem).expect("not found child");
1017                 }
1018             }
1019         }
1020
1021         let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1022         let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1023         all_sources.push(format!(
1024             "sourcesIndex[\"{}\"] = {};",
1025             &krate.name,
1026             hierarchy.to_json_string()
1027         ));
1028         all_sources.sort();
1029         let v = format!(
1030             "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1031             all_sources.join("\n")
1032         );
1033         cx.shared.fs.write(&dst, v.as_bytes())?;
1034     }
1035
1036     // Update the search index
1037     let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1038     let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name), &dst);
1039     all_indexes.push(search_index);
1040
1041     // Sort the indexes by crate so the file will be generated identically even
1042     // with rustdoc running in parallel.
1043     all_indexes.sort();
1044     {
1045         let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1046         v.push_str(&all_indexes.join(",\\\n"));
1047         // "addSearchOptions" has to be called first so the crate filtering can be set before the
1048         // search might start (if it's set into the URL for example).
1049         v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1050         cx.shared.fs.write(&dst, &v)?;
1051     }
1052     if options.enable_index_page {
1053         if let Some(index_page) = options.index_page.clone() {
1054             let mut md_opts = options.clone();
1055             md_opts.output = cx.dst.clone();
1056             md_opts.external_html = (*cx.shared).layout.external_html.clone();
1057
1058             crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1059                 .map_err(|e| Error::new(e, &index_page))?;
1060         } else {
1061             let dst = cx.dst.join("index.html");
1062             let page = layout::Page {
1063                 title: "Index of crates",
1064                 css_class: "mod",
1065                 root_path: "./",
1066                 static_root_path: cx.shared.static_root_path.as_deref(),
1067                 description: "List of crates",
1068                 keywords: BASIC_KEYWORDS,
1069                 resource_suffix: &cx.shared.resource_suffix,
1070                 extra_scripts: &[],
1071                 static_extra_scripts: &[],
1072             };
1073             krates.push(krate.name.clone());
1074             krates.sort();
1075             krates.dedup();
1076
1077             let content = format!(
1078                 "<h1 class=\"fqn\">\
1079                      <span class=\"in-band\">List of all crates</span>\
1080                 </h1><ul class=\"crate mod\">{}</ul>",
1081                 krates
1082                     .iter()
1083                     .map(|s| {
1084                         format!(
1085                             "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1086                             ensure_trailing_slash(s),
1087                             s
1088                         )
1089                     })
1090                     .collect::<String>()
1091             );
1092             let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1093             cx.shared.fs.write(&dst, v.as_bytes())?;
1094         }
1095     }
1096
1097     // Update the list of all implementors for traits
1098     let dst = cx.dst.join("implementors");
1099     for (&did, imps) in &cache.implementors {
1100         // Private modules can leak through to this phase of rustdoc, which
1101         // could contain implementations for otherwise private types. In some
1102         // rare cases we could find an implementation for an item which wasn't
1103         // indexed, so we just skip this step in that case.
1104         //
1105         // FIXME: this is a vague explanation for why this can't be a `get`, in
1106         //        theory it should be...
1107         let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1108             Some(p) => p,
1109             None => match cache.external_paths.get(&did) {
1110                 Some(p) => p,
1111                 None => continue,
1112             },
1113         };
1114
1115         #[derive(Serialize)]
1116         struct Implementor {
1117             text: String,
1118             synthetic: bool,
1119             types: Vec<String>,
1120         }
1121
1122         let implementors = imps
1123             .iter()
1124             .filter_map(|imp| {
1125                 // If the trait and implementation are in the same crate, then
1126                 // there's no need to emit information about it (there's inlining
1127                 // going on). If they're in different crates then the crate defining
1128                 // the trait will be interested in our implementation.
1129                 //
1130                 // If the implementation is from another crate then that crate
1131                 // should add it.
1132                 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1133                     None
1134                 } else {
1135                     Some(Implementor {
1136                         text: imp.inner_impl().print().to_string(),
1137                         synthetic: imp.inner_impl().synthetic,
1138                         types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1139                     })
1140                 }
1141             })
1142             .collect::<Vec<_>>();
1143
1144         // Only create a js file if we have impls to add to it. If the trait is
1145         // documented locally though we always create the file to avoid dead
1146         // links.
1147         if implementors.is_empty() && !cache.paths.contains_key(&did) {
1148             continue;
1149         }
1150
1151         let implementors = format!(
1152             r#"implementors["{}"] = {};"#,
1153             krate.name,
1154             serde_json::to_string(&implementors).unwrap()
1155         );
1156
1157         let mut mydst = dst.clone();
1158         for part in &remote_path[..remote_path.len() - 1] {
1159             mydst.push(part);
1160         }
1161         cx.shared.ensure_dir(&mydst)?;
1162         mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1163
1164         let (mut all_implementors, _) =
1165             try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1166         all_implementors.push(implementors);
1167         // Sort the implementors by crate so the file will be generated
1168         // identically even with rustdoc running in parallel.
1169         all_implementors.sort();
1170
1171         let mut v = String::from("(function() {var implementors = {};\n");
1172         for implementor in &all_implementors {
1173             writeln!(v, "{}", *implementor).unwrap();
1174         }
1175         v.push_str(
1176             "if (window.register_implementors) {\
1177                  window.register_implementors(implementors);\
1178              } else {\
1179                  window.pending_implementors = implementors;\
1180              }",
1181         );
1182         v.push_str("})()");
1183         cx.shared.fs.write(&mydst, &v)?;
1184     }
1185     Ok(())
1186 }
1187
1188 fn write_minify(
1189     fs: &DocFS,
1190     dst: PathBuf,
1191     contents: &str,
1192     enable_minification: bool,
1193 ) -> Result<(), Error> {
1194     if enable_minification {
1195         if dst.extension() == Some(&OsStr::new("css")) {
1196             let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1197             fs.write(dst, res.as_bytes())
1198         } else {
1199             fs.write(dst, minifier::js::minify(contents).as_bytes())
1200         }
1201     } else {
1202         fs.write(dst, contents.as_bytes())
1203     }
1204 }
1205
1206 fn write_srclink(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1207     if let Some(l) = cx.src_href(item, cache) {
1208         write!(
1209             buf,
1210             "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
1211             l, "goto source code"
1212         )
1213     }
1214 }
1215
1216 #[derive(Debug, Eq, PartialEq, Hash)]
1217 struct ItemEntry {
1218     url: String,
1219     name: String,
1220 }
1221
1222 impl ItemEntry {
1223     fn new(mut url: String, name: String) -> ItemEntry {
1224         while url.starts_with('/') {
1225             url.remove(0);
1226         }
1227         ItemEntry { url, name }
1228     }
1229 }
1230
1231 impl ItemEntry {
1232     crate fn print(&self) -> impl fmt::Display + '_ {
1233         crate::html::format::display_fn(move |f| {
1234             write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1235         })
1236     }
1237 }
1238
1239 impl PartialOrd for ItemEntry {
1240     fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1241         Some(self.cmp(other))
1242     }
1243 }
1244
1245 impl Ord for ItemEntry {
1246     fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1247         self.name.cmp(&other.name)
1248     }
1249 }
1250
1251 #[derive(Debug)]
1252 struct AllTypes {
1253     structs: FxHashSet<ItemEntry>,
1254     enums: FxHashSet<ItemEntry>,
1255     unions: FxHashSet<ItemEntry>,
1256     primitives: FxHashSet<ItemEntry>,
1257     traits: FxHashSet<ItemEntry>,
1258     macros: FxHashSet<ItemEntry>,
1259     functions: FxHashSet<ItemEntry>,
1260     typedefs: FxHashSet<ItemEntry>,
1261     opaque_tys: FxHashSet<ItemEntry>,
1262     statics: FxHashSet<ItemEntry>,
1263     constants: FxHashSet<ItemEntry>,
1264     keywords: FxHashSet<ItemEntry>,
1265     attributes: FxHashSet<ItemEntry>,
1266     derives: FxHashSet<ItemEntry>,
1267     trait_aliases: FxHashSet<ItemEntry>,
1268 }
1269
1270 impl AllTypes {
1271     fn new() -> AllTypes {
1272         let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1273         AllTypes {
1274             structs: new_set(100),
1275             enums: new_set(100),
1276             unions: new_set(100),
1277             primitives: new_set(26),
1278             traits: new_set(100),
1279             macros: new_set(100),
1280             functions: new_set(100),
1281             typedefs: new_set(100),
1282             opaque_tys: new_set(100),
1283             statics: new_set(100),
1284             constants: new_set(100),
1285             keywords: new_set(100),
1286             attributes: new_set(100),
1287             derives: new_set(100),
1288             trait_aliases: new_set(100),
1289         }
1290     }
1291
1292     fn append(&mut self, item_name: String, item_type: &ItemType) {
1293         let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1294         if let Some(name) = url.pop() {
1295             let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1296             url.push(name);
1297             let name = url.join("::");
1298             match *item_type {
1299                 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1300                 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1301                 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1302                 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1303                 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1304                 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1305                 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1306                 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1307                 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1308                 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1309                 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1310                 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1311                 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1312                 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1313                 _ => true,
1314             };
1315         }
1316     }
1317 }
1318
1319 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1320     if !e.is_empty() {
1321         let mut e: Vec<&ItemEntry> = e.iter().collect();
1322         e.sort();
1323         write!(
1324             f,
1325             "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">{}</ul>",
1326             title,
1327             Escape(title),
1328             class,
1329             e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1330         );
1331     }
1332 }
1333
1334 impl AllTypes {
1335     fn print(self, f: &mut Buffer) {
1336         write!(
1337             f,
1338             "<h1 class=\"fqn\">\
1339                  <span class=\"out-of-band\">\
1340                      <span id=\"render-detail\">\
1341                          <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1342                             title=\"collapse all docs\">\
1343                              [<span class=\"inner\">&#x2212;</span>]\
1344                          </a>\
1345                      </span>
1346                  </span>
1347                  <span class=\"in-band\">List of all items</span>\
1348              </h1>"
1349         );
1350         print_entries(f, &self.structs, "Structs", "structs");
1351         print_entries(f, &self.enums, "Enums", "enums");
1352         print_entries(f, &self.unions, "Unions", "unions");
1353         print_entries(f, &self.primitives, "Primitives", "primitives");
1354         print_entries(f, &self.traits, "Traits", "traits");
1355         print_entries(f, &self.macros, "Macros", "macros");
1356         print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1357         print_entries(f, &self.derives, "Derive Macros", "derives");
1358         print_entries(f, &self.functions, "Functions", "functions");
1359         print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1360         print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1361         print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1362         print_entries(f, &self.statics, "Statics", "statics");
1363         print_entries(f, &self.constants, "Constants", "constants")
1364     }
1365 }
1366
1367 #[derive(Debug)]
1368 enum Setting {
1369     Section {
1370         description: &'static str,
1371         sub_settings: Vec<Setting>,
1372     },
1373     Toggle {
1374         js_data_name: &'static str,
1375         description: &'static str,
1376         default_value: bool,
1377     },
1378     Select {
1379         js_data_name: &'static str,
1380         description: &'static str,
1381         default_value: &'static str,
1382         options: Vec<(String, String)>,
1383     },
1384 }
1385
1386 impl Setting {
1387     fn display(&self, root_path: &str, suffix: &str) -> String {
1388         match *self {
1389             Setting::Section { description, ref sub_settings } => format!(
1390                 "<div class=\"setting-line\">\
1391                      <div class=\"title\">{}</div>\
1392                      <div class=\"sub-settings\">{}</div>
1393                  </div>",
1394                 description,
1395                 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1396             ),
1397             Setting::Toggle { js_data_name, description, default_value } => format!(
1398                 "<div class=\"setting-line\">\
1399                      <label class=\"toggle\">\
1400                      <input type=\"checkbox\" id=\"{}\" {}>\
1401                      <span class=\"slider\"></span>\
1402                      </label>\
1403                      <div>{}</div>\
1404                  </div>",
1405                 js_data_name,
1406                 if default_value { " checked" } else { "" },
1407                 description,
1408             ),
1409             Setting::Select { js_data_name, description, default_value, ref options } => format!(
1410                 "<div class=\"setting-line\">\
1411                      <div>{}</div>\
1412                      <label class=\"select-wrapper\">\
1413                          <select id=\"{}\" autocomplete=\"off\">{}</select>\
1414                          <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1415                      </label>\
1416                  </div>",
1417                 description,
1418                 js_data_name,
1419                 options
1420                     .iter()
1421                     .map(|opt| format!(
1422                         "<option value=\"{}\" {}>{}</option>",
1423                         opt.0,
1424                         if &opt.0 == default_value { "selected" } else { "" },
1425                         opt.1,
1426                     ))
1427                     .collect::<String>(),
1428                 root_path,
1429                 suffix,
1430             ),
1431         }
1432     }
1433 }
1434
1435 impl From<(&'static str, &'static str, bool)> for Setting {
1436     fn from(values: (&'static str, &'static str, bool)) -> Setting {
1437         Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1438     }
1439 }
1440
1441 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1442     fn from(values: (&'static str, Vec<T>)) -> Setting {
1443         Setting::Section {
1444             description: values.0,
1445             sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1446         }
1447     }
1448 }
1449
1450 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1451     let theme_names: Vec<(String, String)> = themes
1452         .iter()
1453         .map(|entry| {
1454             let theme =
1455                 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1456                     .to_string();
1457
1458             Ok((theme.clone(), theme))
1459         })
1460         .collect::<Result<_, Error>>()?;
1461
1462     // (id, explanation, default value)
1463     let settings: &[Setting] = &[
1464         (
1465             "Theme preferences",
1466             vec![
1467                 Setting::from(("use-system-theme", "Use system theme", true)),
1468                 Setting::Select {
1469                     js_data_name: "preferred-dark-theme",
1470                     description: "Preferred dark theme",
1471                     default_value: "dark",
1472                     options: theme_names.clone(),
1473                 },
1474                 Setting::Select {
1475                     js_data_name: "preferred-light-theme",
1476                     description: "Preferred light theme",
1477                     default_value: "light",
1478                     options: theme_names,
1479                 },
1480             ],
1481         )
1482             .into(),
1483         (
1484             "Auto-hide item declarations",
1485             vec![
1486                 ("auto-hide-struct", "Auto-hide structs declaration", true),
1487                 ("auto-hide-enum", "Auto-hide enums declaration", false),
1488                 ("auto-hide-union", "Auto-hide unions declaration", true),
1489                 ("auto-hide-trait", "Auto-hide traits declaration", true),
1490                 ("auto-hide-macro", "Auto-hide macros declaration", false),
1491             ],
1492         )
1493             .into(),
1494         ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1495         ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1496         ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1497             .into(),
1498         ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1499         ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1500             .into(),
1501         ("line-numbers", "Show line numbers on code examples", false).into(),
1502         ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1503     ];
1504
1505     Ok(format!(
1506         "<h1 class=\"fqn\">\
1507             <span class=\"in-band\">Rustdoc settings</span>\
1508         </h1>\
1509         <div class=\"settings\">{}</div>\
1510         <script src=\"{}settings{}.js\"></script>",
1511         settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1512         root_path,
1513         suffix
1514     ))
1515 }
1516
1517 impl Context {
1518     fn derive_id(&self, id: String) -> String {
1519         let mut map = self.id_map.borrow_mut();
1520         map.derive(id)
1521     }
1522
1523     /// String representation of how to get back to the root path of the 'doc/'
1524     /// folder in terms of a relative URL.
1525     fn root_path(&self) -> String {
1526         "../".repeat(self.current.len())
1527     }
1528
1529     fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1530         // A little unfortunate that this is done like this, but it sure
1531         // does make formatting *a lot* nicer.
1532         CURRENT_DEPTH.with(|slot| {
1533             slot.set(self.current.len());
1534         });
1535
1536         let mut title = if it.is_primitive() || it.is_keyword() {
1537             // No need to include the namespace for primitive types and keywords
1538             String::new()
1539         } else {
1540             self.current.join("::")
1541         };
1542         if pushname {
1543             if !title.is_empty() {
1544                 title.push_str("::");
1545             }
1546             title.push_str(&it.name.unwrap().as_str());
1547         }
1548         title.push_str(" - Rust");
1549         let tyname = it.type_();
1550         let desc = if it.is_crate() {
1551             format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1552         } else {
1553             format!(
1554                 "API documentation for the Rust `{}` {} in crate `{}`.",
1555                 it.name.as_ref().unwrap(),
1556                 tyname,
1557                 self.shared.layout.krate
1558             )
1559         };
1560         let keywords = make_item_keywords(it);
1561         let page = layout::Page {
1562             css_class: tyname.as_str(),
1563             root_path: &self.root_path(),
1564             static_root_path: self.shared.static_root_path.as_deref(),
1565             title: &title,
1566             description: &desc,
1567             keywords: &keywords,
1568             resource_suffix: &self.shared.resource_suffix,
1569             extra_scripts: &[],
1570             static_extra_scripts: &[],
1571         };
1572
1573         {
1574             self.id_map.borrow_mut().reset();
1575             self.id_map.borrow_mut().populate(initial_ids());
1576         }
1577
1578         if !self.render_redirect_pages {
1579             layout::render(
1580                 &self.shared.layout,
1581                 &page,
1582                 |buf: &mut _| print_sidebar(self, it, buf, cache),
1583                 |buf: &mut _| print_item(self, it, buf, cache),
1584                 &self.shared.style_files,
1585             )
1586         } else {
1587             let mut url = self.root_path();
1588             if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1589                 for name in &names[..names.len() - 1] {
1590                     url.push_str(name);
1591                     url.push_str("/");
1592                 }
1593                 url.push_str(&item_path(ty, names.last().unwrap()));
1594                 layout::redirect(&url)
1595             } else {
1596                 String::new()
1597             }
1598         }
1599     }
1600
1601     /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1602     fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1603         // BTreeMap instead of HashMap to get a sorted output
1604         let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1605         for item in &m.items {
1606             if item.is_stripped() {
1607                 continue;
1608             }
1609
1610             let short = item.type_();
1611             let myname = match item.name {
1612                 None => continue,
1613                 Some(ref s) => s.to_string(),
1614             };
1615             let short = short.to_string();
1616             map.entry(short).or_default().push((
1617                 myname,
1618                 Some(item.doc_value().map_or_else(|| String::new(), plain_text_summary)),
1619             ));
1620         }
1621
1622         if self.shared.sort_modules_alphabetically {
1623             for items in map.values_mut() {
1624                 items.sort();
1625             }
1626         }
1627         map
1628     }
1629
1630     /// Generates a url appropriate for an `href` attribute back to the source of
1631     /// this item.
1632     ///
1633     /// The url generated, when clicked, will redirect the browser back to the
1634     /// original source code.
1635     ///
1636     /// If `None` is returned, then a source link couldn't be generated. This
1637     /// may happen, for example, with externally inlined items where the source
1638     /// of their crate documentation isn't known.
1639     fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1640         let mut root = self.root_path();
1641         let mut path = String::new();
1642         let cnum = item.source.cnum(self.sess());
1643
1644         // We can safely ignore synthetic `SourceFile`s.
1645         let file = match item.source.filename(self.sess()) {
1646             FileName::Real(ref path) => path.local_path().to_path_buf(),
1647             _ => return None,
1648         };
1649         let file = &file;
1650
1651         let (krate, path) = if cnum == LOCAL_CRATE {
1652             if let Some(path) = self.shared.local_sources.get(file) {
1653                 (&self.shared.layout.krate, path)
1654             } else {
1655                 return None;
1656             }
1657         } else {
1658             let (krate, src_root) = match *cache.extern_locations.get(&cnum)? {
1659                 (ref name, ref src, ExternalLocation::Local) => (name, src),
1660                 (ref name, ref src, ExternalLocation::Remote(ref s)) => {
1661                     root = s.to_string();
1662                     (name, src)
1663                 }
1664                 (_, _, ExternalLocation::Unknown) => return None,
1665             };
1666
1667             sources::clean_path(&src_root, file, false, |component| {
1668                 path.push_str(&component.to_string_lossy());
1669                 path.push('/');
1670             });
1671             let mut fname = file.file_name().expect("source has no filename").to_os_string();
1672             fname.push(".html");
1673             path.push_str(&fname.to_string_lossy());
1674             (krate, &path)
1675         };
1676
1677         let loline = item.source.lo(self.sess()).line;
1678         let hiline = item.source.hi(self.sess()).line;
1679         let lines =
1680             if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) };
1681         Some(format!(
1682             "{root}src/{krate}/{path}#{lines}",
1683             root = Escape(&root),
1684             krate = krate,
1685             path = path,
1686             lines = lines
1687         ))
1688     }
1689 }
1690
1691 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1692 where
1693     F: FnOnce(&mut Buffer),
1694 {
1695     write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1696     f(w);
1697     write!(w, "</div>")
1698 }
1699
1700 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1701     debug_assert!(!item.is_stripped());
1702     // Write the breadcrumb trail header for the top
1703     write!(buf, "<h1 class=\"fqn\"><span class=\"out-of-band\">");
1704     render_stability_since_raw(
1705         buf,
1706         item.stable_since().as_deref(),
1707         item.const_stable_since().as_deref(),
1708         None,
1709         None,
1710     );
1711     write!(
1712         buf,
1713         "<span id=\"render-detail\">\
1714                 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1715                     title=\"collapse all docs\">\
1716                     [<span class=\"inner\">&#x2212;</span>]\
1717                 </a>\
1718             </span>"
1719     );
1720
1721     // Write `src` tag
1722     //
1723     // When this item is part of a `crate use` in a downstream crate, the
1724     // [src] link in the downstream documentation will actually come back to
1725     // this page, and this link will be auto-clicked. The `id` attribute is
1726     // used to find the link to auto-click.
1727     if cx.shared.include_sources && !item.is_primitive() {
1728         write_srclink(cx, item, buf, cache);
1729     }
1730
1731     write!(buf, "</span>"); // out-of-band
1732     write!(buf, "<span class=\"in-band\">");
1733     let name = match item.kind {
1734         clean::ModuleItem(ref m) => {
1735             if m.is_crate {
1736                 "Crate "
1737             } else {
1738                 "Module "
1739             }
1740         }
1741         clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1742         clean::TraitItem(..) => "Trait ",
1743         clean::StructItem(..) => "Struct ",
1744         clean::UnionItem(..) => "Union ",
1745         clean::EnumItem(..) => "Enum ",
1746         clean::TypedefItem(..) => "Type Definition ",
1747         clean::MacroItem(..) => "Macro ",
1748         clean::ProcMacroItem(ref mac) => match mac.kind {
1749             MacroKind::Bang => "Macro ",
1750             MacroKind::Attr => "Attribute Macro ",
1751             MacroKind::Derive => "Derive Macro ",
1752         },
1753         clean::PrimitiveItem(..) => "Primitive Type ",
1754         clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1755         clean::ConstantItem(..) => "Constant ",
1756         clean::ForeignTypeItem => "Foreign Type ",
1757         clean::KeywordItem(..) => "Keyword ",
1758         clean::OpaqueTyItem(..) => "Opaque Type ",
1759         clean::TraitAliasItem(..) => "Trait Alias ",
1760         _ => {
1761             // We don't generate pages for any other type.
1762             unreachable!();
1763         }
1764     };
1765     buf.write_str(name);
1766     if !item.is_primitive() && !item.is_keyword() {
1767         let cur = &cx.current;
1768         let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1769         for (i, component) in cur.iter().enumerate().take(amt) {
1770             write!(
1771                 buf,
1772                 "<a href=\"{}index.html\">{}</a>::<wbr>",
1773                 "../".repeat(cur.len() - i - 1),
1774                 component
1775             );
1776         }
1777     }
1778     write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1779
1780     write!(buf, "</span></h1>"); // in-band
1781
1782     match item.kind {
1783         clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1784         clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1785             item_function(buf, cx, item, f)
1786         }
1787         clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1788         clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1789         clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1790         clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1791         clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1792         clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1793         clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1794         clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1795         clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1796         clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1797         clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1798         clean::KeywordItem(_) => item_keyword(buf, cx, item),
1799         clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e, cache),
1800         clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1801         _ => {
1802             // We don't generate pages for any other type.
1803             unreachable!();
1804         }
1805     }
1806 }
1807
1808 fn item_path(ty: ItemType, name: &str) -> String {
1809     match ty {
1810         ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1811         _ => format!("{}.{}.html", ty, name),
1812     }
1813 }
1814
1815 fn full_path(cx: &Context, item: &clean::Item) -> String {
1816     let mut s = cx.current.join("::");
1817     s.push_str("::");
1818     s.push_str(&item.name.unwrap().as_str());
1819     s
1820 }
1821
1822 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item, parent: Option<&clean::Item>) {
1823     if let Some(ref name) = item.name {
1824         info!("Documenting {}", name);
1825     }
1826     document_item_info(w, cx, item, false, parent);
1827     document_full(w, item, cx, "", false);
1828 }
1829
1830 /// Render md_text as markdown.
1831 fn render_markdown(
1832     w: &mut Buffer,
1833     cx: &Context,
1834     md_text: &str,
1835     links: Vec<RenderedLink>,
1836     prefix: &str,
1837     is_hidden: bool,
1838 ) {
1839     let mut ids = cx.id_map.borrow_mut();
1840     write!(
1841         w,
1842         "<div class=\"docblock{}\">{}{}</div>",
1843         if is_hidden { " hidden" } else { "" },
1844         prefix,
1845         Markdown(
1846             md_text,
1847             &links,
1848             &mut ids,
1849             cx.shared.codes,
1850             cx.shared.edition,
1851             &cx.shared.playground
1852         )
1853         .into_string()
1854     )
1855 }
1856
1857 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1858 /// docs are longer, a "Read more" link is appended to the end.
1859 fn document_short(
1860     w: &mut Buffer,
1861     item: &clean::Item,
1862     cx: &Context,
1863     link: AssocItemLink<'_>,
1864     prefix: &str,
1865     is_hidden: bool,
1866     parent: Option<&clean::Item>,
1867     show_def_docs: bool,
1868 ) {
1869     document_item_info(w, cx, item, is_hidden, parent);
1870     if !show_def_docs {
1871         return;
1872     }
1873     if let Some(s) = item.doc_value() {
1874         let mut summary_html = MarkdownSummaryLine(s, &item.links()).into_string();
1875
1876         if s.contains('\n') {
1877             let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link));
1878
1879             if let Some(idx) = summary_html.rfind("</p>") {
1880                 summary_html.insert_str(idx, &link);
1881             } else {
1882                 summary_html.push_str(&link);
1883             }
1884         }
1885
1886         write!(
1887             w,
1888             "<div class='docblock{}'>{}{}</div>",
1889             if is_hidden { " hidden" } else { "" },
1890             prefix,
1891             summary_html,
1892         );
1893     } else if !prefix.is_empty() {
1894         write!(
1895             w,
1896             "<div class=\"docblock{}\">{}</div>",
1897             if is_hidden { " hidden" } else { "" },
1898             prefix
1899         );
1900     }
1901 }
1902
1903 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1904     if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1905         debug!("Doc block: =====\n{}\n=====", s);
1906         render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1907     } else if !prefix.is_empty() {
1908         write!(
1909             w,
1910             "<div class=\"docblock{}\">{}</div>",
1911             if is_hidden { " hidden" } else { "" },
1912             prefix
1913         );
1914     }
1915 }
1916
1917 /// Add extra information about an item such as:
1918 ///
1919 /// * Stability
1920 /// * Deprecated
1921 /// * Required features (through the `doc_cfg` feature)
1922 fn document_item_info(
1923     w: &mut Buffer,
1924     cx: &Context,
1925     item: &clean::Item,
1926     is_hidden: bool,
1927     parent: Option<&clean::Item>,
1928 ) {
1929     let item_infos = short_item_info(item, cx, parent);
1930     if !item_infos.is_empty() {
1931         write!(w, "<div class=\"item-info{}\">", if is_hidden { " hidden" } else { "" });
1932         for info in item_infos {
1933             write!(w, "{}", info);
1934         }
1935         write!(w, "</div>");
1936     }
1937 }
1938
1939 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1940     if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1941 }
1942
1943 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1944     if item.is_non_exhaustive() {
1945         write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1946             if item.is_struct() {
1947                 "struct"
1948             } else if item.is_enum() {
1949                 "enum"
1950             } else if item.is_variant() {
1951                 "variant"
1952             } else {
1953                 "type"
1954             }
1955         });
1956
1957         if item.is_struct() {
1958             write!(
1959                 w,
1960                 "Non-exhaustive structs could have additional fields added in future. \
1961                  Therefore, non-exhaustive structs cannot be constructed in external crates \
1962                  using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1963                  matched against without a wildcard <code>..</code>; and \
1964                  struct update syntax will not work."
1965             );
1966         } else if item.is_enum() {
1967             write!(
1968                 w,
1969                 "Non-exhaustive enums could have additional variants added in future. \
1970                  Therefore, when matching against variants of non-exhaustive enums, an \
1971                  extra wildcard arm must be added to account for any future variants."
1972             );
1973         } else if item.is_variant() {
1974             write!(
1975                 w,
1976                 "Non-exhaustive enum variants could have additional fields added in future. \
1977                  Therefore, non-exhaustive enum variants cannot be constructed in external \
1978                  crates and cannot be matched against."
1979             );
1980         } else {
1981             write!(
1982                 w,
1983                 "This type will require a wildcard arm in any match statements or constructors."
1984             );
1985         }
1986
1987         write!(w, "</div>");
1988     }
1989 }
1990
1991 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1992 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1993     /// Takes a non-numeric and a numeric part from the given &str.
1994     fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1995         let i = s.find(|c: char| c.is_ascii_digit());
1996         let (a, b) = s.split_at(i.unwrap_or(s.len()));
1997         let i = b.find(|c: char| !c.is_ascii_digit());
1998         let (b, c) = b.split_at(i.unwrap_or(b.len()));
1999         *s = c;
2000         (a, b)
2001     }
2002
2003     while !lhs.is_empty() || !rhs.is_empty() {
2004         let (la, lb) = take_parts(&mut lhs);
2005         let (ra, rb) = take_parts(&mut rhs);
2006         // First process the non-numeric part.
2007         match la.cmp(ra) {
2008             Ordering::Equal => (),
2009             x => return x,
2010         }
2011         // Then process the numeric part, if both sides have one (and they fit in a u64).
2012         if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2013             match ln.cmp(&rn) {
2014                 Ordering::Equal => (),
2015                 x => return x,
2016             }
2017         }
2018         // Then process the numeric part again, but this time as strings.
2019         match lb.cmp(rb) {
2020             Ordering::Equal => (),
2021             x => return x,
2022         }
2023     }
2024
2025     Ordering::Equal
2026 }
2027
2028 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
2029     document(w, cx, item, None);
2030
2031     let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2032
2033     // the order of item types in the listing
2034     fn reorder(ty: ItemType) -> u8 {
2035         match ty {
2036             ItemType::ExternCrate => 0,
2037             ItemType::Import => 1,
2038             ItemType::Primitive => 2,
2039             ItemType::Module => 3,
2040             ItemType::Macro => 4,
2041             ItemType::Struct => 5,
2042             ItemType::Enum => 6,
2043             ItemType::Constant => 7,
2044             ItemType::Static => 8,
2045             ItemType::Trait => 9,
2046             ItemType::Function => 10,
2047             ItemType::Typedef => 12,
2048             ItemType::Union => 13,
2049             _ => 14 + ty as u8,
2050         }
2051     }
2052
2053     fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2054         let ty1 = i1.type_();
2055         let ty2 = i2.type_();
2056         if ty1 != ty2 {
2057             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2058         }
2059         let s1 = i1.stability.as_ref().map(|s| s.level);
2060         let s2 = i2.stability.as_ref().map(|s| s.level);
2061         if let (Some(a), Some(b)) = (s1, s2) {
2062             match (a.is_stable(), b.is_stable()) {
2063                 (true, true) | (false, false) => {}
2064                 (false, true) => return Ordering::Less,
2065                 (true, false) => return Ordering::Greater,
2066             }
2067         }
2068         let lhs = i1.name.unwrap_or(kw::Invalid).as_str();
2069         let rhs = i2.name.unwrap_or(kw::Invalid).as_str();
2070         compare_names(&lhs, &rhs)
2071     }
2072
2073     if cx.shared.sort_modules_alphabetically {
2074         indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2075     }
2076     // This call is to remove re-export duplicates in cases such as:
2077     //
2078     // ```
2079     // crate mod foo {
2080     //     crate mod bar {
2081     //         crate trait Double { fn foo(); }
2082     //     }
2083     // }
2084     //
2085     // crate use foo::bar::*;
2086     // crate use foo::*;
2087     // ```
2088     //
2089     // `Double` will appear twice in the generated docs.
2090     //
2091     // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2092     // can be identical even if the elements are different (mostly in imports).
2093     // So in case this is an import, we keep everything by adding a "unique id"
2094     // (which is the position in the vector).
2095     indices.dedup_by_key(|i| {
2096         (
2097             items[*i].def_id,
2098             if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2099             items[*i].type_(),
2100             if items[*i].is_import() { *i } else { 0 },
2101         )
2102     });
2103
2104     debug!("{:?}", indices);
2105     let mut curty = None;
2106     for &idx in &indices {
2107         let myitem = &items[idx];
2108         if myitem.is_stripped() {
2109             continue;
2110         }
2111
2112         let myty = Some(myitem.type_());
2113         if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2114             // Put `extern crate` and `use` re-exports in the same section.
2115             curty = myty;
2116         } else if myty != curty {
2117             if curty.is_some() {
2118                 write!(w, "</table>");
2119             }
2120             curty = myty;
2121             let (short, name) = item_ty_to_strs(&myty.unwrap());
2122             write!(
2123                 w,
2124                 "<h2 id=\"{id}\" class=\"section-header\">\
2125                        <a href=\"#{id}\">{name}</a></h2>\n<table>",
2126                 id = cx.derive_id(short.to_owned()),
2127                 name = name
2128             );
2129         }
2130
2131         match myitem.kind {
2132             clean::ExternCrateItem(ref name, ref src) => {
2133                 use crate::html::format::anchor;
2134
2135                 match *src {
2136                     Some(ref src) => write!(
2137                         w,
2138                         "<tr><td><code>{}extern crate {} as {};",
2139                         myitem.visibility.print_with_space(),
2140                         anchor(myitem.def_id, src),
2141                         name
2142                     ),
2143                     None => write!(
2144                         w,
2145                         "<tr><td><code>{}extern crate {};",
2146                         myitem.visibility.print_with_space(),
2147                         anchor(myitem.def_id, name)
2148                     ),
2149                 }
2150                 write!(w, "</code></td></tr>");
2151             }
2152
2153             clean::ImportItem(ref import) => {
2154                 write!(
2155                     w,
2156                     "<tr><td><code>{}{}</code></td></tr>",
2157                     myitem.visibility.print_with_space(),
2158                     import.print()
2159                 );
2160             }
2161
2162             _ => {
2163                 if myitem.name.is_none() {
2164                     continue;
2165                 }
2166
2167                 let unsafety_flag = match myitem.kind {
2168                     clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2169                         if func.header.unsafety == hir::Unsafety::Unsafe =>
2170                     {
2171                         "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2172                     }
2173                     _ => "",
2174                 };
2175
2176                 let stab = myitem.stability_class();
2177                 let add = if stab.is_some() { " " } else { "" };
2178
2179                 let doc_value = myitem.doc_value().unwrap_or("");
2180                 write!(
2181                     w,
2182                     "<tr class=\"{stab}{add}module-item\">\
2183                          <td><a class=\"{class}\" href=\"{href}\" \
2184                              title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2185                          <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2186                      </tr>",
2187                     name = *myitem.name.as_ref().unwrap(),
2188                     stab_tags = extra_info_tags(myitem, item),
2189                     docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2190                     class = myitem.type_(),
2191                     add = add,
2192                     stab = stab.unwrap_or_else(String::new),
2193                     unsafety_flag = unsafety_flag,
2194                     href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()),
2195                     title = [full_path(cx, myitem), myitem.type_().to_string()]
2196                         .iter()
2197                         .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2198                         .collect::<Vec<_>>()
2199                         .join(" "),
2200                 );
2201             }
2202         }
2203     }
2204
2205     if curty.is_some() {
2206         write!(w, "</table>");
2207     }
2208 }
2209
2210 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
2211 /// at the module level.
2212 fn extra_info_tags(item: &clean::Item, parent: &clean::Item) -> String {
2213     let mut tags = String::new();
2214
2215     fn tag_html(class: &str, title: &str, contents: &str) -> String {
2216         format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2217     }
2218
2219     // The trailing space after each tag is to space it properly against the rest of the docs.
2220     if let Some(depr) = &item.deprecation {
2221         let mut message = "Deprecated";
2222         if !stability::deprecation_in_effect(
2223             depr.is_since_rustc_version,
2224             depr.since.map(|s| s.as_str()).as_deref(),
2225         ) {
2226             message = "Deprecation planned";
2227         }
2228         tags += &tag_html("deprecated", "", message);
2229     }
2230
2231     // The "rustc_private" crates are permanently unstable so it makes no sense
2232     // to render "unstable" everywhere.
2233     if item.stability.as_ref().map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2234         == Some(true)
2235     {
2236         tags += &tag_html("unstable", "", "Experimental");
2237     }
2238
2239     let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2240         (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2241         (cfg, _) => cfg.as_deref().cloned(),
2242     };
2243
2244     debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2245     if let Some(ref cfg) = cfg {
2246         tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2247     }
2248
2249     tags
2250 }
2251
2252 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2253     let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2254         (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2255         (cfg, _) => cfg.as_deref().cloned(),
2256     };
2257
2258     debug!(
2259         "Portability {:?} - {:?} = {:?}",
2260         item.attrs.cfg,
2261         parent.and_then(|p| p.attrs.cfg.as_ref()),
2262         cfg
2263     );
2264
2265     Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2266 }
2267
2268 /// Render the stability, deprecation and portability information that is displayed at the top of
2269 /// the item's documentation.
2270 fn short_item_info(item: &clean::Item, cx: &Context, parent: Option<&clean::Item>) -> Vec<String> {
2271     let mut extra_info = vec![];
2272     let error_codes = cx.shared.codes;
2273
2274     if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
2275         item.deprecation
2276     {
2277         // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2278         // but only display the future-deprecation messages for #[rustc_deprecated].
2279         let mut message = if let Some(since) = since {
2280             let since = &since.as_str();
2281             if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2282                 format!("Deprecating in {}", Escape(since))
2283             } else {
2284                 format!("Deprecated since {}", Escape(since))
2285             }
2286         } else {
2287             String::from("Deprecated")
2288         };
2289
2290         if let Some(note) = note {
2291             let note = note.as_str();
2292             let mut ids = cx.id_map.borrow_mut();
2293             let html = MarkdownHtml(
2294                 &note,
2295                 &mut ids,
2296                 error_codes,
2297                 cx.shared.edition,
2298                 &cx.shared.playground,
2299             );
2300             message.push_str(&format!(": {}", html.into_string()));
2301         }
2302         extra_info.push(format!(
2303             "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2304             message,
2305         ));
2306     }
2307
2308     // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2309     // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2310     if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2311         .stability
2312         .as_ref()
2313         .filter(|stab| stab.feature != sym::rustc_private)
2314         .map(|stab| (stab.level, stab.feature))
2315     {
2316         let mut message =
2317             "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2318
2319         let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2320         if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2321             feature.push_str(&format!(
2322                 "&nbsp;<a href=\"{url}{issue}\">#{issue}</a>",
2323                 url = url,
2324                 issue = issue
2325             ));
2326         }
2327
2328         message.push_str(&format!(" ({})", feature));
2329
2330         if let Some(unstable_reason) = reason {
2331             let mut ids = cx.id_map.borrow_mut();
2332             message = format!(
2333                 "<details><summary>{}</summary>{}</details>",
2334                 message,
2335                 MarkdownHtml(
2336                     &unstable_reason.as_str(),
2337                     &mut ids,
2338                     error_codes,
2339                     cx.shared.edition,
2340                     &cx.shared.playground,
2341                 )
2342                 .into_string()
2343             );
2344         }
2345
2346         extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2347     }
2348
2349     if let Some(portability) = portability(item, parent) {
2350         extra_info.push(portability);
2351     }
2352
2353     extra_info
2354 }
2355
2356 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2357     write!(w, "<pre class=\"rust const\">");
2358     render_attributes(w, it, false);
2359
2360     write!(
2361         w,
2362         "{vis}const {name}: {typ}",
2363         vis = it.visibility.print_with_space(),
2364         name = it.name.as_ref().unwrap(),
2365         typ = c.type_.print(),
2366     );
2367
2368     if c.value.is_some() || c.is_literal {
2369         write!(w, " = {expr};", expr = Escape(&c.expr));
2370     } else {
2371         write!(w, ";");
2372     }
2373
2374     if let Some(value) = &c.value {
2375         if !c.is_literal {
2376             let value_lowercase = value.to_lowercase();
2377             let expr_lowercase = c.expr.to_lowercase();
2378
2379             if value_lowercase != expr_lowercase
2380                 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2381             {
2382                 write!(w, " // {value}", value = Escape(value));
2383             }
2384         }
2385     }
2386
2387     write!(w, "</pre>");
2388     document(w, cx, it, None)
2389 }
2390
2391 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2392     write!(w, "<pre class=\"rust static\">");
2393     render_attributes(w, it, false);
2394     write!(
2395         w,
2396         "{vis}static {mutability}{name}: {typ}</pre>",
2397         vis = it.visibility.print_with_space(),
2398         mutability = s.mutability.print_with_space(),
2399         name = it.name.as_ref().unwrap(),
2400         typ = s.type_.print()
2401     );
2402     document(w, cx, it, None)
2403 }
2404
2405 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2406     let header_len = format!(
2407         "{}{}{}{}{:#}fn {}{:#}",
2408         it.visibility.print_with_space(),
2409         f.header.constness.print_with_space(),
2410         f.header.asyncness.print_with_space(),
2411         f.header.unsafety.print_with_space(),
2412         print_abi_with_space(f.header.abi),
2413         it.name.as_ref().unwrap(),
2414         f.generics.print()
2415     )
2416     .len();
2417     write!(w, "<pre class=\"rust fn\">");
2418     render_attributes(w, it, false);
2419     write!(
2420         w,
2421         "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2422          {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2423         vis = it.visibility.print_with_space(),
2424         constness = f.header.constness.print_with_space(),
2425         asyncness = f.header.asyncness.print_with_space(),
2426         unsafety = f.header.unsafety.print_with_space(),
2427         abi = print_abi_with_space(f.header.abi),
2428         name = it.name.as_ref().unwrap(),
2429         generics = f.generics.print(),
2430         where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2431         decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2432             .print(),
2433         spotlight = spotlight_decl(&f.decl),
2434     );
2435     document(w, cx, it, None)
2436 }
2437
2438 fn render_implementor(
2439     cx: &Context,
2440     implementor: &Impl,
2441     parent: &clean::Item,
2442     w: &mut Buffer,
2443     implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2444     aliases: &[String],
2445     cache: &Cache,
2446 ) {
2447     // If there's already another implementor that has the same abbridged name, use the
2448     // full path, for example in `std::iter::ExactSizeIterator`
2449     let use_absolute = match implementor.inner_impl().for_ {
2450         clean::ResolvedPath { ref path, is_generic: false, .. }
2451         | clean::BorrowedRef {
2452             type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2453             ..
2454         } => implementor_dups[path.last_name()].1,
2455         _ => false,
2456     };
2457     render_impl(
2458         w,
2459         cx,
2460         implementor,
2461         parent,
2462         AssocItemLink::Anchor(None),
2463         RenderMode::Normal,
2464         implementor.impl_item.stable_since().as_deref(),
2465         implementor.impl_item.const_stable_since().as_deref(),
2466         false,
2467         Some(use_absolute),
2468         false,
2469         false,
2470         aliases,
2471         cache,
2472     );
2473 }
2474
2475 fn render_impls(
2476     cx: &Context,
2477     w: &mut Buffer,
2478     traits: &[&&Impl],
2479     containing_item: &clean::Item,
2480     cache: &Cache,
2481 ) {
2482     let mut impls = traits
2483         .iter()
2484         .map(|i| {
2485             let did = i.trait_did().unwrap();
2486             let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2487             let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2488             render_impl(
2489                 &mut buffer,
2490                 cx,
2491                 i,
2492                 containing_item,
2493                 assoc_link,
2494                 RenderMode::Normal,
2495                 containing_item.stable_since().as_deref(),
2496                 containing_item.const_stable_since().as_deref(),
2497                 true,
2498                 None,
2499                 false,
2500                 true,
2501                 &[],
2502                 cache,
2503             );
2504             buffer.into_inner()
2505         })
2506         .collect::<Vec<_>>();
2507     impls.sort();
2508     w.write_str(&impls.join(""));
2509 }
2510
2511 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2512     let mut bounds = String::new();
2513     if !t_bounds.is_empty() {
2514         if !trait_alias {
2515             bounds.push_str(": ");
2516         }
2517         for (i, p) in t_bounds.iter().enumerate() {
2518             if i > 0 {
2519                 bounds.push_str(" + ");
2520             }
2521             bounds.push_str(&p.print().to_string());
2522         }
2523     }
2524     bounds
2525 }
2526
2527 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2528     let lhs = format!("{}", lhs.inner_impl().print());
2529     let rhs = format!("{}", rhs.inner_impl().print());
2530
2531     // lhs and rhs are formatted as HTML, which may be unnecessary
2532     compare_names(&lhs, &rhs)
2533 }
2534
2535 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2536     let bounds = bounds(&t.bounds, false);
2537     let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2538     let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2539     let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2540     let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2541
2542     // Output the trait definition
2543     wrap_into_docblock(w, |w| {
2544         write!(w, "<pre class=\"rust trait\">");
2545         render_attributes(w, it, true);
2546         write!(
2547             w,
2548             "{}{}{}trait {}{}{}",
2549             it.visibility.print_with_space(),
2550             t.unsafety.print_with_space(),
2551             if t.is_auto { "auto " } else { "" },
2552             it.name.as_ref().unwrap(),
2553             t.generics.print(),
2554             bounds
2555         );
2556
2557         if !t.generics.where_predicates.is_empty() {
2558             write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2559         } else {
2560             write!(w, " ");
2561         }
2562
2563         if t.items.is_empty() {
2564             write!(w, "{{ }}");
2565         } else {
2566             // FIXME: we should be using a derived_id for the Anchors here
2567             write!(w, "{{\n");
2568             for t in &types {
2569                 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2570                 write!(w, ";\n");
2571             }
2572             if !types.is_empty() && !consts.is_empty() {
2573                 w.write_str("\n");
2574             }
2575             for t in &consts {
2576                 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2577                 write!(w, ";\n");
2578             }
2579             if !consts.is_empty() && !required.is_empty() {
2580                 w.write_str("\n");
2581             }
2582             for (pos, m) in required.iter().enumerate() {
2583                 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2584                 write!(w, ";\n");
2585
2586                 if pos < required.len() - 1 {
2587                     write!(w, "<div class=\"item-spacer\"></div>");
2588                 }
2589             }
2590             if !required.is_empty() && !provided.is_empty() {
2591                 w.write_str("\n");
2592             }
2593             for (pos, m) in provided.iter().enumerate() {
2594                 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2595                 match m.kind {
2596                     clean::MethodItem(ref inner, _)
2597                         if !inner.generics.where_predicates.is_empty() =>
2598                     {
2599                         write!(w, ",\n    {{ ... }}\n");
2600                     }
2601                     _ => {
2602                         write!(w, " {{ ... }}\n");
2603                     }
2604                 }
2605                 if pos < provided.len() - 1 {
2606                     write!(w, "<div class=\"item-spacer\"></div>");
2607                 }
2608             }
2609             write!(w, "}}");
2610         }
2611         write!(w, "</pre>")
2612     });
2613
2614     // Trait documentation
2615     document(w, cx, it, None);
2616
2617     fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2618         write!(
2619             w,
2620             "<h2 id=\"{0}\" class=\"small-section-header\">\
2621                 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2622              </h2>{2}",
2623             id, title, extra_content
2624         )
2625     }
2626
2627     fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2628         write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2629     }
2630
2631     fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item, cache: &Cache) {
2632         let name = m.name.as_ref().unwrap();
2633         info!("Documenting {} on {:?}", name, t.name);
2634         let item_type = m.type_();
2635         let id = cx.derive_id(format!("{}.{}", item_type, name));
2636         write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2637         render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2638         write!(w, "</code>");
2639         render_stability_since(w, m, t);
2640         write_srclink(cx, m, w, cache);
2641         write!(w, "</h3>");
2642         document(w, cx, m, Some(t));
2643     }
2644
2645     if !types.is_empty() {
2646         write_small_section_header(
2647             w,
2648             "associated-types",
2649             "Associated Types",
2650             "<div class=\"methods\">",
2651         );
2652         for t in types {
2653             trait_item(w, cx, t, it, cache);
2654         }
2655         write_loading_content(w, "</div>");
2656     }
2657
2658     if !consts.is_empty() {
2659         write_small_section_header(
2660             w,
2661             "associated-const",
2662             "Associated Constants",
2663             "<div class=\"methods\">",
2664         );
2665         for t in consts {
2666             trait_item(w, cx, t, it, cache);
2667         }
2668         write_loading_content(w, "</div>");
2669     }
2670
2671     // Output the documentation for each function individually
2672     if !required.is_empty() {
2673         write_small_section_header(
2674             w,
2675             "required-methods",
2676             "Required methods",
2677             "<div class=\"methods\">",
2678         );
2679         for m in required {
2680             trait_item(w, cx, m, it, cache);
2681         }
2682         write_loading_content(w, "</div>");
2683     }
2684     if !provided.is_empty() {
2685         write_small_section_header(
2686             w,
2687             "provided-methods",
2688             "Provided methods",
2689             "<div class=\"methods\">",
2690         );
2691         for m in provided {
2692             trait_item(w, cx, m, it, cache);
2693         }
2694         write_loading_content(w, "</div>");
2695     }
2696
2697     // If there are methods directly on this trait object, render them here.
2698     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2699
2700     if let Some(implementors) = cache.implementors.get(&it.def_id) {
2701         // The DefId is for the first Type found with that name. The bool is
2702         // if any Types with the same name but different DefId have been found.
2703         let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2704         for implementor in implementors {
2705             match implementor.inner_impl().for_ {
2706                 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2707                 | clean::BorrowedRef {
2708                     type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2709                     ..
2710                 } => {
2711                     let &mut (prev_did, ref mut has_duplicates) =
2712                         implementor_dups.entry(path.last_name()).or_insert((did, false));
2713                     if prev_did != did {
2714                         *has_duplicates = true;
2715                     }
2716                 }
2717                 _ => {}
2718             }
2719         }
2720
2721         let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2722             i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2723         });
2724
2725         let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2726             local.iter().partition(|i| i.inner_impl().synthetic);
2727
2728         synthetic.sort_by(compare_impl);
2729         concrete.sort_by(compare_impl);
2730
2731         if !foreign.is_empty() {
2732             write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2733
2734             for implementor in foreign {
2735                 let assoc_link = AssocItemLink::GotoSource(
2736                     implementor.impl_item.def_id,
2737                     &implementor.inner_impl().provided_trait_methods,
2738                 );
2739                 render_impl(
2740                     w,
2741                     cx,
2742                     &implementor,
2743                     it,
2744                     assoc_link,
2745                     RenderMode::Normal,
2746                     implementor.impl_item.stable_since().as_deref(),
2747                     implementor.impl_item.const_stable_since().as_deref(),
2748                     false,
2749                     None,
2750                     true,
2751                     false,
2752                     &[],
2753                     cache,
2754                 );
2755             }
2756             write_loading_content(w, "");
2757         }
2758
2759         write_small_section_header(
2760             w,
2761             "implementors",
2762             "Implementors",
2763             "<div class=\"item-list\" id=\"implementors-list\">",
2764         );
2765         for implementor in concrete {
2766             render_implementor(cx, implementor, it, w, &implementor_dups, &[], cache);
2767         }
2768         write_loading_content(w, "</div>");
2769
2770         if t.is_auto {
2771             write_small_section_header(
2772                 w,
2773                 "synthetic-implementors",
2774                 "Auto implementors",
2775                 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2776             );
2777             for implementor in synthetic {
2778                 render_implementor(
2779                     cx,
2780                     implementor,
2781                     it,
2782                     w,
2783                     &implementor_dups,
2784                     &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2785                     cache,
2786                 );
2787             }
2788             write_loading_content(w, "</div>");
2789         }
2790     } else {
2791         // even without any implementations to write in, we still want the heading and list, so the
2792         // implementors javascript file pulled in below has somewhere to write the impls into
2793         write_small_section_header(
2794             w,
2795             "implementors",
2796             "Implementors",
2797             "<div class=\"item-list\" id=\"implementors-list\">",
2798         );
2799         write_loading_content(w, "</div>");
2800
2801         if t.is_auto {
2802             write_small_section_header(
2803                 w,
2804                 "synthetic-implementors",
2805                 "Auto implementors",
2806                 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2807             );
2808             write_loading_content(w, "</div>");
2809         }
2810     }
2811
2812     write!(
2813         w,
2814         "<script type=\"text/javascript\" \
2815                  src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2816          </script>",
2817         root_path = vec![".."; cx.current.len()].join("/"),
2818         path = if it.def_id.is_local() {
2819             cx.current.join("/")
2820         } else {
2821             let (ref path, _) = cache.external_paths[&it.def_id];
2822             path[..path.len() - 1].join("/")
2823         },
2824         ty = it.type_(),
2825         name = *it.name.as_ref().unwrap()
2826     );
2827 }
2828
2829 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2830     use crate::formats::item_type::ItemType::*;
2831
2832     let name = it.name.as_ref().unwrap();
2833     let ty = match it.type_() {
2834         Typedef | AssocType => AssocType,
2835         s => s,
2836     };
2837
2838     let anchor = format!("#{}.{}", ty, name);
2839     match link {
2840         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2841         AssocItemLink::Anchor(None) => anchor,
2842         AssocItemLink::GotoSource(did, _) => {
2843             href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2844         }
2845     }
2846 }
2847
2848 fn assoc_const(
2849     w: &mut Buffer,
2850     it: &clean::Item,
2851     ty: &clean::Type,
2852     _default: Option<&String>,
2853     link: AssocItemLink<'_>,
2854     extra: &str,
2855 ) {
2856     write!(
2857         w,
2858         "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2859         extra,
2860         it.visibility.print_with_space(),
2861         naive_assoc_href(it, link),
2862         it.name.as_ref().unwrap(),
2863         ty.print()
2864     );
2865 }
2866
2867 fn assoc_type(
2868     w: &mut Buffer,
2869     it: &clean::Item,
2870     bounds: &[clean::GenericBound],
2871     default: Option<&clean::Type>,
2872     link: AssocItemLink<'_>,
2873     extra: &str,
2874 ) {
2875     write!(
2876         w,
2877         "{}type <a href=\"{}\" class=\"type\">{}</a>",
2878         extra,
2879         naive_assoc_href(it, link),
2880         it.name.as_ref().unwrap()
2881     );
2882     if !bounds.is_empty() {
2883         write!(w, ": {}", print_generic_bounds(bounds))
2884     }
2885     if let Some(default) = default {
2886         write!(w, " = {}", default.print())
2887     }
2888 }
2889
2890 fn render_stability_since_raw(
2891     w: &mut Buffer,
2892     ver: Option<&str>,
2893     const_ver: Option<&str>,
2894     containing_ver: Option<&str>,
2895     containing_const_ver: Option<&str>,
2896 ) {
2897     let ver = ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2898
2899     let const_ver = const_ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2900
2901     if let Some(v) = ver {
2902         if let Some(cv) = const_ver {
2903             if const_ver != containing_const_ver {
2904                 write!(
2905                     w,
2906                     "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2907                     v, cv
2908                 );
2909             } else if ver != containing_ver {
2910                 write!(
2911                     w,
2912                     "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2913                     v
2914                 );
2915             }
2916         } else {
2917             if ver != containing_ver {
2918                 write!(
2919                     w,
2920                     "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2921                     v
2922                 );
2923             }
2924         }
2925     }
2926 }
2927
2928 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2929     render_stability_since_raw(
2930         w,
2931         item.stable_since().as_deref(),
2932         item.const_stable_since().as_deref(),
2933         containing_item.stable_since().as_deref(),
2934         containing_item.const_stable_since().as_deref(),
2935     )
2936 }
2937
2938 fn render_assoc_item(
2939     w: &mut Buffer,
2940     item: &clean::Item,
2941     link: AssocItemLink<'_>,
2942     parent: ItemType,
2943 ) {
2944     fn method(
2945         w: &mut Buffer,
2946         meth: &clean::Item,
2947         header: hir::FnHeader,
2948         g: &clean::Generics,
2949         d: &clean::FnDecl,
2950         link: AssocItemLink<'_>,
2951         parent: ItemType,
2952     ) {
2953         let name = meth.name.as_ref().unwrap();
2954         let anchor = format!("#{}.{}", meth.type_(), name);
2955         let href = match link {
2956             AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2957             AssocItemLink::Anchor(None) => anchor,
2958             AssocItemLink::GotoSource(did, provided_methods) => {
2959                 // We're creating a link from an impl-item to the corresponding
2960                 // trait-item and need to map the anchored type accordingly.
2961                 let ty = if provided_methods.contains(&*name.as_str()) {
2962                     ItemType::Method
2963                 } else {
2964                     ItemType::TyMethod
2965                 };
2966
2967                 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2968             }
2969         };
2970         let mut header_len = format!(
2971             "{}{}{}{}{}{:#}fn {}{:#}",
2972             meth.visibility.print_with_space(),
2973             header.constness.print_with_space(),
2974             header.asyncness.print_with_space(),
2975             header.unsafety.print_with_space(),
2976             print_default_space(meth.is_default()),
2977             print_abi_with_space(header.abi),
2978             name,
2979             g.print()
2980         )
2981         .len();
2982         let (indent, end_newline) = if parent == ItemType::Trait {
2983             header_len += 4;
2984             (4, false)
2985         } else {
2986             (0, true)
2987         };
2988         render_attributes(w, meth, false);
2989         write!(
2990             w,
2991             "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
2992              {generics}{decl}{spotlight}{where_clause}",
2993             if parent == ItemType::Trait { "    " } else { "" },
2994             meth.visibility.print_with_space(),
2995             header.constness.print_with_space(),
2996             header.asyncness.print_with_space(),
2997             header.unsafety.print_with_space(),
2998             print_default_space(meth.is_default()),
2999             print_abi_with_space(header.abi),
3000             href = href,
3001             name = name,
3002             generics = g.print(),
3003             decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
3004             spotlight = spotlight_decl(&d),
3005             where_clause = WhereClause { gens: g, indent, end_newline }
3006         )
3007     }
3008     match item.kind {
3009         clean::StrippedItem(..) => {}
3010         clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
3011         clean::MethodItem(ref m, _) => {
3012             method(w, item, m.header, &m.generics, &m.decl, link, parent)
3013         }
3014         clean::AssocConstItem(ref ty, ref default) => assoc_const(
3015             w,
3016             item,
3017             ty,
3018             default.as_ref(),
3019             link,
3020             if parent == ItemType::Trait { "    " } else { "" },
3021         ),
3022         clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3023             w,
3024             item,
3025             bounds,
3026             default.as_ref(),
3027             link,
3028             if parent == ItemType::Trait { "    " } else { "" },
3029         ),
3030         _ => panic!("render_assoc_item called on non-associated-item"),
3031     }
3032 }
3033
3034 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
3035     wrap_into_docblock(w, |w| {
3036         write!(w, "<pre class=\"rust struct\">");
3037         render_attributes(w, it, true);
3038         render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
3039         write!(w, "</pre>")
3040     });
3041
3042     document(w, cx, it, None);
3043     let mut fields = s
3044         .fields
3045         .iter()
3046         .filter_map(|f| match f.kind {
3047             clean::StructFieldItem(ref ty) => Some((f, ty)),
3048             _ => None,
3049         })
3050         .peekable();
3051     if let doctree::Plain = s.struct_type {
3052         if fields.peek().is_some() {
3053             write!(
3054                 w,
3055                 "<h2 id=\"fields\" class=\"fields small-section-header\">
3056                        Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3057                 document_non_exhaustive_header(it)
3058             );
3059             document_non_exhaustive(w, it);
3060             for (field, ty) in fields {
3061                 let id = cx.derive_id(format!(
3062                     "{}.{}",
3063                     ItemType::StructField,
3064                     field.name.as_ref().unwrap()
3065                 ));
3066                 write!(
3067                     w,
3068                     "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3069                          <a href=\"#{id}\" class=\"anchor field\"></a>\
3070                          <code>{name}: {ty}</code>\
3071                      </span>",
3072                     item_type = ItemType::StructField,
3073                     id = id,
3074                     name = field.name.as_ref().unwrap(),
3075                     ty = ty.print()
3076                 );
3077                 document(w, cx, field, Some(it));
3078             }
3079         }
3080     }
3081     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3082 }
3083
3084 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
3085     wrap_into_docblock(w, |w| {
3086         write!(w, "<pre class=\"rust union\">");
3087         render_attributes(w, it, true);
3088         render_union(w, it, Some(&s.generics), &s.fields, "", true);
3089         write!(w, "</pre>")
3090     });
3091
3092     document(w, cx, it, None);
3093     let mut fields = s
3094         .fields
3095         .iter()
3096         .filter_map(|f| match f.kind {
3097             clean::StructFieldItem(ref ty) => Some((f, ty)),
3098             _ => None,
3099         })
3100         .peekable();
3101     if fields.peek().is_some() {
3102         write!(
3103             w,
3104             "<h2 id=\"fields\" class=\"fields small-section-header\">
3105                    Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3106         );
3107         for (field, ty) in fields {
3108             let name = field.name.as_ref().expect("union field name");
3109             let id = format!("{}.{}", ItemType::StructField, name);
3110             write!(
3111                 w,
3112                 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3113                      <a href=\"#{id}\" class=\"anchor field\"></a>\
3114                      <code>{name}: {ty}</code>\
3115                  </span>",
3116                 id = id,
3117                 name = name,
3118                 shortty = ItemType::StructField,
3119                 ty = ty.print()
3120             );
3121             if let Some(stability_class) = field.stability_class() {
3122                 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3123             }
3124             document(w, cx, field, Some(it));
3125         }
3126     }
3127     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3128 }
3129
3130 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
3131     wrap_into_docblock(w, |w| {
3132         write!(w, "<pre class=\"rust enum\">");
3133         render_attributes(w, it, true);
3134         write!(
3135             w,
3136             "{}enum {}{}{}",
3137             it.visibility.print_with_space(),
3138             it.name.as_ref().unwrap(),
3139             e.generics.print(),
3140             WhereClause { gens: &e.generics, indent: 0, end_newline: true }
3141         );
3142         if e.variants.is_empty() && !e.variants_stripped {
3143             write!(w, " {{}}");
3144         } else {
3145             write!(w, " {{\n");
3146             for v in &e.variants {
3147                 write!(w, "    ");
3148                 let name = v.name.as_ref().unwrap();
3149                 match v.kind {
3150                     clean::VariantItem(ref var) => match var.kind {
3151                         clean::VariantKind::CLike => write!(w, "{}", name),
3152                         clean::VariantKind::Tuple(ref tys) => {
3153                             write!(w, "{}(", name);
3154                             for (i, ty) in tys.iter().enumerate() {
3155                                 if i > 0 {
3156                                     write!(w, ",&nbsp;")
3157                                 }
3158                                 write!(w, "{}", ty.print());
3159                             }
3160                             write!(w, ")");
3161                         }
3162                         clean::VariantKind::Struct(ref s) => {
3163                             render_struct(w, v, None, s.struct_type, &s.fields, "    ", false);
3164                         }
3165                     },
3166                     _ => unreachable!(),
3167                 }
3168                 write!(w, ",\n");
3169             }
3170
3171             if e.variants_stripped {
3172                 write!(w, "    // some variants omitted\n");
3173             }
3174             write!(w, "}}");
3175         }
3176         write!(w, "</pre>")
3177     });
3178
3179     document(w, cx, it, None);
3180     if !e.variants.is_empty() {
3181         write!(
3182             w,
3183             "<h2 id=\"variants\" class=\"variants small-section-header\">
3184                    Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3185             document_non_exhaustive_header(it)
3186         );
3187         document_non_exhaustive(w, it);
3188         for variant in &e.variants {
3189             let id =
3190                 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3191             write!(
3192                 w,
3193                 "<div id=\"{id}\" class=\"variant small-section-header\">\
3194                     <a href=\"#{id}\" class=\"anchor field\"></a>\
3195                     <code>{name}",
3196                 id = id,
3197                 name = variant.name.as_ref().unwrap()
3198             );
3199             if let clean::VariantItem(ref var) = variant.kind {
3200                 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3201                     write!(w, "(");
3202                     for (i, ty) in tys.iter().enumerate() {
3203                         if i > 0 {
3204                             write!(w, ",&nbsp;");
3205                         }
3206                         write!(w, "{}", ty.print());
3207                     }
3208                     write!(w, ")");
3209                 }
3210             }
3211             write!(w, "</code></div>");
3212             document(w, cx, variant, Some(it));
3213             document_non_exhaustive(w, variant);
3214
3215             use crate::clean::{Variant, VariantKind};
3216             if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.kind {
3217                 let variant_id = cx.derive_id(format!(
3218                     "{}.{}.fields",
3219                     ItemType::Variant,
3220                     variant.name.as_ref().unwrap()
3221                 ));
3222                 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3223                 write!(
3224                     w,
3225                     "<h3>Fields of <b>{name}</b></h3><div>",
3226                     name = variant.name.as_ref().unwrap()
3227                 );
3228                 for field in &s.fields {
3229                     use crate::clean::StructFieldItem;
3230                     if let StructFieldItem(ref ty) = field.kind {
3231                         let id = cx.derive_id(format!(
3232                             "variant.{}.field.{}",
3233                             variant.name.as_ref().unwrap(),
3234                             field.name.as_ref().unwrap()
3235                         ));
3236                         write!(
3237                             w,
3238                             "<span id=\"{id}\" class=\"variant small-section-header\">\
3239                                  <a href=\"#{id}\" class=\"anchor field\"></a>\
3240                                  <code>{f}:&nbsp;{t}</code>\
3241                              </span>",
3242                             id = id,
3243                             f = field.name.as_ref().unwrap(),
3244                             t = ty.print()
3245                         );
3246                         document(w, cx, field, Some(variant));
3247                     }
3248                 }
3249                 write!(w, "</div></div>");
3250             }
3251             render_stability_since(w, variant, it);
3252         }
3253     }
3254     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3255 }
3256
3257 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3258     sym::export_name,
3259     sym::lang,
3260     sym::link_section,
3261     sym::must_use,
3262     sym::no_mangle,
3263     sym::repr,
3264     sym::non_exhaustive,
3265 ];
3266
3267 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3268 // left padding. For example:
3269 //
3270 // #[foo] <----- "top" attribute
3271 // struct Foo {
3272 //     #[bar] <---- not "top" attribute
3273 //     bar: usize,
3274 // }
3275 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3276     let attrs = it
3277         .attrs
3278         .other_attrs
3279         .iter()
3280         .filter_map(|attr| {
3281             if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3282                 Some(pprust::attribute_to_string(&attr))
3283             } else {
3284                 None
3285             }
3286         })
3287         .join("\n");
3288
3289     if !attrs.is_empty() {
3290         write!(
3291             w,
3292             "<span class=\"docblock attributes{}\">{}</span>",
3293             if top { " top-attr" } else { "" },
3294             &attrs
3295         );
3296     }
3297 }
3298
3299 fn render_struct(
3300     w: &mut Buffer,
3301     it: &clean::Item,
3302     g: Option<&clean::Generics>,
3303     ty: doctree::StructType,
3304     fields: &[clean::Item],
3305     tab: &str,
3306     structhead: bool,
3307 ) {
3308     write!(
3309         w,
3310         "{}{}{}",
3311         it.visibility.print_with_space(),
3312         if structhead { "struct " } else { "" },
3313         it.name.as_ref().unwrap()
3314     );
3315     if let Some(g) = g {
3316         write!(w, "{}", g.print())
3317     }
3318     match ty {
3319         doctree::Plain => {
3320             if let Some(g) = g {
3321                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3322             }
3323             let mut has_visible_fields = false;
3324             write!(w, " {{");
3325             for field in fields {
3326                 if let clean::StructFieldItem(ref ty) = field.kind {
3327                     write!(
3328                         w,
3329                         "\n{}    {}{}: {},",
3330                         tab,
3331                         field.visibility.print_with_space(),
3332                         field.name.as_ref().unwrap(),
3333                         ty.print()
3334                     );
3335                     has_visible_fields = true;
3336                 }
3337             }
3338
3339             if has_visible_fields {
3340                 if it.has_stripped_fields().unwrap() {
3341                     write!(w, "\n{}    // some fields omitted", tab);
3342                 }
3343                 write!(w, "\n{}", tab);
3344             } else if it.has_stripped_fields().unwrap() {
3345                 // If there are no visible fields we can just display
3346                 // `{ /* fields omitted */ }` to save space.
3347                 write!(w, " /* fields omitted */ ");
3348             }
3349             write!(w, "}}");
3350         }
3351         doctree::Tuple => {
3352             write!(w, "(");
3353             for (i, field) in fields.iter().enumerate() {
3354                 if i > 0 {
3355                     write!(w, ", ");
3356                 }
3357                 match field.kind {
3358                     clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3359                     clean::StructFieldItem(ref ty) => {
3360                         write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3361                     }
3362                     _ => unreachable!(),
3363                 }
3364             }
3365             write!(w, ")");
3366             if let Some(g) = g {
3367                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3368             }
3369             write!(w, ";");
3370         }
3371         doctree::Unit => {
3372             // Needed for PhantomData.
3373             if let Some(g) = g {
3374                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3375             }
3376             write!(w, ";");
3377         }
3378     }
3379 }
3380
3381 fn render_union(
3382     w: &mut Buffer,
3383     it: &clean::Item,
3384     g: Option<&clean::Generics>,
3385     fields: &[clean::Item],
3386     tab: &str,
3387     structhead: bool,
3388 ) {
3389     write!(
3390         w,
3391         "{}{}{}",
3392         it.visibility.print_with_space(),
3393         if structhead { "union " } else { "" },
3394         it.name.as_ref().unwrap()
3395     );
3396     if let Some(g) = g {
3397         write!(w, "{}", g.print());
3398         write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3399     }
3400
3401     write!(w, " {{\n{}", tab);
3402     for field in fields {
3403         if let clean::StructFieldItem(ref ty) = field.kind {
3404             write!(
3405                 w,
3406                 "    {}{}: {},\n{}",
3407                 field.visibility.print_with_space(),
3408                 field.name.as_ref().unwrap(),
3409                 ty.print(),
3410                 tab
3411             );
3412         }
3413     }
3414
3415     if it.has_stripped_fields().unwrap() {
3416         write!(w, "    // some fields omitted\n{}", tab);
3417     }
3418     write!(w, "}}");
3419 }
3420
3421 #[derive(Copy, Clone)]
3422 enum AssocItemLink<'a> {
3423     Anchor(Option<&'a str>),
3424     GotoSource(DefId, &'a FxHashSet<String>),
3425 }
3426
3427 impl<'a> AssocItemLink<'a> {
3428     fn anchor(&self, id: &'a String) -> Self {
3429         match *self {
3430             AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3431             ref other => *other,
3432         }
3433     }
3434 }
3435
3436 fn render_assoc_items(
3437     w: &mut Buffer,
3438     cx: &Context,
3439     containing_item: &clean::Item,
3440     it: DefId,
3441     what: AssocItemRender<'_>,
3442     cache: &Cache,
3443 ) {
3444     info!("Documenting associated items of {:?}", containing_item.name);
3445     let v = match cache.impls.get(&it) {
3446         Some(v) => v,
3447         None => return,
3448     };
3449     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3450     if !non_trait.is_empty() {
3451         let render_mode = match what {
3452             AssocItemRender::All => {
3453                 write!(
3454                     w,
3455                     "<h2 id=\"implementations\" class=\"small-section-header\">\
3456                          Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3457                     </h2>"
3458                 );
3459                 RenderMode::Normal
3460             }
3461             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3462                 write!(
3463                     w,
3464                     "<h2 id=\"deref-methods\" class=\"small-section-header\">\
3465                          Methods from {}&lt;Target = {}&gt;\
3466                          <a href=\"#deref-methods\" class=\"anchor\"></a>\
3467                      </h2>",
3468                     trait_.print(),
3469                     type_.print()
3470                 );
3471                 RenderMode::ForDeref { mut_: deref_mut_ }
3472             }
3473         };
3474         for i in &non_trait {
3475             render_impl(
3476                 w,
3477                 cx,
3478                 i,
3479                 containing_item,
3480                 AssocItemLink::Anchor(None),
3481                 render_mode,
3482                 containing_item.stable_since().as_deref(),
3483                 containing_item.const_stable_since().as_deref(),
3484                 true,
3485                 None,
3486                 false,
3487                 true,
3488                 &[],
3489                 cache,
3490             );
3491         }
3492     }
3493     if let AssocItemRender::DerefFor { .. } = what {
3494         return;
3495     }
3496     if !traits.is_empty() {
3497         let deref_impl =
3498             traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3499         if let Some(impl_) = deref_impl {
3500             let has_deref_mut =
3501                 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3502             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3503         }
3504
3505         let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3506             traits.iter().partition(|t| t.inner_impl().synthetic);
3507         let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3508             concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3509
3510         let mut impls = Buffer::empty_from(&w);
3511         render_impls(cx, &mut impls, &concrete, containing_item, cache);
3512         let impls = impls.into_inner();
3513         if !impls.is_empty() {
3514             write!(
3515                 w,
3516                 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3517                      Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3518                  </h2>\
3519                  <div id=\"trait-implementations-list\">{}</div>",
3520                 impls
3521             );
3522         }
3523
3524         if !synthetic.is_empty() {
3525             write!(
3526                 w,
3527                 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3528                      Auto Trait Implementations\
3529                      <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3530                  </h2>\
3531                  <div id=\"synthetic-implementations-list\">"
3532             );
3533             render_impls(cx, w, &synthetic, containing_item, cache);
3534             write!(w, "</div>");
3535         }
3536
3537         if !blanket_impl.is_empty() {
3538             write!(
3539                 w,
3540                 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3541                      Blanket Implementations\
3542                      <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3543                  </h2>\
3544                  <div id=\"blanket-implementations-list\">"
3545             );
3546             render_impls(cx, w, &blanket_impl, containing_item, cache);
3547             write!(w, "</div>");
3548         }
3549     }
3550 }
3551
3552 fn render_deref_methods(
3553     w: &mut Buffer,
3554     cx: &Context,
3555     impl_: &Impl,
3556     container_item: &clean::Item,
3557     deref_mut: bool,
3558     cache: &Cache,
3559 ) {
3560     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3561     let (target, real_target) = impl_
3562         .inner_impl()
3563         .items
3564         .iter()
3565         .find_map(|item| match item.kind {
3566             clean::TypedefItem(ref t, true) => Some(match *t {
3567                 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3568                 _ => (&t.type_, &t.type_),
3569             }),
3570             _ => None,
3571         })
3572         .expect("Expected associated type binding");
3573     let what =
3574         AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3575     if let Some(did) = target.def_id() {
3576         render_assoc_items(w, cx, container_item, did, what, cache);
3577     } else {
3578         if let Some(prim) = target.primitive_type() {
3579             if let Some(&did) = cache.primitive_locations.get(&prim) {
3580                 render_assoc_items(w, cx, container_item, did, what, cache);
3581             }
3582         }
3583     }
3584 }
3585
3586 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3587     let self_type_opt = match item.kind {
3588         clean::MethodItem(ref method, _) => method.decl.self_type(),
3589         clean::TyMethodItem(ref method) => method.decl.self_type(),
3590         _ => None,
3591     };
3592
3593     if let Some(self_ty) = self_type_opt {
3594         let (by_mut_ref, by_box, by_value) = match self_ty {
3595             SelfTy::SelfBorrowed(_, mutability)
3596             | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3597                 (mutability == Mutability::Mut, false, false)
3598             }
3599             SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3600                 (false, Some(did) == cache().owned_box_did, false)
3601             }
3602             SelfTy::SelfValue => (false, false, true),
3603             _ => (false, false, false),
3604         };
3605
3606         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3607     } else {
3608         false
3609     }
3610 }
3611
3612 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3613     let mut out = Buffer::html();
3614     let mut trait_ = String::new();
3615
3616     if let Some(did) = decl.output.def_id() {
3617         let c = cache();
3618         if let Some(impls) = c.impls.get(&did) {
3619             for i in impls {
3620                 let impl_ = i.inner_impl();
3621                 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3622                     if out.is_empty() {
3623                         out.push_str(&format!(
3624                             "<h3 class=\"notable\">Notable traits for {}</h3>\
3625                              <code class=\"content\">",
3626                             impl_.for_.print()
3627                         ));
3628                         trait_.push_str(&impl_.for_.print().to_string());
3629                     }
3630
3631                     //use the "where" class here to make it small
3632                     out.push_str(&format!(
3633                         "<span class=\"where fmt-newline\">{}</span>",
3634                         impl_.print()
3635                     ));
3636                     let t_did = impl_.trait_.def_id().unwrap();
3637                     for it in &impl_.items {
3638                         if let clean::TypedefItem(ref tydef, _) = it.kind {
3639                             out.push_str("<span class=\"where fmt-newline\">    ");
3640                             assoc_type(
3641                                 &mut out,
3642                                 it,
3643                                 &[],
3644                                 Some(&tydef.type_),
3645                                 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3646                                 "",
3647                             );
3648                             out.push_str(";</span>");
3649                         }
3650                     }
3651                 }
3652             }
3653         }
3654     }
3655
3656     if !out.is_empty() {
3657         out.insert_str(
3658             0,
3659             "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3660             <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3661         );
3662         out.push_str("</code></span></div></span></span>");
3663     }
3664
3665     out.into_inner()
3666 }
3667
3668 fn render_impl(
3669     w: &mut Buffer,
3670     cx: &Context,
3671     i: &Impl,
3672     parent: &clean::Item,
3673     link: AssocItemLink<'_>,
3674     render_mode: RenderMode,
3675     outer_version: Option<&str>,
3676     outer_const_version: Option<&str>,
3677     show_def_docs: bool,
3678     use_absolute: Option<bool>,
3679     is_on_foreign_type: bool,
3680     show_default_items: bool,
3681     // This argument is used to reference same type with different paths to avoid duplication
3682     // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3683     aliases: &[String],
3684     cache: &Cache,
3685 ) {
3686     let traits = &cache.traits;
3687     let trait_ = i.trait_did().map(|did| &traits[&did]);
3688
3689     if render_mode == RenderMode::Normal {
3690         let id = cx.derive_id(match i.inner_impl().trait_ {
3691             Some(ref t) => {
3692                 if is_on_foreign_type {
3693                     get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3694                 } else {
3695                     format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3696                 }
3697             }
3698             None => "impl".to_string(),
3699         });
3700         let aliases = if aliases.is_empty() {
3701             String::new()
3702         } else {
3703             format!(" aliases=\"{}\"", aliases.join(","))
3704         };
3705         if let Some(use_absolute) = use_absolute {
3706             write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3707             fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3708             if show_def_docs {
3709                 for it in &i.inner_impl().items {
3710                     if let clean::TypedefItem(ref tydef, _) = it.kind {
3711                         write!(w, "<span class=\"where fmt-newline\">  ");
3712                         assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3713                         write!(w, ";</span>");
3714                     }
3715                 }
3716             }
3717             write!(w, "</code>");
3718         } else {
3719             write!(
3720                 w,
3721                 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3722                 id,
3723                 aliases,
3724                 i.inner_impl().print()
3725             );
3726         }
3727         write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3728         render_stability_since_raw(
3729             w,
3730             i.impl_item.stable_since().as_deref(),
3731             i.impl_item.const_stable_since().as_deref(),
3732             outer_version,
3733             outer_const_version,
3734         );
3735         write_srclink(cx, &i.impl_item, w, cache);
3736         write!(w, "</h3>");
3737
3738         if trait_.is_some() {
3739             if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3740                 write!(w, "<div class=\"item-info\">{}</div>", portability);
3741             }
3742         }
3743
3744         if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3745             let mut ids = cx.id_map.borrow_mut();
3746             write!(
3747                 w,
3748                 "<div class=\"docblock\">{}</div>",
3749                 Markdown(
3750                     &*dox,
3751                     &i.impl_item.links(),
3752                     &mut ids,
3753                     cx.shared.codes,
3754                     cx.shared.edition,
3755                     &cx.shared.playground
3756                 )
3757                 .into_string()
3758             );
3759         }
3760     }
3761
3762     fn doc_impl_item(
3763         w: &mut Buffer,
3764         cx: &Context,
3765         item: &clean::Item,
3766         parent: &clean::Item,
3767         link: AssocItemLink<'_>,
3768         render_mode: RenderMode,
3769         is_default_item: bool,
3770         outer_version: Option<&str>,
3771         outer_const_version: Option<&str>,
3772         trait_: Option<&clean::Trait>,
3773         show_def_docs: bool,
3774         cache: &Cache,
3775     ) {
3776         let item_type = item.type_();
3777         let name = item.name.as_ref().unwrap();
3778
3779         let render_method_item = match render_mode {
3780             RenderMode::Normal => true,
3781             RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3782         };
3783
3784         let (is_hidden, extra_class) =
3785             if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3786                 && !is_default_item
3787             {
3788                 (false, "")
3789             } else {
3790                 (true, " hidden")
3791             };
3792         match item.kind {
3793             clean::MethodItem(..) | clean::TyMethodItem(_) => {
3794                 // Only render when the method is not static or we allow static methods
3795                 if render_method_item {
3796                     let id = cx.derive_id(format!("{}.{}", item_type, name));
3797                     write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3798                     write!(w, "<code>");
3799                     render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3800                     write!(w, "</code>");
3801                     render_stability_since_raw(
3802                         w,
3803                         item.stable_since().as_deref(),
3804                         item.const_stable_since().as_deref(),
3805                         outer_version,
3806                         outer_const_version,
3807                     );
3808                     write_srclink(cx, item, w, cache);
3809                     write!(w, "</h4>");
3810                 }
3811             }
3812             clean::TypedefItem(ref tydef, _) => {
3813                 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3814                 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3815                 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3816                 write!(w, "</code></h4>");
3817             }
3818             clean::AssocConstItem(ref ty, ref default) => {
3819                 let id = cx.derive_id(format!("{}.{}", item_type, name));
3820                 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3821                 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3822                 write!(w, "</code>");
3823                 render_stability_since_raw(
3824                     w,
3825                     item.stable_since().as_deref(),
3826                     item.const_stable_since().as_deref(),
3827                     outer_version,
3828                     outer_const_version,
3829                 );
3830                 write_srclink(cx, item, w, cache);
3831                 write!(w, "</h4>");
3832             }
3833             clean::AssocTypeItem(ref bounds, ref default) => {
3834                 let id = cx.derive_id(format!("{}.{}", item_type, name));
3835                 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3836                 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3837                 write!(w, "</code></h4>");
3838             }
3839             clean::StrippedItem(..) => return,
3840             _ => panic!("can't make docs for trait item with name {:?}", item.name),
3841         }
3842
3843         if render_method_item {
3844             if !is_default_item {
3845                 if let Some(t) = trait_ {
3846                     // The trait item may have been stripped so we might not
3847                     // find any documentation or stability for it.
3848                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3849                         // We need the stability of the item from the trait
3850                         // because impls can't have a stability.
3851                         if item.doc_value().is_some() {
3852                             document_item_info(w, cx, it, is_hidden, Some(parent));
3853                             document_full(w, item, cx, "", is_hidden);
3854                         } else {
3855                             // In case the item isn't documented,
3856                             // provide short documentation from the trait.
3857                             document_short(
3858                                 w,
3859                                 it,
3860                                 cx,
3861                                 link,
3862                                 "",
3863                                 is_hidden,
3864                                 Some(parent),
3865                                 show_def_docs,
3866                             );
3867                         }
3868                     }
3869                 } else {
3870                     document_item_info(w, cx, item, is_hidden, Some(parent));
3871                     if show_def_docs {
3872                         document_full(w, item, cx, "", is_hidden);
3873                     }
3874                 }
3875             } else {
3876                 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3877             }
3878         }
3879     }
3880
3881     write!(w, "<div class=\"impl-items\">");
3882     for trait_item in &i.inner_impl().items {
3883         doc_impl_item(
3884             w,
3885             cx,
3886             trait_item,
3887             if trait_.is_some() { &i.impl_item } else { parent },
3888             link,
3889             render_mode,
3890             false,
3891             outer_version,
3892             outer_const_version,
3893             trait_,
3894             show_def_docs,
3895             cache,
3896         );
3897     }
3898
3899     fn render_default_items(
3900         w: &mut Buffer,
3901         cx: &Context,
3902         t: &clean::Trait,
3903         i: &clean::Impl,
3904         parent: &clean::Item,
3905         render_mode: RenderMode,
3906         outer_version: Option<&str>,
3907         outer_const_version: Option<&str>,
3908         show_def_docs: bool,
3909         cache: &Cache,
3910     ) {
3911         for trait_item in &t.items {
3912             let n = trait_item.name.clone();
3913             if i.items.iter().any(|m| m.name == n) {
3914                 continue;
3915             }
3916             let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3917             let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3918
3919             doc_impl_item(
3920                 w,
3921                 cx,
3922                 trait_item,
3923                 parent,
3924                 assoc_link,
3925                 render_mode,
3926                 true,
3927                 outer_version,
3928                 outer_const_version,
3929                 None,
3930                 show_def_docs,
3931                 cache,
3932             );
3933         }
3934     }
3935
3936     // If we've implemented a trait, then also emit documentation for all
3937     // default items which weren't overridden in the implementation block.
3938     // We don't emit documentation for default items if they appear in the
3939     // Implementations on Foreign Types or Implementors sections.
3940     if show_default_items {
3941         if let Some(t) = trait_ {
3942             render_default_items(
3943                 w,
3944                 cx,
3945                 t,
3946                 &i.inner_impl(),
3947                 &i.impl_item,
3948                 render_mode,
3949                 outer_version,
3950                 outer_const_version,
3951                 show_def_docs,
3952                 cache,
3953             );
3954         }
3955     }
3956     write!(w, "</div>");
3957 }
3958
3959 fn item_opaque_ty(
3960     w: &mut Buffer,
3961     cx: &Context,
3962     it: &clean::Item,
3963     t: &clean::OpaqueTy,
3964     cache: &Cache,
3965 ) {
3966     write!(w, "<pre class=\"rust opaque\">");
3967     render_attributes(w, it, false);
3968     write!(
3969         w,
3970         "type {}{}{where_clause} = impl {bounds};</pre>",
3971         it.name.as_ref().unwrap(),
3972         t.generics.print(),
3973         where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3974         bounds = bounds(&t.bounds, false)
3975     );
3976
3977     document(w, cx, it, None);
3978
3979     // Render any items associated directly to this alias, as otherwise they
3980     // won't be visible anywhere in the docs. It would be nice to also show
3981     // associated items from the aliased type (see discussion in #32077), but
3982     // we need #14072 to make sense of the generics.
3983     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3984 }
3985
3986 fn item_trait_alias(
3987     w: &mut Buffer,
3988     cx: &Context,
3989     it: &clean::Item,
3990     t: &clean::TraitAlias,
3991     cache: &Cache,
3992 ) {
3993     write!(w, "<pre class=\"rust trait-alias\">");
3994     render_attributes(w, it, false);
3995     write!(
3996         w,
3997         "trait {}{}{} = {};</pre>",
3998         it.name.as_ref().unwrap(),
3999         t.generics.print(),
4000         WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4001         bounds(&t.bounds, true)
4002     );
4003
4004     document(w, cx, it, None);
4005
4006     // Render any items associated directly to this alias, as otherwise they
4007     // won't be visible anywhere in the docs. It would be nice to also show
4008     // associated items from the aliased type (see discussion in #32077), but
4009     // we need #14072 to make sense of the generics.
4010     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4011 }
4012
4013 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
4014     write!(w, "<pre class=\"rust typedef\">");
4015     render_attributes(w, it, false);
4016     write!(
4017         w,
4018         "type {}{}{where_clause} = {type_};</pre>",
4019         it.name.as_ref().unwrap(),
4020         t.generics.print(),
4021         where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4022         type_ = t.type_.print()
4023     );
4024
4025     document(w, cx, it, None);
4026
4027     // Render any items associated directly to this alias, as otherwise they
4028     // won't be visible anywhere in the docs. It would be nice to also show
4029     // associated items from the aliased type (see discussion in #32077), but
4030     // we need #14072 to make sense of the generics.
4031     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4032 }
4033
4034 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4035     writeln!(w, "<pre class=\"rust foreigntype\">extern {{");
4036     render_attributes(w, it, false);
4037     write!(
4038         w,
4039         "    {}type {};\n}}</pre>",
4040         it.visibility.print_with_space(),
4041         it.name.as_ref().unwrap(),
4042     );
4043
4044     document(w, cx, it, None);
4045
4046     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4047 }
4048
4049 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
4050     let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4051
4052     if it.is_struct()
4053         || it.is_trait()
4054         || it.is_primitive()
4055         || it.is_union()
4056         || it.is_enum()
4057         || it.is_mod()
4058         || it.is_typedef()
4059     {
4060         write!(
4061             buffer,
4062             "<p class=\"location\">{}{}</p>",
4063             match it.kind {
4064                 clean::StructItem(..) => "Struct ",
4065                 clean::TraitItem(..) => "Trait ",
4066                 clean::PrimitiveItem(..) => "Primitive Type ",
4067                 clean::UnionItem(..) => "Union ",
4068                 clean::EnumItem(..) => "Enum ",
4069                 clean::TypedefItem(..) => "Type Definition ",
4070                 clean::ForeignTypeItem => "Foreign Type ",
4071                 clean::ModuleItem(..) =>
4072                     if it.is_crate() {
4073                         "Crate "
4074                     } else {
4075                         "Module "
4076                     },
4077                 _ => "",
4078             },
4079             it.name.as_ref().unwrap()
4080         );
4081     }
4082
4083     if it.is_crate() {
4084         if let Some(ref version) = cache.crate_version {
4085             write!(
4086                 buffer,
4087                 "<div class=\"block version\">\
4088                      <p>Version {}</p>\
4089                  </div>",
4090                 Escape(version)
4091             );
4092         }
4093     }
4094
4095     write!(buffer, "<div class=\"sidebar-elems\">");
4096     if it.is_crate() {
4097         write!(
4098             buffer,
4099             "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4100             it.name.as_ref().expect("crates always have a name")
4101         );
4102     }
4103     match it.kind {
4104         clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
4105         clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
4106         clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
4107         clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
4108         clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
4109         clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
4110         clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4111         clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
4112         _ => (),
4113     }
4114
4115     // The sidebar is designed to display sibling functions, modules and
4116     // other miscellaneous information. since there are lots of sibling
4117     // items (and that causes quadratic growth in large modules),
4118     // we refactor common parts into a shared JavaScript file per module.
4119     // still, we don't move everything into JS because we want to preserve
4120     // as much HTML as possible in order to allow non-JS-enabled browsers
4121     // to navigate the documentation (though slightly inefficiently).
4122
4123     write!(buffer, "<p class=\"location\">");
4124     for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4125         if i > 0 {
4126             write!(buffer, "::<wbr>");
4127         }
4128         write!(
4129             buffer,
4130             "<a href=\"{}index.html\">{}</a>",
4131             &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4132             *name
4133         );
4134     }
4135     write!(buffer, "</p>");
4136
4137     // Sidebar refers to the enclosing module, not this module.
4138     let relpath = if it.is_mod() { "../" } else { "" };
4139     write!(
4140         buffer,
4141         "<script>window.sidebarCurrent = {{\
4142                 name: \"{name}\", \
4143                 ty: \"{ty}\", \
4144                 relpath: \"{path}\"\
4145             }};</script>",
4146         name = it.name.unwrap_or(kw::Invalid),
4147         ty = it.type_(),
4148         path = relpath
4149     );
4150     if parentlen == 0 {
4151         // There is no sidebar-items.js beyond the crate root path
4152         // FIXME maybe dynamic crate loading can be merged here
4153     } else {
4154         write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4155     }
4156     // Closes sidebar-elems div.
4157     write!(buffer, "</div>");
4158 }
4159
4160 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4161     if used_links.insert(url.clone()) {
4162         return url;
4163     }
4164     let mut add = 1;
4165     while !used_links.insert(format!("{}-{}", url, add)) {
4166         add += 1;
4167     }
4168     format!("{}-{}", url, add)
4169 }
4170
4171 fn get_methods(
4172     i: &clean::Impl,
4173     for_deref: bool,
4174     used_links: &mut FxHashSet<String>,
4175     deref_mut: bool,
4176 ) -> Vec<String> {
4177     i.items
4178         .iter()
4179         .filter_map(|item| match item.name {
4180             Some(ref name) if !name.is_empty() && item.is_method() => {
4181                 if !for_deref || should_render_item(item, deref_mut) {
4182                     Some(format!(
4183                         "<a href=\"#{}\">{}</a>",
4184                         get_next_url(used_links, format!("method.{}", name)),
4185                         name
4186                     ))
4187                 } else {
4188                     None
4189                 }
4190             }
4191             _ => None,
4192         })
4193         .collect::<Vec<_>>()
4194 }
4195
4196 // The point is to url encode any potential character from a type with genericity.
4197 fn small_url_encode(s: &str) -> String {
4198     s.replace("<", "%3C")
4199         .replace(">", "%3E")
4200         .replace(" ", "%20")
4201         .replace("?", "%3F")
4202         .replace("'", "%27")
4203         .replace("&", "%26")
4204         .replace(",", "%2C")
4205         .replace(":", "%3A")
4206         .replace(";", "%3B")
4207         .replace("[", "%5B")
4208         .replace("]", "%5D")
4209         .replace("\"", "%22")
4210 }
4211
4212 fn sidebar_assoc_items(it: &clean::Item) -> String {
4213     let mut out = String::new();
4214     let c = cache();
4215     if let Some(v) = c.impls.get(&it.def_id) {
4216         let mut used_links = FxHashSet::default();
4217
4218         {
4219             let used_links_bor = &mut used_links;
4220             let mut ret = v
4221                 .iter()
4222                 .filter(|i| i.inner_impl().trait_.is_none())
4223                 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4224                 .collect::<Vec<_>>();
4225             if !ret.is_empty() {
4226                 // We want links' order to be reproducible so we don't use unstable sort.
4227                 ret.sort();
4228                 out.push_str(&format!(
4229                     "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4230                      <div class=\"sidebar-links\">{}</div>",
4231                     ret.join("")
4232                 ));
4233             }
4234         }
4235
4236         if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4237             if let Some(impl_) = v
4238                 .iter()
4239                 .filter(|i| i.inner_impl().trait_.is_some())
4240                 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4241             {
4242                 if let Some((target, real_target)) =
4243                     impl_.inner_impl().items.iter().find_map(|item| match item.kind {
4244                         clean::TypedefItem(ref t, true) => Some(match *t {
4245                             clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4246                             _ => (&t.type_, &t.type_),
4247                         }),
4248                         _ => None,
4249                     })
4250                 {
4251                     let deref_mut = v
4252                         .iter()
4253                         .filter(|i| i.inner_impl().trait_.is_some())
4254                         .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4255                     let inner_impl = target
4256                         .def_id()
4257                         .or(target
4258                             .primitive_type()
4259                             .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4260                         .and_then(|did| c.impls.get(&did));
4261                     if let Some(impls) = inner_impl {
4262                         out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4263                         out.push_str(&format!(
4264                             "Methods from {}&lt;Target={}&gt;",
4265                             Escape(&format!(
4266                                 "{:#}",
4267                                 impl_.inner_impl().trait_.as_ref().unwrap().print()
4268                             )),
4269                             Escape(&format!("{:#}", real_target.print()))
4270                         ));
4271                         out.push_str("</a>");
4272                         let mut ret = impls
4273                             .iter()
4274                             .filter(|i| i.inner_impl().trait_.is_none())
4275                             .flat_map(|i| {
4276                                 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4277                             })
4278                             .collect::<Vec<_>>();
4279                         // We want links' order to be reproducible so we don't use unstable sort.
4280                         ret.sort();
4281                         if !ret.is_empty() {
4282                             out.push_str(&format!(
4283                                 "<div class=\"sidebar-links\">{}</div>",
4284                                 ret.join("")
4285                             ));
4286                         }
4287                     }
4288                 }
4289             }
4290             let format_impls = |impls: Vec<&Impl>| {
4291                 let mut links = FxHashSet::default();
4292
4293                 let mut ret = impls
4294                     .iter()
4295                     .filter_map(|i| {
4296                         let is_negative_impl = is_negative_impl(i.inner_impl());
4297                         if let Some(ref i) = i.inner_impl().trait_ {
4298                             let i_display = format!("{:#}", i.print());
4299                             let out = Escape(&i_display);
4300                             let encoded = small_url_encode(&format!("{:#}", i.print()));
4301                             let generated = format!(
4302                                 "<a href=\"#impl-{}\">{}{}</a>",
4303                                 encoded,
4304                                 if is_negative_impl { "!" } else { "" },
4305                                 out
4306                             );
4307                             if links.insert(generated.clone()) { Some(generated) } else { None }
4308                         } else {
4309                             None
4310                         }
4311                     })
4312                     .collect::<Vec<String>>();
4313                 ret.sort();
4314                 ret.join("")
4315             };
4316
4317             let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4318                 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4319             let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4320                 .into_iter()
4321                 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4322
4323             let concrete_format = format_impls(concrete);
4324             let synthetic_format = format_impls(synthetic);
4325             let blanket_format = format_impls(blanket_impl);
4326
4327             if !concrete_format.is_empty() {
4328                 out.push_str(
4329                     "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4330                         Trait Implementations</a>",
4331                 );
4332                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4333             }
4334
4335             if !synthetic_format.is_empty() {
4336                 out.push_str(
4337                     "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4338                         Auto Trait Implementations</a>",
4339                 );
4340                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4341             }
4342
4343             if !blanket_format.is_empty() {
4344                 out.push_str(
4345                     "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4346                         Blanket Implementations</a>",
4347                 );
4348                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4349             }
4350         }
4351     }
4352
4353     out
4354 }
4355
4356 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4357     let mut sidebar = String::new();
4358     let fields = get_struct_fields_name(&s.fields);
4359
4360     if !fields.is_empty() {
4361         if let doctree::Plain = s.struct_type {
4362             sidebar.push_str(&format!(
4363                 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4364                  <div class=\"sidebar-links\">{}</div>",
4365                 fields
4366             ));
4367         }
4368     }
4369
4370     sidebar.push_str(&sidebar_assoc_items(it));
4371
4372     if !sidebar.is_empty() {
4373         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4374     }
4375 }
4376
4377 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4378     small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4379 }
4380
4381 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4382     match item.kind {
4383         clean::ItemKind::ImplItem(ref i) => {
4384             if let Some(ref trait_) = i.trait_ {
4385                 Some((
4386                     format!("{:#}", i.for_.print()),
4387                     get_id_for_impl_on_foreign_type(&i.for_, trait_),
4388                 ))
4389             } else {
4390                 None
4391             }
4392         }
4393         _ => None,
4394     }
4395 }
4396
4397 fn is_negative_impl(i: &clean::Impl) -> bool {
4398     i.polarity == Some(clean::ImplPolarity::Negative)
4399 }
4400
4401 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4402     let mut sidebar = String::new();
4403
4404     let mut types = t
4405         .items
4406         .iter()
4407         .filter_map(|m| match m.name {
4408             Some(ref name) if m.is_associated_type() => {
4409                 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4410             }
4411             _ => None,
4412         })
4413         .collect::<Vec<_>>();
4414     let mut consts = t
4415         .items
4416         .iter()
4417         .filter_map(|m| match m.name {
4418             Some(ref name) if m.is_associated_const() => {
4419                 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4420             }
4421             _ => None,
4422         })
4423         .collect::<Vec<_>>();
4424     let mut required = t
4425         .items
4426         .iter()
4427         .filter_map(|m| match m.name {
4428             Some(ref name) if m.is_ty_method() => {
4429                 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4430             }
4431             _ => None,
4432         })
4433         .collect::<Vec<String>>();
4434     let mut provided = t
4435         .items
4436         .iter()
4437         .filter_map(|m| match m.name {
4438             Some(ref name) if m.is_method() => {
4439                 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4440             }
4441             _ => None,
4442         })
4443         .collect::<Vec<String>>();
4444
4445     if !types.is_empty() {
4446         types.sort();
4447         sidebar.push_str(&format!(
4448             "<a class=\"sidebar-title\" href=\"#associated-types\">\
4449                 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4450             types.join("")
4451         ));
4452     }
4453     if !consts.is_empty() {
4454         consts.sort();
4455         sidebar.push_str(&format!(
4456             "<a class=\"sidebar-title\" href=\"#associated-const\">\
4457                 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4458             consts.join("")
4459         ));
4460     }
4461     if !required.is_empty() {
4462         required.sort();
4463         sidebar.push_str(&format!(
4464             "<a class=\"sidebar-title\" href=\"#required-methods\">\
4465                 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4466             required.join("")
4467         ));
4468     }
4469     if !provided.is_empty() {
4470         provided.sort();
4471         sidebar.push_str(&format!(
4472             "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4473                 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4474             provided.join("")
4475         ));
4476     }
4477
4478     let c = cache();
4479
4480     if let Some(implementors) = c.implementors.get(&it.def_id) {
4481         let mut res = implementors
4482             .iter()
4483             .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4484             .filter_map(|i| extract_for_impl_name(&i.impl_item))
4485             .collect::<Vec<_>>();
4486
4487         if !res.is_empty() {
4488             res.sort();
4489             sidebar.push_str(&format!(
4490                 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4491                     Implementations on Foreign Types</a>\
4492                  <div class=\"sidebar-links\">{}</div>",
4493                 res.into_iter()
4494                     .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4495                     .collect::<Vec<_>>()
4496                     .join("")
4497             ));
4498         }
4499     }
4500
4501     sidebar.push_str(&sidebar_assoc_items(it));
4502
4503     sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4504     if t.is_auto {
4505         sidebar.push_str(
4506             "<a class=\"sidebar-title\" \
4507                 href=\"#synthetic-implementors\">Auto Implementors</a>",
4508         );
4509     }
4510
4511     write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4512 }
4513
4514 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4515     let sidebar = sidebar_assoc_items(it);
4516
4517     if !sidebar.is_empty() {
4518         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4519     }
4520 }
4521
4522 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4523     let sidebar = sidebar_assoc_items(it);
4524
4525     if !sidebar.is_empty() {
4526         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4527     }
4528 }
4529
4530 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4531     let mut fields = fields
4532         .iter()
4533         .filter(|f| if let clean::StructFieldItem(..) = f.kind { true } else { false })
4534         .filter_map(|f| match f.name {
4535             Some(ref name) => {
4536                 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4537             }
4538             _ => None,
4539         })
4540         .collect::<Vec<_>>();
4541     fields.sort();
4542     fields.join("")
4543 }
4544
4545 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4546     let mut sidebar = String::new();
4547     let fields = get_struct_fields_name(&u.fields);
4548
4549     if !fields.is_empty() {
4550         sidebar.push_str(&format!(
4551             "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4552              <div class=\"sidebar-links\">{}</div>",
4553             fields
4554         ));
4555     }
4556
4557     sidebar.push_str(&sidebar_assoc_items(it));
4558
4559     if !sidebar.is_empty() {
4560         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4561     }
4562 }
4563
4564 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4565     let mut sidebar = String::new();
4566
4567     let mut variants = e
4568         .variants
4569         .iter()
4570         .filter_map(|v| match v.name {
4571             Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4572             _ => None,
4573         })
4574         .collect::<Vec<_>>();
4575     if !variants.is_empty() {
4576         variants.sort_unstable();
4577         sidebar.push_str(&format!(
4578             "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4579              <div class=\"sidebar-links\">{}</div>",
4580             variants.join(""),
4581         ));
4582     }
4583
4584     sidebar.push_str(&sidebar_assoc_items(it));
4585
4586     if !sidebar.is_empty() {
4587         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4588     }
4589 }
4590
4591 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4592     match *ty {
4593         ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4594         ItemType::Module => ("modules", "Modules"),
4595         ItemType::Struct => ("structs", "Structs"),
4596         ItemType::Union => ("unions", "Unions"),
4597         ItemType::Enum => ("enums", "Enums"),
4598         ItemType::Function => ("functions", "Functions"),
4599         ItemType::Typedef => ("types", "Type Definitions"),
4600         ItemType::Static => ("statics", "Statics"),
4601         ItemType::Constant => ("constants", "Constants"),
4602         ItemType::Trait => ("traits", "Traits"),
4603         ItemType::Impl => ("impls", "Implementations"),
4604         ItemType::TyMethod => ("tymethods", "Type Methods"),
4605         ItemType::Method => ("methods", "Methods"),
4606         ItemType::StructField => ("fields", "Struct Fields"),
4607         ItemType::Variant => ("variants", "Variants"),
4608         ItemType::Macro => ("macros", "Macros"),
4609         ItemType::Primitive => ("primitives", "Primitive Types"),
4610         ItemType::AssocType => ("associated-types", "Associated Types"),
4611         ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4612         ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4613         ItemType::Keyword => ("keywords", "Keywords"),
4614         ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4615         ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4616         ItemType::ProcDerive => ("derives", "Derive Macros"),
4617         ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4618     }
4619 }
4620
4621 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4622     let mut sidebar = String::new();
4623
4624     if items.iter().any(|it| {
4625         it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4626     }) {
4627         sidebar.push_str(&format!(
4628             "<li><a href=\"#{id}\">{name}</a></li>",
4629             id = "reexports",
4630             name = "Re-exports"
4631         ));
4632     }
4633
4634     // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4635     // to print its headings
4636     for &myty in &[
4637         ItemType::Primitive,
4638         ItemType::Module,
4639         ItemType::Macro,
4640         ItemType::Struct,
4641         ItemType::Enum,
4642         ItemType::Constant,
4643         ItemType::Static,
4644         ItemType::Trait,
4645         ItemType::Function,
4646         ItemType::Typedef,
4647         ItemType::Union,
4648         ItemType::Impl,
4649         ItemType::TyMethod,
4650         ItemType::Method,
4651         ItemType::StructField,
4652         ItemType::Variant,
4653         ItemType::AssocType,
4654         ItemType::AssocConst,
4655         ItemType::ForeignType,
4656         ItemType::Keyword,
4657     ] {
4658         if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4659             let (short, name) = item_ty_to_strs(&myty);
4660             sidebar.push_str(&format!(
4661                 "<li><a href=\"#{id}\">{name}</a></li>",
4662                 id = short,
4663                 name = name
4664             ));
4665         }
4666     }
4667
4668     if !sidebar.is_empty() {
4669         write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4670     }
4671 }
4672
4673 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4674     let sidebar = sidebar_assoc_items(it);
4675     if !sidebar.is_empty() {
4676         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4677     }
4678 }
4679
4680 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4681     wrap_into_docblock(w, |w| {
4682         w.write_str(&highlight::render_with_highlighting(
4683             t.source.clone(),
4684             Some("macro"),
4685             None,
4686             None,
4687         ))
4688     });
4689     document(w, cx, it, None)
4690 }
4691
4692 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4693     let name = it.name.as_ref().expect("proc-macros always have names");
4694     match m.kind {
4695         MacroKind::Bang => {
4696             write!(w, "<pre class=\"rust macro\">");
4697             write!(w, "{}!() {{ /* proc-macro */ }}", name);
4698             write!(w, "</pre>");
4699         }
4700         MacroKind::Attr => {
4701             write!(w, "<pre class=\"rust attr\">");
4702             write!(w, "#[{}]", name);
4703             write!(w, "</pre>");
4704         }
4705         MacroKind::Derive => {
4706             write!(w, "<pre class=\"rust derive\">");
4707             write!(w, "#[derive({})]", name);
4708             if !m.helpers.is_empty() {
4709                 writeln!(w, "\n{{");
4710                 writeln!(w, "    // Attributes available to this derive:");
4711                 for attr in &m.helpers {
4712                     writeln!(w, "    #[{}]", attr);
4713                 }
4714                 write!(w, "}}");
4715             }
4716             write!(w, "</pre>");
4717         }
4718     }
4719     document(w, cx, it, None)
4720 }
4721
4722 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4723     document(w, cx, it, None);
4724     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4725 }
4726
4727 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4728     document(w, cx, it, None)
4729 }
4730
4731 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4732
4733 fn make_item_keywords(it: &clean::Item) -> String {
4734     format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4735 }
4736
4737 /// Returns a list of all paths used in the type.
4738 /// This is used to help deduplicate imported impls
4739 /// for reexported types. If any of the contained
4740 /// types are re-exported, we don't use the corresponding
4741 /// entry from the js file, as inlining will have already
4742 /// picked up the impl
4743 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4744     let mut out = Vec::new();
4745     let mut visited = FxHashSet::default();
4746     let mut work = VecDeque::new();
4747     let cache = cache();
4748
4749     work.push_back(first_ty);
4750
4751     while let Some(ty) = work.pop_front() {
4752         if !visited.insert(ty.clone()) {
4753             continue;
4754         }
4755
4756         match ty {
4757             clean::Type::ResolvedPath { did, .. } => {
4758                 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4759                 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4760
4761                 if let Some(path) = fqp {
4762                     out.push(path.join("::"));
4763                 }
4764             }
4765             clean::Type::Tuple(tys) => {
4766                 work.extend(tys.into_iter());
4767             }
4768             clean::Type::Slice(ty) => {
4769                 work.push_back(*ty);
4770             }
4771             clean::Type::Array(ty, _) => {
4772                 work.push_back(*ty);
4773             }
4774             clean::Type::RawPointer(_, ty) => {
4775                 work.push_back(*ty);
4776             }
4777             clean::Type::BorrowedRef { type_, .. } => {
4778                 work.push_back(*type_);
4779             }
4780             clean::Type::QPath { self_type, trait_, .. } => {
4781                 work.push_back(*self_type);
4782                 work.push_back(*trait_);
4783             }
4784             _ => {}
4785         }
4786     }
4787     out
4788 }