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