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