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