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