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