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