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