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