]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/mod.rs
Rollup merge of #82351 - notriddle:docs-meta-description, r=jyn514
[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) -> &'tcx 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 = it.doc_value().as_ref().map(|doc| plain_text_summary(&doc));
1552         let desc = if let Some(desc) = desc {
1553             desc
1554         } else if it.is_crate() {
1555             format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1556         } else {
1557             format!(
1558                 "API documentation for the Rust `{}` {} in crate `{}`.",
1559                 it.name.as_ref().unwrap(),
1560                 tyname,
1561                 self.shared.layout.krate
1562             )
1563         };
1564         let keywords = make_item_keywords(it);
1565         let page = layout::Page {
1566             css_class: tyname.as_str(),
1567             root_path: &self.root_path(),
1568             static_root_path: self.shared.static_root_path.as_deref(),
1569             title: &title,
1570             description: &desc,
1571             keywords: &keywords,
1572             resource_suffix: &self.shared.resource_suffix,
1573             extra_scripts: &[],
1574             static_extra_scripts: &[],
1575         };
1576
1577         {
1578             self.id_map.borrow_mut().reset();
1579             self.id_map.borrow_mut().populate(&INITIAL_IDS);
1580         }
1581
1582         if !self.render_redirect_pages {
1583             layout::render(
1584                 &self.shared.layout,
1585                 &page,
1586                 |buf: &mut _| print_sidebar(self, it, buf),
1587                 |buf: &mut _| print_item(self, it, buf),
1588                 &self.shared.style_files,
1589             )
1590         } else {
1591             let mut url = self.root_path();
1592             if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) {
1593                 for name in &names[..names.len() - 1] {
1594                     url.push_str(name);
1595                     url.push('/');
1596                 }
1597                 url.push_str(&item_path(ty, names.last().unwrap()));
1598                 layout::redirect(&url)
1599             } else {
1600                 String::new()
1601             }
1602         }
1603     }
1604
1605     /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1606     fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1607         // BTreeMap instead of HashMap to get a sorted output
1608         let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1609         for item in &m.items {
1610             if item.is_stripped() {
1611                 continue;
1612             }
1613
1614             let short = item.type_();
1615             let myname = match item.name {
1616                 None => continue,
1617                 Some(ref s) => s.to_string(),
1618             };
1619             let short = short.to_string();
1620             map.entry(short).or_default().push((
1621                 myname,
1622                 Some(item.doc_value().map_or_else(String::new, |s| plain_text_summary(&s))),
1623             ));
1624         }
1625
1626         if self.shared.sort_modules_alphabetically {
1627             for items in map.values_mut() {
1628                 items.sort();
1629             }
1630         }
1631         map
1632     }
1633
1634     /// Generates a url appropriate for an `href` attribute back to the source of
1635     /// this item.
1636     ///
1637     /// The url generated, when clicked, will redirect the browser back to the
1638     /// original source code.
1639     ///
1640     /// If `None` is returned, then a source link couldn't be generated. This
1641     /// may happen, for example, with externally inlined items where the source
1642     /// of their crate documentation isn't known.
1643     fn src_href(&self, item: &clean::Item) -> Option<String> {
1644         if item.source.is_dummy() {
1645             return None;
1646         }
1647         let mut root = self.root_path();
1648         let mut path = String::new();
1649         let cnum = item.source.cnum(self.sess());
1650
1651         // We can safely ignore synthetic `SourceFile`s.
1652         let file = match item.source.filename(self.sess()) {
1653             FileName::Real(ref path) => path.local_path().to_path_buf(),
1654             _ => return None,
1655         };
1656         let file = &file;
1657
1658         let symbol;
1659         let (krate, path) = if cnum == LOCAL_CRATE {
1660             if let Some(path) = self.shared.local_sources.get(file) {
1661                 (self.shared.layout.krate.as_str(), path)
1662             } else {
1663                 return None;
1664             }
1665         } else {
1666             let (krate, src_root) = match *self.cache.extern_locations.get(&cnum)? {
1667                 (name, ref src, ExternalLocation::Local) => (name, src),
1668                 (name, ref src, ExternalLocation::Remote(ref s)) => {
1669                     root = s.to_string();
1670                     (name, src)
1671                 }
1672                 (_, _, ExternalLocation::Unknown) => return None,
1673             };
1674
1675             sources::clean_path(&src_root, file, false, |component| {
1676                 path.push_str(&component.to_string_lossy());
1677                 path.push('/');
1678             });
1679             let mut fname = file.file_name().expect("source has no filename").to_os_string();
1680             fname.push(".html");
1681             path.push_str(&fname.to_string_lossy());
1682             symbol = krate.as_str();
1683             (&*symbol, &path)
1684         };
1685
1686         let loline = item.source.lo(self.sess()).line;
1687         let hiline = item.source.hi(self.sess()).line;
1688         let lines =
1689             if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) };
1690         Some(format!(
1691             "{root}src/{krate}/{path}#{lines}",
1692             root = Escape(&root),
1693             krate = krate,
1694             path = path,
1695             lines = lines
1696         ))
1697     }
1698 }
1699
1700 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1701 where
1702     F: FnOnce(&mut Buffer),
1703 {
1704     w.write_str("<div class=\"docblock type-decl hidden-by-usual-hider\">");
1705     f(w);
1706     w.write_str("</div>")
1707 }
1708
1709 fn print_item(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
1710     debug_assert!(!item.is_stripped());
1711     // Write the breadcrumb trail header for the top
1712     buf.write_str("<h1 class=\"fqn\"><span class=\"in-band\">");
1713     let name = match *item.kind {
1714         clean::ModuleItem(ref m) => {
1715             if m.is_crate {
1716                 "Crate "
1717             } else {
1718                 "Module "
1719             }
1720         }
1721         clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1722         clean::TraitItem(..) => "Trait ",
1723         clean::StructItem(..) => "Struct ",
1724         clean::UnionItem(..) => "Union ",
1725         clean::EnumItem(..) => "Enum ",
1726         clean::TypedefItem(..) => "Type Definition ",
1727         clean::MacroItem(..) => "Macro ",
1728         clean::ProcMacroItem(ref mac) => match mac.kind {
1729             MacroKind::Bang => "Macro ",
1730             MacroKind::Attr => "Attribute Macro ",
1731             MacroKind::Derive => "Derive Macro ",
1732         },
1733         clean::PrimitiveItem(..) => "Primitive Type ",
1734         clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1735         clean::ConstantItem(..) => "Constant ",
1736         clean::ForeignTypeItem => "Foreign Type ",
1737         clean::KeywordItem(..) => "Keyword ",
1738         clean::OpaqueTyItem(..) => "Opaque Type ",
1739         clean::TraitAliasItem(..) => "Trait Alias ",
1740         _ => {
1741             // We don't generate pages for any other type.
1742             unreachable!();
1743         }
1744     };
1745     buf.write_str(name);
1746     if !item.is_primitive() && !item.is_keyword() {
1747         let cur = &cx.current;
1748         let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1749         for (i, component) in cur.iter().enumerate().take(amt) {
1750             write!(
1751                 buf,
1752                 "<a href=\"{}index.html\">{}</a>::<wbr>",
1753                 "../".repeat(cur.len() - i - 1),
1754                 component
1755             );
1756         }
1757     }
1758     write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1759
1760     buf.write_str("</span>"); // in-band
1761     buf.write_str("<span class=\"out-of-band\">");
1762     render_stability_since_raw(
1763         buf,
1764         item.stable_since(cx.tcx()).as_deref(),
1765         item.const_stable_since(cx.tcx()).as_deref(),
1766         None,
1767         None,
1768     );
1769     buf.write_str(
1770         "<span id=\"render-detail\">\
1771                 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1772                     title=\"collapse all docs\">\
1773                     [<span class=\"inner\">&#x2212;</span>]\
1774                 </a>\
1775             </span>",
1776     );
1777
1778     // Write `src` tag
1779     //
1780     // When this item is part of a `crate use` in a downstream crate, the
1781     // [src] link in the downstream documentation will actually come back to
1782     // this page, and this link will be auto-clicked. The `id` attribute is
1783     // used to find the link to auto-click.
1784     if cx.shared.include_sources && !item.is_primitive() {
1785         write_srclink(cx, item, buf);
1786     }
1787
1788     buf.write_str("</span></h1>"); // out-of-band
1789
1790     match *item.kind {
1791         clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1792         clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1793             item_function(buf, cx, item, f)
1794         }
1795         clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
1796         clean::StructItem(ref s) => item_struct(buf, cx, item, s),
1797         clean::UnionItem(ref s) => item_union(buf, cx, item, s),
1798         clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
1799         clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t),
1800         clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1801         clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1802         clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
1803         clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1804         clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1805         clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
1806         clean::KeywordItem(_) => item_keyword(buf, cx, item),
1807         clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
1808         clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
1809         _ => {
1810             // We don't generate pages for any other type.
1811             unreachable!();
1812         }
1813     }
1814 }
1815
1816 fn item_path(ty: ItemType, name: &str) -> String {
1817     match ty {
1818         ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1819         _ => format!("{}.{}.html", ty, name),
1820     }
1821 }
1822
1823 fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1824     let mut s = cx.current.join("::");
1825     s.push_str("::");
1826     s.push_str(&item.name.unwrap().as_str());
1827     s
1828 }
1829
1830 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
1831     if let Some(ref name) = item.name {
1832         info!("Documenting {}", name);
1833     }
1834     document_item_info(w, cx, item, false, parent);
1835     document_full(w, item, cx, "", false);
1836 }
1837
1838 /// Render md_text as markdown.
1839 fn render_markdown(
1840     w: &mut Buffer,
1841     cx: &Context<'_>,
1842     md_text: &str,
1843     links: Vec<RenderedLink>,
1844     prefix: &str,
1845     is_hidden: bool,
1846 ) {
1847     let mut ids = cx.id_map.borrow_mut();
1848     write!(
1849         w,
1850         "<div class=\"docblock{}\">{}{}</div>",
1851         if is_hidden { " hidden" } else { "" },
1852         prefix,
1853         Markdown(
1854             md_text,
1855             &links,
1856             &mut ids,
1857             cx.shared.codes,
1858             cx.shared.edition,
1859             &cx.shared.playground
1860         )
1861         .into_string()
1862     )
1863 }
1864
1865 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1866 /// docs are longer, a "Read more" link is appended to the end.
1867 fn document_short(
1868     w: &mut Buffer,
1869     item: &clean::Item,
1870     cx: &Context<'_>,
1871     link: AssocItemLink<'_>,
1872     prefix: &str,
1873     is_hidden: bool,
1874     parent: Option<&clean::Item>,
1875     show_def_docs: bool,
1876 ) {
1877     document_item_info(w, cx, item, is_hidden, parent);
1878     if !show_def_docs {
1879         return;
1880     }
1881     if let Some(s) = item.doc_value() {
1882         let mut summary_html = MarkdownSummaryLine(&s, &item.links(&cx.cache)).into_string();
1883
1884         if s.contains('\n') {
1885             let link =
1886                 format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx.cache()));
1887
1888             if let Some(idx) = summary_html.rfind("</p>") {
1889                 summary_html.insert_str(idx, &link);
1890             } else {
1891                 summary_html.push_str(&link);
1892             }
1893         }
1894
1895         write!(
1896             w,
1897             "<div class='docblock{}'>{}{}</div>",
1898             if is_hidden { " hidden" } else { "" },
1899             prefix,
1900             summary_html,
1901         );
1902     } else if !prefix.is_empty() {
1903         write!(
1904             w,
1905             "<div class=\"docblock{}\">{}</div>",
1906             if is_hidden { " hidden" } else { "" },
1907             prefix
1908         );
1909     }
1910 }
1911
1912 fn document_full(
1913     w: &mut Buffer,
1914     item: &clean::Item,
1915     cx: &Context<'_>,
1916     prefix: &str,
1917     is_hidden: bool,
1918 ) {
1919     if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1920         debug!("Doc block: =====\n{}\n=====", s);
1921         render_markdown(w, cx, &*s, item.links(&cx.cache), prefix, is_hidden);
1922     } else if !prefix.is_empty() {
1923         if is_hidden {
1924             w.write_str("<div class=\"docblock hidden\">");
1925         } else {
1926             w.write_str("<div class=\"docblock\">");
1927         }
1928         w.write_str(prefix);
1929         w.write_str("</div>");
1930     }
1931 }
1932
1933 /// Add extra information about an item such as:
1934 ///
1935 /// * Stability
1936 /// * Deprecated
1937 /// * Required features (through the `doc_cfg` feature)
1938 fn document_item_info(
1939     w: &mut Buffer,
1940     cx: &Context<'_>,
1941     item: &clean::Item,
1942     is_hidden: bool,
1943     parent: Option<&clean::Item>,
1944 ) {
1945     let item_infos = short_item_info(item, cx, parent);
1946     if !item_infos.is_empty() {
1947         if is_hidden {
1948             w.write_str("<div class=\"item-info hidden\">");
1949         } else {
1950             w.write_str("<div class=\"item-info\">");
1951         }
1952         for info in item_infos {
1953             w.write_str(&info);
1954         }
1955         w.write_str("</div>");
1956     }
1957 }
1958
1959 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1960     if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1961 }
1962
1963 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1964     if item.is_non_exhaustive() {
1965         write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1966             if item.is_struct() {
1967                 "struct"
1968             } else if item.is_enum() {
1969                 "enum"
1970             } else if item.is_variant() {
1971                 "variant"
1972             } else {
1973                 "type"
1974             }
1975         });
1976
1977         if item.is_struct() {
1978             w.write_str(
1979                 "Non-exhaustive structs could have additional fields added in future. \
1980                  Therefore, non-exhaustive structs cannot be constructed in external crates \
1981                  using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1982                  matched against without a wildcard <code>..</code>; and \
1983                  struct update syntax will not work.",
1984             );
1985         } else if item.is_enum() {
1986             w.write_str(
1987                 "Non-exhaustive enums could have additional variants added in future. \
1988                  Therefore, when matching against variants of non-exhaustive enums, an \
1989                  extra wildcard arm must be added to account for any future variants.",
1990             );
1991         } else if item.is_variant() {
1992             w.write_str(
1993                 "Non-exhaustive enum variants could have additional fields added in future. \
1994                  Therefore, non-exhaustive enum variants cannot be constructed in external \
1995                  crates and cannot be matched against.",
1996             );
1997         } else {
1998             w.write_str(
1999                 "This type will require a wildcard arm in any match statements or constructors.",
2000             );
2001         }
2002
2003         w.write_str("</div>");
2004     }
2005 }
2006
2007 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
2008 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
2009     /// Takes a non-numeric and a numeric part from the given &str.
2010     fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
2011         let i = s.find(|c: char| c.is_ascii_digit());
2012         let (a, b) = s.split_at(i.unwrap_or(s.len()));
2013         let i = b.find(|c: char| !c.is_ascii_digit());
2014         let (b, c) = b.split_at(i.unwrap_or(b.len()));
2015         *s = c;
2016         (a, b)
2017     }
2018
2019     while !lhs.is_empty() || !rhs.is_empty() {
2020         let (la, lb) = take_parts(&mut lhs);
2021         let (ra, rb) = take_parts(&mut rhs);
2022         // First process the non-numeric part.
2023         match la.cmp(ra) {
2024             Ordering::Equal => (),
2025             x => return x,
2026         }
2027         // Then process the numeric part, if both sides have one (and they fit in a u64).
2028         if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2029             match ln.cmp(&rn) {
2030                 Ordering::Equal => (),
2031                 x => return x,
2032             }
2033         }
2034         // Then process the numeric part again, but this time as strings.
2035         match lb.cmp(rb) {
2036             Ordering::Equal => (),
2037             x => return x,
2038         }
2039     }
2040
2041     Ordering::Equal
2042 }
2043
2044 fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) {
2045     document(w, cx, item, None);
2046
2047     let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2048
2049     // the order of item types in the listing
2050     fn reorder(ty: ItemType) -> u8 {
2051         match ty {
2052             ItemType::ExternCrate => 0,
2053             ItemType::Import => 1,
2054             ItemType::Primitive => 2,
2055             ItemType::Module => 3,
2056             ItemType::Macro => 4,
2057             ItemType::Struct => 5,
2058             ItemType::Enum => 6,
2059             ItemType::Constant => 7,
2060             ItemType::Static => 8,
2061             ItemType::Trait => 9,
2062             ItemType::Function => 10,
2063             ItemType::Typedef => 12,
2064             ItemType::Union => 13,
2065             _ => 14 + ty as u8,
2066         }
2067     }
2068
2069     fn cmp(
2070         i1: &clean::Item,
2071         i2: &clean::Item,
2072         idx1: usize,
2073         idx2: usize,
2074         tcx: TyCtxt<'_>,
2075     ) -> Ordering {
2076         let ty1 = i1.type_();
2077         let ty2 = i2.type_();
2078         if ty1 != ty2 {
2079             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2080         }
2081         let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
2082         let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
2083         if let (Some(a), Some(b)) = (s1, s2) {
2084             match (a.is_stable(), b.is_stable()) {
2085                 (true, true) | (false, false) => {}
2086                 (false, true) => return Ordering::Less,
2087                 (true, false) => return Ordering::Greater,
2088             }
2089         }
2090         let lhs = i1.name.unwrap_or(kw::Empty).as_str();
2091         let rhs = i2.name.unwrap_or(kw::Empty).as_str();
2092         compare_names(&lhs, &rhs)
2093     }
2094
2095     if cx.shared.sort_modules_alphabetically {
2096         indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
2097     }
2098     // This call is to remove re-export duplicates in cases such as:
2099     //
2100     // ```
2101     // crate mod foo {
2102     //     crate mod bar {
2103     //         crate trait Double { fn foo(); }
2104     //     }
2105     // }
2106     //
2107     // crate use foo::bar::*;
2108     // crate use foo::*;
2109     // ```
2110     //
2111     // `Double` will appear twice in the generated docs.
2112     //
2113     // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2114     // can be identical even if the elements are different (mostly in imports).
2115     // So in case this is an import, we keep everything by adding a "unique id"
2116     // (which is the position in the vector).
2117     indices.dedup_by_key(|i| {
2118         (
2119             items[*i].def_id,
2120             if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2121             items[*i].type_(),
2122             if items[*i].is_import() { *i } else { 0 },
2123         )
2124     });
2125
2126     debug!("{:?}", indices);
2127     let mut curty = None;
2128     for &idx in &indices {
2129         let myitem = &items[idx];
2130         if myitem.is_stripped() {
2131             continue;
2132         }
2133
2134         let myty = Some(myitem.type_());
2135         if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2136             // Put `extern crate` and `use` re-exports in the same section.
2137             curty = myty;
2138         } else if myty != curty {
2139             if curty.is_some() {
2140                 w.write_str("</table>");
2141             }
2142             curty = myty;
2143             let (short, name) = item_ty_to_strs(&myty.unwrap());
2144             write!(
2145                 w,
2146                 "<h2 id=\"{id}\" class=\"section-header\">\
2147                        <a href=\"#{id}\">{name}</a></h2>\n<table>",
2148                 id = cx.derive_id(short.to_owned()),
2149                 name = name
2150             );
2151         }
2152
2153         match *myitem.kind {
2154             clean::ExternCrateItem(ref name, ref src) => {
2155                 use crate::html::format::anchor;
2156
2157                 match *src {
2158                     Some(ref src) => write!(
2159                         w,
2160                         "<tr><td><code>{}extern crate {} as {};",
2161                         myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2162                         anchor(myitem.def_id, &*src.as_str(), cx.cache()),
2163                         name
2164                     ),
2165                     None => write!(
2166                         w,
2167                         "<tr><td><code>{}extern crate {};",
2168                         myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2169                         anchor(myitem.def_id, &*name.as_str(), cx.cache())
2170                     ),
2171                 }
2172                 w.write_str("</code></td></tr>");
2173             }
2174
2175             clean::ImportItem(ref import) => {
2176                 write!(
2177                     w,
2178                     "<tr><td><code>{}{}</code></td></tr>",
2179                     myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2180                     import.print(cx.cache())
2181                 );
2182             }
2183
2184             _ => {
2185                 if myitem.name.is_none() {
2186                     continue;
2187                 }
2188
2189                 let unsafety_flag = match *myitem.kind {
2190                     clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2191                         if func.header.unsafety == hir::Unsafety::Unsafe =>
2192                     {
2193                         "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2194                     }
2195                     _ => "",
2196                 };
2197
2198                 let stab = myitem.stability_class(cx.tcx());
2199                 let add = if stab.is_some() { " " } else { "" };
2200
2201                 let doc_value = myitem.doc_value().unwrap_or_default();
2202                 write!(
2203                     w,
2204                     "<tr class=\"{stab}{add}module-item\">\
2205                          <td><a class=\"{class}\" href=\"{href}\" \
2206                              title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2207                          <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2208                      </tr>",
2209                     name = *myitem.name.as_ref().unwrap(),
2210                     stab_tags = extra_info_tags(myitem, item, cx.tcx()),
2211                     docs = MarkdownSummaryLine(&doc_value, &myitem.links(&cx.cache)).into_string(),
2212                     class = myitem.type_(),
2213                     add = add,
2214                     stab = stab.unwrap_or_else(String::new),
2215                     unsafety_flag = unsafety_flag,
2216                     href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()),
2217                     title = [full_path(cx, myitem), myitem.type_().to_string()]
2218                         .iter()
2219                         .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2220                         .collect::<Vec<_>>()
2221                         .join(" "),
2222                 );
2223             }
2224         }
2225     }
2226
2227     if curty.is_some() {
2228         w.write_str("</table>");
2229     }
2230 }
2231
2232 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
2233 /// at the module level.
2234 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
2235     let mut tags = String::new();
2236
2237     fn tag_html(class: &str, title: &str, contents: &str) -> String {
2238         format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2239     }
2240
2241     // The trailing space after each tag is to space it properly against the rest of the docs.
2242     if let Some(depr) = &item.deprecation(tcx) {
2243         let mut message = "Deprecated";
2244         if !stability::deprecation_in_effect(
2245             depr.is_since_rustc_version,
2246             depr.since.map(|s| s.as_str()).as_deref(),
2247         ) {
2248             message = "Deprecation planned";
2249         }
2250         tags += &tag_html("deprecated", "", message);
2251     }
2252
2253     // The "rustc_private" crates are permanently unstable so it makes no sense
2254     // to render "unstable" everywhere.
2255     if item
2256         .stability(tcx)
2257         .as_ref()
2258         .map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2259         == Some(true)
2260     {
2261         tags += &tag_html("unstable", "", "Experimental");
2262     }
2263
2264     let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2265         (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2266         (cfg, _) => cfg.as_deref().cloned(),
2267     };
2268
2269     debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2270     if let Some(ref cfg) = cfg {
2271         tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2272     }
2273
2274     tags
2275 }
2276
2277 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2278     let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2279         (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2280         (cfg, _) => cfg.as_deref().cloned(),
2281     };
2282
2283     debug!(
2284         "Portability {:?} - {:?} = {:?}",
2285         item.attrs.cfg,
2286         parent.and_then(|p| p.attrs.cfg.as_ref()),
2287         cfg
2288     );
2289
2290     Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2291 }
2292
2293 /// Render the stability, deprecation and portability information that is displayed at the top of
2294 /// the item's documentation.
2295 fn short_item_info(
2296     item: &clean::Item,
2297     cx: &Context<'_>,
2298     parent: Option<&clean::Item>,
2299 ) -> Vec<String> {
2300     let mut extra_info = vec![];
2301     let error_codes = cx.shared.codes;
2302
2303     if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
2304         item.deprecation(cx.tcx())
2305     {
2306         // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2307         // but only display the future-deprecation messages for #[rustc_deprecated].
2308         let mut message = if let Some(since) = since {
2309             let since = &since.as_str();
2310             if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2311                 if *since == "TBD" {
2312                     String::from("Deprecating in a future Rust version")
2313                 } else {
2314                     format!("Deprecating in {}", Escape(since))
2315                 }
2316             } else {
2317                 format!("Deprecated since {}", Escape(since))
2318             }
2319         } else {
2320             String::from("Deprecated")
2321         };
2322
2323         if let Some(note) = note {
2324             let note = note.as_str();
2325             let mut ids = cx.id_map.borrow_mut();
2326             let html = MarkdownHtml(
2327                 &note,
2328                 &mut ids,
2329                 error_codes,
2330                 cx.shared.edition,
2331                 &cx.shared.playground,
2332             );
2333             message.push_str(&format!(": {}", html.into_string()));
2334         }
2335         extra_info.push(format!(
2336             "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2337             message,
2338         ));
2339     }
2340
2341     // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2342     // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2343     if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2344         .stability(cx.tcx())
2345         .as_ref()
2346         .filter(|stab| stab.feature != sym::rustc_private)
2347         .map(|stab| (stab.level, stab.feature))
2348     {
2349         let mut message =
2350             "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2351
2352         let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2353         if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2354             feature.push_str(&format!(
2355                 "&nbsp;<a href=\"{url}{issue}\">#{issue}</a>",
2356                 url = url,
2357                 issue = issue
2358             ));
2359         }
2360
2361         message.push_str(&format!(" ({})", feature));
2362
2363         if let Some(unstable_reason) = reason {
2364             let mut ids = cx.id_map.borrow_mut();
2365             message = format!(
2366                 "<details><summary>{}</summary>{}</details>",
2367                 message,
2368                 MarkdownHtml(
2369                     &unstable_reason.as_str(),
2370                     &mut ids,
2371                     error_codes,
2372                     cx.shared.edition,
2373                     &cx.shared.playground,
2374                 )
2375                 .into_string()
2376             );
2377         }
2378
2379         extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2380     }
2381
2382     if let Some(portability) = portability(item, parent) {
2383         extra_info.push(portability);
2384     }
2385
2386     extra_info
2387 }
2388
2389 fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) {
2390     w.write_str("<pre class=\"rust const\">");
2391     render_attributes(w, it, false);
2392
2393     write!(
2394         w,
2395         "{vis}const {name}: {typ}",
2396         vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2397         name = it.name.as_ref().unwrap(),
2398         typ = c.type_.print(cx.cache()),
2399     );
2400
2401     if c.value.is_some() || c.is_literal {
2402         write!(w, " = {expr};", expr = Escape(&c.expr));
2403     } else {
2404         w.write_str(";");
2405     }
2406
2407     if let Some(value) = &c.value {
2408         if !c.is_literal {
2409             let value_lowercase = value.to_lowercase();
2410             let expr_lowercase = c.expr.to_lowercase();
2411
2412             if value_lowercase != expr_lowercase
2413                 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2414             {
2415                 write!(w, " // {value}", value = Escape(value));
2416             }
2417         }
2418     }
2419
2420     w.write_str("</pre>");
2421     document(w, cx, it, None)
2422 }
2423
2424 fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
2425     w.write_str("<pre class=\"rust static\">");
2426     render_attributes(w, it, false);
2427     write!(
2428         w,
2429         "{vis}static {mutability}{name}: {typ}</pre>",
2430         vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2431         mutability = s.mutability.print_with_space(),
2432         name = it.name.as_ref().unwrap(),
2433         typ = s.type_.print(cx.cache())
2434     );
2435     document(w, cx, it, None)
2436 }
2437
2438 fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
2439     let header_len = format!(
2440         "{}{}{}{}{:#}fn {}{:#}",
2441         it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2442         f.header.constness.print_with_space(),
2443         f.header.asyncness.print_with_space(),
2444         f.header.unsafety.print_with_space(),
2445         print_abi_with_space(f.header.abi),
2446         it.name.as_ref().unwrap(),
2447         f.generics.print(cx.cache())
2448     )
2449     .len();
2450     w.write_str("<pre class=\"rust fn\">");
2451     render_attributes(w, it, false);
2452     write!(
2453         w,
2454         "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2455          {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2456         vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2457         constness = f.header.constness.print_with_space(),
2458         asyncness = f.header.asyncness.print_with_space(),
2459         unsafety = f.header.unsafety.print_with_space(),
2460         abi = print_abi_with_space(f.header.abi),
2461         name = it.name.as_ref().unwrap(),
2462         generics = f.generics.print(cx.cache()),
2463         where_clause =
2464             WhereClause { gens: &f.generics, indent: 0, end_newline: true }.print(cx.cache()),
2465         decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2466             .print(cx.cache()),
2467         spotlight = spotlight_decl(&f.decl, cx.cache()),
2468     );
2469     document(w, cx, it, None)
2470 }
2471
2472 fn render_implementor(
2473     cx: &Context<'_>,
2474     implementor: &Impl,
2475     trait_: &clean::Item,
2476     w: &mut Buffer,
2477     implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
2478     aliases: &[String],
2479 ) {
2480     // If there's already another implementor that has the same abbridged name, use the
2481     // full path, for example in `std::iter::ExactSizeIterator`
2482     let use_absolute = match implementor.inner_impl().for_ {
2483         clean::ResolvedPath { ref path, is_generic: false, .. }
2484         | clean::BorrowedRef {
2485             type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2486             ..
2487         } => implementor_dups[&path.last()].1,
2488         _ => false,
2489     };
2490     render_impl(
2491         w,
2492         cx,
2493         implementor,
2494         trait_,
2495         AssocItemLink::Anchor(None),
2496         RenderMode::Normal,
2497         trait_.stable_since(cx.tcx()).as_deref(),
2498         trait_.const_stable_since(cx.tcx()).as_deref(),
2499         false,
2500         Some(use_absolute),
2501         false,
2502         false,
2503         aliases,
2504     );
2505 }
2506
2507 fn render_impls(
2508     cx: &Context<'_>,
2509     w: &mut Buffer,
2510     traits: &[&&Impl],
2511     containing_item: &clean::Item,
2512 ) {
2513     let mut impls = traits
2514         .iter()
2515         .map(|i| {
2516             let did = i.trait_did_full(cx.cache()).unwrap();
2517             let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2518             let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2519             render_impl(
2520                 &mut buffer,
2521                 cx,
2522                 i,
2523                 containing_item,
2524                 assoc_link,
2525                 RenderMode::Normal,
2526                 containing_item.stable_since(cx.tcx()).as_deref(),
2527                 containing_item.const_stable_since(cx.tcx()).as_deref(),
2528                 true,
2529                 None,
2530                 false,
2531                 true,
2532                 &[],
2533             );
2534             buffer.into_inner()
2535         })
2536         .collect::<Vec<_>>();
2537     impls.sort();
2538     w.write_str(&impls.join(""));
2539 }
2540
2541 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cache: &Cache) -> String {
2542     let mut bounds = String::new();
2543     if !t_bounds.is_empty() {
2544         if !trait_alias {
2545             bounds.push_str(": ");
2546         }
2547         for (i, p) in t_bounds.iter().enumerate() {
2548             if i > 0 {
2549                 bounds.push_str(" + ");
2550             }
2551             bounds.push_str(&p.print(cache).to_string());
2552         }
2553     }
2554     bounds
2555 }
2556
2557 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cache: &Cache) -> Ordering {
2558     let lhs = format!("{}", lhs.inner_impl().print(cache, false));
2559     let rhs = format!("{}", rhs.inner_impl().print(cache, false));
2560
2561     // lhs and rhs are formatted as HTML, which may be unnecessary
2562     compare_names(&lhs, &rhs)
2563 }
2564
2565 fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) {
2566     let bounds = bounds(&t.bounds, false, cx.cache());
2567     let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2568     let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2569     let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2570     let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2571
2572     // Output the trait definition
2573     wrap_into_docblock(w, |w| {
2574         w.write_str("<pre class=\"rust trait\">");
2575         render_attributes(w, it, true);
2576         write!(
2577             w,
2578             "{}{}{}trait {}{}{}",
2579             it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2580             t.unsafety.print_with_space(),
2581             if t.is_auto { "auto " } else { "" },
2582             it.name.as_ref().unwrap(),
2583             t.generics.print(cx.cache()),
2584             bounds
2585         );
2586
2587         if !t.generics.where_predicates.is_empty() {
2588             let where_ = WhereClause { gens: &t.generics, indent: 0, end_newline: true };
2589             write!(w, "{}", where_.print(cx.cache()));
2590         } else {
2591             w.write_str(" ");
2592         }
2593
2594         if t.items.is_empty() {
2595             w.write_str("{ }");
2596         } else {
2597             // FIXME: we should be using a derived_id for the Anchors here
2598             w.write_str("{\n");
2599             for t in &types {
2600                 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2601                 w.write_str(";\n");
2602             }
2603             if !types.is_empty() && !consts.is_empty() {
2604                 w.write_str("\n");
2605             }
2606             for t in &consts {
2607                 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2608                 w.write_str(";\n");
2609             }
2610             if !consts.is_empty() && !required.is_empty() {
2611                 w.write_str("\n");
2612             }
2613             for (pos, m) in required.iter().enumerate() {
2614                 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2615                 w.write_str(";\n");
2616
2617                 if pos < required.len() - 1 {
2618                     w.write_str("<div class=\"item-spacer\"></div>");
2619                 }
2620             }
2621             if !required.is_empty() && !provided.is_empty() {
2622                 w.write_str("\n");
2623             }
2624             for (pos, m) in provided.iter().enumerate() {
2625                 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2626                 match *m.kind {
2627                     clean::MethodItem(ref inner, _)
2628                         if !inner.generics.where_predicates.is_empty() =>
2629                     {
2630                         w.write_str(",\n    { ... }\n");
2631                     }
2632                     _ => {
2633                         w.write_str(" { ... }\n");
2634                     }
2635                 }
2636                 if pos < provided.len() - 1 {
2637                     w.write_str("<div class=\"item-spacer\"></div>");
2638                 }
2639             }
2640             w.write_str("}");
2641         }
2642         w.write_str("</pre>")
2643     });
2644
2645     // Trait documentation
2646     document(w, cx, it, None);
2647
2648     fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2649         write!(
2650             w,
2651             "<h2 id=\"{0}\" class=\"small-section-header\">\
2652                 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2653              </h2>{2}",
2654             id, title, extra_content
2655         )
2656     }
2657
2658     fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2659         write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2660     }
2661
2662     fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item) {
2663         let name = m.name.as_ref().unwrap();
2664         info!("Documenting {} on {:?}", name, t.name);
2665         let item_type = m.type_();
2666         let id = cx.derive_id(format!("{}.{}", item_type, name));
2667         write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2668         render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl, cx);
2669         w.write_str("</code>");
2670         render_stability_since(w, m, t, cx.tcx());
2671         write_srclink(cx, m, w);
2672         w.write_str("</h3>");
2673         document(w, cx, m, Some(t));
2674     }
2675
2676     if !types.is_empty() {
2677         write_small_section_header(
2678             w,
2679             "associated-types",
2680             "Associated Types",
2681             "<div class=\"methods\">",
2682         );
2683         for t in types {
2684             trait_item(w, cx, t, it);
2685         }
2686         write_loading_content(w, "</div>");
2687     }
2688
2689     if !consts.is_empty() {
2690         write_small_section_header(
2691             w,
2692             "associated-const",
2693             "Associated Constants",
2694             "<div class=\"methods\">",
2695         );
2696         for t in consts {
2697             trait_item(w, cx, t, it);
2698         }
2699         write_loading_content(w, "</div>");
2700     }
2701
2702     // Output the documentation for each function individually
2703     if !required.is_empty() {
2704         write_small_section_header(
2705             w,
2706             "required-methods",
2707             "Required methods",
2708             "<div class=\"methods\">",
2709         );
2710         for m in required {
2711             trait_item(w, cx, m, it);
2712         }
2713         write_loading_content(w, "</div>");
2714     }
2715     if !provided.is_empty() {
2716         write_small_section_header(
2717             w,
2718             "provided-methods",
2719             "Provided methods",
2720             "<div class=\"methods\">",
2721         );
2722         for m in provided {
2723             trait_item(w, cx, m, it);
2724         }
2725         write_loading_content(w, "</div>");
2726     }
2727
2728     // If there are methods directly on this trait object, render them here.
2729     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All);
2730
2731     if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2732         // The DefId is for the first Type found with that name. The bool is
2733         // if any Types with the same name but different DefId have been found.
2734         let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
2735         for implementor in implementors {
2736             match implementor.inner_impl().for_ {
2737                 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2738                 | clean::BorrowedRef {
2739                     type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2740                     ..
2741                 } => {
2742                     let &mut (prev_did, ref mut has_duplicates) =
2743                         implementor_dups.entry(path.last()).or_insert((did, false));
2744                     if prev_did != did {
2745                         *has_duplicates = true;
2746                     }
2747                 }
2748                 _ => {}
2749             }
2750         }
2751
2752         let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2753             i.inner_impl()
2754                 .for_
2755                 .def_id_full(cx.cache())
2756                 .map_or(true, |d| cx.cache.paths.contains_key(&d))
2757         });
2758
2759         let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2760             local.iter().partition(|i| i.inner_impl().synthetic);
2761
2762         synthetic.sort_by(|a, b| compare_impl(a, b, cx.cache()));
2763         concrete.sort_by(|a, b| compare_impl(a, b, cx.cache()));
2764
2765         if !foreign.is_empty() {
2766             write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2767
2768             for implementor in foreign {
2769                 let assoc_link = AssocItemLink::GotoSource(
2770                     implementor.impl_item.def_id,
2771                     &implementor.inner_impl().provided_trait_methods,
2772                 );
2773                 render_impl(
2774                     w,
2775                     cx,
2776                     &implementor,
2777                     it,
2778                     assoc_link,
2779                     RenderMode::Normal,
2780                     implementor.impl_item.stable_since(cx.tcx()).as_deref(),
2781                     implementor.impl_item.const_stable_since(cx.tcx()).as_deref(),
2782                     false,
2783                     None,
2784                     true,
2785                     false,
2786                     &[],
2787                 );
2788             }
2789             write_loading_content(w, "");
2790         }
2791
2792         write_small_section_header(
2793             w,
2794             "implementors",
2795             "Implementors",
2796             "<div class=\"item-list\" id=\"implementors-list\">",
2797         );
2798         for implementor in concrete {
2799             render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
2800         }
2801         write_loading_content(w, "</div>");
2802
2803         if t.is_auto {
2804             write_small_section_header(
2805                 w,
2806                 "synthetic-implementors",
2807                 "Auto implementors",
2808                 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2809             );
2810             for implementor in synthetic {
2811                 render_implementor(
2812                     cx,
2813                     implementor,
2814                     it,
2815                     w,
2816                     &implementor_dups,
2817                     &collect_paths_for_type(implementor.inner_impl().for_.clone(), &cx.cache),
2818                 );
2819             }
2820             write_loading_content(w, "</div>");
2821         }
2822     } else {
2823         // even without any implementations to write in, we still want the heading and list, so the
2824         // implementors javascript file pulled in below has somewhere to write the impls into
2825         write_small_section_header(
2826             w,
2827             "implementors",
2828             "Implementors",
2829             "<div class=\"item-list\" id=\"implementors-list\">",
2830         );
2831         write_loading_content(w, "</div>");
2832
2833         if t.is_auto {
2834             write_small_section_header(
2835                 w,
2836                 "synthetic-implementors",
2837                 "Auto implementors",
2838                 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2839             );
2840             write_loading_content(w, "</div>");
2841         }
2842     }
2843
2844     write!(
2845         w,
2846         "<script type=\"text/javascript\" \
2847                  src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2848          </script>",
2849         root_path = vec![".."; cx.current.len()].join("/"),
2850         path = if it.def_id.is_local() {
2851             cx.current.join("/")
2852         } else {
2853             let (ref path, _) = cx.cache.external_paths[&it.def_id];
2854             path[..path.len() - 1].join("/")
2855         },
2856         ty = it.type_(),
2857         name = *it.name.as_ref().unwrap()
2858     );
2859 }
2860
2861 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cache: &Cache) -> String {
2862     use crate::formats::item_type::ItemType::*;
2863
2864     let name = it.name.as_ref().unwrap();
2865     let ty = match it.type_() {
2866         Typedef | AssocType => AssocType,
2867         s => s,
2868     };
2869
2870     let anchor = format!("#{}.{}", ty, name);
2871     match link {
2872         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2873         AssocItemLink::Anchor(None) => anchor,
2874         AssocItemLink::GotoSource(did, _) => {
2875             href(did, cache).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2876         }
2877     }
2878 }
2879
2880 fn assoc_const(
2881     w: &mut Buffer,
2882     it: &clean::Item,
2883     ty: &clean::Type,
2884     _default: Option<&String>,
2885     link: AssocItemLink<'_>,
2886     extra: &str,
2887     cx: &Context<'_>,
2888 ) {
2889     write!(
2890         w,
2891         "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2892         extra,
2893         it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2894         naive_assoc_href(it, link, cx.cache()),
2895         it.name.as_ref().unwrap(),
2896         ty.print(cx.cache())
2897     );
2898 }
2899
2900 fn assoc_type(
2901     w: &mut Buffer,
2902     it: &clean::Item,
2903     bounds: &[clean::GenericBound],
2904     default: Option<&clean::Type>,
2905     link: AssocItemLink<'_>,
2906     extra: &str,
2907     cache: &Cache,
2908 ) {
2909     write!(
2910         w,
2911         "{}type <a href=\"{}\" class=\"type\">{}</a>",
2912         extra,
2913         naive_assoc_href(it, link, cache),
2914         it.name.as_ref().unwrap()
2915     );
2916     if !bounds.is_empty() {
2917         write!(w, ": {}", print_generic_bounds(bounds, cache))
2918     }
2919     if let Some(default) = default {
2920         write!(w, " = {}", default.print(cache))
2921     }
2922 }
2923
2924 fn render_stability_since_raw(
2925     w: &mut Buffer,
2926     ver: Option<&str>,
2927     const_ver: Option<&str>,
2928     containing_ver: Option<&str>,
2929     containing_const_ver: Option<&str>,
2930 ) {
2931     let ver = ver.filter(|inner| !inner.is_empty());
2932     let const_ver = const_ver.filter(|inner| !inner.is_empty());
2933
2934     match (ver, const_ver) {
2935         (Some(v), Some(cv)) if const_ver != containing_const_ver => {
2936             write!(
2937                 w,
2938                 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2939                 v, cv
2940             );
2941         }
2942         (Some(v), _) if ver != containing_ver => {
2943             write!(
2944                 w,
2945                 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2946                 v
2947             );
2948         }
2949         _ => {}
2950     }
2951 }
2952
2953 fn render_stability_since(
2954     w: &mut Buffer,
2955     item: &clean::Item,
2956     containing_item: &clean::Item,
2957     tcx: TyCtxt<'_>,
2958 ) {
2959     render_stability_since_raw(
2960         w,
2961         item.stable_since(tcx).as_deref(),
2962         item.const_stable_since(tcx).as_deref(),
2963         containing_item.stable_since(tcx).as_deref(),
2964         containing_item.const_stable_since(tcx).as_deref(),
2965     )
2966 }
2967
2968 fn render_assoc_item(
2969     w: &mut Buffer,
2970     item: &clean::Item,
2971     link: AssocItemLink<'_>,
2972     parent: ItemType,
2973     cx: &Context<'_>,
2974 ) {
2975     fn method(
2976         w: &mut Buffer,
2977         meth: &clean::Item,
2978         header: hir::FnHeader,
2979         g: &clean::Generics,
2980         d: &clean::FnDecl,
2981         link: AssocItemLink<'_>,
2982         parent: ItemType,
2983         cx: &Context<'_>,
2984     ) {
2985         let name = meth.name.as_ref().unwrap();
2986         let anchor = format!("#{}.{}", meth.type_(), name);
2987         let href = match link {
2988             AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2989             AssocItemLink::Anchor(None) => anchor,
2990             AssocItemLink::GotoSource(did, provided_methods) => {
2991                 // We're creating a link from an impl-item to the corresponding
2992                 // trait-item and need to map the anchored type accordingly.
2993                 let ty = if provided_methods.contains(&name) {
2994                     ItemType::Method
2995                 } else {
2996                     ItemType::TyMethod
2997                 };
2998
2999                 href(did, cx.cache()).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3000             }
3001         };
3002         let mut header_len = format!(
3003             "{}{}{}{}{}{:#}fn {}{:#}",
3004             meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
3005             header.constness.print_with_space(),
3006             header.asyncness.print_with_space(),
3007             header.unsafety.print_with_space(),
3008             print_default_space(meth.is_default()),
3009             print_abi_with_space(header.abi),
3010             name,
3011             g.print(cx.cache())
3012         )
3013         .len();
3014         let (indent, end_newline) = if parent == ItemType::Trait {
3015             header_len += 4;
3016             (4, false)
3017         } else {
3018             (0, true)
3019         };
3020         render_attributes(w, meth, false);
3021         write!(
3022             w,
3023             "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
3024              {generics}{decl}{spotlight}{where_clause}",
3025             if parent == ItemType::Trait { "    " } else { "" },
3026             meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
3027             header.constness.print_with_space(),
3028             header.asyncness.print_with_space(),
3029             header.unsafety.print_with_space(),
3030             print_default_space(meth.is_default()),
3031             print_abi_with_space(header.abi),
3032             href = href,
3033             name = name,
3034             generics = g.print(cx.cache()),
3035             decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }
3036                 .print(cx.cache()),
3037             spotlight = spotlight_decl(&d, cx.cache()),
3038             where_clause = WhereClause { gens: g, indent, end_newline }.print(cx.cache())
3039         )
3040     }
3041     match *item.kind {
3042         clean::StrippedItem(..) => {}
3043         clean::TyMethodItem(ref m) => {
3044             method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
3045         }
3046         clean::MethodItem(ref m, _) => {
3047             method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
3048         }
3049         clean::AssocConstItem(ref ty, ref default) => assoc_const(
3050             w,
3051             item,
3052             ty,
3053             default.as_ref(),
3054             link,
3055             if parent == ItemType::Trait { "    " } else { "" },
3056             cx,
3057         ),
3058         clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3059             w,
3060             item,
3061             bounds,
3062             default.as_ref(),
3063             link,
3064             if parent == ItemType::Trait { "    " } else { "" },
3065             cx.cache(),
3066         ),
3067         _ => panic!("render_assoc_item called on non-associated-item"),
3068     }
3069 }
3070
3071 fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) {
3072     wrap_into_docblock(w, |w| {
3073         w.write_str("<pre class=\"rust struct\">");
3074         render_attributes(w, it, true);
3075         render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
3076         w.write_str("</pre>")
3077     });
3078
3079     document(w, cx, it, None);
3080     let mut fields = s
3081         .fields
3082         .iter()
3083         .filter_map(|f| match *f.kind {
3084             clean::StructFieldItem(ref ty) => Some((f, ty)),
3085             _ => None,
3086         })
3087         .peekable();
3088     if let CtorKind::Fictive = s.struct_type {
3089         if fields.peek().is_some() {
3090             write!(
3091                 w,
3092                 "<h2 id=\"fields\" class=\"fields small-section-header\">
3093                        Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3094                 document_non_exhaustive_header(it)
3095             );
3096             document_non_exhaustive(w, it);
3097             for (field, ty) in fields {
3098                 let id = cx.derive_id(format!(
3099                     "{}.{}",
3100                     ItemType::StructField,
3101                     field.name.as_ref().unwrap()
3102                 ));
3103                 write!(
3104                     w,
3105                     "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3106                          <a href=\"#{id}\" class=\"anchor field\"></a>\
3107                          <code>{name}: {ty}</code>\
3108                      </span>",
3109                     item_type = ItemType::StructField,
3110                     id = id,
3111                     name = field.name.as_ref().unwrap(),
3112                     ty = ty.print(cx.cache())
3113                 );
3114                 document(w, cx, field, Some(it));
3115             }
3116         }
3117     }
3118     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3119 }
3120
3121 fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
3122     wrap_into_docblock(w, |w| {
3123         w.write_str("<pre class=\"rust union\">");
3124         render_attributes(w, it, true);
3125         render_union(w, it, Some(&s.generics), &s.fields, "", true, cx);
3126         w.write_str("</pre>")
3127     });
3128
3129     document(w, cx, it, None);
3130     let mut fields = s
3131         .fields
3132         .iter()
3133         .filter_map(|f| match *f.kind {
3134             clean::StructFieldItem(ref ty) => Some((f, ty)),
3135             _ => None,
3136         })
3137         .peekable();
3138     if fields.peek().is_some() {
3139         write!(
3140             w,
3141             "<h2 id=\"fields\" class=\"fields small-section-header\">
3142                    Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3143         );
3144         for (field, ty) in fields {
3145             let name = field.name.as_ref().expect("union field name");
3146             let id = format!("{}.{}", ItemType::StructField, name);
3147             write!(
3148                 w,
3149                 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3150                      <a href=\"#{id}\" class=\"anchor field\"></a>\
3151                      <code>{name}: {ty}</code>\
3152                  </span>",
3153                 id = id,
3154                 name = name,
3155                 shortty = ItemType::StructField,
3156                 ty = ty.print(cx.cache())
3157             );
3158             if let Some(stability_class) = field.stability_class(cx.tcx()) {
3159                 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3160             }
3161             document(w, cx, field, Some(it));
3162         }
3163     }
3164     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3165 }
3166
3167 fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
3168     wrap_into_docblock(w, |w| {
3169         w.write_str("<pre class=\"rust enum\">");
3170         render_attributes(w, it, true);
3171         write!(
3172             w,
3173             "{}enum {}{}{}",
3174             it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3175             it.name.as_ref().unwrap(),
3176             e.generics.print(cx.cache()),
3177             WhereClause { gens: &e.generics, indent: 0, end_newline: true }.print(cx.cache())
3178         );
3179         if e.variants.is_empty() && !e.variants_stripped {
3180             w.write_str(" {}");
3181         } else {
3182             w.write_str(" {\n");
3183             for v in &e.variants {
3184                 w.write_str("    ");
3185                 let name = v.name.as_ref().unwrap();
3186                 match *v.kind {
3187                     clean::VariantItem(ref var) => match var {
3188                         clean::Variant::CLike => write!(w, "{}", name),
3189                         clean::Variant::Tuple(ref tys) => {
3190                             write!(w, "{}(", name);
3191                             for (i, ty) in tys.iter().enumerate() {
3192                                 if i > 0 {
3193                                     w.write_str(",&nbsp;")
3194                                 }
3195                                 write!(w, "{}", ty.print(cx.cache()));
3196                             }
3197                             w.write_str(")");
3198                         }
3199                         clean::Variant::Struct(ref s) => {
3200                             render_struct(w, v, None, s.struct_type, &s.fields, "    ", false, cx);
3201                         }
3202                     },
3203                     _ => unreachable!(),
3204                 }
3205                 w.write_str(",\n");
3206             }
3207
3208             if e.variants_stripped {
3209                 w.write_str("    // some variants omitted\n");
3210             }
3211             w.write_str("}");
3212         }
3213         w.write_str("</pre>")
3214     });
3215
3216     document(w, cx, it, None);
3217     if !e.variants.is_empty() {
3218         write!(
3219             w,
3220             "<h2 id=\"variants\" class=\"variants small-section-header\">
3221                    Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3222             document_non_exhaustive_header(it)
3223         );
3224         document_non_exhaustive(w, it);
3225         for variant in &e.variants {
3226             let id =
3227                 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3228             write!(
3229                 w,
3230                 "<div id=\"{id}\" class=\"variant small-section-header\">\
3231                     <a href=\"#{id}\" class=\"anchor field\"></a>\
3232                     <code>{name}",
3233                 id = id,
3234                 name = variant.name.as_ref().unwrap()
3235             );
3236             if let clean::VariantItem(clean::Variant::Tuple(ref tys)) = *variant.kind {
3237                 w.write_str("(");
3238                 for (i, ty) in tys.iter().enumerate() {
3239                     if i > 0 {
3240                         w.write_str(",&nbsp;");
3241                     }
3242                     write!(w, "{}", ty.print(cx.cache()));
3243                 }
3244                 w.write_str(")");
3245             }
3246             w.write_str("</code></div>");
3247             document(w, cx, variant, Some(it));
3248             document_non_exhaustive(w, variant);
3249
3250             use crate::clean::Variant;
3251             if let clean::VariantItem(Variant::Struct(ref s)) = *variant.kind {
3252                 let variant_id = cx.derive_id(format!(
3253                     "{}.{}.fields",
3254                     ItemType::Variant,
3255                     variant.name.as_ref().unwrap()
3256                 ));
3257                 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3258                 write!(
3259                     w,
3260                     "<h3>Fields of <b>{name}</b></h3><div>",
3261                     name = variant.name.as_ref().unwrap()
3262                 );
3263                 for field in &s.fields {
3264                     use crate::clean::StructFieldItem;
3265                     if let StructFieldItem(ref ty) = *field.kind {
3266                         let id = cx.derive_id(format!(
3267                             "variant.{}.field.{}",
3268                             variant.name.as_ref().unwrap(),
3269                             field.name.as_ref().unwrap()
3270                         ));
3271                         write!(
3272                             w,
3273                             "<span id=\"{id}\" class=\"variant small-section-header\">\
3274                                  <a href=\"#{id}\" class=\"anchor field\"></a>\
3275                                  <code>{f}:&nbsp;{t}</code>\
3276                              </span>",
3277                             id = id,
3278                             f = field.name.as_ref().unwrap(),
3279                             t = ty.print(cx.cache())
3280                         );
3281                         document(w, cx, field, Some(variant));
3282                     }
3283                 }
3284                 w.write_str("</div></div>");
3285             }
3286             render_stability_since(w, variant, it, cx.tcx());
3287         }
3288     }
3289     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3290 }
3291
3292 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3293     sym::export_name,
3294     sym::lang,
3295     sym::link_section,
3296     sym::must_use,
3297     sym::no_mangle,
3298     sym::repr,
3299     sym::non_exhaustive,
3300 ];
3301
3302 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3303 // left padding. For example:
3304 //
3305 // #[foo] <----- "top" attribute
3306 // struct Foo {
3307 //     #[bar] <---- not "top" attribute
3308 //     bar: usize,
3309 // }
3310 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3311     let attrs = it
3312         .attrs
3313         .other_attrs
3314         .iter()
3315         .filter_map(|attr| {
3316             if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3317                 Some(pprust::attribute_to_string(&attr))
3318             } else {
3319                 None
3320             }
3321         })
3322         .join("\n");
3323
3324     if !attrs.is_empty() {
3325         write!(
3326             w,
3327             "<span class=\"docblock attributes{}\">{}</span>",
3328             if top { " top-attr" } else { "" },
3329             &attrs
3330         );
3331     }
3332 }
3333
3334 fn render_struct(
3335     w: &mut Buffer,
3336     it: &clean::Item,
3337     g: Option<&clean::Generics>,
3338     ty: CtorKind,
3339     fields: &[clean::Item],
3340     tab: &str,
3341     structhead: bool,
3342     cx: &Context<'_>,
3343 ) {
3344     write!(
3345         w,
3346         "{}{}{}",
3347         it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3348         if structhead { "struct " } else { "" },
3349         it.name.as_ref().unwrap()
3350     );
3351     if let Some(g) = g {
3352         write!(w, "{}", g.print(cx.cache()))
3353     }
3354     match ty {
3355         CtorKind::Fictive => {
3356             if let Some(g) = g {
3357                 write!(
3358                     w,
3359                     "{}",
3360                     WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache())
3361                 )
3362             }
3363             let mut has_visible_fields = false;
3364             w.write_str(" {");
3365             for field in fields {
3366                 if let clean::StructFieldItem(ref ty) = *field.kind {
3367                     write!(
3368                         w,
3369                         "\n{}    {}{}: {},",
3370                         tab,
3371                         field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3372                         field.name.as_ref().unwrap(),
3373                         ty.print(cx.cache())
3374                     );
3375                     has_visible_fields = true;
3376                 }
3377             }
3378
3379             if has_visible_fields {
3380                 if it.has_stripped_fields().unwrap() {
3381                     write!(w, "\n{}    // some fields omitted", tab);
3382                 }
3383                 write!(w, "\n{}", tab);
3384             } else if it.has_stripped_fields().unwrap() {
3385                 // If there are no visible fields we can just display
3386                 // `{ /* fields omitted */ }` to save space.
3387                 write!(w, " /* fields omitted */ ");
3388             }
3389             w.write_str("}");
3390         }
3391         CtorKind::Fn => {
3392             w.write_str("(");
3393             for (i, field) in fields.iter().enumerate() {
3394                 if i > 0 {
3395                     w.write_str(", ");
3396                 }
3397                 match *field.kind {
3398                     clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3399                     clean::StructFieldItem(ref ty) => {
3400                         write!(
3401                             w,
3402                             "{}{}",
3403                             field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3404                             ty.print(cx.cache())
3405                         )
3406                     }
3407                     _ => unreachable!(),
3408                 }
3409             }
3410             w.write_str(")");
3411             if let Some(g) = g {
3412                 write!(
3413                     w,
3414                     "{}",
3415                     WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache())
3416                 )
3417             }
3418             w.write_str(";");
3419         }
3420         CtorKind::Const => {
3421             // Needed for PhantomData.
3422             if let Some(g) = g {
3423                 write!(
3424                     w,
3425                     "{}",
3426                     WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache())
3427                 )
3428             }
3429             w.write_str(";");
3430         }
3431     }
3432 }
3433
3434 fn render_union(
3435     w: &mut Buffer,
3436     it: &clean::Item,
3437     g: Option<&clean::Generics>,
3438     fields: &[clean::Item],
3439     tab: &str,
3440     structhead: bool,
3441     cx: &Context<'_>,
3442 ) {
3443     write!(
3444         w,
3445         "{}{}{}",
3446         it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3447         if structhead { "union " } else { "" },
3448         it.name.as_ref().unwrap()
3449     );
3450     if let Some(g) = g {
3451         write!(w, "{}", g.print(cx.cache()));
3452         write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache()));
3453     }
3454
3455     write!(w, " {{\n{}", tab);
3456     for field in fields {
3457         if let clean::StructFieldItem(ref ty) = *field.kind {
3458             write!(
3459                 w,
3460                 "    {}{}: {},\n{}",
3461                 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3462                 field.name.as_ref().unwrap(),
3463                 ty.print(cx.cache()),
3464                 tab
3465             );
3466         }
3467     }
3468
3469     if it.has_stripped_fields().unwrap() {
3470         write!(w, "    // some fields omitted\n{}", tab);
3471     }
3472     w.write_str("}");
3473 }
3474
3475 #[derive(Copy, Clone)]
3476 enum AssocItemLink<'a> {
3477     Anchor(Option<&'a str>),
3478     GotoSource(DefId, &'a FxHashSet<Symbol>),
3479 }
3480
3481 impl<'a> AssocItemLink<'a> {
3482     fn anchor(&self, id: &'a str) -> Self {
3483         match *self {
3484             AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3485             ref other => *other,
3486         }
3487     }
3488 }
3489
3490 fn render_assoc_items(
3491     w: &mut Buffer,
3492     cx: &Context<'_>,
3493     containing_item: &clean::Item,
3494     it: DefId,
3495     what: AssocItemRender<'_>,
3496 ) {
3497     info!("Documenting associated items of {:?}", containing_item.name);
3498     let v = match cx.cache.impls.get(&it) {
3499         Some(v) => v,
3500         None => return,
3501     };
3502     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3503     if !non_trait.is_empty() {
3504         let render_mode = match what {
3505             AssocItemRender::All => {
3506                 w.write_str(
3507                     "<h2 id=\"implementations\" class=\"small-section-header\">\
3508                          Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3509                     </h2>",
3510                 );
3511                 RenderMode::Normal
3512             }
3513             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3514                 let id = cx.derive_id(small_url_encode(format!(
3515                     "deref-methods-{:#}",
3516                     type_.print(cx.cache())
3517                 )));
3518                 debug!("Adding {} to deref id map", type_.print(cx.cache()));
3519                 cx.deref_id_map
3520                     .borrow_mut()
3521                     .insert(type_.def_id_full(cx.cache()).unwrap(), id.clone());
3522                 write!(
3523                     w,
3524                     "<h2 id=\"{id}\" class=\"small-section-header\">\
3525                          Methods from {trait_}&lt;Target = {type_}&gt;\
3526                          <a href=\"#{id}\" class=\"anchor\"></a>\
3527                      </h2>",
3528                     id = id,
3529                     trait_ = trait_.print(cx.cache()),
3530                     type_ = type_.print(cx.cache()),
3531                 );
3532                 RenderMode::ForDeref { mut_: deref_mut_ }
3533             }
3534         };
3535         for i in &non_trait {
3536             render_impl(
3537                 w,
3538                 cx,
3539                 i,
3540                 containing_item,
3541                 AssocItemLink::Anchor(None),
3542                 render_mode,
3543                 containing_item.stable_since(cx.tcx()).as_deref(),
3544                 containing_item.const_stable_since(cx.tcx()).as_deref(),
3545                 true,
3546                 None,
3547                 false,
3548                 true,
3549                 &[],
3550             );
3551         }
3552     }
3553     if !traits.is_empty() {
3554         let deref_impl = traits
3555             .iter()
3556             .find(|t| t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did);
3557         if let Some(impl_) = deref_impl {
3558             let has_deref_mut = traits.iter().any(|t| {
3559                 t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_mut_trait_did
3560             });
3561             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
3562         }
3563
3564         // If we were already one level into rendering deref methods, we don't want to render
3565         // anything after recursing into any further deref methods above.
3566         if let AssocItemRender::DerefFor { .. } = what {
3567             return;
3568         }
3569
3570         let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3571             traits.iter().partition(|t| t.inner_impl().synthetic);
3572         let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3573             concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3574
3575         let mut impls = Buffer::empty_from(&w);
3576         render_impls(cx, &mut impls, &concrete, containing_item);
3577         let impls = impls.into_inner();
3578         if !impls.is_empty() {
3579             write!(
3580                 w,
3581                 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3582                      Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3583                  </h2>\
3584                  <div id=\"trait-implementations-list\">{}</div>",
3585                 impls
3586             );
3587         }
3588
3589         if !synthetic.is_empty() {
3590             w.write_str(
3591                 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3592                      Auto Trait Implementations\
3593                      <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3594                  </h2>\
3595                  <div id=\"synthetic-implementations-list\">",
3596             );
3597             render_impls(cx, w, &synthetic, containing_item);
3598             w.write_str("</div>");
3599         }
3600
3601         if !blanket_impl.is_empty() {
3602             w.write_str(
3603                 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3604                      Blanket Implementations\
3605                      <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3606                  </h2>\
3607                  <div id=\"blanket-implementations-list\">",
3608             );
3609             render_impls(cx, w, &blanket_impl, containing_item);
3610             w.write_str("</div>");
3611         }
3612     }
3613 }
3614
3615 fn render_deref_methods(
3616     w: &mut Buffer,
3617     cx: &Context<'_>,
3618     impl_: &Impl,
3619     container_item: &clean::Item,
3620     deref_mut: bool,
3621 ) {
3622     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3623     let (target, real_target) = impl_
3624         .inner_impl()
3625         .items
3626         .iter()
3627         .find_map(|item| match *item.kind {
3628             clean::TypedefItem(ref t, true) => Some(match *t {
3629                 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3630                 _ => (&t.type_, &t.type_),
3631             }),
3632             _ => None,
3633         })
3634         .expect("Expected associated type binding");
3635     debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
3636     let what =
3637         AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3638     if let Some(did) = target.def_id_full(cx.cache()) {
3639         if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
3640             // `impl Deref<Target = S> for S`
3641             if did == type_did {
3642                 // Avoid infinite cycles
3643                 return;
3644             }
3645         }
3646         render_assoc_items(w, cx, container_item, did, what);
3647     } else {
3648         if let Some(prim) = target.primitive_type() {
3649             if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
3650                 render_assoc_items(w, cx, container_item, did, what);
3651             }
3652         }
3653     }
3654 }
3655
3656 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
3657     let self_type_opt = match *item.kind {
3658         clean::MethodItem(ref method, _) => method.decl.self_type(),
3659         clean::TyMethodItem(ref method) => method.decl.self_type(),
3660         _ => None,
3661     };
3662
3663     if let Some(self_ty) = self_type_opt {
3664         let (by_mut_ref, by_box, by_value) = match self_ty {
3665             SelfTy::SelfBorrowed(_, mutability)
3666             | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3667                 (mutability == Mutability::Mut, false, false)
3668             }
3669             SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3670                 (false, Some(did) == cache.owned_box_did, false)
3671             }
3672             SelfTy::SelfValue => (false, false, true),
3673             _ => (false, false, false),
3674         };
3675
3676         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3677     } else {
3678         false
3679     }
3680 }
3681
3682 fn spotlight_decl(decl: &clean::FnDecl, cache: &Cache) -> String {
3683     let mut out = Buffer::html();
3684     let mut trait_ = String::new();
3685
3686     if let Some(did) = decl.output.def_id_full(cache) {
3687         if let Some(impls) = cache.impls.get(&did) {
3688             for i in impls {
3689                 let impl_ = i.inner_impl();
3690                 if impl_.trait_.def_id_full(cache).map_or(false, |d| cache.traits[&d].is_spotlight)
3691                 {
3692                     if out.is_empty() {
3693                         write!(
3694                             &mut out,
3695                             "<h3 class=\"notable\">Notable traits for {}</h3>\
3696                              <code class=\"content\">",
3697                             impl_.for_.print(cache)
3698                         );
3699                         trait_.push_str(&impl_.for_.print(cache).to_string());
3700                     }
3701
3702                     //use the "where" class here to make it small
3703                     write!(
3704                         &mut out,
3705                         "<span class=\"where fmt-newline\">{}</span>",
3706                         impl_.print(cache, false)
3707                     );
3708                     let t_did = impl_.trait_.def_id_full(cache).unwrap();
3709                     for it in &impl_.items {
3710                         if let clean::TypedefItem(ref tydef, _) = *it.kind {
3711                             out.push_str("<span class=\"where fmt-newline\">    ");
3712                             assoc_type(
3713                                 &mut out,
3714                                 it,
3715                                 &[],
3716                                 Some(&tydef.type_),
3717                                 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3718                                 "",
3719                                 cache,
3720                             );
3721                             out.push_str(";</span>");
3722                         }
3723                     }
3724                 }
3725             }
3726         }
3727     }
3728
3729     if !out.is_empty() {
3730         out.insert_str(
3731             0,
3732             "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3733             <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3734         );
3735         out.push_str("</code></span></div></span></span>");
3736     }
3737
3738     out.into_inner()
3739 }
3740
3741 fn render_impl(
3742     w: &mut Buffer,
3743     cx: &Context<'_>,
3744     i: &Impl,
3745     parent: &clean::Item,
3746     link: AssocItemLink<'_>,
3747     render_mode: RenderMode,
3748     outer_version: Option<&str>,
3749     outer_const_version: Option<&str>,
3750     show_def_docs: bool,
3751     use_absolute: Option<bool>,
3752     is_on_foreign_type: bool,
3753     show_default_items: bool,
3754     // This argument is used to reference same type with different paths to avoid duplication
3755     // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3756     aliases: &[String],
3757 ) {
3758     let traits = &cx.cache.traits;
3759     let trait_ = i.trait_did_full(cx.cache()).map(|did| &traits[&did]);
3760
3761     if render_mode == RenderMode::Normal {
3762         let id = cx.derive_id(match i.inner_impl().trait_ {
3763             Some(ref t) => {
3764                 if is_on_foreign_type {
3765                     get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx.cache())
3766                 } else {
3767                     format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx.cache()))))
3768                 }
3769             }
3770             None => "impl".to_string(),
3771         });
3772         let aliases = if aliases.is_empty() {
3773             String::new()
3774         } else {
3775             format!(" aliases=\"{}\"", aliases.join(","))
3776         };
3777         if let Some(use_absolute) = use_absolute {
3778             write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3779             write!(w, "{}", i.inner_impl().print(cx.cache(), use_absolute));
3780             if show_def_docs {
3781                 for it in &i.inner_impl().items {
3782                     if let clean::TypedefItem(ref tydef, _) = *it.kind {
3783                         w.write_str("<span class=\"where fmt-newline\">  ");
3784                         assoc_type(
3785                             w,
3786                             it,
3787                             &[],
3788                             Some(&tydef.type_),
3789                             AssocItemLink::Anchor(None),
3790                             "",
3791                             cx.cache(),
3792                         );
3793                         w.write_str(";</span>");
3794                     }
3795                 }
3796             }
3797             w.write_str("</code>");
3798         } else {
3799             write!(
3800                 w,
3801                 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3802                 id,
3803                 aliases,
3804                 i.inner_impl().print(cx.cache(), false)
3805             );
3806         }
3807         write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3808         render_stability_since_raw(
3809             w,
3810             i.impl_item.stable_since(cx.tcx()).as_deref(),
3811             i.impl_item.const_stable_since(cx.tcx()).as_deref(),
3812             outer_version,
3813             outer_const_version,
3814         );
3815         write_srclink(cx, &i.impl_item, w);
3816         w.write_str("</h3>");
3817
3818         if trait_.is_some() {
3819             if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3820                 write!(w, "<div class=\"item-info\">{}</div>", portability);
3821             }
3822         }
3823
3824         if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3825             let mut ids = cx.id_map.borrow_mut();
3826             write!(
3827                 w,
3828                 "<div class=\"docblock\">{}</div>",
3829                 Markdown(
3830                     &*dox,
3831                     &i.impl_item.links(&cx.cache),
3832                     &mut ids,
3833                     cx.shared.codes,
3834                     cx.shared.edition,
3835                     &cx.shared.playground
3836                 )
3837                 .into_string()
3838             );
3839         }
3840     }
3841
3842     fn doc_impl_item(
3843         w: &mut Buffer,
3844         cx: &Context<'_>,
3845         item: &clean::Item,
3846         parent: &clean::Item,
3847         link: AssocItemLink<'_>,
3848         render_mode: RenderMode,
3849         is_default_item: bool,
3850         outer_version: Option<&str>,
3851         outer_const_version: Option<&str>,
3852         trait_: Option<&clean::Trait>,
3853         show_def_docs: bool,
3854     ) {
3855         let item_type = item.type_();
3856         let name = item.name.as_ref().unwrap();
3857
3858         let render_method_item = match render_mode {
3859             RenderMode::Normal => true,
3860             RenderMode::ForDeref { mut_: deref_mut_ } => {
3861                 should_render_item(&item, deref_mut_, &cx.cache)
3862             }
3863         };
3864
3865         let (is_hidden, extra_class) =
3866             if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3867                 && !is_default_item
3868             {
3869                 (false, "")
3870             } else {
3871                 (true, " hidden")
3872             };
3873         match *item.kind {
3874             clean::MethodItem(..) | clean::TyMethodItem(_) => {
3875                 // Only render when the method is not static or we allow static methods
3876                 if render_method_item {
3877                     let id = cx.derive_id(format!("{}.{}", item_type, name));
3878                     write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3879                     w.write_str("<code>");
3880                     render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx);
3881                     w.write_str("</code>");
3882                     render_stability_since_raw(
3883                         w,
3884                         item.stable_since(cx.tcx()).as_deref(),
3885                         item.const_stable_since(cx.tcx()).as_deref(),
3886                         outer_version,
3887                         outer_const_version,
3888                     );
3889                     write_srclink(cx, item, w);
3890                     w.write_str("</h4>");
3891                 }
3892             }
3893             clean::TypedefItem(ref tydef, _) => {
3894                 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3895                 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3896                 assoc_type(
3897                     w,
3898                     item,
3899                     &Vec::new(),
3900                     Some(&tydef.type_),
3901                     link.anchor(&id),
3902                     "",
3903                     cx.cache(),
3904                 );
3905                 w.write_str("</code></h4>");
3906             }
3907             clean::AssocConstItem(ref ty, ref default) => {
3908                 let id = cx.derive_id(format!("{}.{}", item_type, name));
3909                 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3910                 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "", cx);
3911                 w.write_str("</code>");
3912                 render_stability_since_raw(
3913                     w,
3914                     item.stable_since(cx.tcx()).as_deref(),
3915                     item.const_stable_since(cx.tcx()).as_deref(),
3916                     outer_version,
3917                     outer_const_version,
3918                 );
3919                 write_srclink(cx, item, w);
3920                 w.write_str("</h4>");
3921             }
3922             clean::AssocTypeItem(ref bounds, ref default) => {
3923                 let id = cx.derive_id(format!("{}.{}", item_type, name));
3924                 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3925                 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "", cx.cache());
3926                 w.write_str("</code></h4>");
3927             }
3928             clean::StrippedItem(..) => return,
3929             _ => panic!("can't make docs for trait item with name {:?}", item.name),
3930         }
3931
3932         if render_method_item {
3933             if !is_default_item {
3934                 if let Some(t) = trait_ {
3935                     // The trait item may have been stripped so we might not
3936                     // find any documentation or stability for it.
3937                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3938                         // We need the stability of the item from the trait
3939                         // because impls can't have a stability.
3940                         if item.doc_value().is_some() {
3941                             document_item_info(w, cx, it, is_hidden, Some(parent));
3942                             document_full(w, item, cx, "", is_hidden);
3943                         } else {
3944                             // In case the item isn't documented,
3945                             // provide short documentation from the trait.
3946                             document_short(
3947                                 w,
3948                                 it,
3949                                 cx,
3950                                 link,
3951                                 "",
3952                                 is_hidden,
3953                                 Some(parent),
3954                                 show_def_docs,
3955                             );
3956                         }
3957                     }
3958                 } else {
3959                     document_item_info(w, cx, item, is_hidden, Some(parent));
3960                     if show_def_docs {
3961                         document_full(w, item, cx, "", is_hidden);
3962                     }
3963                 }
3964             } else {
3965                 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3966             }
3967         }
3968     }
3969
3970     w.write_str("<div class=\"impl-items\">");
3971     for trait_item in &i.inner_impl().items {
3972         doc_impl_item(
3973             w,
3974             cx,
3975             trait_item,
3976             if trait_.is_some() { &i.impl_item } else { parent },
3977             link,
3978             render_mode,
3979             false,
3980             outer_version,
3981             outer_const_version,
3982             trait_,
3983             show_def_docs,
3984         );
3985     }
3986
3987     fn render_default_items(
3988         w: &mut Buffer,
3989         cx: &Context<'_>,
3990         t: &clean::Trait,
3991         i: &clean::Impl,
3992         parent: &clean::Item,
3993         render_mode: RenderMode,
3994         outer_version: Option<&str>,
3995         outer_const_version: Option<&str>,
3996         show_def_docs: bool,
3997     ) {
3998         for trait_item in &t.items {
3999             let n = trait_item.name;
4000             if i.items.iter().any(|m| m.name == n) {
4001                 continue;
4002             }
4003             let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
4004             let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4005
4006             doc_impl_item(
4007                 w,
4008                 cx,
4009                 trait_item,
4010                 parent,
4011                 assoc_link,
4012                 render_mode,
4013                 true,
4014                 outer_version,
4015                 outer_const_version,
4016                 None,
4017                 show_def_docs,
4018             );
4019         }
4020     }
4021
4022     // If we've implemented a trait, then also emit documentation for all
4023     // default items which weren't overridden in the implementation block.
4024     // We don't emit documentation for default items if they appear in the
4025     // Implementations on Foreign Types or Implementors sections.
4026     if show_default_items {
4027         if let Some(t) = trait_ {
4028             render_default_items(
4029                 w,
4030                 cx,
4031                 t,
4032                 &i.inner_impl(),
4033                 &i.impl_item,
4034                 render_mode,
4035                 outer_version,
4036                 outer_const_version,
4037                 show_def_docs,
4038             );
4039         }
4040     }
4041     w.write_str("</div>");
4042 }
4043
4044 fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
4045     w.write_str("<pre class=\"rust opaque\">");
4046     render_attributes(w, it, false);
4047     write!(
4048         w,
4049         "type {}{}{where_clause} = impl {bounds};</pre>",
4050         it.name.as_ref().unwrap(),
4051         t.generics.print(cx.cache()),
4052         where_clause =
4053             WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4054         bounds = bounds(&t.bounds, false, cx.cache())
4055     );
4056
4057     document(w, cx, it, None);
4058
4059     // Render any items associated directly to this alias, as otherwise they
4060     // won't be visible anywhere in the docs. It would be nice to also show
4061     // associated items from the aliased type (see discussion in #32077), but
4062     // we need #14072 to make sense of the generics.
4063     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4064 }
4065
4066 fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
4067     w.write_str("<pre class=\"rust trait-alias\">");
4068     render_attributes(w, it, false);
4069     write!(
4070         w,
4071         "trait {}{}{} = {};</pre>",
4072         it.name.as_ref().unwrap(),
4073         t.generics.print(cx.cache()),
4074         WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4075         bounds(&t.bounds, true, cx.cache())
4076     );
4077
4078     document(w, cx, it, None);
4079
4080     // Render any items associated directly to this alias, as otherwise they
4081     // won't be visible anywhere in the docs. It would be nice to also show
4082     // associated items from the aliased type (see discussion in #32077), but
4083     // we need #14072 to make sense of the generics.
4084     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4085 }
4086
4087 fn item_typedef(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
4088     w.write_str("<pre class=\"rust typedef\">");
4089     render_attributes(w, it, false);
4090     write!(
4091         w,
4092         "type {}{}{where_clause} = {type_};</pre>",
4093         it.name.as_ref().unwrap(),
4094         t.generics.print(cx.cache()),
4095         where_clause =
4096             WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4097         type_ = t.type_.print(cx.cache())
4098     );
4099
4100     document(w, cx, it, None);
4101
4102     // Render any items associated directly to this alias, as otherwise they
4103     // won't be visible anywhere in the docs. It would be nice to also show
4104     // associated items from the aliased type (see discussion in #32077), but
4105     // we need #14072 to make sense of the generics.
4106     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4107 }
4108
4109 fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4110     w.write_str("<pre class=\"rust foreigntype\">extern {\n");
4111     render_attributes(w, it, false);
4112     write!(
4113         w,
4114         "    {}type {};\n}}</pre>",
4115         it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
4116         it.name.as_ref().unwrap(),
4117     );
4118
4119     document(w, cx, it, None);
4120
4121     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4122 }
4123
4124 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
4125     let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4126
4127     if it.is_struct()
4128         || it.is_trait()
4129         || it.is_primitive()
4130         || it.is_union()
4131         || it.is_enum()
4132         || it.is_mod()
4133         || it.is_typedef()
4134     {
4135         write!(
4136             buffer,
4137             "<p class=\"location\">{}{}</p>",
4138             match *it.kind {
4139                 clean::StructItem(..) => "Struct ",
4140                 clean::TraitItem(..) => "Trait ",
4141                 clean::PrimitiveItem(..) => "Primitive Type ",
4142                 clean::UnionItem(..) => "Union ",
4143                 clean::EnumItem(..) => "Enum ",
4144                 clean::TypedefItem(..) => "Type Definition ",
4145                 clean::ForeignTypeItem => "Foreign Type ",
4146                 clean::ModuleItem(..) =>
4147                     if it.is_crate() {
4148                         "Crate "
4149                     } else {
4150                         "Module "
4151                     },
4152                 _ => "",
4153             },
4154             it.name.as_ref().unwrap()
4155         );
4156     }
4157
4158     if it.is_crate() {
4159         if let Some(ref version) = cx.cache.crate_version {
4160             write!(
4161                 buffer,
4162                 "<div class=\"block version\">\
4163                      <p>Version {}</p>\
4164                  </div>",
4165                 Escape(version)
4166             );
4167         }
4168     }
4169
4170     buffer.write_str("<div class=\"sidebar-elems\">");
4171     if it.is_crate() {
4172         write!(
4173             buffer,
4174             "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4175             it.name.as_ref().expect("crates always have a name")
4176         );
4177     }
4178     match *it.kind {
4179         clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
4180         clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
4181         clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
4182         clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
4183         clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
4184         clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
4185         clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4186         clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
4187         _ => (),
4188     }
4189
4190     // The sidebar is designed to display sibling functions, modules and
4191     // other miscellaneous information. since there are lots of sibling
4192     // items (and that causes quadratic growth in large modules),
4193     // we refactor common parts into a shared JavaScript file per module.
4194     // still, we don't move everything into JS because we want to preserve
4195     // as much HTML as possible in order to allow non-JS-enabled browsers
4196     // to navigate the documentation (though slightly inefficiently).
4197
4198     buffer.write_str("<p class=\"location\">");
4199     for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4200         if i > 0 {
4201             buffer.write_str("::<wbr>");
4202         }
4203         write!(
4204             buffer,
4205             "<a href=\"{}index.html\">{}</a>",
4206             &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4207             *name
4208         );
4209     }
4210     buffer.write_str("</p>");
4211
4212     // Sidebar refers to the enclosing module, not this module.
4213     let relpath = if it.is_mod() { "../" } else { "" };
4214     write!(
4215         buffer,
4216         "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
4217         </div>",
4218         name = it.name.unwrap_or(kw::Empty),
4219         ty = it.type_(),
4220         path = relpath
4221     );
4222     if parentlen == 0 {
4223         // There is no sidebar-items.js beyond the crate root path
4224         // FIXME maybe dynamic crate loading can be merged here
4225     } else {
4226         write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4227     }
4228     // Closes sidebar-elems div.
4229     buffer.write_str("</div>");
4230 }
4231
4232 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4233     if used_links.insert(url.clone()) {
4234         return url;
4235     }
4236     let mut add = 1;
4237     while !used_links.insert(format!("{}-{}", url, add)) {
4238         add += 1;
4239     }
4240     format!("{}-{}", url, add)
4241 }
4242
4243 fn get_methods(
4244     i: &clean::Impl,
4245     for_deref: bool,
4246     used_links: &mut FxHashSet<String>,
4247     deref_mut: bool,
4248     cache: &Cache,
4249 ) -> Vec<String> {
4250     i.items
4251         .iter()
4252         .filter_map(|item| match item.name {
4253             Some(ref name) if !name.is_empty() && item.is_method() => {
4254                 if !for_deref || should_render_item(item, deref_mut, cache) {
4255                     Some(format!(
4256                         "<a href=\"#{}\">{}</a>",
4257                         get_next_url(used_links, format!("method.{}", name)),
4258                         name
4259                     ))
4260                 } else {
4261                     None
4262                 }
4263             }
4264             _ => None,
4265         })
4266         .collect::<Vec<_>>()
4267 }
4268
4269 // The point is to url encode any potential character from a type with genericity.
4270 fn small_url_encode(s: String) -> String {
4271     let mut st = String::new();
4272     let mut last_match = 0;
4273     for (idx, c) in s.char_indices() {
4274         let escaped = match c {
4275             '<' => "%3C",
4276             '>' => "%3E",
4277             ' ' => "%20",
4278             '?' => "%3F",
4279             '\'' => "%27",
4280             '&' => "%26",
4281             ',' => "%2C",
4282             ':' => "%3A",
4283             ';' => "%3B",
4284             '[' => "%5B",
4285             ']' => "%5D",
4286             '"' => "%22",
4287             _ => continue,
4288         };
4289
4290         st += &s[last_match..idx];
4291         st += escaped;
4292         // NOTE: we only expect single byte characters here - which is fine as long as we
4293         // only match single byte characters
4294         last_match = idx + 1;
4295     }
4296
4297     if last_match != 0 {
4298         st += &s[last_match..];
4299         st
4300     } else {
4301         s
4302     }
4303 }
4304
4305 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
4306     if let Some(v) = cx.cache.impls.get(&it.def_id) {
4307         let mut used_links = FxHashSet::default();
4308
4309         {
4310             let used_links_bor = &mut used_links;
4311             let mut ret = v
4312                 .iter()
4313                 .filter(|i| i.inner_impl().trait_.is_none())
4314                 .flat_map(move |i| {
4315                     get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
4316                 })
4317                 .collect::<Vec<_>>();
4318             if !ret.is_empty() {
4319                 // We want links' order to be reproducible so we don't use unstable sort.
4320                 ret.sort();
4321
4322                 out.push_str(
4323                     "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4324                      <div class=\"sidebar-links\">",
4325                 );
4326                 for line in ret {
4327                     out.push_str(&line);
4328                 }
4329                 out.push_str("</div>");
4330             }
4331         }
4332
4333         if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4334             if let Some(impl_) = v
4335                 .iter()
4336                 .filter(|i| i.inner_impl().trait_.is_some())
4337                 .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did)
4338             {
4339                 sidebar_deref_methods(cx, out, impl_, v);
4340             }
4341             let format_impls = |impls: Vec<&Impl>| {
4342                 let mut links = FxHashSet::default();
4343
4344                 let mut ret = impls
4345                     .iter()
4346                     .filter_map(|it| {
4347                         if let Some(ref i) = it.inner_impl().trait_ {
4348                             let i_display = format!("{:#}", i.print(cx.cache()));
4349                             let out = Escape(&i_display);
4350                             let encoded = small_url_encode(format!("{:#}", i.print(cx.cache())));
4351                             let generated = format!(
4352                                 "<a href=\"#impl-{}\">{}{}</a>",
4353                                 encoded,
4354                                 if it.inner_impl().negative_polarity { "!" } else { "" },
4355                                 out
4356                             );
4357                             if links.insert(generated.clone()) { Some(generated) } else { None }
4358                         } else {
4359                             None
4360                         }
4361                     })
4362                     .collect::<Vec<String>>();
4363                 ret.sort();
4364                 ret
4365             };
4366
4367             let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
4368                 out.push_str("<div class=\"sidebar-links\">");
4369                 for link in links {
4370                     out.push_str(&link);
4371                 }
4372                 out.push_str("</div>");
4373             };
4374
4375             let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4376                 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4377             let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4378                 .into_iter()
4379                 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4380
4381             let concrete_format = format_impls(concrete);
4382             let synthetic_format = format_impls(synthetic);
4383             let blanket_format = format_impls(blanket_impl);
4384
4385             if !concrete_format.is_empty() {
4386                 out.push_str(
4387                     "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4388                         Trait Implementations</a>",
4389                 );
4390                 write_sidebar_links(out, concrete_format);
4391             }
4392
4393             if !synthetic_format.is_empty() {
4394                 out.push_str(
4395                     "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4396                         Auto Trait Implementations</a>",
4397                 );
4398                 write_sidebar_links(out, synthetic_format);
4399             }
4400
4401             if !blanket_format.is_empty() {
4402                 out.push_str(
4403                     "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4404                         Blanket Implementations</a>",
4405                 );
4406                 write_sidebar_links(out, blanket_format);
4407             }
4408         }
4409     }
4410 }
4411
4412 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
4413     let c = cx.cache();
4414
4415     debug!("found Deref: {:?}", impl_);
4416     if let Some((target, real_target)) =
4417         impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
4418             clean::TypedefItem(ref t, true) => Some(match *t {
4419                 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4420                 _ => (&t.type_, &t.type_),
4421             }),
4422             _ => None,
4423         })
4424     {
4425         debug!("found target, real_target: {:?} {:?}", target, real_target);
4426         if let Some(did) = target.def_id_full(cx.cache()) {
4427             if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
4428                 // `impl Deref<Target = S> for S`
4429                 if did == type_did {
4430                     // Avoid infinite cycles
4431                     return;
4432                 }
4433             }
4434         }
4435         let deref_mut = v
4436             .iter()
4437             .filter(|i| i.inner_impl().trait_.is_some())
4438             .any(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_mut_trait_did);
4439         let inner_impl = target
4440             .def_id_full(cx.cache())
4441             .or_else(|| {
4442                 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
4443             })
4444             .and_then(|did| c.impls.get(&did));
4445         if let Some(impls) = inner_impl {
4446             debug!("found inner_impl: {:?}", impls);
4447             let mut used_links = FxHashSet::default();
4448             let mut ret = impls
4449                 .iter()
4450                 .filter(|i| i.inner_impl().trait_.is_none())
4451                 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
4452                 .collect::<Vec<_>>();
4453             if !ret.is_empty() {
4454                 let deref_id_map = cx.deref_id_map.borrow();
4455                 let id = deref_id_map
4456                     .get(&real_target.def_id_full(cx.cache()).unwrap())
4457                     .expect("Deref section without derived id");
4458                 write!(
4459                     out,
4460                     "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}&lt;Target={}&gt;</a>",
4461                     id,
4462                     Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(c))),
4463                     Escape(&format!("{:#}", real_target.print(c))),
4464                 );
4465                 // We want links' order to be reproducible so we don't use unstable sort.
4466                 ret.sort();
4467                 out.push_str("<div class=\"sidebar-links\">");
4468                 for link in ret {
4469                     out.push_str(&link);
4470                 }
4471                 out.push_str("</div>");
4472             }
4473         }
4474
4475         // Recurse into any further impls that might exist for `target`
4476         if let Some(target_did) = target.def_id_full(cx.cache()) {
4477             if let Some(target_impls) = c.impls.get(&target_did) {
4478                 if let Some(target_deref_impl) = target_impls
4479                     .iter()
4480                     .filter(|i| i.inner_impl().trait_.is_some())
4481                     .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_trait_did)
4482                 {
4483                     sidebar_deref_methods(cx, out, target_deref_impl, target_impls);
4484                 }
4485             }
4486         }
4487     }
4488 }
4489
4490 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4491     let mut sidebar = Buffer::new();
4492     let fields = get_struct_fields_name(&s.fields);
4493
4494     if !fields.is_empty() {
4495         if let CtorKind::Fictive = s.struct_type {
4496             sidebar.push_str(
4497                 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4498                 <div class=\"sidebar-links\">",
4499             );
4500
4501             for field in fields {
4502                 sidebar.push_str(&field);
4503             }
4504
4505             sidebar.push_str("</div>");
4506         }
4507     }
4508
4509     sidebar_assoc_items(cx, &mut sidebar, it);
4510
4511     if !sidebar.is_empty() {
4512         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4513     }
4514 }
4515
4516 fn get_id_for_impl_on_foreign_type(
4517     for_: &clean::Type,
4518     trait_: &clean::Type,
4519     cache: &Cache,
4520 ) -> String {
4521     small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cache), for_.print(cache)))
4522 }
4523
4524 fn extract_for_impl_name(item: &clean::Item, cache: &Cache) -> Option<(String, String)> {
4525     match *item.kind {
4526         clean::ItemKind::ImplItem(ref i) => {
4527             if let Some(ref trait_) = i.trait_ {
4528                 Some((
4529                     format!("{:#}", i.for_.print(cache)),
4530                     get_id_for_impl_on_foreign_type(&i.for_, trait_, cache),
4531                 ))
4532             } else {
4533                 None
4534             }
4535         }
4536         _ => None,
4537     }
4538 }
4539
4540 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4541     buf.write_str("<div class=\"block items\">");
4542
4543     fn print_sidebar_section(
4544         out: &mut Buffer,
4545         items: &[clean::Item],
4546         before: &str,
4547         filter: impl Fn(&clean::Item) -> bool,
4548         write: impl Fn(&mut Buffer, &Symbol),
4549         after: &str,
4550     ) {
4551         let mut items = items
4552             .iter()
4553             .filter_map(|m| match m.name {
4554                 Some(ref name) if filter(m) => Some(name),
4555                 _ => None,
4556             })
4557             .collect::<Vec<_>>();
4558
4559         if !items.is_empty() {
4560             items.sort();
4561             out.push_str(before);
4562             for item in items.into_iter() {
4563                 write(out, item);
4564             }
4565             out.push_str(after);
4566         }
4567     }
4568
4569     print_sidebar_section(
4570         buf,
4571         &t.items,
4572         "<a class=\"sidebar-title\" href=\"#associated-types\">\
4573             Associated Types</a><div class=\"sidebar-links\">",
4574         |m| m.is_associated_type(),
4575         |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
4576         "</div>",
4577     );
4578
4579     print_sidebar_section(
4580         buf,
4581         &t.items,
4582         "<a class=\"sidebar-title\" href=\"#associated-const\">\
4583             Associated Constants</a><div class=\"sidebar-links\">",
4584         |m| m.is_associated_const(),
4585         |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
4586         "</div>",
4587     );
4588
4589     print_sidebar_section(
4590         buf,
4591         &t.items,
4592         "<a class=\"sidebar-title\" href=\"#required-methods\">\
4593             Required Methods</a><div class=\"sidebar-links\">",
4594         |m| m.is_ty_method(),
4595         |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
4596         "</div>",
4597     );
4598
4599     print_sidebar_section(
4600         buf,
4601         &t.items,
4602         "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4603             Provided Methods</a><div class=\"sidebar-links\">",
4604         |m| m.is_method(),
4605         |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
4606         "</div>",
4607     );
4608
4609     if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
4610         let mut res = implementors
4611             .iter()
4612             .filter(|i| {
4613                 i.inner_impl()
4614                     .for_
4615                     .def_id_full(cx.cache())
4616                     .map_or(false, |d| !cx.cache.paths.contains_key(&d))
4617             })
4618             .filter_map(|i| extract_for_impl_name(&i.impl_item, cx.cache()))
4619             .collect::<Vec<_>>();
4620
4621         if !res.is_empty() {
4622             res.sort();
4623             buf.push_str(
4624                 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4625                     Implementations on Foreign Types</a>\
4626                  <div class=\"sidebar-links\">",
4627             );
4628             for (name, id) in res.into_iter() {
4629                 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
4630             }
4631             buf.push_str("</div>");
4632         }
4633     }
4634
4635     sidebar_assoc_items(cx, buf, it);
4636
4637     buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4638     if t.is_auto {
4639         buf.push_str(
4640             "<a class=\"sidebar-title\" \
4641                 href=\"#synthetic-implementors\">Auto Implementors</a>",
4642         );
4643     }
4644
4645     buf.push_str("</div>")
4646 }
4647
4648 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4649     let mut sidebar = Buffer::new();
4650     sidebar_assoc_items(cx, &mut sidebar, it);
4651
4652     if !sidebar.is_empty() {
4653         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4654     }
4655 }
4656
4657 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4658     let mut sidebar = Buffer::new();
4659     sidebar_assoc_items(cx, &mut sidebar, it);
4660
4661     if !sidebar.is_empty() {
4662         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4663     }
4664 }
4665
4666 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
4667     let mut fields = fields
4668         .iter()
4669         .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
4670         .filter_map(|f| {
4671             f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4672         })
4673         .collect::<Vec<_>>();
4674     fields.sort();
4675     fields
4676 }
4677
4678 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4679     let mut sidebar = Buffer::new();
4680     let fields = get_struct_fields_name(&u.fields);
4681
4682     if !fields.is_empty() {
4683         sidebar.push_str(
4684             "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4685             <div class=\"sidebar-links\">",
4686         );
4687
4688         for field in fields {
4689             sidebar.push_str(&field);
4690         }
4691
4692         sidebar.push_str("</div>");
4693     }
4694
4695     sidebar_assoc_items(cx, &mut sidebar, it);
4696
4697     if !sidebar.is_empty() {
4698         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4699     }
4700 }
4701
4702 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4703     let mut sidebar = Buffer::new();
4704
4705     let mut variants = e
4706         .variants
4707         .iter()
4708         .filter_map(|v| match v.name {
4709             Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4710             _ => None,
4711         })
4712         .collect::<Vec<_>>();
4713     if !variants.is_empty() {
4714         variants.sort_unstable();
4715         sidebar.push_str(&format!(
4716             "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4717              <div class=\"sidebar-links\">{}</div>",
4718             variants.join(""),
4719         ));
4720     }
4721
4722     sidebar_assoc_items(cx, &mut sidebar, it);
4723
4724     if !sidebar.is_empty() {
4725         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4726     }
4727 }
4728
4729 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4730     match *ty {
4731         ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4732         ItemType::Module => ("modules", "Modules"),
4733         ItemType::Struct => ("structs", "Structs"),
4734         ItemType::Union => ("unions", "Unions"),
4735         ItemType::Enum => ("enums", "Enums"),
4736         ItemType::Function => ("functions", "Functions"),
4737         ItemType::Typedef => ("types", "Type Definitions"),
4738         ItemType::Static => ("statics", "Statics"),
4739         ItemType::Constant => ("constants", "Constants"),
4740         ItemType::Trait => ("traits", "Traits"),
4741         ItemType::Impl => ("impls", "Implementations"),
4742         ItemType::TyMethod => ("tymethods", "Type Methods"),
4743         ItemType::Method => ("methods", "Methods"),
4744         ItemType::StructField => ("fields", "Struct Fields"),
4745         ItemType::Variant => ("variants", "Variants"),
4746         ItemType::Macro => ("macros", "Macros"),
4747         ItemType::Primitive => ("primitives", "Primitive Types"),
4748         ItemType::AssocType => ("associated-types", "Associated Types"),
4749         ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4750         ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4751         ItemType::Keyword => ("keywords", "Keywords"),
4752         ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4753         ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4754         ItemType::ProcDerive => ("derives", "Derive Macros"),
4755         ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4756     }
4757 }
4758
4759 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4760     let mut sidebar = String::new();
4761
4762     if items.iter().any(|it| {
4763         it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4764     }) {
4765         sidebar.push_str("<li><a href=\"#reexports\">Re-exports</a></li>");
4766     }
4767
4768     // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4769     // to print its headings
4770     for &myty in &[
4771         ItemType::Primitive,
4772         ItemType::Module,
4773         ItemType::Macro,
4774         ItemType::Struct,
4775         ItemType::Enum,
4776         ItemType::Constant,
4777         ItemType::Static,
4778         ItemType::Trait,
4779         ItemType::Function,
4780         ItemType::Typedef,
4781         ItemType::Union,
4782         ItemType::Impl,
4783         ItemType::TyMethod,
4784         ItemType::Method,
4785         ItemType::StructField,
4786         ItemType::Variant,
4787         ItemType::AssocType,
4788         ItemType::AssocConst,
4789         ItemType::ForeignType,
4790         ItemType::Keyword,
4791     ] {
4792         if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4793             let (short, name) = item_ty_to_strs(&myty);
4794             sidebar.push_str(&format!(
4795                 "<li><a href=\"#{id}\">{name}</a></li>",
4796                 id = short,
4797                 name = name
4798             ));
4799         }
4800     }
4801
4802     if !sidebar.is_empty() {
4803         write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4804     }
4805 }
4806
4807 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4808     let mut sidebar = Buffer::new();
4809     sidebar_assoc_items(cx, &mut sidebar, it);
4810
4811     if !sidebar.is_empty() {
4812         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4813     }
4814 }
4815
4816 fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
4817     wrap_into_docblock(w, |w| {
4818         highlight::render_with_highlighting(
4819             &t.source,
4820             w,
4821             Some("macro"),
4822             None,
4823             None,
4824             it.source.span().edition(),
4825         );
4826     });
4827     document(w, cx, it, None)
4828 }
4829
4830 fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
4831     let name = it.name.as_ref().expect("proc-macros always have names");
4832     match m.kind {
4833         MacroKind::Bang => {
4834             w.push_str("<pre class=\"rust macro\">");
4835             write!(w, "{}!() {{ /* proc-macro */ }}", name);
4836             w.push_str("</pre>");
4837         }
4838         MacroKind::Attr => {
4839             w.push_str("<pre class=\"rust attr\">");
4840             write!(w, "#[{}]", name);
4841             w.push_str("</pre>");
4842         }
4843         MacroKind::Derive => {
4844             w.push_str("<pre class=\"rust derive\">");
4845             write!(w, "#[derive({})]", name);
4846             if !m.helpers.is_empty() {
4847                 w.push_str("\n{\n");
4848                 w.push_str("    // Attributes available to this derive:\n");
4849                 for attr in &m.helpers {
4850                     writeln!(w, "    #[{}]", attr);
4851                 }
4852                 w.push_str("}\n");
4853             }
4854             w.push_str("</pre>");
4855         }
4856     }
4857     document(w, cx, it, None)
4858 }
4859
4860 fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4861     document(w, cx, it, None);
4862     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4863 }
4864
4865 fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4866     document(w, cx, it, None)
4867 }
4868
4869 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4870
4871 fn make_item_keywords(it: &clean::Item) -> String {
4872     format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4873 }
4874
4875 /// Returns a list of all paths used in the type.
4876 /// This is used to help deduplicate imported impls
4877 /// for reexported types. If any of the contained
4878 /// types are re-exported, we don't use the corresponding
4879 /// entry from the js file, as inlining will have already
4880 /// picked up the impl
4881 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
4882     let mut out = Vec::new();
4883     let mut visited = FxHashSet::default();
4884     let mut work = VecDeque::new();
4885
4886     work.push_back(first_ty);
4887
4888     while let Some(ty) = work.pop_front() {
4889         if !visited.insert(ty.clone()) {
4890             continue;
4891         }
4892
4893         match ty {
4894             clean::Type::ResolvedPath { did, .. } => {
4895                 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4896                 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4897
4898                 if let Some(path) = fqp {
4899                     out.push(path.join("::"));
4900                 }
4901             }
4902             clean::Type::Tuple(tys) => {
4903                 work.extend(tys.into_iter());
4904             }
4905             clean::Type::Slice(ty) => {
4906                 work.push_back(*ty);
4907             }
4908             clean::Type::Array(ty, _) => {
4909                 work.push_back(*ty);
4910             }
4911             clean::Type::RawPointer(_, ty) => {
4912                 work.push_back(*ty);
4913             }
4914             clean::Type::BorrowedRef { type_, .. } => {
4915                 work.push_back(*type_);
4916             }
4917             clean::Type::QPath { self_type, trait_, .. } => {
4918                 work.push_back(*self_type);
4919                 work.push_back(*trait_);
4920             }
4921             _ => {}
4922         }
4923     }
4924     out
4925 }