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