1 // ignore-tidy-filelength
3 //! Rustdoc's HTML rendering module.
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.
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
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).
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.
34 use std::cell::{Cell, RefCell};
35 use std::cmp::Ordering;
36 use std::collections::{BTreeMap, VecDeque};
37 use std::default::Default;
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};
46 use std::string::ToString;
47 use std::sync::mpsc::{channel, Receiver};
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;
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};
66 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, RenderedLink, SelfTy, TypeKind};
67 use crate::config::{RenderInfo, RenderOptions};
68 use crate::docfs::{DocFS, PathError};
70 use crate::error::Error;
71 use crate::formats::cache::{cache, Cache};
72 use crate::formats::item_type::ItemType;
73 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
74 use crate::html::escape::Escape;
75 use crate::html::format::fmt_impl_for_trait_page;
76 use crate::html::format::Function;
77 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
78 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
79 use crate::html::markdown::{self, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine};
80 use crate::html::sources;
81 use crate::html::{highlight, layout, static_files};
82 use cache::{build_index, ExternalLocation};
84 /// A pair of name and its optional document.
85 pub type NameDoc = (String, Option<String>);
87 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
88 crate::html::format::display_fn(move |f| {
89 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
93 /// Major driving force in all rustdoc rendering. This contains information
94 /// about where in the tree-like hierarchy rendering is occurring and controls
95 /// how the current page is being rendered.
97 /// It is intended that this context is a lightweight object which can be fairly
98 /// easily cloned because it is cloned per work-job (about once per item in the
101 crate struct Context {
102 /// Current hierarchy of components leading down to what's currently being
104 pub current: Vec<String>,
105 /// The current destination folder of where HTML artifacts should be placed.
106 /// This changes as the context descends into the module hierarchy.
108 /// A flag, which when `true`, will render pages which redirect to the
109 /// real location of an item. This is used to allow external links to
110 /// publicly reused items to redirect to the right location.
111 pub render_redirect_pages: bool,
112 /// The map used to ensure all generated 'id=' attributes are unique.
113 id_map: Rc<RefCell<IdMap>>,
114 pub shared: Arc<SharedContext>,
115 all: Rc<RefCell<AllTypes>>,
116 /// Storage for the errors produced while generating documentation so they
117 /// can be printed together at the end.
118 pub errors: Rc<Receiver<String>>,
121 crate struct SharedContext {
122 /// The path to the crate root source minus the file name.
123 /// Used for simplifying paths to the highlighted source code files.
124 pub src_root: PathBuf,
125 /// This describes the layout of each page, and is not modified after
126 /// creation of the context (contains info like the favicon and added html).
127 pub layout: layout::Layout,
128 /// This flag indicates whether `[src]` links should be generated or not. If
129 /// the source files are present in the html rendering, then this will be
131 pub include_sources: bool,
132 /// The local file sources we've emitted and their respective url-paths.
133 pub local_sources: FxHashMap<PathBuf, String>,
134 /// Whether the collapsed pass ran
136 /// The base-URL of the issue tracker for when an item has been tagged with
138 pub issue_tracker_base_url: Option<String>,
139 /// The directories that have already been created in this doc run. Used to reduce the number
140 /// of spurious `create_dir_all` calls.
141 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
142 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
143 /// should be ordered alphabetically or in order of appearance (in the source code).
144 pub sort_modules_alphabetically: bool,
145 /// Additional CSS files to be added to the generated docs.
146 pub style_files: Vec<StylePath>,
147 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
149 pub resource_suffix: String,
150 /// Optional path string to be used to load static files on output pages. If not set, uses
151 /// combinations of `../` to reach the documentation root.
152 pub static_root_path: Option<String>,
153 /// The fs handle we are working with.
155 /// The default edition used to parse doctests.
156 pub edition: Edition,
157 pub codes: ErrorCodes,
158 playground: Option<markdown::Playground>,
162 fn path(&self, filename: &str) -> PathBuf {
163 // We use splitn vs Path::extension here because we might get a filename
164 // like `style.min.css` and we want to process that into
165 // `style-suffix.min.css`. Path::extension would just return `css`
166 // which would result in `style.min-suffix.css` which isn't what we
168 let mut iter = filename.splitn(2, '.');
169 let base = iter.next().unwrap();
170 let ext = iter.next().unwrap();
171 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext,);
172 self.dst.join(&filename)
177 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
178 let mut dirs = self.created_dirs.borrow_mut();
179 if !dirs.contains(dst) {
180 try_err!(self.fs.create_dir_all(dst), dst);
181 dirs.insert(dst.to_path_buf());
187 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
188 /// `collapsed_doc_value` of the given item.
189 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
191 item.collapsed_doc_value().map(|s| s.into())
193 item.doc_value().map(|s| s.into())
198 // Helper structs for rendering items/sidebars and carrying along contextual
201 /// Struct representing one entry in the JS search index. These are all emitted
202 /// by hand to a large JS file at the end of cache-creation.
204 pub struct IndexItem {
209 pub parent: Option<DefId>,
210 pub parent_idx: Option<usize>,
211 pub search_type: Option<IndexItemFunctionType>,
214 impl Serialize for IndexItem {
215 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
220 self.parent.is_some(),
221 self.parent_idx.is_some(),
222 "`{}` is missing idx",
226 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
227 .serialize(serializer)
231 /// A type used for the search index.
233 crate struct RenderType {
236 name: Option<String>,
237 generics: Option<Vec<Generic>>,
240 impl Serialize for RenderType {
241 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
245 if let Some(name) = &self.name {
246 let mut seq = serializer.serialize_seq(None)?;
247 if let Some(id) = self.idx {
248 seq.serialize_element(&id)?;
250 seq.serialize_element(&name)?;
252 if let Some(generics) = &self.generics {
253 seq.serialize_element(&generics)?;
257 serializer.serialize_none()
262 /// A type used for the search index.
264 crate struct Generic {
266 defid: Option<DefId>,
270 impl Serialize for Generic {
271 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
275 if let Some(id) = self.idx {
276 serializer.serialize_some(&id)
278 serializer.serialize_some(&self.name)
283 /// Full type of functions/methods in the search index.
285 pub struct IndexItemFunctionType {
286 inputs: Vec<TypeWithKind>,
287 output: Option<Vec<TypeWithKind>>,
290 impl Serialize for IndexItemFunctionType {
291 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
295 // If we couldn't figure out a type, just write `null`.
296 let mut iter = self.inputs.iter();
297 if match self.output {
298 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
299 None => iter.any(|ref i| i.ty.name.is_none()),
301 serializer.serialize_none()
303 let mut seq = serializer.serialize_seq(None)?;
304 seq.serialize_element(&self.inputs)?;
305 if let Some(output) = &self.output {
306 if output.len() > 1 {
307 seq.serialize_element(&output)?;
309 seq.serialize_element(&output[0])?;
318 crate struct TypeWithKind {
323 impl From<(RenderType, TypeKind)> for TypeWithKind {
324 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
325 TypeWithKind { ty: x.0, kind: x.1 }
329 impl Serialize for TypeWithKind {
330 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
334 let mut seq = serializer.serialize_seq(None)?;
335 seq.serialize_element(&self.ty.name)?;
336 let x: ItemType = self.kind.into();
337 seq.serialize_element(&x)?;
342 #[derive(Debug, Clone)]
343 pub struct StylePath {
344 /// The path to the theme
346 /// What the `disabled` attribute should be set to in the HTML tag
350 thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
352 pub fn initial_ids() -> Vec<String> {
364 "synthetic-implementors",
366 "synthetic-implementors-list",
372 .map(|id| (String::from(*id)))
376 /// Generates the documentation for `crate` into the directory `dst`
377 impl FormatRenderer for Context {
379 mut krate: clean::Crate,
380 options: RenderOptions,
381 _render_info: RenderInfo,
384 ) -> Result<(Context, clean::Crate), Error> {
385 // need to save a copy of the options for rendering the index page
386 let md_opts = options.clone();
392 sort_modules_alphabetically,
397 generate_search_filter,
401 let src_root = match krate.src {
402 FileName::Real(ref p) => match p.local_path().parent() {
403 Some(p) => p.to_path_buf(),
404 None => PathBuf::new(),
408 // If user passed in `--playground-url` arg, we fill in crate name here
409 let mut playground = None;
410 if let Some(url) = playground_url {
411 playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url });
413 let mut layout = layout::Layout {
415 favicon: String::new(),
417 krate: krate.name.clone(),
418 css_file_extension: extension_css,
419 generate_search_filter,
421 let mut issue_tracker_base_url = None;
422 let mut include_sources = true;
424 // Crawl the crate attributes looking for attributes which control how we're
425 // going to emit HTML
426 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
427 for attr in attrs.lists(sym::doc) {
428 match (attr.name_or_empty(), attr.value_str()) {
429 (sym::html_favicon_url, Some(s)) => {
430 layout.favicon = s.to_string();
432 (sym::html_logo_url, Some(s)) => {
433 layout.logo = s.to_string();
435 (sym::html_playground_url, Some(s)) => {
436 playground = Some(markdown::Playground {
437 crate_name: Some(krate.name.clone()),
441 (sym::issue_tracker_base_url, Some(s)) => {
442 issue_tracker_base_url = Some(s.to_string());
444 (sym::html_no_source, None) if attr.is_word() => {
445 include_sources = false;
451 let (sender, receiver) = channel();
452 let mut scx = SharedContext {
453 collapsed: krate.collapsed,
456 local_sources: Default::default(),
457 issue_tracker_base_url,
459 created_dirs: Default::default(),
460 sort_modules_alphabetically,
464 fs: DocFS::new(sender),
466 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
470 // Add the default themes to the `Vec` of stylepaths
472 // Note that these must be added before `sources::render` is called
473 // so that the resulting source pages are styled
475 // `light.css` is not disabled because it is the stylesheet that stays loaded
476 // by the browser as the theme stylesheet. The theme system (hackily) works by
477 // changing the href to this stylesheet. All other themes are disabled to
478 // prevent rule conflicts
479 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
480 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
481 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
484 scx.ensure_dir(&dst)?;
485 krate = sources::render(&dst, &mut scx, krate)?;
487 // Build our search index
488 let index = build_index(&krate, cache);
490 let cache = Arc::new(cache);
491 let mut cx = Context {
494 render_redirect_pages: false,
495 id_map: Rc::new(RefCell::new(id_map)),
496 shared: Arc::new(scx),
497 all: Rc::new(RefCell::new(AllTypes::new())),
498 errors: Rc::new(receiver),
501 CURRENT_DEPTH.with(|s| s.set(0));
503 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
504 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
505 write_shared(&cx, &krate, index, &md_opts, &cache)?;
506 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
510 fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
511 Arc::get_mut(&mut self.shared).unwrap().fs.close();
512 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
514 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
520 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
521 let final_file = self.dst.join(&krate.name).join("all.html");
522 let settings_file = self.dst.join("settings.html");
523 let crate_name = krate.name.clone();
525 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
526 if !root_path.ends_with('/') {
529 let mut page = layout::Page {
530 title: "List of all items in this crate",
533 static_root_path: self.shared.static_root_path.as_deref(),
534 description: "List of all items in this crate",
535 keywords: BASIC_KEYWORDS,
536 resource_suffix: &self.shared.resource_suffix,
538 static_extra_scripts: &[],
540 let sidebar = if let Some(ref version) = cache.crate_version {
542 "<p class='location'>Crate {}</p>\
543 <div class='block version'>\
546 <a id='all-types' href='index.html'><p>Back to index</p></a>",
553 let all = self.all.replace(AllTypes::new());
554 let v = layout::render(
558 |buf: &mut Buffer| all.print(buf),
559 &self.shared.style_files,
561 self.shared.fs.write(&final_file, v.as_bytes())?;
563 // Generating settings page.
564 page.title = "Rustdoc settings";
565 page.description = "Settings of Rustdoc";
566 page.root_path = "./";
568 let mut style_files = self.shared.style_files.clone();
569 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
570 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
571 let v = layout::render(
576 self.shared.static_root_path.as_deref().unwrap_or("./"),
577 &self.shared.resource_suffix,
581 self.shared.fs.write(&settings_file, v.as_bytes())?;
590 ) -> Result<(), Error> {
591 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
592 // if they contain impls for public types. These modules can also
593 // contain items such as publicly re-exported structures.
595 // External crates will provide links to these structures, so
596 // these modules are recursed into, but not rendered normally
597 // (a flag on the context).
598 if !self.render_redirect_pages {
599 self.render_redirect_pages = item.is_stripped();
601 let scx = &self.shared;
602 self.dst.push(item_name);
603 self.current.push(item_name.to_owned());
605 info!("Recursing into {}", self.dst.display());
607 let buf = self.render_item(item, false, cache);
608 // buf will be empty if the module is stripped and there is no redirect for it
610 self.shared.ensure_dir(&self.dst)?;
611 let joint_dst = self.dst.join("index.html");
612 scx.fs.write(&joint_dst, buf.as_bytes())?;
615 // Render sidebar-items.js used throughout this module.
616 if !self.render_redirect_pages {
617 let module = match item.inner {
618 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
621 let items = self.build_sidebar_items(module);
622 let js_dst = self.dst.join("sidebar-items.js");
623 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
624 scx.fs.write(&js_dst, &v)?;
629 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
630 info!("Recursed; leaving {}", self.dst.display());
632 // Go back to where we were at
638 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
639 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
640 // if they contain impls for public types. These modules can also
641 // contain items such as publicly re-exported structures.
643 // External crates will provide links to these structures, so
644 // these modules are recursed into, but not rendered normally
645 // (a flag on the context).
646 if !self.render_redirect_pages {
647 self.render_redirect_pages = item.is_stripped();
650 let buf = self.render_item(&item, true, cache);
651 // buf will be empty if the item is stripped and there is no redirect for it
653 let name = item.name.as_ref().unwrap();
654 let item_type = item.type_();
655 let file_name = &item_path(item_type, name);
656 self.shared.ensure_dir(&self.dst)?;
657 let joint_dst = self.dst.join(file_name);
658 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
660 if !self.render_redirect_pages {
661 self.all.borrow_mut().append(full_path(self, &item), &item_type);
663 // If the item is a macro, redirect from the old macro URL (with !)
664 // to the new one (without).
665 if item_type == ItemType::Macro {
666 let redir_name = format!("{}.{}!.html", item_type, name);
667 let redir_dst = self.dst.join(redir_name);
668 let v = layout::redirect(file_name);
669 self.shared.fs.write(&redir_dst, v.as_bytes())?;
678 krate: &clean::Crate,
679 search_index: String,
680 options: &RenderOptions,
682 ) -> Result<(), Error> {
683 // Write out the shared files. Note that these are shared among all rustdoc
684 // docs placed in the output directory, so this needs to be a synchronized
685 // operation with respect to all other rustdocs running around.
686 let lock_file = cx.dst.join(".lock");
687 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
689 // Add all the static files. These may already exist, but we just
690 // overwrite them anyway to make sure that they're fresh and up-to-date.
694 cx.path("rustdoc.css"),
695 static_files::RUSTDOC_CSS,
696 options.enable_minification,
700 cx.path("settings.css"),
701 static_files::SETTINGS_CSS,
702 options.enable_minification,
706 cx.path("noscript.css"),
707 static_files::NOSCRIPT_CSS,
708 options.enable_minification,
711 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
712 // then we'll run over the "official" styles.
713 let mut themes: FxHashSet<String> = FxHashSet::default();
715 for entry in &cx.shared.style_files {
716 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
718 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
720 // Handle the official themes
722 "light" => write_minify(
724 cx.path("light.css"),
725 static_files::themes::LIGHT,
726 options.enable_minification,
728 "dark" => write_minify(
731 static_files::themes::DARK,
732 options.enable_minification,
734 "ayu" => write_minify(
737 static_files::themes::AYU,
738 options.enable_minification,
741 // Handle added third-party themes
742 let content = try_err!(fs::read(&entry.path), &entry.path);
745 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
749 themes.insert(theme.to_owned());
752 let write = |p, c| cx.shared.fs.write(p, c);
753 if (*cx.shared).layout.logo.is_empty() {
754 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
756 if (*cx.shared).layout.favicon.is_empty() {
757 write(cx.path("favicon.ico"), static_files::RUST_FAVICON)?;
759 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
760 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
761 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
763 let mut themes: Vec<&String> = themes.iter().collect();
765 // To avoid theme switch latencies as much as possible, we put everything theme related
766 // at the beginning of the html files into another js file.
767 let theme_js = format!(
768 r#"var themes = document.getElementById("theme-choices");
769 var themePicker = document.getElementById("theme-picker");
771 function showThemeButtonState() {{
772 themes.style.display = "block";
773 themePicker.style.borderBottomRightRadius = "0";
774 themePicker.style.borderBottomLeftRadius = "0";
777 function hideThemeButtonState() {{
778 themes.style.display = "none";
779 themePicker.style.borderBottomRightRadius = "3px";
780 themePicker.style.borderBottomLeftRadius = "3px";
783 function switchThemeButtonState() {{
784 if (themes.style.display === "block") {{
785 hideThemeButtonState();
787 showThemeButtonState();
791 function handleThemeButtonsBlur(e) {{
792 var active = document.activeElement;
793 var related = e.relatedTarget;
795 if (active.id !== "themePicker" &&
796 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
798 (related.id !== "themePicker" &&
799 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
800 hideThemeButtonState();
804 themePicker.onclick = switchThemeButtonState;
805 themePicker.onblur = handleThemeButtonsBlur;
806 {}.forEach(function(item) {{
807 var but = document.createElement('button');
808 but.textContent = item;
809 but.onclick = function(el) {{
810 switchTheme(currentTheme, mainTheme, item, true);
812 but.onblur = handleThemeButtonsBlur;
813 themes.appendChild(but);
815 serde_json::to_string(&themes).unwrap()
818 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
822 static_files::MAIN_JS,
823 options.enable_minification,
827 cx.path("settings.js"),
828 static_files::SETTINGS_JS,
829 options.enable_minification,
831 if cx.shared.include_sources {
834 cx.path("source-script.js"),
835 static_files::sidebar::SOURCE_SCRIPT,
836 options.enable_minification,
843 cx.path("storage.js"),
845 "var resourcesSuffix = \"{}\";{}",
846 cx.shared.resource_suffix,
847 static_files::STORAGE_JS
849 options.enable_minification,
853 if let Some(ref css) = cx.shared.layout.css_file_extension {
854 let out = cx.path("theme.css");
855 let buffer = try_err!(fs::read_to_string(css), css);
856 if !options.enable_minification {
857 cx.shared.fs.write(&out, &buffer)?;
859 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
864 cx.path("normalize.css"),
865 static_files::NORMALIZE_CSS,
866 options.enable_minification,
868 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
869 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
870 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
871 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
872 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
873 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
874 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
875 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
876 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
877 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
878 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
879 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
880 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
882 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
883 let mut ret = Vec::new();
884 let mut krates = Vec::new();
887 for line in BufReader::new(File::open(path)?).lines() {
889 if !line.starts_with(key) {
892 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
895 ret.push(line.to_string());
897 line[key.len() + 2..]
900 .map(|s| s.to_owned())
901 .unwrap_or_else(String::new),
908 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
909 let mut ret = Vec::new();
910 let mut krates = Vec::new();
913 for line in BufReader::new(File::open(path)?).lines() {
915 if !line.starts_with('"') {
918 if line.starts_with(&format!("\"{}\"", krate)) {
921 if line.ends_with(",\\") {
922 ret.push(line[..line.len() - 2].to_string());
924 // Ends with "\\" (it's the case for the last added crate line)
925 ret.push(line[..line.len() - 1].to_string());
929 .find(|s| !s.is_empty())
930 .map(|s| s.to_owned())
931 .unwrap_or_else(String::new),
938 use std::ffi::OsString;
943 children: FxHashMap<OsString, Hierarchy>,
944 elems: FxHashSet<OsString>,
948 fn new(elem: OsString) -> Hierarchy {
949 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
952 fn to_json_string(&self) -> String {
953 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
954 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
958 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
959 .collect::<Vec<_>>();
960 files.sort_unstable_by(|a, b| a.cmp(b));
961 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
963 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
964 let files = files.join(",");
966 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
968 "{{\"name\":\"{name}\"{dirs}{files}}}",
969 name = self.elem.to_str().expect("invalid osstring conversion"),
976 if cx.shared.include_sources {
977 let mut hierarchy = Hierarchy::new(OsString::new());
982 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
984 let mut h = &mut hierarchy;
985 let mut elems = source
987 .filter_map(|s| match s {
988 Component::Normal(s) => Some(s.to_owned()),
993 let cur_elem = elems.next().expect("empty file path");
994 if elems.peek().is_none() {
995 h.elems.insert(cur_elem);
998 let e = cur_elem.clone();
999 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1000 h = h.children.get_mut(&cur_elem).expect("not found child");
1005 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1006 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1007 all_sources.push(format!(
1008 "sourcesIndex[\"{}\"] = {};",
1010 hierarchy.to_json_string()
1014 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1015 all_sources.join("\n")
1017 cx.shared.fs.write(&dst, v.as_bytes())?;
1020 // Update the search index
1021 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1022 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name), &dst);
1023 all_indexes.push(search_index);
1025 // Sort the indexes by crate so the file will be generated identically even
1026 // with rustdoc running in parallel.
1029 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1030 v.push_str(&all_indexes.join(",\\\n"));
1031 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1032 // search might start (if it's set into the URL for example).
1033 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1034 cx.shared.fs.write(&dst, &v)?;
1036 if options.enable_index_page {
1037 if let Some(index_page) = options.index_page.clone() {
1038 let mut md_opts = options.clone();
1039 md_opts.output = cx.dst.clone();
1040 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1042 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1043 .map_err(|e| Error::new(e, &index_page))?;
1045 let dst = cx.dst.join("index.html");
1046 let page = layout::Page {
1047 title: "Index of crates",
1050 static_root_path: cx.shared.static_root_path.as_deref(),
1051 description: "List of crates",
1052 keywords: BASIC_KEYWORDS,
1053 resource_suffix: &cx.shared.resource_suffix,
1055 static_extra_scripts: &[],
1057 krates.push(krate.name.clone());
1061 let content = format!(
1063 <span class='in-band'>List of all crates</span>\
1065 <ul class='crate mod'>{}</ul>",
1070 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1071 ensure_trailing_slash(s),
1075 .collect::<String>()
1077 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1078 cx.shared.fs.write(&dst, v.as_bytes())?;
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.
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) {
1094 None => match cache.external_paths.get(&did) {
1100 #[derive(Serialize)]
1101 struct Implementor {
1107 let implementors = imps
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.
1115 // If the implementation is from another crate then that crate
1117 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
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()),
1127 .collect::<Vec<_>>();
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
1132 if implementors.is_empty() && !cache.paths.contains_key(&did) {
1136 let implementors = format!(
1137 r#"implementors["{}"] = {};"#,
1139 serde_json::to_string(&implementors).unwrap()
1142 let mut mydst = dst.clone();
1143 for part in &remote_path[..remote_path.len() - 1] {
1146 cx.shared.ensure_dir(&mydst)?;
1147 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
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();
1156 let mut v = String::from("(function() {var implementors = {};\n");
1157 for implementor in &all_implementors {
1158 writeln!(v, "{}", *implementor).unwrap();
1161 "if (window.register_implementors) {\
1162 window.register_implementors(implementors);\
1164 window.pending_implementors = implementors;\
1168 cx.shared.fs.write(&mydst, &v)?;
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())
1184 fs.write(dst, minifier::js::minify(contents).as_bytes())
1187 fs.write(dst, contents.as_bytes())
1191 #[derive(Debug, Eq, PartialEq, Hash)]
1198 fn new(mut url: String, name: String) -> ItemEntry {
1199 while url.starts_with('/') {
1202 ItemEntry { url, name }
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))
1214 impl PartialOrd for ItemEntry {
1215 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1216 Some(self.cmp(other))
1220 impl Ord for ItemEntry {
1221 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1222 self.name.cmp(&other.name)
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>,
1246 fn new() -> AllTypes {
1247 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
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),
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);
1272 let name = url.join("::");
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)),
1294 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1296 let mut e: Vec<&ItemEntry> = e.iter().collect();
1300 "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1304 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1310 fn print(self, f: &mut Buffer) {
1314 <span class='out-of-band'>\
1315 <span id='render-detail'>\
1316 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1317 title=\"collapse all docs\">\
1318 [<span class='inner'>−</span>]\
1322 <span class='in-band'>List of all items</span>\
1325 print_entries(f, &self.structs, "Structs", "structs");
1326 print_entries(f, &self.enums, "Enums", "enums");
1327 print_entries(f, &self.unions, "Unions", "unions");
1328 print_entries(f, &self.primitives, "Primitives", "primitives");
1329 print_entries(f, &self.traits, "Traits", "traits");
1330 print_entries(f, &self.macros, "Macros", "macros");
1331 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1332 print_entries(f, &self.derives, "Derive Macros", "derives");
1333 print_entries(f, &self.functions, "Functions", "functions");
1334 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1335 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1336 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1337 print_entries(f, &self.statics, "Statics", "statics");
1338 print_entries(f, &self.constants, "Constants", "constants")
1344 Section { description: &'static str, sub_settings: Vec<Setting> },
1345 Entry { js_data_name: &'static str, description: &'static str, default_value: bool },
1349 fn display(&self) -> String {
1351 Setting::Section { ref description, ref sub_settings } => format!(
1352 "<div class='setting-line'>\
1353 <div class='title'>{}</div>\
1354 <div class='sub-settings'>{}</div>
1357 sub_settings.iter().map(|s| s.display()).collect::<String>()
1359 Setting::Entry { ref js_data_name, ref description, ref default_value } => format!(
1360 "<div class='setting-line'>\
1361 <label class='toggle'>\
1362 <input type='checkbox' id='{}' {}>\
1363 <span class='slider'></span>\
1368 if *default_value { " checked" } else { "" },
1375 impl From<(&'static str, &'static str, bool)> for Setting {
1376 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1377 Setting::Entry { js_data_name: values.0, description: values.1, default_value: values.2 }
1381 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1382 fn from(values: (&'static str, Vec<T>)) -> Setting {
1384 description: values.0,
1385 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1390 fn settings(root_path: &str, suffix: &str) -> String {
1391 // (id, explanation, default value)
1392 let settings: &[Setting] = &[
1394 "Auto-hide item declarations",
1396 ("auto-hide-struct", "Auto-hide structs declaration", true),
1397 ("auto-hide-enum", "Auto-hide enums declaration", false),
1398 ("auto-hide-union", "Auto-hide unions declaration", true),
1399 ("auto-hide-trait", "Auto-hide traits declaration", true),
1400 ("auto-hide-macro", "Auto-hide macros declaration", false),
1404 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1405 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1406 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1408 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1409 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1411 ("line-numbers", "Show line numbers on code examples", false).into(),
1412 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1416 <span class='in-band'>Rustdoc settings</span>\
1418 <div class='settings'>{}</div>\
1419 <script src='{}settings{}.js'></script>",
1420 settings.iter().map(|s| s.display()).collect::<String>(),
1427 fn derive_id(&self, id: String) -> String {
1428 let mut map = self.id_map.borrow_mut();
1432 /// String representation of how to get back to the root path of the 'doc/'
1433 /// folder in terms of a relative URL.
1434 fn root_path(&self) -> String {
1435 "../".repeat(self.current.len())
1438 fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1439 // A little unfortunate that this is done like this, but it sure
1440 // does make formatting *a lot* nicer.
1441 CURRENT_DEPTH.with(|slot| {
1442 slot.set(self.current.len());
1445 let mut title = if it.is_primitive() || it.is_keyword() {
1446 // No need to include the namespace for primitive types and keywords
1449 self.current.join("::")
1452 if !title.is_empty() {
1453 title.push_str("::");
1455 title.push_str(it.name.as_ref().unwrap());
1457 title.push_str(" - Rust");
1458 let tyname = it.type_();
1459 let desc = if it.is_crate() {
1460 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1463 "API documentation for the Rust `{}` {} in crate `{}`.",
1464 it.name.as_ref().unwrap(),
1466 self.shared.layout.krate
1469 let keywords = make_item_keywords(it);
1470 let page = layout::Page {
1471 css_class: tyname.as_str(),
1472 root_path: &self.root_path(),
1473 static_root_path: self.shared.static_root_path.as_deref(),
1476 keywords: &keywords,
1477 resource_suffix: &self.shared.resource_suffix,
1479 static_extra_scripts: &[],
1483 self.id_map.borrow_mut().reset();
1484 self.id_map.borrow_mut().populate(initial_ids());
1487 if !self.render_redirect_pages {
1489 &self.shared.layout,
1491 |buf: &mut _| print_sidebar(self, it, buf, cache),
1492 |buf: &mut _| print_item(self, it, buf, cache),
1493 &self.shared.style_files,
1496 let mut url = self.root_path();
1497 if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1498 for name in &names[..names.len() - 1] {
1502 url.push_str(&item_path(ty, names.last().unwrap()));
1503 layout::redirect(&url)
1510 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1511 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1512 // BTreeMap instead of HashMap to get a sorted output
1513 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1514 for item in &m.items {
1515 if item.is_stripped() {
1519 let short = item.type_();
1520 let myname = match item.name {
1522 Some(ref s) => s.to_string(),
1524 let short = short.to_string();
1527 .push((myname, Some(plain_text_summary(item.doc_value()))));
1530 if self.shared.sort_modules_alphabetically {
1531 for items in map.values_mut() {
1538 /// Generates a url appropriate for an `href` attribute back to the source of
1541 /// The url generated, when clicked, will redirect the browser back to the
1542 /// original source code.
1544 /// If `None` is returned, then a source link couldn't be generated. This
1545 /// may happen, for example, with externally inlined items where the source
1546 /// of their crate documentation isn't known.
1547 fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1548 let mut root = self.root_path();
1550 let mut path = String::new();
1552 // We can safely ignore synthetic `SourceFile`s.
1553 let file = match item.source.filename {
1554 FileName::Real(ref path) => path.local_path().to_path_buf(),
1559 let (krate, path) = if item.source.cnum == LOCAL_CRATE {
1560 if let Some(path) = self.shared.local_sources.get(file) {
1561 (&self.shared.layout.krate, path)
1566 let (krate, src_root) = match *cache.extern_locations.get(&item.source.cnum)? {
1567 (ref name, ref src, ExternalLocation::Local) => (name, src),
1568 (ref name, ref src, ExternalLocation::Remote(ref s)) => {
1569 root = s.to_string();
1572 (_, _, ExternalLocation::Unknown) => return None,
1575 sources::clean_path(&src_root, file, false, |component| {
1576 path.push_str(&component.to_string_lossy());
1579 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1580 fname.push(".html");
1581 path.push_str(&fname.to_string_lossy());
1585 let lines = if item.source.loline == item.source.hiline {
1586 item.source.loline.to_string()
1588 format!("{}-{}", item.source.loline, item.source.hiline)
1591 "{root}src/{krate}/{path}#{lines}",
1592 root = Escape(&root),
1600 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1602 F: FnOnce(&mut Buffer),
1604 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1609 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1610 debug_assert!(!item.is_stripped());
1611 // Write the breadcrumb trail header for the top
1612 write!(buf, "<h1 class='fqn'><span class='out-of-band'>");
1613 if let Some(version) = item.stable_since() {
1616 "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1622 "<span id='render-detail'>\
1623 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1624 title=\"collapse all docs\">\
1625 [<span class='inner'>−</span>]\
1632 // When this item is part of a `pub use` in a downstream crate, the
1633 // [src] link in the downstream documentation will actually come back to
1634 // this page, and this link will be auto-clicked. The `id` attribute is
1635 // used to find the link to auto-click.
1636 if cx.shared.include_sources && !item.is_primitive() {
1637 if let Some(l) = cx.src_href(item, cache) {
1638 write!(buf, "<a class='srclink' href='{}' title='{}'>[src]</a>", l, "goto source code");
1642 write!(buf, "</span>"); // out-of-band
1643 write!(buf, "<span class='in-band'>");
1644 let name = match item.inner {
1645 clean::ModuleItem(ref m) => {
1652 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1653 clean::TraitItem(..) => "Trait ",
1654 clean::StructItem(..) => "Struct ",
1655 clean::UnionItem(..) => "Union ",
1656 clean::EnumItem(..) => "Enum ",
1657 clean::TypedefItem(..) => "Type Definition ",
1658 clean::MacroItem(..) => "Macro ",
1659 clean::ProcMacroItem(ref mac) => match mac.kind {
1660 MacroKind::Bang => "Macro ",
1661 MacroKind::Attr => "Attribute Macro ",
1662 MacroKind::Derive => "Derive Macro ",
1664 clean::PrimitiveItem(..) => "Primitive Type ",
1665 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1666 clean::ConstantItem(..) => "Constant ",
1667 clean::ForeignTypeItem => "Foreign Type ",
1668 clean::KeywordItem(..) => "Keyword ",
1669 clean::OpaqueTyItem(..) => "Opaque Type ",
1670 clean::TraitAliasItem(..) => "Trait Alias ",
1672 // We don't generate pages for any other type.
1676 buf.write_str(name);
1677 if !item.is_primitive() && !item.is_keyword() {
1678 let cur = &cx.current;
1679 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1680 for (i, component) in cur.iter().enumerate().take(amt) {
1683 "<a href='{}index.html'>{}</a>::<wbr>",
1684 "../".repeat(cur.len() - i - 1),
1689 write!(buf, "<a class=\"{}\" href=''>{}</a>", item.type_(), item.name.as_ref().unwrap());
1691 write!(buf, "</span></h1>"); // in-band
1694 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1695 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1696 item_function(buf, cx, item, f)
1698 clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1699 clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1700 clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1701 clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1702 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1703 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1704 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1705 clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1706 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1707 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1708 clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1709 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1710 clean::OpaqueTyItem(ref e, _) => item_opaque_ty(buf, cx, item, e, cache),
1711 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1713 // We don't generate pages for any other type.
1719 fn item_path(ty: ItemType, name: &str) -> String {
1721 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1722 _ => format!("{}.{}.html", ty, name),
1726 fn full_path(cx: &Context, item: &clean::Item) -> String {
1727 let mut s = cx.current.join("::");
1729 s.push_str(item.name.as_ref().unwrap());
1733 /// Renders the first paragraph of the given markdown as plain text, making it suitable for
1734 /// contexts like alt-text or the search index.
1736 /// If no markdown is supplied, the empty string is returned.
1738 /// See [`markdown::plain_text_summary`] for further details.
1740 crate fn plain_text_summary(s: Option<&str>) -> String {
1741 s.map(markdown::plain_text_summary).unwrap_or_default()
1744 crate fn shorten(s: String) -> String {
1745 if s.chars().count() > 60 {
1750 // + 1 for the added character after the word.
1751 len += p.chars().count() + 1;
1754 .collect::<Vec<_>>()
1763 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item) {
1764 if let Some(ref name) = item.name {
1765 info!("Documenting {}", name);
1767 document_stability(w, cx, item, false);
1768 document_full(w, item, cx, "", false);
1771 /// Render md_text as markdown.
1776 links: Vec<RenderedLink>,
1780 let mut ids = cx.id_map.borrow_mut();
1783 "<div class='docblock{}'>{}{}</div>",
1784 if is_hidden { " hidden" } else { "" },
1792 &cx.shared.playground
1798 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1799 /// docs are longer, a "Read more" link is appended to the end.
1803 link: AssocItemLink<'_>,
1807 if let Some(s) = item.doc_value() {
1808 let mut summary_html = MarkdownSummaryLine(s, &item.links()).into_string();
1810 if s.contains('\n') {
1811 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link));
1813 if let Some(idx) = summary_html.rfind("</p>") {
1814 summary_html.insert_str(idx, &link);
1816 summary_html.push_str(&link);
1822 "<div class='docblock{}'>{}{}</div>",
1823 if is_hidden { " hidden" } else { "" },
1827 } else if !prefix.is_empty() {
1830 "<div class='docblock{}'>{}</div>",
1831 if is_hidden { " hidden" } else { "" },
1837 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1838 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1839 debug!("Doc block: =====\n{}\n=====", s);
1840 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1841 } else if !prefix.is_empty() {
1844 "<div class='docblock{}'>{}</div>",
1845 if is_hidden { " hidden" } else { "" },
1851 fn document_stability(w: &mut Buffer, cx: &Context, item: &clean::Item, is_hidden: bool) {
1852 let stabilities = short_stability(item, cx);
1853 if !stabilities.is_empty() {
1854 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" });
1855 for stability in stabilities {
1856 write!(w, "{}", stability);
1858 write!(w, "</div>");
1862 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1863 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1866 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1867 if item.is_non_exhaustive() {
1868 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
1869 if item.is_struct() {
1871 } else if item.is_enum() {
1873 } else if item.is_variant() {
1880 if item.is_struct() {
1883 "Non-exhaustive structs could have additional fields added in future. \
1884 Therefore, non-exhaustive structs cannot be constructed in external crates \
1885 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1886 matched against without a wildcard <code>..</code>; and \
1887 struct update syntax will not work."
1889 } else if item.is_enum() {
1892 "Non-exhaustive enums could have additional variants added in future. \
1893 Therefore, when matching against variants of non-exhaustive enums, an \
1894 extra wildcard arm must be added to account for any future variants."
1896 } else if item.is_variant() {
1899 "Non-exhaustive enum variants could have additional fields added in future. \
1900 Therefore, non-exhaustive enum variants cannot be constructed in external \
1901 crates and cannot be matched against."
1906 "This type will require a wildcard arm in any match statements or constructors."
1910 write!(w, "</div>");
1914 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1915 pub fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1916 /// Takes a non-numeric and a numeric part from the given &str.
1917 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1918 let i = s.find(|c: char| c.is_ascii_digit());
1919 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1920 let i = b.find(|c: char| !c.is_ascii_digit());
1921 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1926 while !lhs.is_empty() || !rhs.is_empty() {
1927 let (la, lb) = take_parts(&mut lhs);
1928 let (ra, rb) = take_parts(&mut rhs);
1929 // First process the non-numeric part.
1931 Ordering::Equal => (),
1934 // Then process the numeric part, if both sides have one (and they fit in a u64).
1935 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1937 Ordering::Equal => (),
1941 // Then process the numeric part again, but this time as strings.
1943 Ordering::Equal => (),
1951 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
1952 document(w, cx, item);
1954 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1956 // the order of item types in the listing
1957 fn reorder(ty: ItemType) -> u8 {
1959 ItemType::ExternCrate => 0,
1960 ItemType::Import => 1,
1961 ItemType::Primitive => 2,
1962 ItemType::Module => 3,
1963 ItemType::Macro => 4,
1964 ItemType::Struct => 5,
1965 ItemType::Enum => 6,
1966 ItemType::Constant => 7,
1967 ItemType::Static => 8,
1968 ItemType::Trait => 9,
1969 ItemType::Function => 10,
1970 ItemType::Typedef => 12,
1971 ItemType::Union => 13,
1976 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1977 let ty1 = i1.type_();
1978 let ty2 = i2.type_();
1980 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
1982 let s1 = i1.stability.as_ref().map(|s| s.level);
1983 let s2 = i2.stability.as_ref().map(|s| s.level);
1985 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1986 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1989 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1990 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1991 compare_names(lhs, rhs)
1994 if cx.shared.sort_modules_alphabetically {
1995 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1997 // This call is to remove re-export duplicates in cases such as:
2002 // pub trait Double { fn foo(); }
2006 // pub use foo::bar::*;
2010 // `Double` will appear twice in the generated docs.
2012 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2013 // can be identical even if the elements are different (mostly in imports).
2014 // So in case this is an import, we keep everything by adding a "unique id"
2015 // (which is the position in the vector).
2016 indices.dedup_by_key(|i| {
2019 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2021 if items[*i].is_import() { *i } else { 0 },
2025 debug!("{:?}", indices);
2026 let mut curty = None;
2027 for &idx in &indices {
2028 let myitem = &items[idx];
2029 if myitem.is_stripped() {
2033 let myty = Some(myitem.type_());
2034 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2035 // Put `extern crate` and `use` re-exports in the same section.
2037 } else if myty != curty {
2038 if curty.is_some() {
2039 write!(w, "</table>");
2042 let (short, name) = item_ty_to_strs(&myty.unwrap());
2045 "<h2 id='{id}' class='section-header'>\
2046 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2047 id = cx.derive_id(short.to_owned()),
2052 match myitem.inner {
2053 clean::ExternCrateItem(ref name, ref src) => {
2054 use crate::html::format::anchor;
2057 Some(ref src) => write!(
2059 "<tr><td><code>{}extern crate {} as {};",
2060 myitem.visibility.print_with_space(),
2061 anchor(myitem.def_id, src),
2066 "<tr><td><code>{}extern crate {};",
2067 myitem.visibility.print_with_space(),
2068 anchor(myitem.def_id, name)
2071 write!(w, "</code></td></tr>");
2074 clean::ImportItem(ref import) => {
2077 "<tr><td><code>{}{}</code></td></tr>",
2078 myitem.visibility.print_with_space(),
2084 if myitem.name.is_none() {
2088 let unsafety_flag = match myitem.inner {
2089 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2090 if func.header.unsafety == hir::Unsafety::Unsafe =>
2092 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2097 let stab = myitem.stability_class();
2098 let add = if stab.is_some() { " " } else { "" };
2100 let doc_value = myitem.doc_value().unwrap_or("");
2103 "<tr class='{stab}{add}module-item'>\
2104 <td><a class=\"{class}\" href=\"{href}\" \
2105 title='{title}'>{name}</a>{unsafety_flag}</td>\
2106 <td class='docblock-short'>{stab_tags}{docs}</td>\
2108 name = *myitem.name.as_ref().unwrap(),
2109 stab_tags = stability_tags(myitem),
2110 docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2111 class = myitem.type_(),
2113 stab = stab.unwrap_or_else(String::new),
2114 unsafety_flag = unsafety_flag,
2115 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2116 title = [full_path(cx, myitem), myitem.type_().to_string()]
2118 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2119 .collect::<Vec<_>>()
2126 if curty.is_some() {
2127 write!(w, "</table>");
2131 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2133 fn stability_tags(item: &clean::Item) -> String {
2134 let mut tags = String::new();
2136 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2137 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2140 // The trailing space after each tag is to space it properly against the rest of the docs.
2141 if let Some(depr) = &item.deprecation {
2142 let mut message = "Deprecated";
2143 if !stability::deprecation_in_effect(depr.is_since_rustc_version, depr.since.as_deref()) {
2144 message = "Deprecation planned";
2146 tags += &tag_html("deprecated", "", message);
2149 // The "rustc_private" crates are permanently unstable so it makes no sense
2150 // to render "unstable" everywhere.
2154 .map(|s| s.level == stability::Unstable && s.feature != "rustc_private")
2157 tags += &tag_html("unstable", "", "Experimental");
2160 if let Some(ref cfg) = item.attrs.cfg {
2161 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2167 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2169 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2170 let mut stability = vec![];
2171 let error_codes = cx.shared.codes;
2173 if let Some(Deprecation { ref note, ref since, is_since_rustc_version }) = item.deprecation {
2174 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2175 // but only display the future-deprecation messages for #[rustc_deprecated].
2176 let mut message = if let Some(since) = since {
2177 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2178 format!("Deprecating in {}", Escape(&since))
2180 format!("Deprecated since {}", Escape(&since))
2183 String::from("Deprecated")
2186 if let Some(note) = note {
2187 let mut ids = cx.id_map.borrow_mut();
2188 let html = MarkdownHtml(
2193 &cx.shared.playground,
2195 message.push_str(&format!(": {}", html.into_string()));
2197 stability.push(format!(
2198 "<div class='stab deprecated'><span class='emoji'>👎</span> {}</div>",
2203 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2204 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2205 if let Some(stab) = item
2208 .filter(|stab| stab.level == stability::Unstable && stab.feature != "rustc_private")
2211 "<span class='emoji'>🔬</span> This is a nightly-only experimental API.".to_owned();
2213 let mut feature = format!("<code>{}</code>", Escape(&stab.feature));
2214 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2215 feature.push_str(&format!(
2216 " <a href=\"{url}{issue}\">#{issue}</a>",
2222 message.push_str(&format!(" ({})", feature));
2224 if let Some(unstable_reason) = &stab.unstable_reason {
2225 let mut ids = cx.id_map.borrow_mut();
2227 "<details><summary>{}</summary>{}</details>",
2234 &cx.shared.playground,
2240 stability.push(format!("<div class='stab unstable'>{}</div>", message));
2243 if let Some(ref cfg) = item.attrs.cfg {
2244 stability.push(format!("<div class='stab portability'>{}</div>", cfg.render_long_html()));
2250 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2251 write!(w, "<pre class='rust const'>");
2252 render_attributes(w, it, false);
2256 "{vis}const {name}: {typ}",
2257 vis = it.visibility.print_with_space(),
2258 name = it.name.as_ref().unwrap(),
2259 typ = c.type_.print(),
2262 if c.value.is_some() || c.is_literal {
2263 write!(w, " = {expr};", expr = Escape(&c.expr));
2268 if let Some(value) = &c.value {
2270 let value_lowercase = value.to_lowercase();
2271 let expr_lowercase = c.expr.to_lowercase();
2273 if value_lowercase != expr_lowercase
2274 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2276 write!(w, " // {value}", value = Escape(value));
2281 write!(w, "</pre>");
2285 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2286 write!(w, "<pre class='rust static'>");
2287 render_attributes(w, it, false);
2290 "{vis}static {mutability} {name}: {typ}</pre>",
2291 vis = it.visibility.print_with_space(),
2292 mutability = s.mutability.print_with_space(),
2293 name = it.name.as_ref().unwrap(),
2294 typ = s.type_.print()
2299 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2300 let header_len = format!(
2301 "{}{}{}{}{:#}fn {}{:#}",
2302 it.visibility.print_with_space(),
2303 f.header.constness.print_with_space(),
2304 f.header.asyncness.print_with_space(),
2305 f.header.unsafety.print_with_space(),
2306 print_abi_with_space(f.header.abi),
2307 it.name.as_ref().unwrap(),
2311 write!(w, "<pre class='rust fn'>");
2312 render_attributes(w, it, false);
2315 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2316 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2317 vis = it.visibility.print_with_space(),
2318 constness = f.header.constness.print_with_space(),
2319 asyncness = f.header.asyncness.print_with_space(),
2320 unsafety = f.header.unsafety.print_with_space(),
2321 abi = print_abi_with_space(f.header.abi),
2322 name = it.name.as_ref().unwrap(),
2323 generics = f.generics.print(),
2324 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2325 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2327 spotlight = spotlight_decl(&f.decl),
2332 fn render_implementor(
2336 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2340 // If there's already another implementor that has the same abbridged name, use the
2341 // full path, for example in `std::iter::ExactSizeIterator`
2342 let use_absolute = match implementor.inner_impl().for_ {
2343 clean::ResolvedPath { ref path, is_generic: false, .. }
2344 | clean::BorrowedRef {
2345 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2347 } => implementor_dups[path.last_name()].1,
2354 AssocItemLink::Anchor(None),
2356 implementor.impl_item.stable_since(),
2370 containing_item: &clean::Item,
2373 let mut impls = traits
2376 let did = i.trait_did().unwrap();
2377 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2378 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2385 containing_item.stable_since(),
2395 .collect::<Vec<_>>();
2397 w.write_str(&impls.join(""));
2400 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2401 let mut bounds = String::new();
2402 if !t_bounds.is_empty() {
2404 bounds.push_str(": ");
2406 for (i, p) in t_bounds.iter().enumerate() {
2408 bounds.push_str(" + ");
2410 bounds.push_str(&p.print().to_string());
2416 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2417 let lhs = format!("{}", lhs.inner_impl().print());
2418 let rhs = format!("{}", rhs.inner_impl().print());
2420 // lhs and rhs are formatted as HTML, which may be unnecessary
2421 compare_names(&lhs, &rhs)
2424 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2425 let bounds = bounds(&t.bounds, false);
2426 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2427 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2428 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2429 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2431 // Output the trait definition
2432 wrap_into_docblock(w, |w| {
2433 write!(w, "<pre class='rust trait'>");
2434 render_attributes(w, it, true);
2437 "{}{}{}trait {}{}{}",
2438 it.visibility.print_with_space(),
2439 t.unsafety.print_with_space(),
2440 if t.is_auto { "auto " } else { "" },
2441 it.name.as_ref().unwrap(),
2446 if !t.generics.where_predicates.is_empty() {
2447 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2452 if t.items.is_empty() {
2455 // FIXME: we should be using a derived_id for the Anchors here
2458 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2461 if !types.is_empty() && !consts.is_empty() {
2465 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2468 if !consts.is_empty() && !required.is_empty() {
2471 for (pos, m) in required.iter().enumerate() {
2472 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2475 if pos < required.len() - 1 {
2476 write!(w, "<div class='item-spacer'></div>");
2479 if !required.is_empty() && !provided.is_empty() {
2482 for (pos, m) in provided.iter().enumerate() {
2483 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2485 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2486 write!(w, ",\n {{ ... }}\n");
2489 write!(w, " {{ ... }}\n");
2492 if pos < provided.len() - 1 {
2493 write!(w, "<div class='item-spacer'></div>");
2501 // Trait documentation
2502 document(w, cx, it);
2504 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2507 "<h2 id='{0}' class='small-section-header'>\
2508 {1}<a href='#{0}' class='anchor'></a>\
2510 id, title, extra_content
2514 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2515 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
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);
2530 if !types.is_empty() {
2531 write_small_section_header(
2535 "<div class='methods'>",
2538 trait_item(w, cx, *t, it);
2540 write_loading_content(w, "</div>");
2543 if !consts.is_empty() {
2544 write_small_section_header(
2547 "Associated Constants",
2548 "<div class='methods'>",
2551 trait_item(w, cx, *t, it);
2553 write_loading_content(w, "</div>");
2556 // Output the documentation for each function individually
2557 if !required.is_empty() {
2558 write_small_section_header(
2562 "<div class='methods'>",
2564 for m in &required {
2565 trait_item(w, cx, *m, it);
2567 write_loading_content(w, "</div>");
2569 if !provided.is_empty() {
2570 write_small_section_header(
2574 "<div class='methods'>",
2576 for m in &provided {
2577 trait_item(w, cx, *m, it);
2579 write_loading_content(w, "</div>");
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);
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, .. },
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;
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))
2610 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2611 local.iter().partition(|i| i.inner_impl().synthetic);
2613 synthetic.sort_by(compare_impl);
2614 concrete.sort_by(compare_impl);
2616 if !foreign.is_empty() {
2617 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2619 for implementor in foreign {
2620 let assoc_link = AssocItemLink::GotoSource(
2621 implementor.impl_item.def_id,
2622 &implementor.inner_impl().provided_trait_methods,
2630 implementor.impl_item.stable_since(),
2639 write_loading_content(w, "");
2642 write_small_section_header(
2646 "<div class='item-list' id='implementors-list'>",
2648 for implementor in concrete {
2649 render_implementor(cx, implementor, w, &implementor_dups, &[], cache);
2651 write_loading_content(w, "</div>");
2654 write_small_section_header(
2656 "synthetic-implementors",
2657 "Auto implementors",
2658 "<div class='item-list' id='synthetic-implementors-list'>",
2660 for implementor in synthetic {
2666 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2670 write_loading_content(w, "</div>");
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(
2679 "<div class='item-list' id='implementors-list'>",
2681 write_loading_content(w, "</div>");
2684 write_small_section_header(
2686 "synthetic-implementors",
2687 "Auto implementors",
2688 "<div class='item-list' id='synthetic-implementors-list'>",
2690 write_loading_content(w, "</div>");
2696 "<script type=\"text/javascript\" \
2697 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2699 root_path = vec![".."; cx.current.len()].join("/"),
2700 path = if it.def_id.is_local() {
2701 cx.current.join("/")
2703 let (ref path, _) = cache.external_paths[&it.def_id];
2704 path[..path.len() - 1].join("/")
2707 name = *it.name.as_ref().unwrap()
2711 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2712 use crate::formats::item_type::ItemType::*;
2714 let name = it.name.as_ref().unwrap();
2715 let ty = match it.type_() {
2716 Typedef | AssocType => AssocType,
2720 let anchor = format!("#{}.{}", ty, name);
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)
2734 _default: Option<&String>,
2735 link: AssocItemLink<'_>,
2740 "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2742 it.visibility.print_with_space(),
2743 naive_assoc_href(it, link),
2744 it.name.as_ref().unwrap(),
2752 bounds: &[clean::GenericBound],
2753 default: Option<&clean::Type>,
2754 link: AssocItemLink<'_>,
2759 "{}type <a href='{}' class=\"type\">{}</a>",
2761 naive_assoc_href(it, link),
2762 it.name.as_ref().unwrap()
2764 if !bounds.is_empty() {
2765 write!(w, ": {}", print_generic_bounds(bounds))
2767 if let Some(default) = default {
2768 write!(w, " = {}", default.print())
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)
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())
2784 fn render_assoc_item(
2787 link: AssocItemLink<'_>,
2793 header: hir::FnHeader,
2794 g: &clean::Generics,
2796 link: AssocItemLink<'_>,
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) {
2813 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
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),
2828 let (indent, end_newline) = if parent == ItemType::Trait {
2834 render_attributes(w, meth, false);
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),
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 }
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(
2864 if parent == ItemType::Trait { " " } else { "" },
2866 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
2872 if parent == ItemType::Trait { " " } else { "" },
2874 _ => panic!("render_assoc_item called on non-associated-item"),
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);
2886 document(w, cx, it);
2890 .filter_map(|f| match f.inner {
2891 clean::StructFieldItem(ref ty) => Some((f, ty)),
2895 if let doctree::Plain = s.struct_type {
2896 if fields.peek().is_some() {
2899 "<h2 id='fields' class='fields small-section-header'>
2900 Fields{}<a href='#fields' class='anchor'></a></h2>",
2901 document_non_exhaustive_header(it)
2903 document_non_exhaustive(w, it);
2904 for (field, ty) in fields {
2905 let id = cx.derive_id(format!(
2907 ItemType::StructField,
2908 field.name.as_ref().unwrap()
2912 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
2913 <a href=\"#{id}\" class=\"anchor field\"></a>\
2914 <code>{name}: {ty}</code>\
2916 item_type = ItemType::StructField,
2918 name = field.name.as_ref().unwrap(),
2921 document(w, cx, field);
2925 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
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);
2936 document(w, cx, it);
2940 .filter_map(|f| match f.inner {
2941 clean::StructFieldItem(ref ty) => Some((f, ty)),
2945 if fields.peek().is_some() {
2948 "<h2 id='fields' class='fields small-section-header'>
2949 Fields<a href='#fields' class='anchor'></a></h2>"
2951 for (field, ty) in fields {
2952 let name = field.name.as_ref().expect("union field name");
2953 let id = format!("{}.{}", ItemType::StructField, name);
2956 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
2957 <a href=\"#{id}\" class=\"anchor field\"></a>\
2958 <code>{name}: {ty}</code>\
2962 shortty = ItemType::StructField,
2965 if let Some(stability_class) = field.stability_class() {
2966 write!(w, "<span class='stab {stab}'></span>", stab = stability_class);
2968 document(w, cx, field);
2971 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
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);
2981 it.visibility.print_with_space(),
2982 it.name.as_ref().unwrap(),
2984 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
2986 if e.variants.is_empty() && !e.variants_stripped {
2990 for v in &e.variants {
2992 let name = v.name.as_ref().unwrap();
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() {
3000 write!(w, ", ")
3002 write!(w, "{}", ty.print());
3006 clean::VariantKind::Struct(ref s) => {
3007 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
3010 _ => unreachable!(),
3015 if e.variants_stripped {
3016 write!(w, " // some variants omitted\n");
3023 document(w, cx, it);
3024 if !e.variants.is_empty() {
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)
3031 document_non_exhaustive(w, it);
3032 for variant in &e.variants {
3034 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3037 "<div id=\"{id}\" class=\"variant small-section-header\">\
3038 <a href=\"#{id}\" class=\"anchor field\"></a>\
3041 name = variant.name.as_ref().unwrap()
3043 if let clean::VariantItem(ref var) = variant.inner {
3044 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3046 for (i, ty) in tys.iter().enumerate() {
3048 write!(w, ", ");
3050 write!(w, "{}", ty.print());
3055 write!(w, "</code></div>");
3056 document(w, cx, variant);
3057 document_non_exhaustive(w, variant);
3059 use crate::clean::{Variant, VariantKind};
3060 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.inner
3062 let variant_id = cx.derive_id(format!(
3065 variant.name.as_ref().unwrap()
3067 write!(w, "<div class='autohide sub-variant' id='{id}'>", id = variant_id);
3070 "<h3>Fields of <b>{name}</b></h3><div>",
3071 name = variant.name.as_ref().unwrap()
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()
3083 "<span id=\"{id}\" class=\"variant small-section-header\">\
3084 <a href=\"#{id}\" class=\"anchor field\"></a>\
3085 <code>{f}: {t}</code>\
3088 f = field.name.as_ref().unwrap(),
3091 document(w, cx, field);
3094 write!(w, "</div></div>");
3096 render_stability_since(w, variant, it);
3099 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3102 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3109 sym::non_exhaustive,
3112 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3113 // left padding. For example:
3115 // #[foo] <----- "top" attribute
3117 // #[bar] <---- not "top" attribute
3120 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3125 .filter_map(|attr| {
3126 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3127 Some(pprust::attribute_to_string(&attr))
3134 if !attrs.is_empty() {
3137 "<span class=\"docblock attributes{}\">{}</span>",
3138 if top { " top-attr" } else { "" },
3147 g: Option<&clean::Generics>,
3148 ty: doctree::StructType,
3149 fields: &[clean::Item],
3156 it.visibility.print_with_space(),
3157 if structhead { "struct " } else { "" },
3158 it.name.as_ref().unwrap()
3160 if let Some(g) = g {
3161 write!(w, "{}", g.print())
3165 if let Some(g) = g {
3166 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3168 let mut has_visible_fields = false;
3170 for field in fields {
3171 if let clean::StructFieldItem(ref ty) = field.inner {
3176 field.visibility.print_with_space(),
3177 field.name.as_ref().unwrap(),
3180 has_visible_fields = true;
3184 if has_visible_fields {
3185 if it.has_stripped_fields().unwrap() {
3186 write!(w, "\n{} // some fields omitted", tab);
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 */ ");
3198 for (i, field) in fields.iter().enumerate() {
3203 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3204 clean::StructFieldItem(ref ty) => {
3205 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3207 _ => unreachable!(),
3211 if let Some(g) = g {
3212 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3217 // Needed for PhantomData.
3218 if let Some(g) = g {
3219 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3229 g: Option<&clean::Generics>,
3230 fields: &[clean::Item],
3237 it.visibility.print_with_space(),
3238 if structhead { "union " } else { "" },
3239 it.name.as_ref().unwrap()
3241 if let Some(g) = g {
3242 write!(w, "{}", g.print());
3243 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3246 write!(w, " {{\n{}", tab);
3247 for field in fields {
3248 if let clean::StructFieldItem(ref ty) = field.inner {
3252 field.visibility.print_with_space(),
3253 field.name.as_ref().unwrap(),
3260 if it.has_stripped_fields().unwrap() {
3261 write!(w, " // some fields omitted\n{}", tab);
3266 #[derive(Copy, Clone)]
3267 enum AssocItemLink<'a> {
3268 Anchor(Option<&'a str>),
3269 GotoSource(DefId, &'a FxHashSet<String>),
3272 impl<'a> AssocItemLink<'a> {
3273 fn anchor(&self, id: &'a String) -> Self {
3275 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3276 ref other => *other,
3281 fn render_assoc_items(
3284 containing_item: &clean::Item,
3286 what: AssocItemRender<'_>,
3289 let v = match cache.impls.get(&it) {
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 => {
3299 "<h2 id='implementations' class='small-section-header'>\
3300 Implementations<a href='#implementations' class='anchor'></a>\
3305 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3308 "<h2 id='deref-methods' class='small-section-header'>\
3309 Methods from {}<Target = {}>\
3310 <a href='#deref-methods' class='anchor'></a>\
3315 RenderMode::ForDeref { mut_: deref_mut_ }
3318 for i in &non_trait {
3323 AssocItemLink::Anchor(None),
3325 containing_item.stable_since(),
3335 if let AssocItemRender::DerefFor { .. } = what {
3338 if !traits.is_empty() {
3340 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3341 if let Some(impl_) = deref_impl {
3343 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3344 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3347 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3348 traits.iter().partition(|t| t.inner_impl().synthetic);
3349 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3350 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3352 let mut impls = Buffer::empty_from(&w);
3353 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3354 let impls = impls.into_inner();
3355 if !impls.is_empty() {
3358 "<h2 id='trait-implementations' class='small-section-header'>\
3359 Trait Implementations<a href='#trait-implementations' class='anchor'></a>\
3361 <div id='trait-implementations-list'>{}</div>",
3366 if !synthetic.is_empty() {
3369 "<h2 id='synthetic-implementations' class='small-section-header'>\
3370 Auto Trait Implementations\
3371 <a href='#synthetic-implementations' class='anchor'></a>\
3373 <div id='synthetic-implementations-list'>"
3375 render_impls(cx, w, &synthetic, containing_item, cache);
3376 write!(w, "</div>");
3379 if !blanket_impl.is_empty() {
3382 "<h2 id='blanket-implementations' class='small-section-header'>\
3383 Blanket Implementations\
3384 <a href='#blanket-implementations' class='anchor'></a>\
3386 <div id='blanket-implementations-list'>"
3388 render_impls(cx, w, &blanket_impl, containing_item, cache);
3389 write!(w, "</div>");
3394 fn render_deref_methods(
3398 container_item: &clean::Item,
3402 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3403 let (target, real_target) = impl_
3407 .find_map(|item| match item.inner {
3408 clean::TypedefItem(ref t, true) => Some(match *t {
3409 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3410 _ => (&t.type_, &t.type_),
3414 .expect("Expected associated type binding");
3416 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3417 if let Some(did) = target.def_id() {
3418 render_assoc_items(w, cx, container_item, did, what, cache);
3420 if let Some(prim) = target.primitive_type() {
3421 if let Some(&did) = cache.primitive_locations.get(&prim) {
3422 render_assoc_items(w, cx, container_item, did, what, cache);
3428 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3429 let self_type_opt = match item.inner {
3430 clean::MethodItem(ref method) => method.decl.self_type(),
3431 clean::TyMethodItem(ref method) => method.decl.self_type(),
3435 if let Some(self_ty) = self_type_opt {
3436 let (by_mut_ref, by_box, by_value) = match self_ty {
3437 SelfTy::SelfBorrowed(_, mutability)
3438 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3439 (mutability == Mutability::Mut, false, false)
3441 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3442 (false, Some(did) == cache().owned_box_did, false)
3444 SelfTy::SelfValue => (false, false, true),
3445 _ => (false, false, false),
3448 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3454 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3455 let mut out = Buffer::html();
3456 let mut trait_ = String::new();
3458 if let Some(did) = decl.output.def_id() {
3460 if let Some(impls) = c.impls.get(&did) {
3462 let impl_ = i.inner_impl();
3463 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3465 out.push_str(&format!(
3466 "<h3 class=\"notable\">Notable traits for {}</h3>\
3467 <code class=\"content\">",
3470 trait_.push_str(&impl_.for_.print().to_string());
3473 //use the "where" class here to make it small
3474 out.push_str(&format!(
3475 "<span class=\"where fmt-newline\">{}</span>",
3478 let t_did = impl_.trait_.def_id().unwrap();
3479 for it in &impl_.items {
3480 if let clean::TypedefItem(ref tydef, _) = it.inner {
3481 out.push_str("<span class=\"where fmt-newline\"> ");
3487 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3490 out.push_str(";</span>");
3498 if !out.is_empty() {
3501 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ<div class='notable-traits-tooltiptext'><span class=\"docblock\">"
3504 out.push_str("</code></span></div></span></span>");
3514 link: AssocItemLink<'_>,
3515 render_mode: RenderMode,
3516 outer_version: Option<&str>,
3517 show_def_docs: bool,
3518 use_absolute: Option<bool>,
3519 is_on_foreign_type: bool,
3520 show_default_items: bool,
3521 // This argument is used to reference same type with different paths to avoid duplication
3522 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3526 if render_mode == RenderMode::Normal {
3527 let id = cx.derive_id(match i.inner_impl().trait_ {
3529 if is_on_foreign_type {
3530 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3532 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3535 None => "impl".to_string(),
3537 let aliases = if aliases.is_empty() {
3540 format!(" aliases=\"{}\"", aliases.join(","))
3542 if let Some(use_absolute) = use_absolute {
3543 write!(w, "<h3 id='{}' class='impl'{}><code class='in-band'>", id, aliases);
3544 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3546 for it in &i.inner_impl().items {
3547 if let clean::TypedefItem(ref tydef, _) = it.inner {
3548 write!(w, "<span class=\"where fmt-newline\"> ");
3549 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3550 write!(w, ";</span>");
3554 write!(w, "</code>");
3558 "<h3 id='{}' class='impl'{}><code class='in-band'>{}</code>",
3561 i.inner_impl().print()
3564 write!(w, "<a href='#{}' class='anchor'></a>", id);
3565 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3566 render_stability_since_raw(w, since, outer_version);
3567 if let Some(l) = cx.src_href(&i.impl_item, cache) {
3568 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>", l, "goto source code");
3571 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3572 let mut ids = cx.id_map.borrow_mut();
3575 "<div class='docblock'>{}</div>",
3578 &i.impl_item.links(),
3582 &cx.shared.playground
3593 link: AssocItemLink<'_>,
3594 render_mode: RenderMode,
3595 is_default_item: bool,
3596 outer_version: Option<&str>,
3597 trait_: Option<&clean::Trait>,
3598 show_def_docs: bool,
3601 let item_type = item.type_();
3602 let name = item.name.as_ref().unwrap();
3604 let render_method_item = match render_mode {
3605 RenderMode::Normal => true,
3606 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3609 let (is_hidden, extra_class) =
3610 if (trait_.is_none() || item.doc_value().is_some() || item.inner.is_type_alias())
3618 clean::MethodItem(clean::Method { .. })
3619 | clean::TyMethodItem(clean::TyMethod { .. }) => {
3620 // Only render when the method is not static or we allow static methods
3621 if render_method_item {
3622 let id = cx.derive_id(format!("{}.{}", item_type, name));
3623 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3624 write!(w, "<code>");
3625 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3626 write!(w, "</code>");
3627 render_stability_since_raw(w, item.stable_since(), outer_version);
3628 if let Some(l) = cx.src_href(item, cache) {
3631 "<a class='srclink' href='{}' title='{}'>[src]</a>",
3632 l, "goto source code"
3638 clean::TypedefItem(ref tydef, _) => {
3639 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3640 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3641 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3642 write!(w, "</code></h4>");
3644 clean::AssocConstItem(ref ty, ref default) => {
3645 let id = cx.derive_id(format!("{}.{}", item_type, name));
3646 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3647 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3648 write!(w, "</code>");
3649 render_stability_since_raw(w, item.stable_since(), outer_version);
3650 if let Some(l) = cx.src_href(item, cache) {
3653 "<a class='srclink' href='{}' title='{}'>[src]</a>",
3654 l, "goto source code"
3659 clean::AssocTypeItem(ref bounds, ref default) => {
3660 let id = cx.derive_id(format!("{}.{}", item_type, name));
3661 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3662 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3663 write!(w, "</code></h4>");
3665 clean::StrippedItem(..) => return,
3666 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3669 if render_method_item {
3670 if !is_default_item {
3671 if let Some(t) = trait_ {
3672 // The trait item may have been stripped so we might not
3673 // find any documentation or stability for it.
3674 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3675 // We need the stability of the item from the trait
3676 // because impls can't have a stability.
3677 document_stability(w, cx, it, is_hidden);
3678 if item.doc_value().is_some() {
3679 document_full(w, item, cx, "", is_hidden);
3680 } else if show_def_docs {
3681 // In case the item isn't documented,
3682 // provide short documentation from the trait.
3683 document_short(w, it, link, "", is_hidden);
3687 document_stability(w, cx, item, is_hidden);
3689 document_full(w, item, cx, "", is_hidden);
3693 document_stability(w, cx, item, is_hidden);
3695 document_short(w, item, link, "", is_hidden);
3701 let traits = &cache.traits;
3702 let trait_ = i.trait_did().map(|did| &traits[&did]);
3704 write!(w, "<div class='impl-items'>");
3705 for trait_item in &i.inner_impl().items {
3720 fn render_default_items(
3725 render_mode: RenderMode,
3726 outer_version: Option<&str>,
3727 show_def_docs: bool,
3730 for trait_item in &t.items {
3731 let n = trait_item.name.clone();
3732 if i.items.iter().any(|m| m.name == n) {
3735 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3736 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3753 // If we've implemented a trait, then also emit documentation for all
3754 // default items which weren't overridden in the implementation block.
3755 // We don't emit documentation for default items if they appear in the
3756 // Implementations on Foreign Types or Implementors sections.
3757 if show_default_items {
3758 if let Some(t) = trait_ {
3759 render_default_items(
3771 write!(w, "</div>");
3778 t: &clean::OpaqueTy,
3781 write!(w, "<pre class='rust opaque'>");
3782 render_attributes(w, it, false);
3785 "type {}{}{where_clause} = impl {bounds};</pre>",
3786 it.name.as_ref().unwrap(),
3788 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3789 bounds = bounds(&t.bounds, false)
3792 document(w, cx, it);
3794 // Render any items associated directly to this alias, as otherwise they
3795 // won't be visible anywhere in the docs. It would be nice to also show
3796 // associated items from the aliased type (see discussion in #32077), but
3797 // we need #14072 to make sense of the generics.
3798 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3801 fn item_trait_alias(
3805 t: &clean::TraitAlias,
3808 write!(w, "<pre class='rust trait-alias'>");
3809 render_attributes(w, it, false);
3812 "trait {}{}{} = {};</pre>",
3813 it.name.as_ref().unwrap(),
3815 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3816 bounds(&t.bounds, true)
3819 document(w, cx, it);
3821 // Render any items associated directly to this alias, as otherwise they
3822 // won't be visible anywhere in the docs. It would be nice to also show
3823 // associated items from the aliased type (see discussion in #32077), but
3824 // we need #14072 to make sense of the generics.
3825 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3828 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
3829 write!(w, "<pre class='rust typedef'>");
3830 render_attributes(w, it, false);
3833 "type {}{}{where_clause} = {type_};</pre>",
3834 it.name.as_ref().unwrap(),
3836 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3837 type_ = t.type_.print()
3840 document(w, cx, it);
3842 // Render any items associated directly to this alias, as otherwise they
3843 // won't be visible anywhere in the docs. It would be nice to also show
3844 // associated items from the aliased type (see discussion in #32077), but
3845 // we need #14072 to make sense of the generics.
3846 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3849 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
3850 writeln!(w, "<pre class='rust foreigntype'>extern {{");
3851 render_attributes(w, it, false);
3854 " {}type {};\n}}</pre>",
3855 it.visibility.print_with_space(),
3856 it.name.as_ref().unwrap(),
3859 document(w, cx, it);
3861 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3864 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
3865 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
3869 || it.is_primitive()
3877 "<p class='location'>{}{}</p>",
3879 clean::StructItem(..) => "Struct ",
3880 clean::TraitItem(..) => "Trait ",
3881 clean::PrimitiveItem(..) => "Primitive Type ",
3882 clean::UnionItem(..) => "Union ",
3883 clean::EnumItem(..) => "Enum ",
3884 clean::TypedefItem(..) => "Type Definition ",
3885 clean::ForeignTypeItem => "Foreign Type ",
3886 clean::ModuleItem(..) =>
3894 it.name.as_ref().unwrap()
3899 if let Some(ref version) = cache.crate_version {
3902 "<div class='block version'>\
3910 write!(buffer, "<div class=\"sidebar-elems\">");
3914 "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3915 it.name.as_ref().expect("crates always have a name")
3919 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
3920 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
3921 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
3922 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
3923 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
3924 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
3925 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
3926 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
3930 // The sidebar is designed to display sibling functions, modules and
3931 // other miscellaneous information. since there are lots of sibling
3932 // items (and that causes quadratic growth in large modules),
3933 // we refactor common parts into a shared JavaScript file per module.
3934 // still, we don't move everything into JS because we want to preserve
3935 // as much HTML as possible in order to allow non-JS-enabled browsers
3936 // to navigate the documentation (though slightly inefficiently).
3938 write!(buffer, "<p class='location'>");
3939 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3941 write!(buffer, "::<wbr>");
3945 "<a href='{}index.html'>{}</a>",
3946 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3950 write!(buffer, "</p>");
3952 // Sidebar refers to the enclosing module, not this module.
3953 let relpath = if it.is_mod() { "../" } else { "" };
3956 "<script>window.sidebarCurrent = {{\
3961 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3966 // There is no sidebar-items.js beyond the crate root path
3967 // FIXME maybe dynamic crate loading can be merged here
3969 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
3971 // Closes sidebar-elems div.
3972 write!(buffer, "</div>");
3975 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
3976 if used_links.insert(url.clone()) {
3980 while !used_links.insert(format!("{}-{}", url, add)) {
3983 format!("{}-{}", url, add)
3989 used_links: &mut FxHashSet<String>,
3994 .filter_map(|item| match item.name {
3995 Some(ref name) if !name.is_empty() && item.is_method() => {
3996 if !for_deref || should_render_item(item, deref_mut) {
3998 "<a href=\"#{}\">{}</a>",
3999 get_next_url(used_links, format!("method.{}", name)),
4008 .collect::<Vec<_>>()
4011 // The point is to url encode any potential character from a type with genericity.
4012 fn small_url_encode(s: &str) -> String {
4013 s.replace("<", "%3C")
4014 .replace(">", "%3E")
4015 .replace(" ", "%20")
4016 .replace("?", "%3F")
4017 .replace("'", "%27")
4018 .replace("&", "%26")
4019 .replace(",", "%2C")
4020 .replace(":", "%3A")
4021 .replace(";", "%3B")
4022 .replace("[", "%5B")
4023 .replace("]", "%5D")
4024 .replace("\"", "%22")
4027 fn sidebar_assoc_items(it: &clean::Item) -> String {
4028 let mut out = String::new();
4030 if let Some(v) = c.impls.get(&it.def_id) {
4031 let mut used_links = FxHashSet::default();
4034 let used_links_bor = &mut used_links;
4037 .filter(|i| i.inner_impl().trait_.is_none())
4038 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4039 .collect::<Vec<_>>();
4040 if !ret.is_empty() {
4041 // We want links' order to be reproducible so we don't use unstable sort.
4043 out.push_str(&format!(
4044 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4045 <div class=\"sidebar-links\">{}</div>",
4051 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4052 if let Some(impl_) = v
4054 .filter(|i| i.inner_impl().trait_.is_some())
4055 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4057 if let Some((target, real_target)) =
4058 impl_.inner_impl().items.iter().find_map(|item| match item.inner {
4059 clean::TypedefItem(ref t, true) => Some(match *t {
4060 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4061 _ => (&t.type_, &t.type_),
4068 .filter(|i| i.inner_impl().trait_.is_some())
4069 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4070 let inner_impl = target
4074 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4075 .and_then(|did| c.impls.get(&did));
4076 if let Some(impls) = inner_impl {
4077 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4078 out.push_str(&format!(
4079 "Methods from {}<Target={}>",
4082 impl_.inner_impl().trait_.as_ref().unwrap().print()
4084 Escape(&format!("{:#}", real_target.print()))
4086 out.push_str("</a>");
4089 .filter(|i| i.inner_impl().trait_.is_none())
4091 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4093 .collect::<Vec<_>>();
4094 // We want links' order to be reproducible so we don't use unstable sort.
4096 if !ret.is_empty() {
4097 out.push_str(&format!(
4098 "<div class=\"sidebar-links\">{}</div>",
4105 let format_impls = |impls: Vec<&Impl>| {
4106 let mut links = FxHashSet::default();
4111 let is_negative_impl = is_negative_impl(i.inner_impl());
4112 if let Some(ref i) = i.inner_impl().trait_ {
4113 let i_display = format!("{:#}", i.print());
4114 let out = Escape(&i_display);
4115 let encoded = small_url_encode(&format!("{:#}", i.print()));
4116 let generated = format!(
4117 "<a href=\"#impl-{}\">{}{}</a>",
4119 if is_negative_impl { "!" } else { "" },
4122 if links.insert(generated.clone()) { Some(generated) } else { None }
4127 .collect::<Vec<String>>();
4132 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4133 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4134 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4136 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4138 let concrete_format = format_impls(concrete);
4139 let synthetic_format = format_impls(synthetic);
4140 let blanket_format = format_impls(blanket_impl);
4142 if !concrete_format.is_empty() {
4144 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4145 Trait Implementations</a>",
4147 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4150 if !synthetic_format.is_empty() {
4152 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4153 Auto Trait Implementations</a>",
4155 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4158 if !blanket_format.is_empty() {
4160 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4161 Blanket Implementations</a>",
4163 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4171 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4172 let mut sidebar = String::new();
4173 let fields = get_struct_fields_name(&s.fields);
4175 if !fields.is_empty() {
4176 if let doctree::Plain = s.struct_type {
4177 sidebar.push_str(&format!(
4178 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4179 <div class=\"sidebar-links\">{}</div>",
4185 sidebar.push_str(&sidebar_assoc_items(it));
4187 if !sidebar.is_empty() {
4188 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4192 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4193 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4196 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4198 clean::ItemEnum::ImplItem(ref i) => {
4199 if let Some(ref trait_) = i.trait_ {
4201 format!("{:#}", i.for_.print()),
4202 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4212 fn is_negative_impl(i: &clean::Impl) -> bool {
4213 i.polarity == Some(clean::ImplPolarity::Negative)
4216 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4217 let mut sidebar = String::new();
4222 .filter_map(|m| match m.name {
4223 Some(ref name) if m.is_associated_type() => {
4224 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4228 .collect::<Vec<_>>();
4232 .filter_map(|m| match m.name {
4233 Some(ref name) if m.is_associated_const() => {
4234 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4238 .collect::<Vec<_>>();
4239 let mut required = t
4242 .filter_map(|m| match m.name {
4243 Some(ref name) if m.is_ty_method() => {
4244 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4248 .collect::<Vec<String>>();
4249 let mut provided = t
4252 .filter_map(|m| match m.name {
4253 Some(ref name) if m.is_method() => {
4254 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4258 .collect::<Vec<String>>();
4260 if !types.is_empty() {
4262 sidebar.push_str(&format!(
4263 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4264 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4268 if !consts.is_empty() {
4270 sidebar.push_str(&format!(
4271 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4272 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4276 if !required.is_empty() {
4278 sidebar.push_str(&format!(
4279 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4280 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4284 if !provided.is_empty() {
4286 sidebar.push_str(&format!(
4287 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4288 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4295 if let Some(implementors) = c.implementors.get(&it.def_id) {
4296 let mut res = implementors
4298 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4299 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4300 .collect::<Vec<_>>();
4302 if !res.is_empty() {
4304 sidebar.push_str(&format!(
4305 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4306 Implementations on Foreign Types</a>\
4307 <div class=\"sidebar-links\">{}</div>",
4309 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4310 .collect::<Vec<_>>()
4316 sidebar.push_str(&sidebar_assoc_items(it));
4318 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4321 "<a class=\"sidebar-title\" \
4322 href=\"#synthetic-implementors\">Auto Implementors</a>",
4326 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4329 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4330 let sidebar = sidebar_assoc_items(it);
4332 if !sidebar.is_empty() {
4333 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4337 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4338 let sidebar = sidebar_assoc_items(it);
4340 if !sidebar.is_empty() {
4341 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4345 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4346 let mut fields = fields
4348 .filter(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false })
4349 .filter_map(|f| match f.name {
4351 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4355 .collect::<Vec<_>>();
4360 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4361 let mut sidebar = String::new();
4362 let fields = get_struct_fields_name(&u.fields);
4364 if !fields.is_empty() {
4365 sidebar.push_str(&format!(
4366 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4367 <div class=\"sidebar-links\">{}</div>",
4372 sidebar.push_str(&sidebar_assoc_items(it));
4374 if !sidebar.is_empty() {
4375 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4379 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4380 let mut sidebar = String::new();
4382 let mut variants = e
4385 .filter_map(|v| match v.name {
4386 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4389 .collect::<Vec<_>>();
4390 if !variants.is_empty() {
4391 variants.sort_unstable();
4392 sidebar.push_str(&format!(
4393 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4394 <div class=\"sidebar-links\">{}</div>",
4399 sidebar.push_str(&sidebar_assoc_items(it));
4401 if !sidebar.is_empty() {
4402 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4406 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4408 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4409 ItemType::Module => ("modules", "Modules"),
4410 ItemType::Struct => ("structs", "Structs"),
4411 ItemType::Union => ("unions", "Unions"),
4412 ItemType::Enum => ("enums", "Enums"),
4413 ItemType::Function => ("functions", "Functions"),
4414 ItemType::Typedef => ("types", "Type Definitions"),
4415 ItemType::Static => ("statics", "Statics"),
4416 ItemType::Constant => ("constants", "Constants"),
4417 ItemType::Trait => ("traits", "Traits"),
4418 ItemType::Impl => ("impls", "Implementations"),
4419 ItemType::TyMethod => ("tymethods", "Type Methods"),
4420 ItemType::Method => ("methods", "Methods"),
4421 ItemType::StructField => ("fields", "Struct Fields"),
4422 ItemType::Variant => ("variants", "Variants"),
4423 ItemType::Macro => ("macros", "Macros"),
4424 ItemType::Primitive => ("primitives", "Primitive Types"),
4425 ItemType::AssocType => ("associated-types", "Associated Types"),
4426 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4427 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4428 ItemType::Keyword => ("keywords", "Keywords"),
4429 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4430 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4431 ItemType::ProcDerive => ("derives", "Derive Macros"),
4432 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4436 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4437 let mut sidebar = String::new();
4439 if items.iter().any(|it| it.type_() == ItemType::ExternCrate || it.type_() == ItemType::Import)
4441 sidebar.push_str(&format!(
4442 "<li><a href=\"#{id}\">{name}</a></li>",
4448 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4449 // to print its headings
4451 ItemType::Primitive,
4465 ItemType::StructField,
4467 ItemType::AssocType,
4468 ItemType::AssocConst,
4469 ItemType::ForeignType,
4472 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4473 let (short, name) = item_ty_to_strs(&myty);
4474 sidebar.push_str(&format!(
4475 "<li><a href=\"#{id}\">{name}</a></li>",
4482 if !sidebar.is_empty() {
4483 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4487 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4488 let sidebar = sidebar_assoc_items(it);
4489 if !sidebar.is_empty() {
4490 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4494 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4495 wrap_into_docblock(w, |w| {
4496 w.write_str(&highlight::render_with_highlighting(
4506 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4507 let name = it.name.as_ref().expect("proc-macros always have names");
4509 MacroKind::Bang => {
4510 write!(w, "<pre class='rust macro'>");
4511 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4512 write!(w, "</pre>");
4514 MacroKind::Attr => {
4515 write!(w, "<pre class='rust attr'>");
4516 write!(w, "#[{}]", name);
4517 write!(w, "</pre>");
4519 MacroKind::Derive => {
4520 write!(w, "<pre class='rust derive'>");
4521 write!(w, "#[derive({})]", name);
4522 if !m.helpers.is_empty() {
4523 writeln!(w, "\n{{");
4524 writeln!(w, " // Attributes available to this derive:");
4525 for attr in &m.helpers {
4526 writeln!(w, " #[{}]", attr);
4530 write!(w, "</pre>");
4536 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4537 document(w, cx, it);
4538 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4541 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4545 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4547 fn make_item_keywords(it: &clean::Item) -> String {
4548 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4551 /// Returns a list of all paths used in the type.
4552 /// This is used to help deduplicate imported impls
4553 /// for reexported types. If any of the contained
4554 /// types are re-exported, we don't use the corresponding
4555 /// entry from the js file, as inlining will have already
4556 /// picked up the impl
4557 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4558 let mut out = Vec::new();
4559 let mut visited = FxHashSet::default();
4560 let mut work = VecDeque::new();
4561 let cache = cache();
4563 work.push_back(first_ty);
4565 while let Some(ty) = work.pop_front() {
4566 if !visited.insert(ty.clone()) {
4571 clean::Type::ResolvedPath { did, .. } => {
4572 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4573 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4575 if let Some(path) = fqp {
4576 out.push(path.join("::"));
4579 clean::Type::Tuple(tys) => {
4580 work.extend(tys.into_iter());
4582 clean::Type::Slice(ty) => {
4583 work.push_back(*ty);
4585 clean::Type::Array(ty, _) => {
4586 work.push_back(*ty);
4588 clean::Type::RawPointer(_, ty) => {
4589 work.push_back(*ty);
4591 clean::Type::BorrowedRef { type_, .. } => {
4592 work.push_back(*type_);
4594 clean::Type::QPath { self_type, trait_, .. } => {
4595 work.push_back(*self_type);
4596 work.push_back(*trait_);