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