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