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_attr::StabilityLevel;
53 use rustc_data_structures::flock;
54 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
55 use rustc_feature::UnstableFeatures;
57 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
58 use rustc_hir::Mutability;
59 use rustc_middle::middle::stability;
60 use rustc_span::edition::Edition;
61 use rustc_span::hygiene::MacroKind;
62 use rustc_span::source_map::FileName;
63 use rustc_span::symbol::{sym, Symbol};
64 use serde::ser::SerializeSeq;
65 use serde::{Serialize, Serializer};
67 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, RenderedLink, SelfTy, TypeKind};
68 use crate::config::{RenderInfo, RenderOptions};
69 use crate::docfs::{DocFS, PathError};
71 use crate::error::Error;
72 use crate::formats::cache::{cache, Cache};
73 use crate::formats::item_type::ItemType;
74 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
75 use crate::html::escape::Escape;
76 use crate::html::format::fmt_impl_for_trait_page;
77 use crate::html::format::Function;
78 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
79 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
80 use crate::html::markdown::{self, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine};
81 use crate::html::sources;
82 use crate::html::{highlight, layout, static_files};
83 use cache::{build_index, ExternalLocation};
85 /// A pair of name and its optional document.
86 pub type NameDoc = (String, Option<String>);
88 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
89 crate::html::format::display_fn(move |f| {
90 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
94 /// Major driving force in all rustdoc rendering. This contains information
95 /// about where in the tree-like hierarchy rendering is occurring and controls
96 /// how the current page is being rendered.
98 /// It is intended that this context is a lightweight object which can be fairly
99 /// easily cloned because it is cloned per work-job (about once per item in the
102 crate struct Context {
103 /// Current hierarchy of components leading down to what's currently being
105 pub current: Vec<String>,
106 /// The current destination folder of where HTML artifacts should be placed.
107 /// This changes as the context descends into the module hierarchy.
109 /// A flag, which when `true`, will render pages which redirect to the
110 /// real location of an item. This is used to allow external links to
111 /// publicly reused items to redirect to the right location.
112 pub render_redirect_pages: bool,
113 /// The map used to ensure all generated 'id=' attributes are unique.
114 id_map: Rc<RefCell<IdMap>>,
115 pub shared: Arc<SharedContext>,
116 all: Rc<RefCell<AllTypes>>,
117 /// Storage for the errors produced while generating documentation so they
118 /// can be printed together at the end.
119 pub errors: Rc<Receiver<String>>,
122 crate struct SharedContext {
123 /// The path to the crate root source minus the file name.
124 /// Used for simplifying paths to the highlighted source code files.
125 pub src_root: PathBuf,
126 /// This describes the layout of each page, and is not modified after
127 /// creation of the context (contains info like the favicon and added html).
128 pub layout: layout::Layout,
129 /// This flag indicates whether `[src]` links should be generated or not. If
130 /// the source files are present in the html rendering, then this will be
132 pub include_sources: bool,
133 /// The local file sources we've emitted and their respective url-paths.
134 pub local_sources: FxHashMap<PathBuf, String>,
135 /// Whether the collapsed pass ran
137 /// The base-URL of the issue tracker for when an item has been tagged with
139 pub issue_tracker_base_url: Option<String>,
140 /// The directories that have already been created in this doc run. Used to reduce the number
141 /// of spurious `create_dir_all` calls.
142 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
143 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
144 /// should be ordered alphabetically or in order of appearance (in the source code).
145 pub sort_modules_alphabetically: bool,
146 /// Additional CSS files to be added to the generated docs.
147 pub style_files: Vec<StylePath>,
148 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
150 pub resource_suffix: String,
151 /// Optional path string to be used to load static files on output pages. If not set, uses
152 /// combinations of `../` to reach the documentation root.
153 pub static_root_path: Option<String>,
154 /// The fs handle we are working with.
156 /// The default edition used to parse doctests.
157 pub edition: Edition,
158 pub codes: ErrorCodes,
159 playground: Option<markdown::Playground>,
163 fn path(&self, filename: &str) -> PathBuf {
164 // We use splitn vs Path::extension here because we might get a filename
165 // like `style.min.css` and we want to process that into
166 // `style-suffix.min.css`. Path::extension would just return `css`
167 // which would result in `style.min-suffix.css` which isn't what we
169 let mut iter = filename.splitn(2, '.');
170 let base = iter.next().unwrap();
171 let ext = iter.next().unwrap();
172 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext,);
173 self.dst.join(&filename)
178 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
179 let mut dirs = self.created_dirs.borrow_mut();
180 if !dirs.contains(dst) {
181 try_err!(self.fs.create_dir_all(dst), dst);
182 dirs.insert(dst.to_path_buf());
188 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
189 /// `collapsed_doc_value` of the given item.
190 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
192 item.collapsed_doc_value().map(|s| s.into())
194 item.doc_value().map(|s| s.into())
199 // Helper structs for rendering items/sidebars and carrying along contextual
202 /// Struct representing one entry in the JS search index. These are all emitted
203 /// by hand to a large JS file at the end of cache-creation.
205 pub struct IndexItem {
210 pub parent: Option<DefId>,
211 pub parent_idx: Option<usize>,
212 pub search_type: Option<IndexItemFunctionType>,
215 impl Serialize for IndexItem {
216 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
221 self.parent.is_some(),
222 self.parent_idx.is_some(),
223 "`{}` is missing idx",
227 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
228 .serialize(serializer)
232 /// A type used for the search index.
234 crate struct RenderType {
237 name: Option<String>,
238 generics: Option<Vec<Generic>>,
241 impl Serialize for RenderType {
242 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
246 if let Some(name) = &self.name {
247 let mut seq = serializer.serialize_seq(None)?;
248 if let Some(id) = self.idx {
249 seq.serialize_element(&id)?;
251 seq.serialize_element(&name)?;
253 if let Some(generics) = &self.generics {
254 seq.serialize_element(&generics)?;
258 serializer.serialize_none()
263 /// A type used for the search index.
265 crate struct Generic {
267 defid: Option<DefId>,
271 impl Serialize for Generic {
272 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
276 if let Some(id) = self.idx {
277 serializer.serialize_some(&id)
279 serializer.serialize_some(&self.name)
284 /// Full type of functions/methods in the search index.
286 pub struct IndexItemFunctionType {
287 inputs: Vec<TypeWithKind>,
288 output: Option<Vec<TypeWithKind>>,
291 impl Serialize for IndexItemFunctionType {
292 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
296 // If we couldn't figure out a type, just write `null`.
297 let mut iter = self.inputs.iter();
298 if match self.output {
299 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
300 None => iter.any(|ref i| i.ty.name.is_none()),
302 serializer.serialize_none()
304 let mut seq = serializer.serialize_seq(None)?;
305 seq.serialize_element(&self.inputs)?;
306 if let Some(output) = &self.output {
307 if output.len() > 1 {
308 seq.serialize_element(&output)?;
310 seq.serialize_element(&output[0])?;
319 crate struct TypeWithKind {
324 impl From<(RenderType, TypeKind)> for TypeWithKind {
325 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
326 TypeWithKind { ty: x.0, kind: x.1 }
330 impl Serialize for TypeWithKind {
331 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
335 let mut seq = serializer.serialize_seq(None)?;
336 seq.serialize_element(&self.ty.name)?;
337 let x: ItemType = self.kind.into();
338 seq.serialize_element(&x)?;
343 #[derive(Debug, Clone)]
344 pub struct StylePath {
345 /// The path to the theme
347 /// What the `disabled` attribute should be set to in the HTML tag
351 thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
353 pub fn initial_ids() -> Vec<String> {
365 "synthetic-implementors",
367 "synthetic-implementors-list",
373 .map(|id| (String::from(*id)))
377 /// Generates the documentation for `crate` into the directory `dst`
378 impl FormatRenderer for Context {
380 mut krate: clean::Crate,
381 options: RenderOptions,
382 _render_info: RenderInfo,
385 ) -> Result<(Context, clean::Crate), Error> {
386 // need to save a copy of the options for rendering the index page
387 let md_opts = options.clone();
393 sort_modules_alphabetically,
399 generate_search_filter,
403 let src_root = match krate.src {
404 FileName::Real(ref p) => match p.local_path().parent() {
405 Some(p) => p.to_path_buf(),
406 None => PathBuf::new(),
410 // If user passed in `--playground-url` arg, we fill in crate name here
411 let mut playground = None;
412 if let Some(url) = playground_url {
413 playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url });
415 let mut layout = layout::Layout {
417 favicon: String::new(),
420 krate: krate.name.clone(),
421 css_file_extension: extension_css,
422 generate_search_filter,
424 let mut issue_tracker_base_url = None;
425 let mut include_sources = true;
427 // Crawl the crate attributes looking for attributes which control how we're
428 // going to emit HTML
429 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
430 for attr in attrs.lists(sym::doc) {
431 match (attr.name_or_empty(), attr.value_str()) {
432 (sym::html_favicon_url, Some(s)) => {
433 layout.favicon = s.to_string();
435 (sym::html_logo_url, Some(s)) => {
436 layout.logo = s.to_string();
438 (sym::html_playground_url, Some(s)) => {
439 playground = Some(markdown::Playground {
440 crate_name: Some(krate.name.clone()),
444 (sym::issue_tracker_base_url, Some(s)) => {
445 issue_tracker_base_url = Some(s.to_string());
447 (sym::html_no_source, None) if attr.is_word() => {
448 include_sources = false;
454 let (sender, receiver) = channel();
455 let mut scx = SharedContext {
456 collapsed: krate.collapsed,
459 local_sources: Default::default(),
460 issue_tracker_base_url,
462 created_dirs: Default::default(),
463 sort_modules_alphabetically,
467 fs: DocFS::new(sender),
469 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
473 // Add the default themes to the `Vec` of stylepaths
475 // Note that these must be added before `sources::render` is called
476 // so that the resulting source pages are styled
478 // `light.css` is not disabled because it is the stylesheet that stays loaded
479 // by the browser as the theme stylesheet. The theme system (hackily) works by
480 // changing the href to this stylesheet. All other themes are disabled to
481 // prevent rule conflicts
482 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
483 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
484 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
487 scx.ensure_dir(&dst)?;
488 krate = sources::render(&dst, &mut scx, krate)?;
490 // Build our search index
491 let index = build_index(&krate, cache);
493 let cache = Arc::new(cache);
494 let mut cx = Context {
497 render_redirect_pages: false,
498 id_map: Rc::new(RefCell::new(id_map)),
499 shared: Arc::new(scx),
500 all: Rc::new(RefCell::new(AllTypes::new())),
501 errors: Rc::new(receiver),
504 CURRENT_DEPTH.with(|s| s.set(0));
506 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
507 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
508 write_shared(&cx, &krate, index, &md_opts, &cache)?;
509 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
513 fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
514 Arc::get_mut(&mut self.shared).unwrap().fs.close();
515 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
517 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
523 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
524 let final_file = self.dst.join(&krate.name).join("all.html");
525 let settings_file = self.dst.join("settings.html");
526 let crate_name = krate.name.clone();
528 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
529 if !root_path.ends_with('/') {
532 let mut page = layout::Page {
533 title: "List of all items in this crate",
536 static_root_path: self.shared.static_root_path.as_deref(),
537 description: "List of all items in this crate",
538 keywords: BASIC_KEYWORDS,
539 resource_suffix: &self.shared.resource_suffix,
541 static_extra_scripts: &[],
543 let sidebar = if let Some(ref version) = cache.crate_version {
545 "<p class=\"location\">Crate {}</p>\
546 <div class=\"block version\">\
549 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
556 let all = self.all.replace(AllTypes::new());
557 let v = layout::render(
561 |buf: &mut Buffer| all.print(buf),
562 &self.shared.style_files,
564 self.shared.fs.write(&final_file, v.as_bytes())?;
566 // Generating settings page.
567 page.title = "Rustdoc settings";
568 page.description = "Settings of Rustdoc";
569 page.root_path = "./";
571 let mut style_files = self.shared.style_files.clone();
572 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
573 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
574 let v = layout::render(
579 self.shared.static_root_path.as_deref().unwrap_or("./"),
580 &self.shared.resource_suffix,
581 &self.shared.style_files,
585 self.shared.fs.write(&settings_file, v.as_bytes())?;
594 ) -> Result<(), Error> {
595 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
596 // if they contain impls for public types. These modules can also
597 // contain items such as publicly re-exported structures.
599 // External crates will provide links to these structures, so
600 // these modules are recursed into, but not rendered normally
601 // (a flag on the context).
602 if !self.render_redirect_pages {
603 self.render_redirect_pages = item.is_stripped();
605 let scx = &self.shared;
606 self.dst.push(item_name);
607 self.current.push(item_name.to_owned());
609 info!("Recursing into {}", self.dst.display());
611 let buf = self.render_item(item, false, cache);
612 // buf will be empty if the module is stripped and there is no redirect for it
614 self.shared.ensure_dir(&self.dst)?;
615 let joint_dst = self.dst.join("index.html");
616 scx.fs.write(&joint_dst, buf.as_bytes())?;
619 // Render sidebar-items.js used throughout this module.
620 if !self.render_redirect_pages {
621 let module = match item.inner {
622 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
625 let items = self.build_sidebar_items(module);
626 let js_dst = self.dst.join("sidebar-items.js");
627 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
628 scx.fs.write(&js_dst, &v)?;
633 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
634 info!("Recursed; leaving {}", self.dst.display());
636 // Go back to where we were at
642 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
643 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
644 // if they contain impls for public types. These modules can also
645 // contain items such as publicly re-exported structures.
647 // External crates will provide links to these structures, so
648 // these modules are recursed into, but not rendered normally
649 // (a flag on the context).
650 if !self.render_redirect_pages {
651 self.render_redirect_pages = item.is_stripped();
654 let buf = self.render_item(&item, true, cache);
655 // buf will be empty if the item is stripped and there is no redirect for it
657 let name = item.name.as_ref().unwrap();
658 let item_type = item.type_();
659 let file_name = &item_path(item_type, name);
660 self.shared.ensure_dir(&self.dst)?;
661 let joint_dst = self.dst.join(file_name);
662 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
664 if !self.render_redirect_pages {
665 self.all.borrow_mut().append(full_path(self, &item), &item_type);
667 // If the item is a macro, redirect from the old macro URL (with !)
668 // to the new one (without).
669 if item_type == ItemType::Macro {
670 let redir_name = format!("{}.{}!.html", item_type, name);
671 let redir_dst = self.dst.join(redir_name);
672 let v = layout::redirect(file_name);
673 self.shared.fs.write(&redir_dst, v.as_bytes())?;
682 krate: &clean::Crate,
683 search_index: String,
684 options: &RenderOptions,
686 ) -> Result<(), Error> {
687 // Write out the shared files. Note that these are shared among all rustdoc
688 // docs placed in the output directory, so this needs to be a synchronized
689 // operation with respect to all other rustdocs running around.
690 let lock_file = cx.dst.join(".lock");
691 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
693 // Add all the static files. These may already exist, but we just
694 // overwrite them anyway to make sure that they're fresh and up-to-date.
698 cx.path("rustdoc.css"),
699 static_files::RUSTDOC_CSS,
700 options.enable_minification,
704 cx.path("settings.css"),
705 static_files::SETTINGS_CSS,
706 options.enable_minification,
710 cx.path("noscript.css"),
711 static_files::NOSCRIPT_CSS,
712 options.enable_minification,
715 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
716 // then we'll run over the "official" styles.
717 let mut themes: FxHashSet<String> = FxHashSet::default();
719 for entry in &cx.shared.style_files {
720 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
722 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
724 // Handle the official themes
726 "light" => write_minify(
728 cx.path("light.css"),
729 static_files::themes::LIGHT,
730 options.enable_minification,
732 "dark" => write_minify(
735 static_files::themes::DARK,
736 options.enable_minification,
738 "ayu" => write_minify(
741 static_files::themes::AYU,
742 options.enable_minification,
745 // Handle added third-party themes
746 let content = try_err!(fs::read(&entry.path), &entry.path);
749 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
753 themes.insert(theme.to_owned());
756 let write = |p, c| cx.shared.fs.write(p, c);
757 if (*cx.shared).layout.logo.is_empty() {
758 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
760 if (*cx.shared).layout.favicon.is_empty() {
761 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
762 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
763 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
765 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
766 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
767 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
769 let mut themes: Vec<&String> = themes.iter().collect();
771 // To avoid theme switch latencies as much as possible, we put everything theme related
772 // at the beginning of the html files into another js file.
773 let theme_js = format!(
774 r#"var themes = document.getElementById("theme-choices");
775 var themePicker = document.getElementById("theme-picker");
777 function showThemeButtonState() {{
778 themes.style.display = "block";
779 themePicker.style.borderBottomRightRadius = "0";
780 themePicker.style.borderBottomLeftRadius = "0";
783 function hideThemeButtonState() {{
784 themes.style.display = "none";
785 themePicker.style.borderBottomRightRadius = "3px";
786 themePicker.style.borderBottomLeftRadius = "3px";
789 function switchThemeButtonState() {{
790 if (themes.style.display === "block") {{
791 hideThemeButtonState();
793 showThemeButtonState();
797 function handleThemeButtonsBlur(e) {{
798 var active = document.activeElement;
799 var related = e.relatedTarget;
801 if (active.id !== "themePicker" &&
802 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
804 (related.id !== "themePicker" &&
805 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
806 hideThemeButtonState();
810 themePicker.onclick = switchThemeButtonState;
811 themePicker.onblur = handleThemeButtonsBlur;
812 {}.forEach(function(item) {{
813 var but = document.createElement("button");
814 but.textContent = item;
815 but.onclick = function(el) {{
816 switchTheme(currentTheme, mainTheme, item, true);
817 useSystemTheme(false);
819 but.onblur = handleThemeButtonsBlur;
820 themes.appendChild(but);
822 serde_json::to_string(&themes).unwrap()
825 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
829 static_files::MAIN_JS,
830 options.enable_minification,
834 cx.path("settings.js"),
835 static_files::SETTINGS_JS,
836 options.enable_minification,
838 if cx.shared.include_sources {
841 cx.path("source-script.js"),
842 static_files::sidebar::SOURCE_SCRIPT,
843 options.enable_minification,
850 cx.path("storage.js"),
852 "var resourcesSuffix = \"{}\";{}",
853 cx.shared.resource_suffix,
854 static_files::STORAGE_JS
856 options.enable_minification,
860 if let Some(ref css) = cx.shared.layout.css_file_extension {
861 let out = cx.path("theme.css");
862 let buffer = try_err!(fs::read_to_string(css), css);
863 if !options.enable_minification {
864 cx.shared.fs.write(&out, &buffer)?;
866 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
871 cx.path("normalize.css"),
872 static_files::NORMALIZE_CSS,
873 options.enable_minification,
875 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
876 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
877 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
878 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
879 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
880 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
881 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
882 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
883 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
884 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
885 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
886 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
887 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
889 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
890 let mut ret = Vec::new();
891 let mut krates = Vec::new();
894 for line in BufReader::new(File::open(path)?).lines() {
896 if !line.starts_with(key) {
899 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
902 ret.push(line.to_string());
904 line[key.len() + 2..]
907 .map(|s| s.to_owned())
908 .unwrap_or_else(String::new),
915 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
916 let mut ret = Vec::new();
917 let mut krates = Vec::new();
920 for line in BufReader::new(File::open(path)?).lines() {
922 if !line.starts_with('"') {
925 if line.starts_with(&format!("\"{}\"", krate)) {
928 if line.ends_with(",\\") {
929 ret.push(line[..line.len() - 2].to_string());
931 // Ends with "\\" (it's the case for the last added crate line)
932 ret.push(line[..line.len() - 1].to_string());
936 .find(|s| !s.is_empty())
937 .map(|s| s.to_owned())
938 .unwrap_or_else(String::new),
945 use std::ffi::OsString;
950 children: FxHashMap<OsString, Hierarchy>,
951 elems: FxHashSet<OsString>,
955 fn new(elem: OsString) -> Hierarchy {
956 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
959 fn to_json_string(&self) -> String {
960 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
961 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
965 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
966 .collect::<Vec<_>>();
967 files.sort_unstable_by(|a, b| a.cmp(b));
968 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
970 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
971 let files = files.join(",");
973 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
975 "{{\"name\":\"{name}\"{dirs}{files}}}",
976 name = self.elem.to_str().expect("invalid osstring conversion"),
983 if cx.shared.include_sources {
984 let mut hierarchy = Hierarchy::new(OsString::new());
989 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
991 let mut h = &mut hierarchy;
992 let mut elems = source
994 .filter_map(|s| match s {
995 Component::Normal(s) => Some(s.to_owned()),
1000 let cur_elem = elems.next().expect("empty file path");
1001 if elems.peek().is_none() {
1002 h.elems.insert(cur_elem);
1005 let e = cur_elem.clone();
1006 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1007 h = h.children.get_mut(&cur_elem).expect("not found child");
1012 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1013 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1014 all_sources.push(format!(
1015 "sourcesIndex[\"{}\"] = {};",
1017 hierarchy.to_json_string()
1021 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1022 all_sources.join("\n")
1024 cx.shared.fs.write(&dst, v.as_bytes())?;
1027 // Update the search index
1028 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1029 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name), &dst);
1030 all_indexes.push(search_index);
1032 // Sort the indexes by crate so the file will be generated identically even
1033 // with rustdoc running in parallel.
1036 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1037 v.push_str(&all_indexes.join(",\\\n"));
1038 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1039 // search might start (if it's set into the URL for example).
1040 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1041 cx.shared.fs.write(&dst, &v)?;
1043 if options.enable_index_page {
1044 if let Some(index_page) = options.index_page.clone() {
1045 let mut md_opts = options.clone();
1046 md_opts.output = cx.dst.clone();
1047 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1049 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1050 .map_err(|e| Error::new(e, &index_page))?;
1052 let dst = cx.dst.join("index.html");
1053 let page = layout::Page {
1054 title: "Index of crates",
1057 static_root_path: cx.shared.static_root_path.as_deref(),
1058 description: "List of crates",
1059 keywords: BASIC_KEYWORDS,
1060 resource_suffix: &cx.shared.resource_suffix,
1062 static_extra_scripts: &[],
1064 krates.push(krate.name.clone());
1068 let content = format!(
1069 "<h1 class=\"fqn\">\
1070 <span class=\"in-band\">List of all crates</span>\
1071 </h1><ul class=\"crate mod\">{}</ul>",
1076 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1077 ensure_trailing_slash(s),
1081 .collect::<String>()
1083 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1084 cx.shared.fs.write(&dst, v.as_bytes())?;
1088 // Update the list of all implementors for traits
1089 let dst = cx.dst.join("implementors");
1090 for (&did, imps) in &cache.implementors {
1091 // Private modules can leak through to this phase of rustdoc, which
1092 // could contain implementations for otherwise private types. In some
1093 // rare cases we could find an implementation for an item which wasn't
1094 // indexed, so we just skip this step in that case.
1096 // FIXME: this is a vague explanation for why this can't be a `get`, in
1097 // theory it should be...
1098 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1100 None => match cache.external_paths.get(&did) {
1106 #[derive(Serialize)]
1107 struct Implementor {
1113 let implementors = imps
1116 // If the trait and implementation are in the same crate, then
1117 // there's no need to emit information about it (there's inlining
1118 // going on). If they're in different crates then the crate defining
1119 // the trait will be interested in our implementation.
1121 // If the implementation is from another crate then that crate
1123 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1127 text: imp.inner_impl().print().to_string(),
1128 synthetic: imp.inner_impl().synthetic,
1129 types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1133 .collect::<Vec<_>>();
1135 // Only create a js file if we have impls to add to it. If the trait is
1136 // documented locally though we always create the file to avoid dead
1138 if implementors.is_empty() && !cache.paths.contains_key(&did) {
1142 let implementors = format!(
1143 r#"implementors["{}"] = {};"#,
1145 serde_json::to_string(&implementors).unwrap()
1148 let mut mydst = dst.clone();
1149 for part in &remote_path[..remote_path.len() - 1] {
1152 cx.shared.ensure_dir(&mydst)?;
1153 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1155 let (mut all_implementors, _) =
1156 try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1157 all_implementors.push(implementors);
1158 // Sort the implementors by crate so the file will be generated
1159 // identically even with rustdoc running in parallel.
1160 all_implementors.sort();
1162 let mut v = String::from("(function() {var implementors = {};\n");
1163 for implementor in &all_implementors {
1164 writeln!(v, "{}", *implementor).unwrap();
1167 "if (window.register_implementors) {\
1168 window.register_implementors(implementors);\
1170 window.pending_implementors = implementors;\
1174 cx.shared.fs.write(&mydst, &v)?;
1183 enable_minification: bool,
1184 ) -> Result<(), Error> {
1185 if enable_minification {
1186 if dst.extension() == Some(&OsStr::new("css")) {
1187 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1188 fs.write(dst, res.as_bytes())
1190 fs.write(dst, minifier::js::minify(contents).as_bytes())
1193 fs.write(dst, contents.as_bytes())
1197 #[derive(Debug, Eq, PartialEq, Hash)]
1204 fn new(mut url: String, name: String) -> ItemEntry {
1205 while url.starts_with('/') {
1208 ItemEntry { url, name }
1213 crate fn print(&self) -> impl fmt::Display + '_ {
1214 crate::html::format::display_fn(move |f| {
1215 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1220 impl PartialOrd for ItemEntry {
1221 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1222 Some(self.cmp(other))
1226 impl Ord for ItemEntry {
1227 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1228 self.name.cmp(&other.name)
1234 structs: FxHashSet<ItemEntry>,
1235 enums: FxHashSet<ItemEntry>,
1236 unions: FxHashSet<ItemEntry>,
1237 primitives: FxHashSet<ItemEntry>,
1238 traits: FxHashSet<ItemEntry>,
1239 macros: FxHashSet<ItemEntry>,
1240 functions: FxHashSet<ItemEntry>,
1241 typedefs: FxHashSet<ItemEntry>,
1242 opaque_tys: FxHashSet<ItemEntry>,
1243 statics: FxHashSet<ItemEntry>,
1244 constants: FxHashSet<ItemEntry>,
1245 keywords: FxHashSet<ItemEntry>,
1246 attributes: FxHashSet<ItemEntry>,
1247 derives: FxHashSet<ItemEntry>,
1248 trait_aliases: FxHashSet<ItemEntry>,
1252 fn new() -> AllTypes {
1253 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1255 structs: new_set(100),
1256 enums: new_set(100),
1257 unions: new_set(100),
1258 primitives: new_set(26),
1259 traits: new_set(100),
1260 macros: new_set(100),
1261 functions: new_set(100),
1262 typedefs: new_set(100),
1263 opaque_tys: new_set(100),
1264 statics: new_set(100),
1265 constants: new_set(100),
1266 keywords: new_set(100),
1267 attributes: new_set(100),
1268 derives: new_set(100),
1269 trait_aliases: new_set(100),
1273 fn append(&mut self, item_name: String, item_type: &ItemType) {
1274 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1275 if let Some(name) = url.pop() {
1276 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1278 let name = url.join("::");
1280 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1281 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1282 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1283 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1284 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1285 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1286 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1287 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1288 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1289 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1290 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1291 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1292 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1293 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1300 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1302 let mut e: Vec<&ItemEntry> = e.iter().collect();
1306 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">{}</ul>",
1310 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1316 fn print(self, f: &mut Buffer) {
1319 "<h1 class=\"fqn\">\
1320 <span class=\"out-of-band\">\
1321 <span id=\"render-detail\">\
1322 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1323 title=\"collapse all docs\">\
1324 [<span class=\"inner\">−</span>]\
1328 <span class=\"in-band\">List of all items</span>\
1331 print_entries(f, &self.structs, "Structs", "structs");
1332 print_entries(f, &self.enums, "Enums", "enums");
1333 print_entries(f, &self.unions, "Unions", "unions");
1334 print_entries(f, &self.primitives, "Primitives", "primitives");
1335 print_entries(f, &self.traits, "Traits", "traits");
1336 print_entries(f, &self.macros, "Macros", "macros");
1337 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1338 print_entries(f, &self.derives, "Derive Macros", "derives");
1339 print_entries(f, &self.functions, "Functions", "functions");
1340 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1341 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1342 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1343 print_entries(f, &self.statics, "Statics", "statics");
1344 print_entries(f, &self.constants, "Constants", "constants")
1351 description: &'static str,
1352 sub_settings: Vec<Setting>,
1355 js_data_name: &'static str,
1356 description: &'static str,
1357 default_value: bool,
1360 js_data_name: &'static str,
1361 description: &'static str,
1362 default_value: &'static str,
1363 options: Vec<(String, String)>,
1368 fn display(&self, root_path: &str, suffix: &str) -> String {
1370 Setting::Section { description, ref sub_settings } => format!(
1371 "<div class=\"setting-line\">\
1372 <div class=\"title\">{}</div>\
1373 <div class=\"sub-settings\">{}</div>
1376 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1378 Setting::Toggle { js_data_name, description, default_value } => format!(
1379 "<div class=\"setting-line\">\
1380 <label class=\"toggle\">\
1381 <input type=\"checkbox\" id=\"{}\" {}>\
1382 <span class=\"slider\"></span>\
1387 if default_value { " checked" } else { "" },
1390 Setting::Select { js_data_name, description, default_value, ref options } => format!(
1391 "<div class=\"setting-line\">\
1393 <label class=\"select-wrapper\">\
1394 <select id=\"{}\" autocomplete=\"off\">{}</select>\
1395 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1403 "<option value=\"{}\" {}>{}</option>",
1405 if &opt.0 == default_value { "selected" } else { "" },
1408 .collect::<String>(),
1416 impl From<(&'static str, &'static str, bool)> for Setting {
1417 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1418 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1422 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1423 fn from(values: (&'static str, Vec<T>)) -> Setting {
1425 description: values.0,
1426 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1431 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1432 let theme_names: Vec<(String, String)> = themes
1436 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1439 Ok((theme.clone(), theme))
1441 .collect::<Result<_, Error>>()?;
1443 // (id, explanation, default value)
1444 let settings: &[Setting] = &[
1446 "Theme preferences",
1448 Setting::from(("use-system-theme", "Use system theme", true)),
1450 js_data_name: "preferred-dark-theme",
1451 description: "Preferred dark theme",
1452 default_value: "dark",
1453 options: theme_names.clone(),
1456 js_data_name: "preferred-light-theme",
1457 description: "Preferred light theme",
1458 default_value: "light",
1459 options: theme_names,
1465 "Auto-hide item declarations",
1467 ("auto-hide-struct", "Auto-hide structs declaration", true),
1468 ("auto-hide-enum", "Auto-hide enums declaration", false),
1469 ("auto-hide-union", "Auto-hide unions declaration", true),
1470 ("auto-hide-trait", "Auto-hide traits declaration", true),
1471 ("auto-hide-macro", "Auto-hide macros declaration", false),
1475 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1476 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1477 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1479 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1480 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1482 ("line-numbers", "Show line numbers on code examples", false).into(),
1483 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1487 "<h1 class=\"fqn\">\
1488 <span class=\"in-band\">Rustdoc settings</span>\
1490 <div class=\"settings\">{}</div>\
1491 <script src=\"{}settings{}.js\"></script>",
1492 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1499 fn derive_id(&self, id: String) -> String {
1500 let mut map = self.id_map.borrow_mut();
1504 /// String representation of how to get back to the root path of the 'doc/'
1505 /// folder in terms of a relative URL.
1506 fn root_path(&self) -> String {
1507 "../".repeat(self.current.len())
1510 fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1511 // A little unfortunate that this is done like this, but it sure
1512 // does make formatting *a lot* nicer.
1513 CURRENT_DEPTH.with(|slot| {
1514 slot.set(self.current.len());
1517 let mut title = if it.is_primitive() || it.is_keyword() {
1518 // No need to include the namespace for primitive types and keywords
1521 self.current.join("::")
1524 if !title.is_empty() {
1525 title.push_str("::");
1527 title.push_str(it.name.as_ref().unwrap());
1529 title.push_str(" - Rust");
1530 let tyname = it.type_();
1531 let desc = if it.is_crate() {
1532 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1535 "API documentation for the Rust `{}` {} in crate `{}`.",
1536 it.name.as_ref().unwrap(),
1538 self.shared.layout.krate
1541 let keywords = make_item_keywords(it);
1542 let page = layout::Page {
1543 css_class: tyname.as_str(),
1544 root_path: &self.root_path(),
1545 static_root_path: self.shared.static_root_path.as_deref(),
1548 keywords: &keywords,
1549 resource_suffix: &self.shared.resource_suffix,
1551 static_extra_scripts: &[],
1555 self.id_map.borrow_mut().reset();
1556 self.id_map.borrow_mut().populate(initial_ids());
1559 if !self.render_redirect_pages {
1561 &self.shared.layout,
1563 |buf: &mut _| print_sidebar(self, it, buf, cache),
1564 |buf: &mut _| print_item(self, it, buf, cache),
1565 &self.shared.style_files,
1568 let mut url = self.root_path();
1569 if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1570 for name in &names[..names.len() - 1] {
1574 url.push_str(&item_path(ty, names.last().unwrap()));
1575 layout::redirect(&url)
1582 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1583 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1584 // BTreeMap instead of HashMap to get a sorted output
1585 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1586 for item in &m.items {
1587 if item.is_stripped() {
1591 let short = item.type_();
1592 let myname = match item.name {
1594 Some(ref s) => s.to_string(),
1596 let short = short.to_string();
1599 .push((myname, Some(plain_text_summary(item.doc_value()))));
1602 if self.shared.sort_modules_alphabetically {
1603 for items in map.values_mut() {
1610 /// Generates a url appropriate for an `href` attribute back to the source of
1613 /// The url generated, when clicked, will redirect the browser back to the
1614 /// original source code.
1616 /// If `None` is returned, then a source link couldn't be generated. This
1617 /// may happen, for example, with externally inlined items where the source
1618 /// of their crate documentation isn't known.
1619 fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1620 let mut root = self.root_path();
1622 let mut path = String::new();
1624 // We can safely ignore synthetic `SourceFile`s.
1625 let file = match item.source.filename {
1626 FileName::Real(ref path) => path.local_path().to_path_buf(),
1631 let (krate, path) = if item.source.cnum == LOCAL_CRATE {
1632 if let Some(path) = self.shared.local_sources.get(file) {
1633 (&self.shared.layout.krate, path)
1638 let (krate, src_root) = match *cache.extern_locations.get(&item.source.cnum)? {
1639 (ref name, ref src, ExternalLocation::Local) => (name, src),
1640 (ref name, ref src, ExternalLocation::Remote(ref s)) => {
1641 root = s.to_string();
1644 (_, _, ExternalLocation::Unknown) => return None,
1647 sources::clean_path(&src_root, file, false, |component| {
1648 path.push_str(&component.to_string_lossy());
1651 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1652 fname.push(".html");
1653 path.push_str(&fname.to_string_lossy());
1657 let lines = if item.source.loline == item.source.hiline {
1658 item.source.loline.to_string()
1660 format!("{}-{}", item.source.loline, item.source.hiline)
1663 "{root}src/{krate}/{path}#{lines}",
1664 root = Escape(&root),
1672 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1674 F: FnOnce(&mut Buffer),
1676 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1681 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1682 debug_assert!(!item.is_stripped());
1683 // Write the breadcrumb trail header for the top
1684 write!(buf, "<h1 class=\"fqn\"><span class=\"out-of-band\">");
1685 if let Some(version) = item.stable_since() {
1688 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
1694 "<span id=\"render-detail\">\
1695 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1696 title=\"collapse all docs\">\
1697 [<span class=\"inner\">−</span>]\
1704 // When this item is part of a `pub use` in a downstream crate, the
1705 // [src] link in the downstream documentation will actually come back to
1706 // this page, and this link will be auto-clicked. The `id` attribute is
1707 // used to find the link to auto-click.
1708 if cx.shared.include_sources && !item.is_primitive() {
1709 if let Some(l) = cx.src_href(item, cache) {
1712 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
1713 l, "goto source code"
1718 write!(buf, "</span>"); // out-of-band
1719 write!(buf, "<span class=\"in-band\">");
1720 let name = match item.inner {
1721 clean::ModuleItem(ref m) => {
1728 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1729 clean::TraitItem(..) => "Trait ",
1730 clean::StructItem(..) => "Struct ",
1731 clean::UnionItem(..) => "Union ",
1732 clean::EnumItem(..) => "Enum ",
1733 clean::TypedefItem(..) => "Type Definition ",
1734 clean::MacroItem(..) => "Macro ",
1735 clean::ProcMacroItem(ref mac) => match mac.kind {
1736 MacroKind::Bang => "Macro ",
1737 MacroKind::Attr => "Attribute Macro ",
1738 MacroKind::Derive => "Derive Macro ",
1740 clean::PrimitiveItem(..) => "Primitive Type ",
1741 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1742 clean::ConstantItem(..) => "Constant ",
1743 clean::ForeignTypeItem => "Foreign Type ",
1744 clean::KeywordItem(..) => "Keyword ",
1745 clean::OpaqueTyItem(..) => "Opaque Type ",
1746 clean::TraitAliasItem(..) => "Trait Alias ",
1748 // We don't generate pages for any other type.
1752 buf.write_str(name);
1753 if !item.is_primitive() && !item.is_keyword() {
1754 let cur = &cx.current;
1755 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1756 for (i, component) in cur.iter().enumerate().take(amt) {
1759 "<a href=\"{}index.html\">{}</a>::<wbr>",
1760 "../".repeat(cur.len() - i - 1),
1765 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1767 write!(buf, "</span></h1>"); // in-band
1770 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1771 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1772 item_function(buf, cx, item, f)
1774 clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1775 clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1776 clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1777 clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1778 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1779 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1780 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1781 clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1782 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1783 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1784 clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1785 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1786 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e, cache),
1787 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1789 // We don't generate pages for any other type.
1795 fn item_path(ty: ItemType, name: &str) -> String {
1797 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1798 _ => format!("{}.{}.html", ty, name),
1802 fn full_path(cx: &Context, item: &clean::Item) -> String {
1803 let mut s = cx.current.join("::");
1805 s.push_str(item.name.as_ref().unwrap());
1809 /// Renders the first paragraph of the given markdown as plain text, making it suitable for
1810 /// contexts like alt-text or the search index.
1812 /// If no markdown is supplied, the empty string is returned.
1814 /// See [`markdown::plain_text_summary`] for further details.
1816 crate fn plain_text_summary(s: Option<&str>) -> String {
1817 s.map(markdown::plain_text_summary).unwrap_or_default()
1820 crate fn shorten(s: String) -> String {
1821 if s.chars().count() > 60 {
1826 // + 1 for the added character after the word.
1827 len += p.chars().count() + 1;
1830 .collect::<Vec<_>>()
1839 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item, parent: Option<&clean::Item>) {
1840 if let Some(ref name) = item.name {
1841 info!("Documenting {}", name);
1843 document_stability(w, cx, item, false, parent);
1844 document_full(w, item, cx, "", false);
1847 /// Render md_text as markdown.
1852 links: Vec<RenderedLink>,
1856 let mut ids = cx.id_map.borrow_mut();
1859 "<div class=\"docblock{}\">{}{}</div>",
1860 if is_hidden { " hidden" } else { "" },
1868 &cx.shared.playground
1874 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1875 /// docs are longer, a "Read more" link is appended to the end.
1879 link: AssocItemLink<'_>,
1883 if let Some(s) = item.doc_value() {
1884 let mut summary_html = MarkdownSummaryLine(s, &item.links()).into_string();
1886 if s.contains('\n') {
1887 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link));
1889 if let Some(idx) = summary_html.rfind("</p>") {
1890 summary_html.insert_str(idx, &link);
1892 summary_html.push_str(&link);
1898 "<div class='docblock{}'>{}{}</div>",
1899 if is_hidden { " hidden" } else { "" },
1903 } else if !prefix.is_empty() {
1906 "<div class=\"docblock{}\">{}</div>",
1907 if is_hidden { " hidden" } else { "" },
1913 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1914 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1915 debug!("Doc block: =====\n{}\n=====", s);
1916 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1917 } else if !prefix.is_empty() {
1920 "<div class=\"docblock{}\">{}</div>",
1921 if is_hidden { " hidden" } else { "" },
1927 fn document_stability(
1932 parent: Option<&clean::Item>,
1934 let stabilities = short_stability(item, cx, parent);
1935 if !stabilities.is_empty() {
1936 write!(w, "<div class=\"stability{}\">", if is_hidden { " hidden" } else { "" });
1937 for stability in stabilities {
1938 write!(w, "{}", stability);
1940 write!(w, "</div>");
1944 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1945 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1948 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1949 if item.is_non_exhaustive() {
1950 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1951 if item.is_struct() {
1953 } else if item.is_enum() {
1955 } else if item.is_variant() {
1962 if item.is_struct() {
1965 "Non-exhaustive structs could have additional fields added in future. \
1966 Therefore, non-exhaustive structs cannot be constructed in external crates \
1967 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1968 matched against without a wildcard <code>..</code>; and \
1969 struct update syntax will not work."
1971 } else if item.is_enum() {
1974 "Non-exhaustive enums could have additional variants added in future. \
1975 Therefore, when matching against variants of non-exhaustive enums, an \
1976 extra wildcard arm must be added to account for any future variants."
1978 } else if item.is_variant() {
1981 "Non-exhaustive enum variants could have additional fields added in future. \
1982 Therefore, non-exhaustive enum variants cannot be constructed in external \
1983 crates and cannot be matched against."
1988 "This type will require a wildcard arm in any match statements or constructors."
1992 write!(w, "</div>");
1996 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1997 pub fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1998 /// Takes a non-numeric and a numeric part from the given &str.
1999 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
2000 let i = s.find(|c: char| c.is_ascii_digit());
2001 let (a, b) = s.split_at(i.unwrap_or(s.len()));
2002 let i = b.find(|c: char| !c.is_ascii_digit());
2003 let (b, c) = b.split_at(i.unwrap_or(b.len()));
2008 while !lhs.is_empty() || !rhs.is_empty() {
2009 let (la, lb) = take_parts(&mut lhs);
2010 let (ra, rb) = take_parts(&mut rhs);
2011 // First process the non-numeric part.
2013 Ordering::Equal => (),
2016 // Then process the numeric part, if both sides have one (and they fit in a u64).
2017 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2019 Ordering::Equal => (),
2023 // Then process the numeric part again, but this time as strings.
2025 Ordering::Equal => (),
2033 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
2034 document(w, cx, item, None);
2036 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2038 // the order of item types in the listing
2039 fn reorder(ty: ItemType) -> u8 {
2041 ItemType::ExternCrate => 0,
2042 ItemType::Import => 1,
2043 ItemType::Primitive => 2,
2044 ItemType::Module => 3,
2045 ItemType::Macro => 4,
2046 ItemType::Struct => 5,
2047 ItemType::Enum => 6,
2048 ItemType::Constant => 7,
2049 ItemType::Static => 8,
2050 ItemType::Trait => 9,
2051 ItemType::Function => 10,
2052 ItemType::Typedef => 12,
2053 ItemType::Union => 13,
2058 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2059 let ty1 = i1.type_();
2060 let ty2 = i2.type_();
2062 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2064 let s1 = i1.stability.as_ref().map(|s| s.level);
2065 let s2 = i2.stability.as_ref().map(|s| s.level);
2066 if let (Some(a), Some(b)) = (s1, s2) {
2067 match (a.is_stable(), b.is_stable()) {
2068 (true, true) | (false, false) => {}
2069 (false, true) => return Ordering::Less,
2070 (true, false) => return Ordering::Greater,
2073 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2074 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2075 compare_names(lhs, rhs)
2078 if cx.shared.sort_modules_alphabetically {
2079 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2081 // This call is to remove re-export duplicates in cases such as:
2086 // pub trait Double { fn foo(); }
2090 // pub use foo::bar::*;
2094 // `Double` will appear twice in the generated docs.
2096 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2097 // can be identical even if the elements are different (mostly in imports).
2098 // So in case this is an import, we keep everything by adding a "unique id"
2099 // (which is the position in the vector).
2100 indices.dedup_by_key(|i| {
2103 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2105 if items[*i].is_import() { *i } else { 0 },
2109 debug!("{:?}", indices);
2110 let mut curty = None;
2111 for &idx in &indices {
2112 let myitem = &items[idx];
2113 if myitem.is_stripped() {
2117 let myty = Some(myitem.type_());
2118 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2119 // Put `extern crate` and `use` re-exports in the same section.
2121 } else if myty != curty {
2122 if curty.is_some() {
2123 write!(w, "</table>");
2126 let (short, name) = item_ty_to_strs(&myty.unwrap());
2129 "<h2 id=\"{id}\" class=\"section-header\">\
2130 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2131 id = cx.derive_id(short.to_owned()),
2136 match myitem.inner {
2137 clean::ExternCrateItem(ref name, ref src) => {
2138 use crate::html::format::anchor;
2141 Some(ref src) => write!(
2143 "<tr><td><code>{}extern crate {} as {};",
2144 myitem.visibility.print_with_space(),
2145 anchor(myitem.def_id, src),
2150 "<tr><td><code>{}extern crate {};",
2151 myitem.visibility.print_with_space(),
2152 anchor(myitem.def_id, name)
2155 write!(w, "</code></td></tr>");
2158 clean::ImportItem(ref import) => {
2161 "<tr><td><code>{}{}</code></td></tr>",
2162 myitem.visibility.print_with_space(),
2168 if myitem.name.is_none() {
2172 let unsafety_flag = match myitem.inner {
2173 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2174 if func.header.unsafety == hir::Unsafety::Unsafe =>
2176 "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2181 let stab = myitem.stability_class();
2182 let add = if stab.is_some() { " " } else { "" };
2184 let doc_value = myitem.doc_value().unwrap_or("");
2187 "<tr class=\"{stab}{add}module-item\">\
2188 <td><a class=\"{class}\" href=\"{href}\" \
2189 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2190 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2192 name = *myitem.name.as_ref().unwrap(),
2193 stab_tags = stability_tags(myitem, item),
2194 docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2195 class = myitem.type_(),
2197 stab = stab.unwrap_or_else(String::new),
2198 unsafety_flag = unsafety_flag,
2199 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2200 title = [full_path(cx, myitem), myitem.type_().to_string()]
2202 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2203 .collect::<Vec<_>>()
2210 if curty.is_some() {
2211 write!(w, "</table>");
2215 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2217 fn stability_tags(item: &clean::Item, parent: &clean::Item) -> String {
2218 let mut tags = String::new();
2220 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2221 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2224 // The trailing space after each tag is to space it properly against the rest of the docs.
2225 if let Some(depr) = &item.deprecation {
2226 let mut message = "Deprecated";
2227 if !stability::deprecation_in_effect(depr.is_since_rustc_version, depr.since.as_deref()) {
2228 message = "Deprecation planned";
2230 tags += &tag_html("deprecated", "", message);
2233 // The "rustc_private" crates are permanently unstable so it makes no sense
2234 // to render "unstable" everywhere.
2235 if item.stability.as_ref().map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2238 tags += &tag_html("unstable", "", "Experimental");
2241 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2242 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2243 (cfg, _) => cfg.as_deref().cloned(),
2246 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2247 if let Some(ref cfg) = cfg {
2248 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2254 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2256 fn short_stability(item: &clean::Item, cx: &Context, parent: Option<&clean::Item>) -> Vec<String> {
2257 let mut stability = vec![];
2258 let error_codes = cx.shared.codes;
2260 if let Some(Deprecation { ref note, ref since, is_since_rustc_version }) = item.deprecation {
2261 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2262 // but only display the future-deprecation messages for #[rustc_deprecated].
2263 let mut message = if let Some(since) = since {
2264 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2265 format!("Deprecating in {}", Escape(&since))
2267 format!("Deprecated since {}", Escape(&since))
2270 String::from("Deprecated")
2273 if let Some(note) = note {
2274 let mut ids = cx.id_map.borrow_mut();
2275 let html = MarkdownHtml(
2280 &cx.shared.playground,
2282 message.push_str(&format!(": {}", html.into_string()));
2284 stability.push(format!(
2285 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2290 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2291 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2292 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2295 .filter(|stab| stab.feature != sym::rustc_private)
2296 .map(|stab| (stab.level, stab.feature))
2299 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2301 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2302 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2303 feature.push_str(&format!(
2304 " <a href=\"{url}{issue}\">#{issue}</a>",
2310 message.push_str(&format!(" ({})", feature));
2312 if let Some(unstable_reason) = reason {
2313 let mut ids = cx.id_map.borrow_mut();
2315 "<details><summary>{}</summary>{}</details>",
2318 &unstable_reason.as_str(),
2322 &cx.shared.playground,
2328 stability.push(format!("<div class=\"stab unstable\">{}</div>", message));
2331 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2332 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2333 (cfg, _) => cfg.as_deref().cloned(),
2337 "Portability {:?} - {:?} = {:?}",
2339 parent.and_then(|p| p.attrs.cfg.as_ref()),
2342 if let Some(cfg) = cfg {
2343 stability.push(format!("<div class=\"stab portability\">{}</div>", cfg.render_long_html()));
2349 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2350 write!(w, "<pre class=\"rust const\">");
2351 render_attributes(w, it, false);
2355 "{vis}const {name}: {typ}",
2356 vis = it.visibility.print_with_space(),
2357 name = it.name.as_ref().unwrap(),
2358 typ = c.type_.print(),
2361 if c.value.is_some() || c.is_literal {
2362 write!(w, " = {expr};", expr = Escape(&c.expr));
2367 if let Some(value) = &c.value {
2369 let value_lowercase = value.to_lowercase();
2370 let expr_lowercase = c.expr.to_lowercase();
2372 if value_lowercase != expr_lowercase
2373 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2375 write!(w, " // {value}", value = Escape(value));
2380 write!(w, "</pre>");
2381 document(w, cx, it, None)
2384 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2385 write!(w, "<pre class=\"rust static\">");
2386 render_attributes(w, it, false);
2389 "{vis}static {mutability}{name}: {typ}</pre>",
2390 vis = it.visibility.print_with_space(),
2391 mutability = s.mutability.print_with_space(),
2392 name = it.name.as_ref().unwrap(),
2393 typ = s.type_.print()
2395 document(w, cx, it, None)
2398 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2399 let header_len = format!(
2400 "{}{}{}{}{:#}fn {}{:#}",
2401 it.visibility.print_with_space(),
2402 f.header.constness.print_with_space(),
2403 f.header.asyncness.print_with_space(),
2404 f.header.unsafety.print_with_space(),
2405 print_abi_with_space(f.header.abi),
2406 it.name.as_ref().unwrap(),
2410 write!(w, "<pre class=\"rust fn\">");
2411 render_attributes(w, it, false);
2414 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2415 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2416 vis = it.visibility.print_with_space(),
2417 constness = f.header.constness.print_with_space(),
2418 asyncness = f.header.asyncness.print_with_space(),
2419 unsafety = f.header.unsafety.print_with_space(),
2420 abi = print_abi_with_space(f.header.abi),
2421 name = it.name.as_ref().unwrap(),
2422 generics = f.generics.print(),
2423 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2424 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2426 spotlight = spotlight_decl(&f.decl),
2428 document(w, cx, it, None)
2431 fn render_implementor(
2435 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2439 // If there's already another implementor that has the same abbridged name, use the
2440 // full path, for example in `std::iter::ExactSizeIterator`
2441 let use_absolute = match implementor.inner_impl().for_ {
2442 clean::ResolvedPath { ref path, is_generic: false, .. }
2443 | clean::BorrowedRef {
2444 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2446 } => implementor_dups[path.last_name()].1,
2454 AssocItemLink::Anchor(None),
2456 implementor.impl_item.stable_since().as_deref(),
2470 containing_item: &clean::Item,
2473 let mut impls = traits
2476 let did = i.trait_did().unwrap();
2477 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2478 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2483 Some(containing_item),
2486 containing_item.stable_since().as_deref(),
2496 .collect::<Vec<_>>();
2498 w.write_str(&impls.join(""));
2501 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2502 let mut bounds = String::new();
2503 if !t_bounds.is_empty() {
2505 bounds.push_str(": ");
2507 for (i, p) in t_bounds.iter().enumerate() {
2509 bounds.push_str(" + ");
2511 bounds.push_str(&p.print().to_string());
2517 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2518 let lhs = format!("{}", lhs.inner_impl().print());
2519 let rhs = format!("{}", rhs.inner_impl().print());
2521 // lhs and rhs are formatted as HTML, which may be unnecessary
2522 compare_names(&lhs, &rhs)
2525 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2526 let bounds = bounds(&t.bounds, false);
2527 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2528 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2529 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2530 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2532 // Output the trait definition
2533 wrap_into_docblock(w, |w| {
2534 write!(w, "<pre class=\"rust trait\">");
2535 render_attributes(w, it, true);
2538 "{}{}{}trait {}{}{}",
2539 it.visibility.print_with_space(),
2540 t.unsafety.print_with_space(),
2541 if t.is_auto { "auto " } else { "" },
2542 it.name.as_ref().unwrap(),
2547 if !t.generics.where_predicates.is_empty() {
2548 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2553 if t.items.is_empty() {
2556 // FIXME: we should be using a derived_id for the Anchors here
2559 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2562 if !types.is_empty() && !consts.is_empty() {
2566 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2569 if !consts.is_empty() && !required.is_empty() {
2572 for (pos, m) in required.iter().enumerate() {
2573 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2576 if pos < required.len() - 1 {
2577 write!(w, "<div class=\"item-spacer\"></div>");
2580 if !required.is_empty() && !provided.is_empty() {
2583 for (pos, m) in provided.iter().enumerate() {
2584 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2586 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2587 write!(w, ",\n {{ ... }}\n");
2590 write!(w, " {{ ... }}\n");
2593 if pos < provided.len() - 1 {
2594 write!(w, "<div class=\"item-spacer\"></div>");
2602 // Trait documentation
2603 document(w, cx, it, None);
2605 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2608 "<h2 id=\"{0}\" class=\"small-section-header\">\
2609 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2611 id, title, extra_content
2615 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2616 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2619 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item) {
2620 let name = m.name.as_ref().unwrap();
2621 info!("Documenting {} on {}", name, t.name.as_deref().unwrap_or_default());
2622 let item_type = m.type_();
2623 let id = cx.derive_id(format!("{}.{}", item_type, name));
2624 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2625 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2626 write!(w, "</code>");
2627 render_stability_since(w, m, t);
2629 document(w, cx, m, Some(t));
2632 if !types.is_empty() {
2633 write_small_section_header(
2637 "<div class=\"methods\">",
2640 trait_item(w, cx, *t, it);
2642 write_loading_content(w, "</div>");
2645 if !consts.is_empty() {
2646 write_small_section_header(
2649 "Associated Constants",
2650 "<div class=\"methods\">",
2653 trait_item(w, cx, *t, it);
2655 write_loading_content(w, "</div>");
2658 // Output the documentation for each function individually
2659 if !required.is_empty() {
2660 write_small_section_header(
2664 "<div class=\"methods\">",
2666 for m in &required {
2667 trait_item(w, cx, *m, it);
2669 write_loading_content(w, "</div>");
2671 if !provided.is_empty() {
2672 write_small_section_header(
2676 "<div class=\"methods\">",
2678 for m in &provided {
2679 trait_item(w, cx, *m, it);
2681 write_loading_content(w, "</div>");
2684 // If there are methods directly on this trait object, render them here.
2685 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2687 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2688 // The DefId is for the first Type found with that name. The bool is
2689 // if any Types with the same name but different DefId have been found.
2690 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2691 for implementor in implementors {
2692 match implementor.inner_impl().for_ {
2693 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2694 | clean::BorrowedRef {
2695 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2698 let &mut (prev_did, ref mut has_duplicates) =
2699 implementor_dups.entry(path.last_name()).or_insert((did, false));
2700 if prev_did != did {
2701 *has_duplicates = true;
2708 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2709 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2712 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2713 local.iter().partition(|i| i.inner_impl().synthetic);
2715 synthetic.sort_by(compare_impl);
2716 concrete.sort_by(compare_impl);
2718 if !foreign.is_empty() {
2719 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2721 for implementor in foreign {
2722 let assoc_link = AssocItemLink::GotoSource(
2723 implementor.impl_item.def_id,
2724 &implementor.inner_impl().provided_trait_methods,
2733 implementor.impl_item.stable_since().as_deref(),
2742 write_loading_content(w, "");
2745 write_small_section_header(
2749 "<div class=\"item-list\" id=\"implementors-list\">",
2751 for implementor in concrete {
2752 render_implementor(cx, implementor, w, &implementor_dups, &[], cache);
2754 write_loading_content(w, "</div>");
2757 write_small_section_header(
2759 "synthetic-implementors",
2760 "Auto implementors",
2761 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2763 for implementor in synthetic {
2769 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2773 write_loading_content(w, "</div>");
2776 // even without any implementations to write in, we still want the heading and list, so the
2777 // implementors javascript file pulled in below has somewhere to write the impls into
2778 write_small_section_header(
2782 "<div class=\"item-list\" id=\"implementors-list\">",
2784 write_loading_content(w, "</div>");
2787 write_small_section_header(
2789 "synthetic-implementors",
2790 "Auto implementors",
2791 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2793 write_loading_content(w, "</div>");
2799 "<script type=\"text/javascript\" \
2800 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2802 root_path = vec![".."; cx.current.len()].join("/"),
2803 path = if it.def_id.is_local() {
2804 cx.current.join("/")
2806 let (ref path, _) = cache.external_paths[&it.def_id];
2807 path[..path.len() - 1].join("/")
2810 name = *it.name.as_ref().unwrap()
2814 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2815 use crate::formats::item_type::ItemType::*;
2817 let name = it.name.as_ref().unwrap();
2818 let ty = match it.type_() {
2819 Typedef | AssocType => AssocType,
2823 let anchor = format!("#{}.{}", ty, name);
2825 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2826 AssocItemLink::Anchor(None) => anchor,
2827 AssocItemLink::GotoSource(did, _) => {
2828 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2837 _default: Option<&String>,
2838 link: AssocItemLink<'_>,
2843 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2845 it.visibility.print_with_space(),
2846 naive_assoc_href(it, link),
2847 it.name.as_ref().unwrap(),
2855 bounds: &[clean::GenericBound],
2856 default: Option<&clean::Type>,
2857 link: AssocItemLink<'_>,
2862 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2864 naive_assoc_href(it, link),
2865 it.name.as_ref().unwrap()
2867 if !bounds.is_empty() {
2868 write!(w, ": {}", print_generic_bounds(bounds))
2870 if let Some(default) = default {
2871 write!(w, " = {}", default.print())
2875 fn render_stability_since_raw(w: &mut Buffer, ver: Option<&str>, containing_ver: Option<&str>) {
2876 if let Some(v) = ver {
2877 if containing_ver != ver && !v.is_empty() {
2878 write!(w, "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>", v)
2883 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2884 render_stability_since_raw(
2886 item.stable_since().as_deref(),
2887 containing_item.stable_since().as_deref(),
2891 fn render_assoc_item(
2894 link: AssocItemLink<'_>,
2900 header: hir::FnHeader,
2901 g: &clean::Generics,
2903 link: AssocItemLink<'_>,
2906 let name = meth.name.as_ref().unwrap();
2907 let anchor = format!("#{}.{}", meth.type_(), name);
2908 let href = match link {
2909 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2910 AssocItemLink::Anchor(None) => anchor,
2911 AssocItemLink::GotoSource(did, provided_methods) => {
2912 // We're creating a link from an impl-item to the corresponding
2913 // trait-item and need to map the anchored type accordingly.
2914 let ty = if provided_methods.contains(name) {
2920 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2923 let mut header_len = format!(
2924 "{}{}{}{}{}{:#}fn {}{:#}",
2925 meth.visibility.print_with_space(),
2926 header.constness.print_with_space(),
2927 header.asyncness.print_with_space(),
2928 header.unsafety.print_with_space(),
2929 print_default_space(meth.is_default()),
2930 print_abi_with_space(header.abi),
2935 let (indent, end_newline) = if parent == ItemType::Trait {
2941 render_attributes(w, meth, false);
2944 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
2945 {generics}{decl}{spotlight}{where_clause}",
2946 if parent == ItemType::Trait { " " } else { "" },
2947 meth.visibility.print_with_space(),
2948 header.constness.print_with_space(),
2949 header.asyncness.print_with_space(),
2950 header.unsafety.print_with_space(),
2951 print_default_space(meth.is_default()),
2952 print_abi_with_space(header.abi),
2955 generics = g.print(),
2956 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
2957 spotlight = spotlight_decl(&d),
2958 where_clause = WhereClause { gens: g, indent, end_newline }
2962 clean::StrippedItem(..) => {}
2963 clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2964 clean::MethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2965 clean::AssocConstItem(ref ty, ref default) => assoc_const(
2971 if parent == ItemType::Trait { " " } else { "" },
2973 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
2979 if parent == ItemType::Trait { " " } else { "" },
2981 _ => panic!("render_assoc_item called on non-associated-item"),
2985 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
2986 wrap_into_docblock(w, |w| {
2987 write!(w, "<pre class=\"rust struct\">");
2988 render_attributes(w, it, true);
2989 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
2993 document(w, cx, it, None);
2997 .filter_map(|f| match f.inner {
2998 clean::StructFieldItem(ref ty) => Some((f, ty)),
3002 if let doctree::Plain = s.struct_type {
3003 if fields.peek().is_some() {
3006 "<h2 id=\"fields\" class=\"fields small-section-header\">
3007 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3008 document_non_exhaustive_header(it)
3010 document_non_exhaustive(w, it);
3011 for (field, ty) in fields {
3012 let id = cx.derive_id(format!(
3014 ItemType::StructField,
3015 field.name.as_ref().unwrap()
3019 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3020 <a href=\"#{id}\" class=\"anchor field\"></a>\
3021 <code>{name}: {ty}</code>\
3023 item_type = ItemType::StructField,
3025 name = field.name.as_ref().unwrap(),
3028 document(w, cx, field, Some(it));
3032 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3035 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
3036 wrap_into_docblock(w, |w| {
3037 write!(w, "<pre class=\"rust union\">");
3038 render_attributes(w, it, true);
3039 render_union(w, it, Some(&s.generics), &s.fields, "", true);
3043 document(w, cx, it, None);
3047 .filter_map(|f| match f.inner {
3048 clean::StructFieldItem(ref ty) => Some((f, ty)),
3052 if fields.peek().is_some() {
3055 "<h2 id=\"fields\" class=\"fields small-section-header\">
3056 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3058 for (field, ty) in fields {
3059 let name = field.name.as_ref().expect("union field name");
3060 let id = format!("{}.{}", ItemType::StructField, name);
3063 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3064 <a href=\"#{id}\" class=\"anchor field\"></a>\
3065 <code>{name}: {ty}</code>\
3069 shortty = ItemType::StructField,
3072 if let Some(stability_class) = field.stability_class() {
3073 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3075 document(w, cx, field, Some(it));
3078 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3081 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
3082 wrap_into_docblock(w, |w| {
3083 write!(w, "<pre class=\"rust enum\">");
3084 render_attributes(w, it, true);
3088 it.visibility.print_with_space(),
3089 it.name.as_ref().unwrap(),
3091 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
3093 if e.variants.is_empty() && !e.variants_stripped {
3097 for v in &e.variants {
3099 let name = v.name.as_ref().unwrap();
3101 clean::VariantItem(ref var) => match var.kind {
3102 clean::VariantKind::CLike => write!(w, "{}", name),
3103 clean::VariantKind::Tuple(ref tys) => {
3104 write!(w, "{}(", name);
3105 for (i, ty) in tys.iter().enumerate() {
3107 write!(w, ", ")
3109 write!(w, "{}", ty.print());
3113 clean::VariantKind::Struct(ref s) => {
3114 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
3117 _ => unreachable!(),
3122 if e.variants_stripped {
3123 write!(w, " // some variants omitted\n");
3130 document(w, cx, it, None);
3131 if !e.variants.is_empty() {
3134 "<h2 id=\"variants\" class=\"variants small-section-header\">
3135 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3136 document_non_exhaustive_header(it)
3138 document_non_exhaustive(w, it);
3139 for variant in &e.variants {
3141 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3144 "<div id=\"{id}\" class=\"variant small-section-header\">\
3145 <a href=\"#{id}\" class=\"anchor field\"></a>\
3148 name = variant.name.as_ref().unwrap()
3150 if let clean::VariantItem(ref var) = variant.inner {
3151 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3153 for (i, ty) in tys.iter().enumerate() {
3155 write!(w, ", ");
3157 write!(w, "{}", ty.print());
3162 write!(w, "</code></div>");
3163 document(w, cx, variant, Some(it));
3164 document_non_exhaustive(w, variant);
3166 use crate::clean::{Variant, VariantKind};
3167 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.inner
3169 let variant_id = cx.derive_id(format!(
3172 variant.name.as_ref().unwrap()
3174 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3177 "<h3>Fields of <b>{name}</b></h3><div>",
3178 name = variant.name.as_ref().unwrap()
3180 for field in &s.fields {
3181 use crate::clean::StructFieldItem;
3182 if let StructFieldItem(ref ty) = field.inner {
3183 let id = cx.derive_id(format!(
3184 "variant.{}.field.{}",
3185 variant.name.as_ref().unwrap(),
3186 field.name.as_ref().unwrap()
3190 "<span id=\"{id}\" class=\"variant small-section-header\">\
3191 <a href=\"#{id}\" class=\"anchor field\"></a>\
3192 <code>{f}: {t}</code>\
3195 f = field.name.as_ref().unwrap(),
3198 document(w, cx, field, Some(variant));
3201 write!(w, "</div></div>");
3203 render_stability_since(w, variant, it);
3206 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3209 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3216 sym::non_exhaustive,
3219 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3220 // left padding. For example:
3222 // #[foo] <----- "top" attribute
3224 // #[bar] <---- not "top" attribute
3227 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3232 .filter_map(|attr| {
3233 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3234 Some(pprust::attribute_to_string(&attr))
3241 if !attrs.is_empty() {
3244 "<span class=\"docblock attributes{}\">{}</span>",
3245 if top { " top-attr" } else { "" },
3254 g: Option<&clean::Generics>,
3255 ty: doctree::StructType,
3256 fields: &[clean::Item],
3263 it.visibility.print_with_space(),
3264 if structhead { "struct " } else { "" },
3265 it.name.as_ref().unwrap()
3267 if let Some(g) = g {
3268 write!(w, "{}", g.print())
3272 if let Some(g) = g {
3273 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3275 let mut has_visible_fields = false;
3277 for field in fields {
3278 if let clean::StructFieldItem(ref ty) = field.inner {
3283 field.visibility.print_with_space(),
3284 field.name.as_ref().unwrap(),
3287 has_visible_fields = true;
3291 if has_visible_fields {
3292 if it.has_stripped_fields().unwrap() {
3293 write!(w, "\n{} // some fields omitted", tab);
3295 write!(w, "\n{}", tab);
3296 } else if it.has_stripped_fields().unwrap() {
3297 // If there are no visible fields we can just display
3298 // `{ /* fields omitted */ }` to save space.
3299 write!(w, " /* fields omitted */ ");
3305 for (i, field) in fields.iter().enumerate() {
3310 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3311 clean::StructFieldItem(ref ty) => {
3312 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3314 _ => unreachable!(),
3318 if let Some(g) = g {
3319 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3324 // Needed for PhantomData.
3325 if let Some(g) = g {
3326 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3336 g: Option<&clean::Generics>,
3337 fields: &[clean::Item],
3344 it.visibility.print_with_space(),
3345 if structhead { "union " } else { "" },
3346 it.name.as_ref().unwrap()
3348 if let Some(g) = g {
3349 write!(w, "{}", g.print());
3350 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3353 write!(w, " {{\n{}", tab);
3354 for field in fields {
3355 if let clean::StructFieldItem(ref ty) = field.inner {
3359 field.visibility.print_with_space(),
3360 field.name.as_ref().unwrap(),
3367 if it.has_stripped_fields().unwrap() {
3368 write!(w, " // some fields omitted\n{}", tab);
3373 #[derive(Copy, Clone)]
3374 enum AssocItemLink<'a> {
3375 Anchor(Option<&'a str>),
3376 GotoSource(DefId, &'a FxHashSet<String>),
3379 impl<'a> AssocItemLink<'a> {
3380 fn anchor(&self, id: &'a String) -> Self {
3382 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3383 ref other => *other,
3388 fn render_assoc_items(
3391 containing_item: &clean::Item,
3393 what: AssocItemRender<'_>,
3397 "Documenting associated items of {}",
3398 containing_item.name.as_deref().unwrap_or_default()
3400 let v = match cache.impls.get(&it) {
3404 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3405 if !non_trait.is_empty() {
3406 let render_mode = match what {
3407 AssocItemRender::All => {
3410 "<h2 id=\"implementations\" class=\"small-section-header\">\
3411 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3416 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3419 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
3420 Methods from {}<Target = {}>\
3421 <a href=\"#deref-methods\" class=\"anchor\"></a>\
3426 RenderMode::ForDeref { mut_: deref_mut_ }
3429 for i in &non_trait {
3434 Some(containing_item),
3435 AssocItemLink::Anchor(None),
3437 containing_item.stable_since().as_deref(),
3447 if let AssocItemRender::DerefFor { .. } = what {
3450 if !traits.is_empty() {
3452 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3453 if let Some(impl_) = deref_impl {
3455 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3456 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3459 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3460 traits.iter().partition(|t| t.inner_impl().synthetic);
3461 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3462 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3464 let mut impls = Buffer::empty_from(&w);
3465 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3466 let impls = impls.into_inner();
3467 if !impls.is_empty() {
3470 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3471 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3473 <div id=\"trait-implementations-list\">{}</div>",
3478 if !synthetic.is_empty() {
3481 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3482 Auto Trait Implementations\
3483 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3485 <div id=\"synthetic-implementations-list\">"
3487 render_impls(cx, w, &synthetic, containing_item, cache);
3488 write!(w, "</div>");
3491 if !blanket_impl.is_empty() {
3494 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3495 Blanket Implementations\
3496 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3498 <div id=\"blanket-implementations-list\">"
3500 render_impls(cx, w, &blanket_impl, containing_item, cache);
3501 write!(w, "</div>");
3506 fn render_deref_methods(
3510 container_item: &clean::Item,
3514 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3515 let (target, real_target) = impl_
3519 .find_map(|item| match item.inner {
3520 clean::TypedefItem(ref t, true) => Some(match *t {
3521 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3522 _ => (&t.type_, &t.type_),
3526 .expect("Expected associated type binding");
3528 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3529 if let Some(did) = target.def_id() {
3530 render_assoc_items(w, cx, container_item, did, what, cache);
3532 if let Some(prim) = target.primitive_type() {
3533 if let Some(&did) = cache.primitive_locations.get(&prim) {
3534 render_assoc_items(w, cx, container_item, did, what, cache);
3540 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3541 let self_type_opt = match item.inner {
3542 clean::MethodItem(ref method) => method.decl.self_type(),
3543 clean::TyMethodItem(ref method) => method.decl.self_type(),
3547 if let Some(self_ty) = self_type_opt {
3548 let (by_mut_ref, by_box, by_value) = match self_ty {
3549 SelfTy::SelfBorrowed(_, mutability)
3550 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3551 (mutability == Mutability::Mut, false, false)
3553 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3554 (false, Some(did) == cache().owned_box_did, false)
3556 SelfTy::SelfValue => (false, false, true),
3557 _ => (false, false, false),
3560 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3566 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3567 let mut out = Buffer::html();
3568 let mut trait_ = String::new();
3570 if let Some(did) = decl.output.def_id() {
3572 if let Some(impls) = c.impls.get(&did) {
3574 let impl_ = i.inner_impl();
3575 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3577 out.push_str(&format!(
3578 "<h3 class=\"notable\">Notable traits for {}</h3>\
3579 <code class=\"content\">",
3582 trait_.push_str(&impl_.for_.print().to_string());
3585 //use the "where" class here to make it small
3586 out.push_str(&format!(
3587 "<span class=\"where fmt-newline\">{}</span>",
3590 let t_did = impl_.trait_.def_id().unwrap();
3591 for it in &impl_.items {
3592 if let clean::TypedefItem(ref tydef, _) = it.inner {
3593 out.push_str("<span class=\"where fmt-newline\"> ");
3599 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3602 out.push_str(";</span>");
3610 if !out.is_empty() {
3613 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3614 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3616 out.push_str("</code></span></div></span></span>");
3626 parent: Option<&clean::Item>,
3627 link: AssocItemLink<'_>,
3628 render_mode: RenderMode,
3629 outer_version: Option<&str>,
3630 show_def_docs: bool,
3631 use_absolute: Option<bool>,
3632 is_on_foreign_type: bool,
3633 show_default_items: bool,
3634 // This argument is used to reference same type with different paths to avoid duplication
3635 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3639 if render_mode == RenderMode::Normal {
3640 let id = cx.derive_id(match i.inner_impl().trait_ {
3642 if is_on_foreign_type {
3643 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3645 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3648 None => "impl".to_string(),
3650 let aliases = if aliases.is_empty() {
3653 format!(" aliases=\"{}\"", aliases.join(","))
3655 if let Some(use_absolute) = use_absolute {
3656 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3657 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3659 for it in &i.inner_impl().items {
3660 if let clean::TypedefItem(ref tydef, _) = it.inner {
3661 write!(w, "<span class=\"where fmt-newline\"> ");
3662 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3663 write!(w, ";</span>");
3667 write!(w, "</code>");
3671 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3674 i.inner_impl().print()
3677 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3678 let since = i.impl_item.stability.as_ref().and_then(|s| match s.level {
3679 StabilityLevel::Stable { since } => Some(since.as_str()),
3680 StabilityLevel::Unstable { .. } => None,
3682 render_stability_since_raw(w, since.as_deref(), outer_version);
3683 if let Some(l) = cx.src_href(&i.impl_item, cache) {
3686 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
3687 l, "goto source code"
3691 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3692 let mut ids = cx.id_map.borrow_mut();
3695 "<div class=\"docblock\">{}</div>",
3698 &i.impl_item.links(),
3702 &cx.shared.playground
3713 parent: Option<&clean::Item>,
3714 link: AssocItemLink<'_>,
3715 render_mode: RenderMode,
3716 is_default_item: bool,
3717 outer_version: Option<&str>,
3718 trait_: Option<&clean::Trait>,
3719 show_def_docs: bool,
3722 let item_type = item.type_();
3723 let name = item.name.as_ref().unwrap();
3725 let render_method_item = match render_mode {
3726 RenderMode::Normal => true,
3727 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3730 let (is_hidden, extra_class) =
3731 if (trait_.is_none() || item.doc_value().is_some() || item.inner.is_type_alias())
3739 clean::MethodItem(clean::Method { .. })
3740 | clean::TyMethodItem(clean::TyMethod { .. }) => {
3741 // Only render when the method is not static or we allow static methods
3742 if render_method_item {
3743 let id = cx.derive_id(format!("{}.{}", item_type, name));
3744 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3745 write!(w, "<code>");
3746 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3747 write!(w, "</code>");
3748 render_stability_since_raw(w, item.stable_since().as_deref(), outer_version);
3749 if let Some(l) = cx.src_href(item, cache) {
3752 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
3753 l, "goto source code"
3759 clean::TypedefItem(ref tydef, _) => {
3760 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3761 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3762 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3763 write!(w, "</code></h4>");
3765 clean::AssocConstItem(ref ty, ref default) => {
3766 let id = cx.derive_id(format!("{}.{}", item_type, name));
3767 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3768 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3769 write!(w, "</code>");
3770 render_stability_since_raw(w, item.stable_since().as_deref(), outer_version);
3771 if let Some(l) = cx.src_href(item, cache) {
3774 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
3775 l, "goto source code"
3780 clean::AssocTypeItem(ref bounds, ref default) => {
3781 let id = cx.derive_id(format!("{}.{}", item_type, name));
3782 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3783 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3784 write!(w, "</code></h4>");
3786 clean::StrippedItem(..) => return,
3787 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3790 if render_method_item {
3791 if !is_default_item {
3792 if let Some(t) = trait_ {
3793 // The trait item may have been stripped so we might not
3794 // find any documentation or stability for it.
3795 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3796 // We need the stability of the item from the trait
3797 // because impls can't have a stability.
3798 document_stability(w, cx, it, is_hidden, parent);
3799 if item.doc_value().is_some() {
3800 document_full(w, item, cx, "", is_hidden);
3801 } else if show_def_docs {
3802 // In case the item isn't documented,
3803 // provide short documentation from the trait.
3804 document_short(w, it, link, "", is_hidden);
3808 document_stability(w, cx, item, is_hidden, parent);
3810 document_full(w, item, cx, "", is_hidden);
3814 document_stability(w, cx, item, is_hidden, parent);
3816 document_short(w, item, link, "", is_hidden);
3822 let traits = &cache.traits;
3823 let trait_ = i.trait_did().map(|did| &traits[&did]);
3825 write!(w, "<div class=\"impl-items\">");
3826 for trait_item in &i.inner_impl().items {
3842 fn render_default_items(
3847 parent: Option<&clean::Item>,
3848 render_mode: RenderMode,
3849 outer_version: Option<&str>,
3850 show_def_docs: bool,
3853 for trait_item in &t.items {
3854 let n = trait_item.name.clone();
3855 if i.items.iter().any(|m| m.name == n) {
3858 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3859 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3877 // If we've implemented a trait, then also emit documentation for all
3878 // default items which weren't overridden in the implementation block.
3879 // We don't emit documentation for default items if they appear in the
3880 // Implementations on Foreign Types or Implementors sections.
3881 if show_default_items {
3882 if let Some(t) = trait_ {
3883 render_default_items(
3896 write!(w, "</div>");
3903 t: &clean::OpaqueTy,
3906 write!(w, "<pre class=\"rust opaque\">");
3907 render_attributes(w, it, false);
3910 "type {}{}{where_clause} = impl {bounds};</pre>",
3911 it.name.as_ref().unwrap(),
3913 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3914 bounds = bounds(&t.bounds, false)
3917 document(w, cx, it, None);
3919 // Render any items associated directly to this alias, as otherwise they
3920 // won't be visible anywhere in the docs. It would be nice to also show
3921 // associated items from the aliased type (see discussion in #32077), but
3922 // we need #14072 to make sense of the generics.
3923 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3926 fn item_trait_alias(
3930 t: &clean::TraitAlias,
3933 write!(w, "<pre class=\"rust trait-alias\">");
3934 render_attributes(w, it, false);
3937 "trait {}{}{} = {};</pre>",
3938 it.name.as_ref().unwrap(),
3940 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3941 bounds(&t.bounds, true)
3944 document(w, cx, it, None);
3946 // Render any items associated directly to this alias, as otherwise they
3947 // won't be visible anywhere in the docs. It would be nice to also show
3948 // associated items from the aliased type (see discussion in #32077), but
3949 // we need #14072 to make sense of the generics.
3950 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3953 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
3954 write!(w, "<pre class=\"rust typedef\">");
3955 render_attributes(w, it, false);
3958 "type {}{}{where_clause} = {type_};</pre>",
3959 it.name.as_ref().unwrap(),
3961 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3962 type_ = t.type_.print()
3965 document(w, cx, it, None);
3967 // Render any items associated directly to this alias, as otherwise they
3968 // won't be visible anywhere in the docs. It would be nice to also show
3969 // associated items from the aliased type (see discussion in #32077), but
3970 // we need #14072 to make sense of the generics.
3971 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3974 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
3975 writeln!(w, "<pre class=\"rust foreigntype\">extern {{");
3976 render_attributes(w, it, false);
3979 " {}type {};\n}}</pre>",
3980 it.visibility.print_with_space(),
3981 it.name.as_ref().unwrap(),
3984 document(w, cx, it, None);
3986 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3989 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
3990 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
3994 || it.is_primitive()
4002 "<p class=\"location\">{}{}</p>",
4004 clean::StructItem(..) => "Struct ",
4005 clean::TraitItem(..) => "Trait ",
4006 clean::PrimitiveItem(..) => "Primitive Type ",
4007 clean::UnionItem(..) => "Union ",
4008 clean::EnumItem(..) => "Enum ",
4009 clean::TypedefItem(..) => "Type Definition ",
4010 clean::ForeignTypeItem => "Foreign Type ",
4011 clean::ModuleItem(..) =>
4019 it.name.as_ref().unwrap()
4024 if let Some(ref version) = cache.crate_version {
4027 "<div class=\"block version\">\
4035 write!(buffer, "<div class=\"sidebar-elems\">");
4039 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4040 it.name.as_ref().expect("crates always have a name")
4044 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
4045 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
4046 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
4047 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
4048 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
4049 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
4050 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4051 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
4055 // The sidebar is designed to display sibling functions, modules and
4056 // other miscellaneous information. since there are lots of sibling
4057 // items (and that causes quadratic growth in large modules),
4058 // we refactor common parts into a shared JavaScript file per module.
4059 // still, we don't move everything into JS because we want to preserve
4060 // as much HTML as possible in order to allow non-JS-enabled browsers
4061 // to navigate the documentation (though slightly inefficiently).
4063 write!(buffer, "<p class=\"location\">");
4064 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4066 write!(buffer, "::<wbr>");
4070 "<a href=\"{}index.html\">{}</a>",
4071 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4075 write!(buffer, "</p>");
4077 // Sidebar refers to the enclosing module, not this module.
4078 let relpath = if it.is_mod() { "../" } else { "" };
4081 "<script>window.sidebarCurrent = {{\
4084 relpath: \"{path}\"\
4086 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4091 // There is no sidebar-items.js beyond the crate root path
4092 // FIXME maybe dynamic crate loading can be merged here
4094 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4096 // Closes sidebar-elems div.
4097 write!(buffer, "</div>");
4100 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4101 if used_links.insert(url.clone()) {
4105 while !used_links.insert(format!("{}-{}", url, add)) {
4108 format!("{}-{}", url, add)
4114 used_links: &mut FxHashSet<String>,
4119 .filter_map(|item| match item.name {
4120 Some(ref name) if !name.is_empty() && item.is_method() => {
4121 if !for_deref || should_render_item(item, deref_mut) {
4123 "<a href=\"#{}\">{}</a>",
4124 get_next_url(used_links, format!("method.{}", name)),
4133 .collect::<Vec<_>>()
4136 // The point is to url encode any potential character from a type with genericity.
4137 fn small_url_encode(s: &str) -> String {
4138 s.replace("<", "%3C")
4139 .replace(">", "%3E")
4140 .replace(" ", "%20")
4141 .replace("?", "%3F")
4142 .replace("'", "%27")
4143 .replace("&", "%26")
4144 .replace(",", "%2C")
4145 .replace(":", "%3A")
4146 .replace(";", "%3B")
4147 .replace("[", "%5B")
4148 .replace("]", "%5D")
4149 .replace("\"", "%22")
4152 fn sidebar_assoc_items(it: &clean::Item) -> String {
4153 let mut out = String::new();
4155 if let Some(v) = c.impls.get(&it.def_id) {
4156 let mut used_links = FxHashSet::default();
4159 let used_links_bor = &mut used_links;
4162 .filter(|i| i.inner_impl().trait_.is_none())
4163 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4164 .collect::<Vec<_>>();
4165 if !ret.is_empty() {
4166 // We want links' order to be reproducible so we don't use unstable sort.
4168 out.push_str(&format!(
4169 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4170 <div class=\"sidebar-links\">{}</div>",
4176 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4177 if let Some(impl_) = v
4179 .filter(|i| i.inner_impl().trait_.is_some())
4180 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4182 if let Some((target, real_target)) =
4183 impl_.inner_impl().items.iter().find_map(|item| match item.inner {
4184 clean::TypedefItem(ref t, true) => Some(match *t {
4185 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4186 _ => (&t.type_, &t.type_),
4193 .filter(|i| i.inner_impl().trait_.is_some())
4194 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4195 let inner_impl = target
4199 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4200 .and_then(|did| c.impls.get(&did));
4201 if let Some(impls) = inner_impl {
4202 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4203 out.push_str(&format!(
4204 "Methods from {}<Target={}>",
4207 impl_.inner_impl().trait_.as_ref().unwrap().print()
4209 Escape(&format!("{:#}", real_target.print()))
4211 out.push_str("</a>");
4214 .filter(|i| i.inner_impl().trait_.is_none())
4216 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4218 .collect::<Vec<_>>();
4219 // We want links' order to be reproducible so we don't use unstable sort.
4221 if !ret.is_empty() {
4222 out.push_str(&format!(
4223 "<div class=\"sidebar-links\">{}</div>",
4230 let format_impls = |impls: Vec<&Impl>| {
4231 let mut links = FxHashSet::default();
4236 let is_negative_impl = is_negative_impl(i.inner_impl());
4237 if let Some(ref i) = i.inner_impl().trait_ {
4238 let i_display = format!("{:#}", i.print());
4239 let out = Escape(&i_display);
4240 let encoded = small_url_encode(&format!("{:#}", i.print()));
4241 let generated = format!(
4242 "<a href=\"#impl-{}\">{}{}</a>",
4244 if is_negative_impl { "!" } else { "" },
4247 if links.insert(generated.clone()) { Some(generated) } else { None }
4252 .collect::<Vec<String>>();
4257 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4258 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4259 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4261 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4263 let concrete_format = format_impls(concrete);
4264 let synthetic_format = format_impls(synthetic);
4265 let blanket_format = format_impls(blanket_impl);
4267 if !concrete_format.is_empty() {
4269 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4270 Trait Implementations</a>",
4272 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4275 if !synthetic_format.is_empty() {
4277 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4278 Auto Trait Implementations</a>",
4280 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4283 if !blanket_format.is_empty() {
4285 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4286 Blanket Implementations</a>",
4288 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4296 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4297 let mut sidebar = String::new();
4298 let fields = get_struct_fields_name(&s.fields);
4300 if !fields.is_empty() {
4301 if let doctree::Plain = s.struct_type {
4302 sidebar.push_str(&format!(
4303 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4304 <div class=\"sidebar-links\">{}</div>",
4310 sidebar.push_str(&sidebar_assoc_items(it));
4312 if !sidebar.is_empty() {
4313 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4317 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4318 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4321 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4323 clean::ItemEnum::ImplItem(ref i) => {
4324 if let Some(ref trait_) = i.trait_ {
4326 format!("{:#}", i.for_.print()),
4327 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4337 fn is_negative_impl(i: &clean::Impl) -> bool {
4338 i.polarity == Some(clean::ImplPolarity::Negative)
4341 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4342 let mut sidebar = String::new();
4347 .filter_map(|m| match m.name {
4348 Some(ref name) if m.is_associated_type() => {
4349 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4353 .collect::<Vec<_>>();
4357 .filter_map(|m| match m.name {
4358 Some(ref name) if m.is_associated_const() => {
4359 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4363 .collect::<Vec<_>>();
4364 let mut required = t
4367 .filter_map(|m| match m.name {
4368 Some(ref name) if m.is_ty_method() => {
4369 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4373 .collect::<Vec<String>>();
4374 let mut provided = t
4377 .filter_map(|m| match m.name {
4378 Some(ref name) if m.is_method() => {
4379 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4383 .collect::<Vec<String>>();
4385 if !types.is_empty() {
4387 sidebar.push_str(&format!(
4388 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4389 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4393 if !consts.is_empty() {
4395 sidebar.push_str(&format!(
4396 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4397 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4401 if !required.is_empty() {
4403 sidebar.push_str(&format!(
4404 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4405 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4409 if !provided.is_empty() {
4411 sidebar.push_str(&format!(
4412 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4413 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4420 if let Some(implementors) = c.implementors.get(&it.def_id) {
4421 let mut res = implementors
4423 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4424 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4425 .collect::<Vec<_>>();
4427 if !res.is_empty() {
4429 sidebar.push_str(&format!(
4430 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4431 Implementations on Foreign Types</a>\
4432 <div class=\"sidebar-links\">{}</div>",
4434 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4435 .collect::<Vec<_>>()
4441 sidebar.push_str(&sidebar_assoc_items(it));
4443 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4446 "<a class=\"sidebar-title\" \
4447 href=\"#synthetic-implementors\">Auto Implementors</a>",
4451 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4454 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4455 let sidebar = sidebar_assoc_items(it);
4457 if !sidebar.is_empty() {
4458 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4462 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4463 let sidebar = sidebar_assoc_items(it);
4465 if !sidebar.is_empty() {
4466 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4470 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4471 let mut fields = fields
4473 .filter(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false })
4474 .filter_map(|f| match f.name {
4476 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4480 .collect::<Vec<_>>();
4485 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4486 let mut sidebar = String::new();
4487 let fields = get_struct_fields_name(&u.fields);
4489 if !fields.is_empty() {
4490 sidebar.push_str(&format!(
4491 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4492 <div class=\"sidebar-links\">{}</div>",
4497 sidebar.push_str(&sidebar_assoc_items(it));
4499 if !sidebar.is_empty() {
4500 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4504 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4505 let mut sidebar = String::new();
4507 let mut variants = e
4510 .filter_map(|v| match v.name {
4511 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4514 .collect::<Vec<_>>();
4515 if !variants.is_empty() {
4516 variants.sort_unstable();
4517 sidebar.push_str(&format!(
4518 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4519 <div class=\"sidebar-links\">{}</div>",
4524 sidebar.push_str(&sidebar_assoc_items(it));
4526 if !sidebar.is_empty() {
4527 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4531 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4533 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4534 ItemType::Module => ("modules", "Modules"),
4535 ItemType::Struct => ("structs", "Structs"),
4536 ItemType::Union => ("unions", "Unions"),
4537 ItemType::Enum => ("enums", "Enums"),
4538 ItemType::Function => ("functions", "Functions"),
4539 ItemType::Typedef => ("types", "Type Definitions"),
4540 ItemType::Static => ("statics", "Statics"),
4541 ItemType::Constant => ("constants", "Constants"),
4542 ItemType::Trait => ("traits", "Traits"),
4543 ItemType::Impl => ("impls", "Implementations"),
4544 ItemType::TyMethod => ("tymethods", "Type Methods"),
4545 ItemType::Method => ("methods", "Methods"),
4546 ItemType::StructField => ("fields", "Struct Fields"),
4547 ItemType::Variant => ("variants", "Variants"),
4548 ItemType::Macro => ("macros", "Macros"),
4549 ItemType::Primitive => ("primitives", "Primitive Types"),
4550 ItemType::AssocType => ("associated-types", "Associated Types"),
4551 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4552 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4553 ItemType::Keyword => ("keywords", "Keywords"),
4554 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4555 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4556 ItemType::ProcDerive => ("derives", "Derive Macros"),
4557 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4561 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4562 let mut sidebar = String::new();
4564 if items.iter().any(|it| {
4565 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4567 sidebar.push_str(&format!(
4568 "<li><a href=\"#{id}\">{name}</a></li>",
4574 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4575 // to print its headings
4577 ItemType::Primitive,
4591 ItemType::StructField,
4593 ItemType::AssocType,
4594 ItemType::AssocConst,
4595 ItemType::ForeignType,
4598 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4599 let (short, name) = item_ty_to_strs(&myty);
4600 sidebar.push_str(&format!(
4601 "<li><a href=\"#{id}\">{name}</a></li>",
4608 if !sidebar.is_empty() {
4609 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4613 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4614 let sidebar = sidebar_assoc_items(it);
4615 if !sidebar.is_empty() {
4616 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4620 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4621 wrap_into_docblock(w, |w| {
4622 w.write_str(&highlight::render_with_highlighting(
4629 document(w, cx, it, None)
4632 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4633 let name = it.name.as_ref().expect("proc-macros always have names");
4635 MacroKind::Bang => {
4636 write!(w, "<pre class=\"rust macro\">");
4637 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4638 write!(w, "</pre>");
4640 MacroKind::Attr => {
4641 write!(w, "<pre class=\"rust attr\">");
4642 write!(w, "#[{}]", name);
4643 write!(w, "</pre>");
4645 MacroKind::Derive => {
4646 write!(w, "<pre class=\"rust derive\">");
4647 write!(w, "#[derive({})]", name);
4648 if !m.helpers.is_empty() {
4649 writeln!(w, "\n{{");
4650 writeln!(w, " // Attributes available to this derive:");
4651 for attr in &m.helpers {
4652 writeln!(w, " #[{}]", attr);
4656 write!(w, "</pre>");
4659 document(w, cx, it, None)
4662 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4663 document(w, cx, it, None);
4664 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4667 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4668 document(w, cx, it, None)
4671 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4673 fn make_item_keywords(it: &clean::Item) -> String {
4674 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4677 /// Returns a list of all paths used in the type.
4678 /// This is used to help deduplicate imported impls
4679 /// for reexported types. If any of the contained
4680 /// types are re-exported, we don't use the corresponding
4681 /// entry from the js file, as inlining will have already
4682 /// picked up the impl
4683 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4684 let mut out = Vec::new();
4685 let mut visited = FxHashSet::default();
4686 let mut work = VecDeque::new();
4687 let cache = cache();
4689 work.push_back(first_ty);
4691 while let Some(ty) = work.pop_front() {
4692 if !visited.insert(ty.clone()) {
4697 clean::Type::ResolvedPath { did, .. } => {
4698 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4699 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4701 if let Some(path) = fqp {
4702 out.push(path.join("::"));
4705 clean::Type::Tuple(tys) => {
4706 work.extend(tys.into_iter());
4708 clean::Type::Slice(ty) => {
4709 work.push_back(*ty);
4711 clean::Type::Array(ty, _) => {
4712 work.push_back(*ty);
4714 clean::Type::RawPointer(_, ty) => {
4715 work.push_back(*ty);
4717 clean::Type::BorrowedRef { type_, .. } => {
4718 work.push_back(*type_);
4720 clean::Type::QPath { self_type, trait_, .. } => {
4721 work.push_back(*self_type);
4722 work.push_back(*trait_);