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