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