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,
398 generate_search_filter,
402 let src_root = match krate.src {
403 FileName::Real(ref p) => match p.local_path().parent() {
404 Some(p) => p.to_path_buf(),
405 None => PathBuf::new(),
409 // If user passed in `--playground-url` arg, we fill in crate name here
410 let mut playground = None;
411 if let Some(url) = playground_url {
412 playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url });
414 let mut layout = layout::Layout {
416 favicon: String::new(),
418 krate: krate.name.clone(),
419 css_file_extension: extension_css,
420 generate_search_filter,
422 let mut issue_tracker_base_url = None;
423 let mut include_sources = true;
425 // Crawl the crate attributes looking for attributes which control how we're
426 // going to emit HTML
427 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
428 for attr in attrs.lists(sym::doc) {
429 match (attr.name_or_empty(), attr.value_str()) {
430 (sym::html_favicon_url, Some(s)) => {
431 layout.favicon = s.to_string();
433 (sym::html_logo_url, Some(s)) => {
434 layout.logo = s.to_string();
436 (sym::html_playground_url, Some(s)) => {
437 playground = Some(markdown::Playground {
438 crate_name: Some(krate.name.clone()),
442 (sym::issue_tracker_base_url, Some(s)) => {
443 issue_tracker_base_url = Some(s.to_string());
445 (sym::html_no_source, None) if attr.is_word() => {
446 include_sources = false;
452 let (sender, receiver) = channel();
453 let mut scx = SharedContext {
454 collapsed: krate.collapsed,
457 local_sources: Default::default(),
458 issue_tracker_base_url,
460 created_dirs: Default::default(),
461 sort_modules_alphabetically,
465 fs: DocFS::new(sender),
467 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
471 // Add the default themes to the `Vec` of stylepaths
473 // Note that these must be added before `sources::render` is called
474 // so that the resulting source pages are styled
476 // `light.css` is not disabled because it is the stylesheet that stays loaded
477 // by the browser as the theme stylesheet. The theme system (hackily) works by
478 // changing the href to this stylesheet. All other themes are disabled to
479 // prevent rule conflicts
480 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
481 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
482 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
485 scx.ensure_dir(&dst)?;
486 krate = sources::render(&dst, &mut scx, krate)?;
488 // Build our search index
489 let index = build_index(&krate, cache);
491 let cache = Arc::new(cache);
492 let mut cx = Context {
495 render_redirect_pages: false,
496 id_map: Rc::new(RefCell::new(id_map)),
497 shared: Arc::new(scx),
498 all: Rc::new(RefCell::new(AllTypes::new())),
499 errors: Rc::new(receiver),
502 CURRENT_DEPTH.with(|s| s.set(0));
504 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
505 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
506 write_shared(&cx, &krate, index, &md_opts, &cache)?;
507 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
511 fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
512 Arc::get_mut(&mut self.shared).unwrap().fs.close();
513 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
515 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
521 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
522 let final_file = self.dst.join(&krate.name).join("all.html");
523 let settings_file = self.dst.join("settings.html");
524 let crate_name = krate.name.clone();
526 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
527 if !root_path.ends_with('/') {
530 let mut page = layout::Page {
531 title: "List of all items in this crate",
534 static_root_path: self.shared.static_root_path.as_deref(),
535 description: "List of all items in this crate",
536 keywords: BASIC_KEYWORDS,
537 resource_suffix: &self.shared.resource_suffix,
539 static_extra_scripts: &[],
541 let sidebar = if let Some(ref version) = cache.crate_version {
543 "<p class=\"location\">Crate {}</p>\
544 <div class=\"block version\">\
547 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
554 let all = self.all.replace(AllTypes::new());
555 let v = layout::render(
559 |buf: &mut Buffer| all.print(buf),
560 &self.shared.style_files,
562 self.shared.fs.write(&final_file, v.as_bytes())?;
564 // Generating settings page.
565 page.title = "Rustdoc settings";
566 page.description = "Settings of Rustdoc";
567 page.root_path = "./";
569 let mut style_files = self.shared.style_files.clone();
570 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
571 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
572 let v = layout::render(
577 self.shared.static_root_path.as_deref().unwrap_or("./"),
578 &self.shared.resource_suffix,
579 &self.shared.style_files,
583 self.shared.fs.write(&settings_file, v.as_bytes())?;
592 ) -> Result<(), Error> {
593 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
594 // if they contain impls for public types. These modules can also
595 // contain items such as publicly re-exported structures.
597 // External crates will provide links to these structures, so
598 // these modules are recursed into, but not rendered normally
599 // (a flag on the context).
600 if !self.render_redirect_pages {
601 self.render_redirect_pages = item.is_stripped();
603 let scx = &self.shared;
604 self.dst.push(item_name);
605 self.current.push(item_name.to_owned());
607 info!("Recursing into {}", self.dst.display());
609 let buf = self.render_item(item, false, cache);
610 // buf will be empty if the module is stripped and there is no redirect for it
612 self.shared.ensure_dir(&self.dst)?;
613 let joint_dst = self.dst.join("index.html");
614 scx.fs.write(&joint_dst, buf.as_bytes())?;
617 // Render sidebar-items.js used throughout this module.
618 if !self.render_redirect_pages {
619 let module = match item.inner {
620 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
623 let items = self.build_sidebar_items(module);
624 let js_dst = self.dst.join("sidebar-items.js");
625 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
626 scx.fs.write(&js_dst, &v)?;
631 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
632 info!("Recursed; leaving {}", self.dst.display());
634 // Go back to where we were at
640 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
641 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
642 // if they contain impls for public types. These modules can also
643 // contain items such as publicly re-exported structures.
645 // External crates will provide links to these structures, so
646 // these modules are recursed into, but not rendered normally
647 // (a flag on the context).
648 if !self.render_redirect_pages {
649 self.render_redirect_pages = item.is_stripped();
652 let buf = self.render_item(&item, true, cache);
653 // buf will be empty if the item is stripped and there is no redirect for it
655 let name = item.name.as_ref().unwrap();
656 let item_type = item.type_();
657 let file_name = &item_path(item_type, name);
658 self.shared.ensure_dir(&self.dst)?;
659 let joint_dst = self.dst.join(file_name);
660 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
662 if !self.render_redirect_pages {
663 self.all.borrow_mut().append(full_path(self, &item), &item_type);
665 // If the item is a macro, redirect from the old macro URL (with !)
666 // to the new one (without).
667 if item_type == ItemType::Macro {
668 let redir_name = format!("{}.{}!.html", item_type, name);
669 let redir_dst = self.dst.join(redir_name);
670 let v = layout::redirect(file_name);
671 self.shared.fs.write(&redir_dst, v.as_bytes())?;
680 krate: &clean::Crate,
681 search_index: String,
682 options: &RenderOptions,
684 ) -> Result<(), Error> {
685 // Write out the shared files. Note that these are shared among all rustdoc
686 // docs placed in the output directory, so this needs to be a synchronized
687 // operation with respect to all other rustdocs running around.
688 let lock_file = cx.dst.join(".lock");
689 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
691 // Add all the static files. These may already exist, but we just
692 // overwrite them anyway to make sure that they're fresh and up-to-date.
696 cx.path("rustdoc.css"),
697 static_files::RUSTDOC_CSS,
698 options.enable_minification,
702 cx.path("settings.css"),
703 static_files::SETTINGS_CSS,
704 options.enable_minification,
708 cx.path("noscript.css"),
709 static_files::NOSCRIPT_CSS,
710 options.enable_minification,
713 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
714 // then we'll run over the "official" styles.
715 let mut themes: FxHashSet<String> = FxHashSet::default();
717 for entry in &cx.shared.style_files {
718 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
720 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
722 // Handle the official themes
724 "light" => write_minify(
726 cx.path("light.css"),
727 static_files::themes::LIGHT,
728 options.enable_minification,
730 "dark" => write_minify(
733 static_files::themes::DARK,
734 options.enable_minification,
736 "ayu" => write_minify(
739 static_files::themes::AYU,
740 options.enable_minification,
743 // Handle added third-party themes
744 let content = try_err!(fs::read(&entry.path), &entry.path);
747 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
751 themes.insert(theme.to_owned());
754 let write = |p, c| cx.shared.fs.write(p, c);
755 if (*cx.shared).layout.logo.is_empty() {
756 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
758 if (*cx.shared).layout.favicon.is_empty() {
759 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
760 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
761 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
763 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
764 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
765 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
767 let mut themes: Vec<&String> = themes.iter().collect();
769 // To avoid theme switch latencies as much as possible, we put everything theme related
770 // at the beginning of the html files into another js file.
771 let theme_js = format!(
772 r#"var themes = document.getElementById("theme-choices");
773 var themePicker = document.getElementById("theme-picker");
775 function showThemeButtonState() {{
776 themes.style.display = "block";
777 themePicker.style.borderBottomRightRadius = "0";
778 themePicker.style.borderBottomLeftRadius = "0";
781 function hideThemeButtonState() {{
782 themes.style.display = "none";
783 themePicker.style.borderBottomRightRadius = "3px";
784 themePicker.style.borderBottomLeftRadius = "3px";
787 function switchThemeButtonState() {{
788 if (themes.style.display === "block") {{
789 hideThemeButtonState();
791 showThemeButtonState();
795 function handleThemeButtonsBlur(e) {{
796 var active = document.activeElement;
797 var related = e.relatedTarget;
799 if (active.id !== "themePicker" &&
800 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
802 (related.id !== "themePicker" &&
803 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
804 hideThemeButtonState();
808 themePicker.onclick = switchThemeButtonState;
809 themePicker.onblur = handleThemeButtonsBlur;
810 {}.forEach(function(item) {{
811 var but = document.createElement("button");
812 but.textContent = item;
813 but.onclick = function(el) {{
814 switchTheme(currentTheme, mainTheme, item, true);
815 useSystemTheme(false);
817 but.onblur = handleThemeButtonsBlur;
818 themes.appendChild(but);
820 serde_json::to_string(&themes).unwrap()
823 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
827 static_files::MAIN_JS,
828 options.enable_minification,
832 cx.path("settings.js"),
833 static_files::SETTINGS_JS,
834 options.enable_minification,
836 if cx.shared.include_sources {
839 cx.path("source-script.js"),
840 static_files::sidebar::SOURCE_SCRIPT,
841 options.enable_minification,
848 cx.path("storage.js"),
850 "var resourcesSuffix = \"{}\";{}",
851 cx.shared.resource_suffix,
852 static_files::STORAGE_JS
854 options.enable_minification,
858 if let Some(ref css) = cx.shared.layout.css_file_extension {
859 let out = cx.path("theme.css");
860 let buffer = try_err!(fs::read_to_string(css), css);
861 if !options.enable_minification {
862 cx.shared.fs.write(&out, &buffer)?;
864 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
869 cx.path("normalize.css"),
870 static_files::NORMALIZE_CSS,
871 options.enable_minification,
873 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
874 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
875 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
876 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
877 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
878 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
879 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
880 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
881 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
882 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
883 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
884 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
885 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
887 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
888 let mut ret = Vec::new();
889 let mut krates = Vec::new();
892 for line in BufReader::new(File::open(path)?).lines() {
894 if !line.starts_with(key) {
897 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
900 ret.push(line.to_string());
902 line[key.len() + 2..]
905 .map(|s| s.to_owned())
906 .unwrap_or_else(String::new),
913 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
914 let mut ret = Vec::new();
915 let mut krates = Vec::new();
918 for line in BufReader::new(File::open(path)?).lines() {
920 if !line.starts_with('"') {
923 if line.starts_with(&format!("\"{}\"", krate)) {
926 if line.ends_with(",\\") {
927 ret.push(line[..line.len() - 2].to_string());
929 // Ends with "\\" (it's the case for the last added crate line)
930 ret.push(line[..line.len() - 1].to_string());
934 .find(|s| !s.is_empty())
935 .map(|s| s.to_owned())
936 .unwrap_or_else(String::new),
943 use std::ffi::OsString;
948 children: FxHashMap<OsString, Hierarchy>,
949 elems: FxHashSet<OsString>,
953 fn new(elem: OsString) -> Hierarchy {
954 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
957 fn to_json_string(&self) -> String {
958 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
959 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
963 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
964 .collect::<Vec<_>>();
965 files.sort_unstable_by(|a, b| a.cmp(b));
966 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
968 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
969 let files = files.join(",");
971 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
973 "{{\"name\":\"{name}\"{dirs}{files}}}",
974 name = self.elem.to_str().expect("invalid osstring conversion"),
981 if cx.shared.include_sources {
982 let mut hierarchy = Hierarchy::new(OsString::new());
987 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
989 let mut h = &mut hierarchy;
990 let mut elems = source
992 .filter_map(|s| match s {
993 Component::Normal(s) => Some(s.to_owned()),
998 let cur_elem = elems.next().expect("empty file path");
999 if elems.peek().is_none() {
1000 h.elems.insert(cur_elem);
1003 let e = cur_elem.clone();
1004 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1005 h = h.children.get_mut(&cur_elem).expect("not found child");
1010 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1011 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1012 all_sources.push(format!(
1013 "sourcesIndex[\"{}\"] = {};",
1015 hierarchy.to_json_string()
1019 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1020 all_sources.join("\n")
1022 cx.shared.fs.write(&dst, v.as_bytes())?;
1025 // Update the search index
1026 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1027 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name), &dst);
1028 all_indexes.push(search_index);
1030 // Sort the indexes by crate so the file will be generated identically even
1031 // with rustdoc running in parallel.
1034 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1035 v.push_str(&all_indexes.join(",\\\n"));
1036 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1037 // search might start (if it's set into the URL for example).
1038 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1039 cx.shared.fs.write(&dst, &v)?;
1041 if options.enable_index_page {
1042 if let Some(index_page) = options.index_page.clone() {
1043 let mut md_opts = options.clone();
1044 md_opts.output = cx.dst.clone();
1045 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1047 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1048 .map_err(|e| Error::new(e, &index_page))?;
1050 let dst = cx.dst.join("index.html");
1051 let page = layout::Page {
1052 title: "Index of crates",
1055 static_root_path: cx.shared.static_root_path.as_deref(),
1056 description: "List of crates",
1057 keywords: BASIC_KEYWORDS,
1058 resource_suffix: &cx.shared.resource_suffix,
1060 static_extra_scripts: &[],
1062 krates.push(krate.name.clone());
1066 let content = format!(
1067 "<h1 class=\"fqn\">\
1068 <span class=\"in-band\">List of all crates</span>\
1069 </h1><ul class=\"crate mod\">{}</ul>",
1074 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1075 ensure_trailing_slash(s),
1079 .collect::<String>()
1081 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1082 cx.shared.fs.write(&dst, v.as_bytes())?;
1086 // Update the list of all implementors for traits
1087 let dst = cx.dst.join("implementors");
1088 for (&did, imps) in &cache.implementors {
1089 // Private modules can leak through to this phase of rustdoc, which
1090 // could contain implementations for otherwise private types. In some
1091 // rare cases we could find an implementation for an item which wasn't
1092 // indexed, so we just skip this step in that case.
1094 // FIXME: this is a vague explanation for why this can't be a `get`, in
1095 // theory it should be...
1096 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1098 None => match cache.external_paths.get(&did) {
1104 #[derive(Serialize)]
1105 struct Implementor {
1111 let implementors = imps
1114 // If the trait and implementation are in the same crate, then
1115 // there's no need to emit information about it (there's inlining
1116 // going on). If they're in different crates then the crate defining
1117 // the trait will be interested in our implementation.
1119 // If the implementation is from another crate then that crate
1121 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1125 text: imp.inner_impl().print().to_string(),
1126 synthetic: imp.inner_impl().synthetic,
1127 types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1131 .collect::<Vec<_>>();
1133 // Only create a js file if we have impls to add to it. If the trait is
1134 // documented locally though we always create the file to avoid dead
1136 if implementors.is_empty() && !cache.paths.contains_key(&did) {
1140 let implementors = format!(
1141 r#"implementors["{}"] = {};"#,
1143 serde_json::to_string(&implementors).unwrap()
1146 let mut mydst = dst.clone();
1147 for part in &remote_path[..remote_path.len() - 1] {
1150 cx.shared.ensure_dir(&mydst)?;
1151 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1153 let (mut all_implementors, _) =
1154 try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1155 all_implementors.push(implementors);
1156 // Sort the implementors by crate so the file will be generated
1157 // identically even with rustdoc running in parallel.
1158 all_implementors.sort();
1160 let mut v = String::from("(function() {var implementors = {};\n");
1161 for implementor in &all_implementors {
1162 writeln!(v, "{}", *implementor).unwrap();
1165 "if (window.register_implementors) {\
1166 window.register_implementors(implementors);\
1168 window.pending_implementors = implementors;\
1172 cx.shared.fs.write(&mydst, &v)?;
1181 enable_minification: bool,
1182 ) -> Result<(), Error> {
1183 if enable_minification {
1184 if dst.extension() == Some(&OsStr::new("css")) {
1185 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1186 fs.write(dst, res.as_bytes())
1188 fs.write(dst, minifier::js::minify(contents).as_bytes())
1191 fs.write(dst, contents.as_bytes())
1195 #[derive(Debug, Eq, PartialEq, Hash)]
1202 fn new(mut url: String, name: String) -> ItemEntry {
1203 while url.starts_with('/') {
1206 ItemEntry { url, name }
1211 crate fn print(&self) -> impl fmt::Display + '_ {
1212 crate::html::format::display_fn(move |f| {
1213 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1218 impl PartialOrd for ItemEntry {
1219 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1220 Some(self.cmp(other))
1224 impl Ord for ItemEntry {
1225 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1226 self.name.cmp(&other.name)
1232 structs: FxHashSet<ItemEntry>,
1233 enums: FxHashSet<ItemEntry>,
1234 unions: FxHashSet<ItemEntry>,
1235 primitives: FxHashSet<ItemEntry>,
1236 traits: FxHashSet<ItemEntry>,
1237 macros: FxHashSet<ItemEntry>,
1238 functions: FxHashSet<ItemEntry>,
1239 typedefs: FxHashSet<ItemEntry>,
1240 opaque_tys: FxHashSet<ItemEntry>,
1241 statics: FxHashSet<ItemEntry>,
1242 constants: FxHashSet<ItemEntry>,
1243 keywords: FxHashSet<ItemEntry>,
1244 attributes: FxHashSet<ItemEntry>,
1245 derives: FxHashSet<ItemEntry>,
1246 trait_aliases: FxHashSet<ItemEntry>,
1250 fn new() -> AllTypes {
1251 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1253 structs: new_set(100),
1254 enums: new_set(100),
1255 unions: new_set(100),
1256 primitives: new_set(26),
1257 traits: new_set(100),
1258 macros: new_set(100),
1259 functions: new_set(100),
1260 typedefs: new_set(100),
1261 opaque_tys: new_set(100),
1262 statics: new_set(100),
1263 constants: new_set(100),
1264 keywords: new_set(100),
1265 attributes: new_set(100),
1266 derives: new_set(100),
1267 trait_aliases: new_set(100),
1271 fn append(&mut self, item_name: String, item_type: &ItemType) {
1272 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1273 if let Some(name) = url.pop() {
1274 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1276 let name = url.join("::");
1278 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1279 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1280 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1281 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1282 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1283 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1284 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1285 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1286 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1287 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1288 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1289 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1290 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1291 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1298 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1300 let mut e: Vec<&ItemEntry> = e.iter().collect();
1304 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">{}</ul>",
1308 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1314 fn print(self, f: &mut Buffer) {
1317 "<h1 class=\"fqn\">\
1318 <span class=\"out-of-band\">\
1319 <span id=\"render-detail\">\
1320 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1321 title=\"collapse all docs\">\
1322 [<span class=\"inner\">−</span>]\
1326 <span class=\"in-band\">List of all items</span>\
1329 print_entries(f, &self.structs, "Structs", "structs");
1330 print_entries(f, &self.enums, "Enums", "enums");
1331 print_entries(f, &self.unions, "Unions", "unions");
1332 print_entries(f, &self.primitives, "Primitives", "primitives");
1333 print_entries(f, &self.traits, "Traits", "traits");
1334 print_entries(f, &self.macros, "Macros", "macros");
1335 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1336 print_entries(f, &self.derives, "Derive Macros", "derives");
1337 print_entries(f, &self.functions, "Functions", "functions");
1338 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1339 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1340 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1341 print_entries(f, &self.statics, "Statics", "statics");
1342 print_entries(f, &self.constants, "Constants", "constants")
1349 description: &'static str,
1350 sub_settings: Vec<Setting>,
1353 js_data_name: &'static str,
1354 description: &'static str,
1355 default_value: bool,
1358 js_data_name: &'static str,
1359 description: &'static str,
1360 default_value: &'static str,
1361 options: Vec<(String, String)>,
1366 fn display(&self, root_path: &str, suffix: &str) -> String {
1368 Setting::Section { description, ref sub_settings } => format!(
1369 "<div class=\"setting-line\">\
1370 <div class=\"title\">{}</div>\
1371 <div class=\"sub-settings\">{}</div>
1374 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1376 Setting::Toggle { js_data_name, description, default_value } => format!(
1377 "<div class=\"setting-line\">\
1378 <label class=\"toggle\">\
1379 <input type=\"checkbox\" id=\"{}\" {}>\
1380 <span class=\"slider\"></span>\
1385 if default_value { " checked" } else { "" },
1388 Setting::Select { js_data_name, description, default_value, ref options } => format!(
1389 "<div class=\"setting-line\">\
1391 <label class=\"select-wrapper\">\
1392 <select id=\"{}\" autocomplete=\"off\">{}</select>\
1393 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1401 "<option value=\"{}\" {}>{}</option>",
1403 if &opt.0 == default_value { "selected" } else { "" },
1406 .collect::<String>(),
1414 impl From<(&'static str, &'static str, bool)> for Setting {
1415 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1416 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1420 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1421 fn from(values: (&'static str, Vec<T>)) -> Setting {
1423 description: values.0,
1424 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1429 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1430 let theme_names: Vec<(String, String)> = themes
1434 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1437 Ok((theme.clone(), theme))
1439 .collect::<Result<_, Error>>()?;
1441 // (id, explanation, default value)
1442 let settings: &[Setting] = &[
1444 "Theme preferences",
1446 Setting::from(("use-system-theme", "Use system theme", true)),
1448 js_data_name: "preferred-dark-theme",
1449 description: "Preferred dark theme",
1450 default_value: "dark",
1451 options: theme_names.clone(),
1454 js_data_name: "preferred-light-theme",
1455 description: "Preferred light theme",
1456 default_value: "light",
1457 options: theme_names,
1463 "Auto-hide item declarations",
1465 ("auto-hide-struct", "Auto-hide structs declaration", true),
1466 ("auto-hide-enum", "Auto-hide enums declaration", false),
1467 ("auto-hide-union", "Auto-hide unions declaration", true),
1468 ("auto-hide-trait", "Auto-hide traits declaration", true),
1469 ("auto-hide-macro", "Auto-hide macros declaration", false),
1473 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1474 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1475 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1477 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1478 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1480 ("line-numbers", "Show line numbers on code examples", false).into(),
1481 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1485 "<h1 class=\"fqn\">\
1486 <span class=\"in-band\">Rustdoc settings</span>\
1488 <div class=\"settings\">{}</div>\
1489 <script src=\"{}settings{}.js\"></script>",
1490 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1497 fn derive_id(&self, id: String) -> String {
1498 let mut map = self.id_map.borrow_mut();
1502 /// String representation of how to get back to the root path of the 'doc/'
1503 /// folder in terms of a relative URL.
1504 fn root_path(&self) -> String {
1505 "../".repeat(self.current.len())
1508 fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1509 // A little unfortunate that this is done like this, but it sure
1510 // does make formatting *a lot* nicer.
1511 CURRENT_DEPTH.with(|slot| {
1512 slot.set(self.current.len());
1515 let mut title = if it.is_primitive() || it.is_keyword() {
1516 // No need to include the namespace for primitive types and keywords
1519 self.current.join("::")
1522 if !title.is_empty() {
1523 title.push_str("::");
1525 title.push_str(it.name.as_ref().unwrap());
1527 title.push_str(" - Rust");
1528 let tyname = it.type_();
1529 let desc = if it.is_crate() {
1530 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1533 "API documentation for the Rust `{}` {} in crate `{}`.",
1534 it.name.as_ref().unwrap(),
1536 self.shared.layout.krate
1539 let keywords = make_item_keywords(it);
1540 let page = layout::Page {
1541 css_class: tyname.as_str(),
1542 root_path: &self.root_path(),
1543 static_root_path: self.shared.static_root_path.as_deref(),
1546 keywords: &keywords,
1547 resource_suffix: &self.shared.resource_suffix,
1549 static_extra_scripts: &[],
1553 self.id_map.borrow_mut().reset();
1554 self.id_map.borrow_mut().populate(initial_ids());
1557 if !self.render_redirect_pages {
1559 &self.shared.layout,
1561 |buf: &mut _| print_sidebar(self, it, buf, cache),
1562 |buf: &mut _| print_item(self, it, buf, cache),
1563 &self.shared.style_files,
1566 let mut url = self.root_path();
1567 if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1568 for name in &names[..names.len() - 1] {
1572 url.push_str(&item_path(ty, names.last().unwrap()));
1573 layout::redirect(&url)
1580 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1581 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1582 // BTreeMap instead of HashMap to get a sorted output
1583 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1584 for item in &m.items {
1585 if item.is_stripped() {
1589 let short = item.type_();
1590 let myname = match item.name {
1592 Some(ref s) => s.to_string(),
1594 let short = short.to_string();
1597 .push((myname, Some(plain_text_summary(item.doc_value()))));
1600 if self.shared.sort_modules_alphabetically {
1601 for items in map.values_mut() {
1608 /// Generates a url appropriate for an `href` attribute back to the source of
1611 /// The url generated, when clicked, will redirect the browser back to the
1612 /// original source code.
1614 /// If `None` is returned, then a source link couldn't be generated. This
1615 /// may happen, for example, with externally inlined items where the source
1616 /// of their crate documentation isn't known.
1617 fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1618 let mut root = self.root_path();
1620 let mut path = String::new();
1622 // We can safely ignore synthetic `SourceFile`s.
1623 let file = match item.source.filename {
1624 FileName::Real(ref path) => path.local_path().to_path_buf(),
1629 let (krate, path) = if item.source.cnum == LOCAL_CRATE {
1630 if let Some(path) = self.shared.local_sources.get(file) {
1631 (&self.shared.layout.krate, path)
1636 let (krate, src_root) = match *cache.extern_locations.get(&item.source.cnum)? {
1637 (ref name, ref src, ExternalLocation::Local) => (name, src),
1638 (ref name, ref src, ExternalLocation::Remote(ref s)) => {
1639 root = s.to_string();
1642 (_, _, ExternalLocation::Unknown) => return None,
1645 sources::clean_path(&src_root, file, false, |component| {
1646 path.push_str(&component.to_string_lossy());
1649 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1650 fname.push(".html");
1651 path.push_str(&fname.to_string_lossy());
1655 let lines = if item.source.loline == item.source.hiline {
1656 item.source.loline.to_string()
1658 format!("{}-{}", item.source.loline, item.source.hiline)
1661 "{root}src/{krate}/{path}#{lines}",
1662 root = Escape(&root),
1670 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1672 F: FnOnce(&mut Buffer),
1674 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1679 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1680 debug_assert!(!item.is_stripped());
1681 // Write the breadcrumb trail header for the top
1682 write!(buf, "<h1 class=\"fqn\"><span class=\"out-of-band\">");
1683 if let Some(version) = item.stable_since() {
1686 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
1692 "<span id=\"render-detail\">\
1693 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1694 title=\"collapse all docs\">\
1695 [<span class=\"inner\">−</span>]\
1702 // When this item is part of a `pub use` in a downstream crate, the
1703 // [src] link in the downstream documentation will actually come back to
1704 // this page, and this link will be auto-clicked. The `id` attribute is
1705 // used to find the link to auto-click.
1706 if cx.shared.include_sources && !item.is_primitive() {
1707 if let Some(l) = cx.src_href(item, cache) {
1710 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
1711 l, "goto source code"
1716 write!(buf, "</span>"); // out-of-band
1717 write!(buf, "<span class=\"in-band\">");
1718 let name = match item.inner {
1719 clean::ModuleItem(ref m) => {
1726 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1727 clean::TraitItem(..) => "Trait ",
1728 clean::StructItem(..) => "Struct ",
1729 clean::UnionItem(..) => "Union ",
1730 clean::EnumItem(..) => "Enum ",
1731 clean::TypedefItem(..) => "Type Definition ",
1732 clean::MacroItem(..) => "Macro ",
1733 clean::ProcMacroItem(ref mac) => match mac.kind {
1734 MacroKind::Bang => "Macro ",
1735 MacroKind::Attr => "Attribute Macro ",
1736 MacroKind::Derive => "Derive Macro ",
1738 clean::PrimitiveItem(..) => "Primitive Type ",
1739 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1740 clean::ConstantItem(..) => "Constant ",
1741 clean::ForeignTypeItem => "Foreign Type ",
1742 clean::KeywordItem(..) => "Keyword ",
1743 clean::OpaqueTyItem(..) => "Opaque Type ",
1744 clean::TraitAliasItem(..) => "Trait Alias ",
1746 // We don't generate pages for any other type.
1750 buf.write_str(name);
1751 if !item.is_primitive() && !item.is_keyword() {
1752 let cur = &cx.current;
1753 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1754 for (i, component) in cur.iter().enumerate().take(amt) {
1757 "<a href=\"{}index.html\">{}</a>::<wbr>",
1758 "../".repeat(cur.len() - i - 1),
1763 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1765 write!(buf, "</span></h1>"); // in-band
1768 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1769 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1770 item_function(buf, cx, item, f)
1772 clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1773 clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1774 clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1775 clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1776 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1777 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1778 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1779 clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1780 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1781 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1782 clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1783 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1784 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e, cache),
1785 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1787 // We don't generate pages for any other type.
1793 fn item_path(ty: ItemType, name: &str) -> String {
1795 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1796 _ => format!("{}.{}.html", ty, name),
1800 fn full_path(cx: &Context, item: &clean::Item) -> String {
1801 let mut s = cx.current.join("::");
1803 s.push_str(item.name.as_ref().unwrap());
1807 /// Renders the first paragraph of the given markdown as plain text, making it suitable for
1808 /// contexts like alt-text or the search index.
1810 /// If no markdown is supplied, the empty string is returned.
1812 /// See [`markdown::plain_text_summary`] for further details.
1814 crate fn plain_text_summary(s: Option<&str>) -> String {
1815 s.map(markdown::plain_text_summary).unwrap_or_default()
1818 crate fn shorten(s: String) -> String {
1819 if s.chars().count() > 60 {
1824 // + 1 for the added character after the word.
1825 len += p.chars().count() + 1;
1828 .collect::<Vec<_>>()
1837 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item, parent: Option<&clean::Item>) {
1838 if let Some(ref name) = item.name {
1839 info!("Documenting {}", name);
1841 document_stability(w, cx, item, false, parent);
1842 document_full(w, item, cx, "", false);
1845 /// Render md_text as markdown.
1850 links: Vec<RenderedLink>,
1854 let mut ids = cx.id_map.borrow_mut();
1857 "<div class=\"docblock{}\">{}{}</div>",
1858 if is_hidden { " hidden" } else { "" },
1866 &cx.shared.playground
1872 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1873 /// docs are longer, a "Read more" link is appended to the end.
1877 link: AssocItemLink<'_>,
1881 if let Some(s) = item.doc_value() {
1882 let mut summary_html = MarkdownSummaryLine(s, &item.links()).into_string();
1884 if s.contains('\n') {
1885 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link));
1887 if let Some(idx) = summary_html.rfind("</p>") {
1888 summary_html.insert_str(idx, &link);
1890 summary_html.push_str(&link);
1896 "<div class='docblock{}'>{}{}</div>",
1897 if is_hidden { " hidden" } else { "" },
1901 } else if !prefix.is_empty() {
1904 "<div class=\"docblock{}\">{}</div>",
1905 if is_hidden { " hidden" } else { "" },
1911 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1912 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1913 debug!("Doc block: =====\n{}\n=====", s);
1914 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1915 } else if !prefix.is_empty() {
1918 "<div class=\"docblock{}\">{}</div>",
1919 if is_hidden { " hidden" } else { "" },
1925 fn document_stability(
1930 parent: Option<&clean::Item>,
1932 let stabilities = short_stability(item, cx, parent);
1933 if !stabilities.is_empty() {
1934 write!(w, "<div class=\"stability{}\">", if is_hidden { " hidden" } else { "" });
1935 for stability in stabilities {
1936 write!(w, "{}", stability);
1938 write!(w, "</div>");
1942 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1943 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1946 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1947 if item.is_non_exhaustive() {
1948 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1949 if item.is_struct() {
1951 } else if item.is_enum() {
1953 } else if item.is_variant() {
1960 if item.is_struct() {
1963 "Non-exhaustive structs could have additional fields added in future. \
1964 Therefore, non-exhaustive structs cannot be constructed in external crates \
1965 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1966 matched against without a wildcard <code>..</code>; and \
1967 struct update syntax will not work."
1969 } else if item.is_enum() {
1972 "Non-exhaustive enums could have additional variants added in future. \
1973 Therefore, when matching against variants of non-exhaustive enums, an \
1974 extra wildcard arm must be added to account for any future variants."
1976 } else if item.is_variant() {
1979 "Non-exhaustive enum variants could have additional fields added in future. \
1980 Therefore, non-exhaustive enum variants cannot be constructed in external \
1981 crates and cannot be matched against."
1986 "This type will require a wildcard arm in any match statements or constructors."
1990 write!(w, "</div>");
1994 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1995 pub fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1996 /// Takes a non-numeric and a numeric part from the given &str.
1997 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1998 let i = s.find(|c: char| c.is_ascii_digit());
1999 let (a, b) = s.split_at(i.unwrap_or(s.len()));
2000 let i = b.find(|c: char| !c.is_ascii_digit());
2001 let (b, c) = b.split_at(i.unwrap_or(b.len()));
2006 while !lhs.is_empty() || !rhs.is_empty() {
2007 let (la, lb) = take_parts(&mut lhs);
2008 let (ra, rb) = take_parts(&mut rhs);
2009 // First process the non-numeric part.
2011 Ordering::Equal => (),
2014 // Then process the numeric part, if both sides have one (and they fit in a u64).
2015 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2017 Ordering::Equal => (),
2021 // Then process the numeric part again, but this time as strings.
2023 Ordering::Equal => (),
2031 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
2032 document(w, cx, item, None);
2034 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2036 // the order of item types in the listing
2037 fn reorder(ty: ItemType) -> u8 {
2039 ItemType::ExternCrate => 0,
2040 ItemType::Import => 1,
2041 ItemType::Primitive => 2,
2042 ItemType::Module => 3,
2043 ItemType::Macro => 4,
2044 ItemType::Struct => 5,
2045 ItemType::Enum => 6,
2046 ItemType::Constant => 7,
2047 ItemType::Static => 8,
2048 ItemType::Trait => 9,
2049 ItemType::Function => 10,
2050 ItemType::Typedef => 12,
2051 ItemType::Union => 13,
2056 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2057 let ty1 = i1.type_();
2058 let ty2 = i2.type_();
2060 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2062 let s1 = i1.stability.as_ref().map(|s| s.level);
2063 let s2 = i2.stability.as_ref().map(|s| s.level);
2064 if let (Some(a), Some(b)) = (s1, s2) {
2065 match (a.is_stable(), b.is_stable()) {
2066 (true, true) | (false, false) => {}
2067 (false, true) => return Ordering::Less,
2068 (true, false) => return Ordering::Greater,
2071 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2072 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2073 compare_names(lhs, rhs)
2076 if cx.shared.sort_modules_alphabetically {
2077 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2079 // This call is to remove re-export duplicates in cases such as:
2084 // pub trait Double { fn foo(); }
2088 // pub use foo::bar::*;
2092 // `Double` will appear twice in the generated docs.
2094 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2095 // can be identical even if the elements are different (mostly in imports).
2096 // So in case this is an import, we keep everything by adding a "unique id"
2097 // (which is the position in the vector).
2098 indices.dedup_by_key(|i| {
2101 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2103 if items[*i].is_import() { *i } else { 0 },
2107 debug!("{:?}", indices);
2108 let mut curty = None;
2109 for &idx in &indices {
2110 let myitem = &items[idx];
2111 if myitem.is_stripped() {
2115 let myty = Some(myitem.type_());
2116 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2117 // Put `extern crate` and `use` re-exports in the same section.
2119 } else if myty != curty {
2120 if curty.is_some() {
2121 write!(w, "</table>");
2124 let (short, name) = item_ty_to_strs(&myty.unwrap());
2127 "<h2 id=\"{id}\" class=\"section-header\">\
2128 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2129 id = cx.derive_id(short.to_owned()),
2134 match myitem.inner {
2135 clean::ExternCrateItem(ref name, ref src) => {
2136 use crate::html::format::anchor;
2139 Some(ref src) => write!(
2141 "<tr><td><code>{}extern crate {} as {};",
2142 myitem.visibility.print_with_space(),
2143 anchor(myitem.def_id, src),
2148 "<tr><td><code>{}extern crate {};",
2149 myitem.visibility.print_with_space(),
2150 anchor(myitem.def_id, name)
2153 write!(w, "</code></td></tr>");
2156 clean::ImportItem(ref import) => {
2159 "<tr><td><code>{}{}</code></td></tr>",
2160 myitem.visibility.print_with_space(),
2166 if myitem.name.is_none() {
2170 let unsafety_flag = match myitem.inner {
2171 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2172 if func.header.unsafety == hir::Unsafety::Unsafe =>
2174 "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2179 let stab = myitem.stability_class();
2180 let add = if stab.is_some() { " " } else { "" };
2182 let doc_value = myitem.doc_value().unwrap_or("");
2185 "<tr class=\"{stab}{add}module-item\">\
2186 <td><a class=\"{class}\" href=\"{href}\" \
2187 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2188 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2190 name = *myitem.name.as_ref().unwrap(),
2191 stab_tags = stability_tags(myitem, item),
2192 docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2193 class = myitem.type_(),
2195 stab = stab.unwrap_or_else(String::new),
2196 unsafety_flag = unsafety_flag,
2197 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2198 title = [full_path(cx, myitem), myitem.type_().to_string()]
2200 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2201 .collect::<Vec<_>>()
2208 if curty.is_some() {
2209 write!(w, "</table>");
2213 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2215 fn stability_tags(item: &clean::Item, parent: &clean::Item) -> String {
2216 let mut tags = String::new();
2218 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2219 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2222 // The trailing space after each tag is to space it properly against the rest of the docs.
2223 if let Some(depr) = &item.deprecation {
2224 let mut message = "Deprecated";
2225 if !stability::deprecation_in_effect(depr.is_since_rustc_version, depr.since.as_deref()) {
2226 message = "Deprecation planned";
2228 tags += &tag_html("deprecated", "", message);
2231 // The "rustc_private" crates are permanently unstable so it makes no sense
2232 // to render "unstable" everywhere.
2233 if item.stability.as_ref().map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2236 tags += &tag_html("unstable", "", "Experimental");
2239 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2240 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2241 (cfg, _) => cfg.as_deref().cloned(),
2244 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2245 if let Some(ref cfg) = cfg {
2246 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2252 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2254 fn short_stability(item: &clean::Item, cx: &Context, parent: Option<&clean::Item>) -> Vec<String> {
2255 let mut stability = vec![];
2256 let error_codes = cx.shared.codes;
2258 if let Some(Deprecation { ref note, ref since, is_since_rustc_version }) = item.deprecation {
2259 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2260 // but only display the future-deprecation messages for #[rustc_deprecated].
2261 let mut message = if let Some(since) = since {
2262 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2263 format!("Deprecating in {}", Escape(&since))
2265 format!("Deprecated since {}", Escape(&since))
2268 String::from("Deprecated")
2271 if let Some(note) = note {
2272 let mut ids = cx.id_map.borrow_mut();
2273 let html = MarkdownHtml(
2278 &cx.shared.playground,
2280 message.push_str(&format!(": {}", html.into_string()));
2282 stability.push(format!(
2283 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2288 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2289 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2290 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2293 .filter(|stab| stab.feature != sym::rustc_private)
2294 .map(|stab| (stab.level, stab.feature))
2297 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2299 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2300 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2301 feature.push_str(&format!(
2302 " <a href=\"{url}{issue}\">#{issue}</a>",
2308 message.push_str(&format!(" ({})", feature));
2310 if let Some(unstable_reason) = reason {
2311 let mut ids = cx.id_map.borrow_mut();
2313 "<details><summary>{}</summary>{}</details>",
2316 &unstable_reason.as_str(),
2320 &cx.shared.playground,
2326 stability.push(format!("<div class=\"stab unstable\">{}</div>", message));
2329 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2330 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2331 (cfg, _) => cfg.as_deref().cloned(),
2335 "Portability {:?} - {:?} = {:?}",
2337 parent.and_then(|p| p.attrs.cfg.as_ref()),
2340 if let Some(cfg) = cfg {
2341 stability.push(format!("<div class=\"stab portability\">{}</div>", cfg.render_long_html()));
2347 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2348 write!(w, "<pre class=\"rust const\">");
2349 render_attributes(w, it, false);
2353 "{vis}const {name}: {typ}",
2354 vis = it.visibility.print_with_space(),
2355 name = it.name.as_ref().unwrap(),
2356 typ = c.type_.print(),
2359 if c.value.is_some() || c.is_literal {
2360 write!(w, " = {expr};", expr = Escape(&c.expr));
2365 if let Some(value) = &c.value {
2367 let value_lowercase = value.to_lowercase();
2368 let expr_lowercase = c.expr.to_lowercase();
2370 if value_lowercase != expr_lowercase
2371 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2373 write!(w, " // {value}", value = Escape(value));
2378 write!(w, "</pre>");
2379 document(w, cx, it, None)
2382 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2383 write!(w, "<pre class=\"rust static\">");
2384 render_attributes(w, it, false);
2387 "{vis}static {mutability} {name}: {typ}</pre>",
2388 vis = it.visibility.print_with_space(),
2389 mutability = s.mutability.print_with_space(),
2390 name = it.name.as_ref().unwrap(),
2391 typ = s.type_.print()
2393 document(w, cx, it, None)
2396 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2397 let header_len = format!(
2398 "{}{}{}{}{:#}fn {}{:#}",
2399 it.visibility.print_with_space(),
2400 f.header.constness.print_with_space(),
2401 f.header.asyncness.print_with_space(),
2402 f.header.unsafety.print_with_space(),
2403 print_abi_with_space(f.header.abi),
2404 it.name.as_ref().unwrap(),
2408 write!(w, "<pre class=\"rust fn\">");
2409 render_attributes(w, it, false);
2412 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2413 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2414 vis = it.visibility.print_with_space(),
2415 constness = f.header.constness.print_with_space(),
2416 asyncness = f.header.asyncness.print_with_space(),
2417 unsafety = f.header.unsafety.print_with_space(),
2418 abi = print_abi_with_space(f.header.abi),
2419 name = it.name.as_ref().unwrap(),
2420 generics = f.generics.print(),
2421 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2422 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2424 spotlight = spotlight_decl(&f.decl),
2426 document(w, cx, it, None)
2429 fn render_implementor(
2433 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2437 // If there's already another implementor that has the same abbridged name, use the
2438 // full path, for example in `std::iter::ExactSizeIterator`
2439 let use_absolute = match implementor.inner_impl().for_ {
2440 clean::ResolvedPath { ref path, is_generic: false, .. }
2441 | clean::BorrowedRef {
2442 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2444 } => implementor_dups[path.last_name()].1,
2452 AssocItemLink::Anchor(None),
2454 implementor.impl_item.stable_since().as_deref(),
2468 containing_item: &clean::Item,
2471 let mut impls = traits
2474 let did = i.trait_did().unwrap();
2475 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2476 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2481 Some(containing_item),
2484 containing_item.stable_since().as_deref(),
2494 .collect::<Vec<_>>();
2496 w.write_str(&impls.join(""));
2499 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2500 let mut bounds = String::new();
2501 if !t_bounds.is_empty() {
2503 bounds.push_str(": ");
2505 for (i, p) in t_bounds.iter().enumerate() {
2507 bounds.push_str(" + ");
2509 bounds.push_str(&p.print().to_string());
2515 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2516 let lhs = format!("{}", lhs.inner_impl().print());
2517 let rhs = format!("{}", rhs.inner_impl().print());
2519 // lhs and rhs are formatted as HTML, which may be unnecessary
2520 compare_names(&lhs, &rhs)
2523 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2524 let bounds = bounds(&t.bounds, false);
2525 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2526 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2527 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2528 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2530 // Output the trait definition
2531 wrap_into_docblock(w, |w| {
2532 write!(w, "<pre class=\"rust trait\">");
2533 render_attributes(w, it, true);
2536 "{}{}{}trait {}{}{}",
2537 it.visibility.print_with_space(),
2538 t.unsafety.print_with_space(),
2539 if t.is_auto { "auto " } else { "" },
2540 it.name.as_ref().unwrap(),
2545 if !t.generics.where_predicates.is_empty() {
2546 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2551 if t.items.is_empty() {
2554 // FIXME: we should be using a derived_id for the Anchors here
2557 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2560 if !types.is_empty() && !consts.is_empty() {
2564 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2567 if !consts.is_empty() && !required.is_empty() {
2570 for (pos, m) in required.iter().enumerate() {
2571 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2574 if pos < required.len() - 1 {
2575 write!(w, "<div class=\"item-spacer\"></div>");
2578 if !required.is_empty() && !provided.is_empty() {
2581 for (pos, m) in provided.iter().enumerate() {
2582 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2584 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2585 write!(w, ",\n {{ ... }}\n");
2588 write!(w, " {{ ... }}\n");
2591 if pos < provided.len() - 1 {
2592 write!(w, "<div class=\"item-spacer\"></div>");
2600 // Trait documentation
2601 document(w, cx, it, None);
2603 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2606 "<h2 id=\"{0}\" class=\"small-section-header\">\
2607 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2609 id, title, extra_content
2613 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2614 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2617 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item) {
2618 let name = m.name.as_ref().unwrap();
2619 info!("Documenting {} on {}", name, t.name.as_deref().unwrap_or_default());
2620 let item_type = m.type_();
2621 let id = cx.derive_id(format!("{}.{}", item_type, name));
2622 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2623 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2624 write!(w, "</code>");
2625 render_stability_since(w, m, t);
2627 document(w, cx, m, Some(t));
2630 if !types.is_empty() {
2631 write_small_section_header(
2635 "<div class=\"methods\">",
2638 trait_item(w, cx, *t, it);
2640 write_loading_content(w, "</div>");
2643 if !consts.is_empty() {
2644 write_small_section_header(
2647 "Associated Constants",
2648 "<div class=\"methods\">",
2651 trait_item(w, cx, *t, it);
2653 write_loading_content(w, "</div>");
2656 // Output the documentation for each function individually
2657 if !required.is_empty() {
2658 write_small_section_header(
2662 "<div class=\"methods\">",
2664 for m in &required {
2665 trait_item(w, cx, *m, it);
2667 write_loading_content(w, "</div>");
2669 if !provided.is_empty() {
2670 write_small_section_header(
2674 "<div class=\"methods\">",
2676 for m in &provided {
2677 trait_item(w, cx, *m, it);
2679 write_loading_content(w, "</div>");
2682 // If there are methods directly on this trait object, render them here.
2683 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2685 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2686 // The DefId is for the first Type found with that name. The bool is
2687 // if any Types with the same name but different DefId have been found.
2688 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2689 for implementor in implementors {
2690 match implementor.inner_impl().for_ {
2691 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2692 | clean::BorrowedRef {
2693 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2696 let &mut (prev_did, ref mut has_duplicates) =
2697 implementor_dups.entry(path.last_name()).or_insert((did, false));
2698 if prev_did != did {
2699 *has_duplicates = true;
2706 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2707 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2710 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2711 local.iter().partition(|i| i.inner_impl().synthetic);
2713 synthetic.sort_by(compare_impl);
2714 concrete.sort_by(compare_impl);
2716 if !foreign.is_empty() {
2717 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2719 for implementor in foreign {
2720 let assoc_link = AssocItemLink::GotoSource(
2721 implementor.impl_item.def_id,
2722 &implementor.inner_impl().provided_trait_methods,
2731 implementor.impl_item.stable_since().as_deref(),
2740 write_loading_content(w, "");
2743 write_small_section_header(
2747 "<div class=\"item-list\" id=\"implementors-list\">",
2749 for implementor in concrete {
2750 render_implementor(cx, implementor, w, &implementor_dups, &[], cache);
2752 write_loading_content(w, "</div>");
2755 write_small_section_header(
2757 "synthetic-implementors",
2758 "Auto implementors",
2759 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2761 for implementor in synthetic {
2767 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2771 write_loading_content(w, "</div>");
2774 // even without any implementations to write in, we still want the heading and list, so the
2775 // implementors javascript file pulled in below has somewhere to write the impls into
2776 write_small_section_header(
2780 "<div class=\"item-list\" id=\"implementors-list\">",
2782 write_loading_content(w, "</div>");
2785 write_small_section_header(
2787 "synthetic-implementors",
2788 "Auto implementors",
2789 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2791 write_loading_content(w, "</div>");
2797 "<script type=\"text/javascript\" \
2798 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2800 root_path = vec![".."; cx.current.len()].join("/"),
2801 path = if it.def_id.is_local() {
2802 cx.current.join("/")
2804 let (ref path, _) = cache.external_paths[&it.def_id];
2805 path[..path.len() - 1].join("/")
2808 name = *it.name.as_ref().unwrap()
2812 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2813 use crate::formats::item_type::ItemType::*;
2815 let name = it.name.as_ref().unwrap();
2816 let ty = match it.type_() {
2817 Typedef | AssocType => AssocType,
2821 let anchor = format!("#{}.{}", ty, name);
2823 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2824 AssocItemLink::Anchor(None) => anchor,
2825 AssocItemLink::GotoSource(did, _) => {
2826 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2835 _default: Option<&String>,
2836 link: AssocItemLink<'_>,
2841 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2843 it.visibility.print_with_space(),
2844 naive_assoc_href(it, link),
2845 it.name.as_ref().unwrap(),
2853 bounds: &[clean::GenericBound],
2854 default: Option<&clean::Type>,
2855 link: AssocItemLink<'_>,
2860 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2862 naive_assoc_href(it, link),
2863 it.name.as_ref().unwrap()
2865 if !bounds.is_empty() {
2866 write!(w, ": {}", print_generic_bounds(bounds))
2868 if let Some(default) = default {
2869 write!(w, " = {}", default.print())
2873 fn render_stability_since_raw(w: &mut Buffer, ver: Option<&str>, containing_ver: Option<&str>) {
2874 if let Some(v) = ver {
2875 if containing_ver != ver && !v.is_empty() {
2876 write!(w, "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>", v)
2881 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2882 render_stability_since_raw(
2884 item.stable_since().as_deref(),
2885 containing_item.stable_since().as_deref(),
2889 fn render_assoc_item(
2892 link: AssocItemLink<'_>,
2898 header: hir::FnHeader,
2899 g: &clean::Generics,
2901 link: AssocItemLink<'_>,
2904 let name = meth.name.as_ref().unwrap();
2905 let anchor = format!("#{}.{}", meth.type_(), name);
2906 let href = match link {
2907 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2908 AssocItemLink::Anchor(None) => anchor,
2909 AssocItemLink::GotoSource(did, provided_methods) => {
2910 // We're creating a link from an impl-item to the corresponding
2911 // trait-item and need to map the anchored type accordingly.
2912 let ty = if provided_methods.contains(name) {
2918 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2921 let mut header_len = format!(
2922 "{}{}{}{}{}{:#}fn {}{:#}",
2923 meth.visibility.print_with_space(),
2924 header.constness.print_with_space(),
2925 header.asyncness.print_with_space(),
2926 header.unsafety.print_with_space(),
2927 print_default_space(meth.is_default()),
2928 print_abi_with_space(header.abi),
2933 let (indent, end_newline) = if parent == ItemType::Trait {
2939 render_attributes(w, meth, false);
2942 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
2943 {generics}{decl}{spotlight}{where_clause}",
2944 if parent == ItemType::Trait { " " } else { "" },
2945 meth.visibility.print_with_space(),
2946 header.constness.print_with_space(),
2947 header.asyncness.print_with_space(),
2948 header.unsafety.print_with_space(),
2949 print_default_space(meth.is_default()),
2950 print_abi_with_space(header.abi),
2953 generics = g.print(),
2954 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
2955 spotlight = spotlight_decl(&d),
2956 where_clause = WhereClause { gens: g, indent, end_newline }
2960 clean::StrippedItem(..) => {}
2961 clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2962 clean::MethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2963 clean::AssocConstItem(ref ty, ref default) => assoc_const(
2969 if parent == ItemType::Trait { " " } else { "" },
2971 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
2977 if parent == ItemType::Trait { " " } else { "" },
2979 _ => panic!("render_assoc_item called on non-associated-item"),
2983 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
2984 wrap_into_docblock(w, |w| {
2985 write!(w, "<pre class=\"rust struct\">");
2986 render_attributes(w, it, true);
2987 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
2991 document(w, cx, it, None);
2995 .filter_map(|f| match f.inner {
2996 clean::StructFieldItem(ref ty) => Some((f, ty)),
3000 if let doctree::Plain = s.struct_type {
3001 if fields.peek().is_some() {
3004 "<h2 id=\"fields\" class=\"fields small-section-header\">
3005 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3006 document_non_exhaustive_header(it)
3008 document_non_exhaustive(w, it);
3009 for (field, ty) in fields {
3010 let id = cx.derive_id(format!(
3012 ItemType::StructField,
3013 field.name.as_ref().unwrap()
3017 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3018 <a href=\"#{id}\" class=\"anchor field\"></a>\
3019 <code>{name}: {ty}</code>\
3021 item_type = ItemType::StructField,
3023 name = field.name.as_ref().unwrap(),
3026 document(w, cx, field, Some(it));
3030 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3033 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
3034 wrap_into_docblock(w, |w| {
3035 write!(w, "<pre class=\"rust union\">");
3036 render_attributes(w, it, true);
3037 render_union(w, it, Some(&s.generics), &s.fields, "", true);
3041 document(w, cx, it, None);
3045 .filter_map(|f| match f.inner {
3046 clean::StructFieldItem(ref ty) => Some((f, ty)),
3050 if fields.peek().is_some() {
3053 "<h2 id=\"fields\" class=\"fields small-section-header\">
3054 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3056 for (field, ty) in fields {
3057 let name = field.name.as_ref().expect("union field name");
3058 let id = format!("{}.{}", ItemType::StructField, name);
3061 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3062 <a href=\"#{id}\" class=\"anchor field\"></a>\
3063 <code>{name}: {ty}</code>\
3067 shortty = ItemType::StructField,
3070 if let Some(stability_class) = field.stability_class() {
3071 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3073 document(w, cx, field, Some(it));
3076 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3079 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
3080 wrap_into_docblock(w, |w| {
3081 write!(w, "<pre class=\"rust enum\">");
3082 render_attributes(w, it, true);
3086 it.visibility.print_with_space(),
3087 it.name.as_ref().unwrap(),
3089 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
3091 if e.variants.is_empty() && !e.variants_stripped {
3095 for v in &e.variants {
3097 let name = v.name.as_ref().unwrap();
3099 clean::VariantItem(ref var) => match var.kind {
3100 clean::VariantKind::CLike => write!(w, "{}", name),
3101 clean::VariantKind::Tuple(ref tys) => {
3102 write!(w, "{}(", name);
3103 for (i, ty) in tys.iter().enumerate() {
3105 write!(w, ", ")
3107 write!(w, "{}", ty.print());
3111 clean::VariantKind::Struct(ref s) => {
3112 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
3115 _ => unreachable!(),
3120 if e.variants_stripped {
3121 write!(w, " // some variants omitted\n");
3128 document(w, cx, it, None);
3129 if !e.variants.is_empty() {
3132 "<h2 id=\"variants\" class=\"variants small-section-header\">
3133 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3134 document_non_exhaustive_header(it)
3136 document_non_exhaustive(w, it);
3137 for variant in &e.variants {
3139 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3142 "<div id=\"{id}\" class=\"variant small-section-header\">\
3143 <a href=\"#{id}\" class=\"anchor field\"></a>\
3146 name = variant.name.as_ref().unwrap()
3148 if let clean::VariantItem(ref var) = variant.inner {
3149 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3151 for (i, ty) in tys.iter().enumerate() {
3153 write!(w, ", ");
3155 write!(w, "{}", ty.print());
3160 write!(w, "</code></div>");
3161 document(w, cx, variant, Some(it));
3162 document_non_exhaustive(w, variant);
3164 use crate::clean::{Variant, VariantKind};
3165 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.inner
3167 let variant_id = cx.derive_id(format!(
3170 variant.name.as_ref().unwrap()
3172 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3175 "<h3>Fields of <b>{name}</b></h3><div>",
3176 name = variant.name.as_ref().unwrap()
3178 for field in &s.fields {
3179 use crate::clean::StructFieldItem;
3180 if let StructFieldItem(ref ty) = field.inner {
3181 let id = cx.derive_id(format!(
3182 "variant.{}.field.{}",
3183 variant.name.as_ref().unwrap(),
3184 field.name.as_ref().unwrap()
3188 "<span id=\"{id}\" class=\"variant small-section-header\">\
3189 <a href=\"#{id}\" class=\"anchor field\"></a>\
3190 <code>{f}: {t}</code>\
3193 f = field.name.as_ref().unwrap(),
3196 document(w, cx, field, Some(variant));
3199 write!(w, "</div></div>");
3201 render_stability_since(w, variant, it);
3204 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3207 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3214 sym::non_exhaustive,
3217 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3218 // left padding. For example:
3220 // #[foo] <----- "top" attribute
3222 // #[bar] <---- not "top" attribute
3225 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3230 .filter_map(|attr| {
3231 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3232 Some(pprust::attribute_to_string(&attr))
3239 if !attrs.is_empty() {
3242 "<span class=\"docblock attributes{}\">{}</span>",
3243 if top { " top-attr" } else { "" },
3252 g: Option<&clean::Generics>,
3253 ty: doctree::StructType,
3254 fields: &[clean::Item],
3261 it.visibility.print_with_space(),
3262 if structhead { "struct " } else { "" },
3263 it.name.as_ref().unwrap()
3265 if let Some(g) = g {
3266 write!(w, "{}", g.print())
3270 if let Some(g) = g {
3271 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3273 let mut has_visible_fields = false;
3275 for field in fields {
3276 if let clean::StructFieldItem(ref ty) = field.inner {
3281 field.visibility.print_with_space(),
3282 field.name.as_ref().unwrap(),
3285 has_visible_fields = true;
3289 if has_visible_fields {
3290 if it.has_stripped_fields().unwrap() {
3291 write!(w, "\n{} // some fields omitted", tab);
3293 write!(w, "\n{}", tab);
3294 } else if it.has_stripped_fields().unwrap() {
3295 // If there are no visible fields we can just display
3296 // `{ /* fields omitted */ }` to save space.
3297 write!(w, " /* fields omitted */ ");
3303 for (i, field) in fields.iter().enumerate() {
3308 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3309 clean::StructFieldItem(ref ty) => {
3310 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3312 _ => unreachable!(),
3316 if let Some(g) = g {
3317 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3322 // Needed for PhantomData.
3323 if let Some(g) = g {
3324 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3334 g: Option<&clean::Generics>,
3335 fields: &[clean::Item],
3342 it.visibility.print_with_space(),
3343 if structhead { "union " } else { "" },
3344 it.name.as_ref().unwrap()
3346 if let Some(g) = g {
3347 write!(w, "{}", g.print());
3348 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3351 write!(w, " {{\n{}", tab);
3352 for field in fields {
3353 if let clean::StructFieldItem(ref ty) = field.inner {
3357 field.visibility.print_with_space(),
3358 field.name.as_ref().unwrap(),
3365 if it.has_stripped_fields().unwrap() {
3366 write!(w, " // some fields omitted\n{}", tab);
3371 #[derive(Copy, Clone)]
3372 enum AssocItemLink<'a> {
3373 Anchor(Option<&'a str>),
3374 GotoSource(DefId, &'a FxHashSet<String>),
3377 impl<'a> AssocItemLink<'a> {
3378 fn anchor(&self, id: &'a String) -> Self {
3380 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3381 ref other => *other,
3386 fn render_assoc_items(
3389 containing_item: &clean::Item,
3391 what: AssocItemRender<'_>,
3395 "Documenting associated items of {}",
3396 containing_item.name.as_deref().unwrap_or_default()
3398 let v = match cache.impls.get(&it) {
3402 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3403 if !non_trait.is_empty() {
3404 let render_mode = match what {
3405 AssocItemRender::All => {
3408 "<h2 id=\"implementations\" class=\"small-section-header\">\
3409 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3414 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3417 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
3418 Methods from {}<Target = {}>\
3419 <a href=\"#deref-methods\" class=\"anchor\"></a>\
3424 RenderMode::ForDeref { mut_: deref_mut_ }
3427 for i in &non_trait {
3432 Some(containing_item),
3433 AssocItemLink::Anchor(None),
3435 containing_item.stable_since().as_deref(),
3445 if let AssocItemRender::DerefFor { .. } = what {
3448 if !traits.is_empty() {
3450 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3451 if let Some(impl_) = deref_impl {
3453 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3454 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3457 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3458 traits.iter().partition(|t| t.inner_impl().synthetic);
3459 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3460 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3462 let mut impls = Buffer::empty_from(&w);
3463 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3464 let impls = impls.into_inner();
3465 if !impls.is_empty() {
3468 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3469 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3471 <div id=\"trait-implementations-list\">{}</div>",
3476 if !synthetic.is_empty() {
3479 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3480 Auto Trait Implementations\
3481 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3483 <div id=\"synthetic-implementations-list\">"
3485 render_impls(cx, w, &synthetic, containing_item, cache);
3486 write!(w, "</div>");
3489 if !blanket_impl.is_empty() {
3492 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3493 Blanket Implementations\
3494 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3496 <div id=\"blanket-implementations-list\">"
3498 render_impls(cx, w, &blanket_impl, containing_item, cache);
3499 write!(w, "</div>");
3504 fn render_deref_methods(
3508 container_item: &clean::Item,
3512 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3513 let (target, real_target) = impl_
3517 .find_map(|item| match item.inner {
3518 clean::TypedefItem(ref t, true) => Some(match *t {
3519 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3520 _ => (&t.type_, &t.type_),
3524 .expect("Expected associated type binding");
3526 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3527 if let Some(did) = target.def_id() {
3528 render_assoc_items(w, cx, container_item, did, what, cache);
3530 if let Some(prim) = target.primitive_type() {
3531 if let Some(&did) = cache.primitive_locations.get(&prim) {
3532 render_assoc_items(w, cx, container_item, did, what, cache);
3538 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3539 let self_type_opt = match item.inner {
3540 clean::MethodItem(ref method) => method.decl.self_type(),
3541 clean::TyMethodItem(ref method) => method.decl.self_type(),
3545 if let Some(self_ty) = self_type_opt {
3546 let (by_mut_ref, by_box, by_value) = match self_ty {
3547 SelfTy::SelfBorrowed(_, mutability)
3548 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3549 (mutability == Mutability::Mut, false, false)
3551 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3552 (false, Some(did) == cache().owned_box_did, false)
3554 SelfTy::SelfValue => (false, false, true),
3555 _ => (false, false, false),
3558 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3564 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3565 let mut out = Buffer::html();
3566 let mut trait_ = String::new();
3568 if let Some(did) = decl.output.def_id() {
3570 if let Some(impls) = c.impls.get(&did) {
3572 let impl_ = i.inner_impl();
3573 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3575 out.push_str(&format!(
3576 "<h3 class=\"notable\">Notable traits for {}</h3>\
3577 <code class=\"content\">",
3580 trait_.push_str(&impl_.for_.print().to_string());
3583 //use the "where" class here to make it small
3584 out.push_str(&format!(
3585 "<span class=\"where fmt-newline\">{}</span>",
3588 let t_did = impl_.trait_.def_id().unwrap();
3589 for it in &impl_.items {
3590 if let clean::TypedefItem(ref tydef, _) = it.inner {
3591 out.push_str("<span class=\"where fmt-newline\"> ");
3597 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3600 out.push_str(";</span>");
3608 if !out.is_empty() {
3611 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3612 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3614 out.push_str("</code></span></div></span></span>");
3624 parent: Option<&clean::Item>,
3625 link: AssocItemLink<'_>,
3626 render_mode: RenderMode,
3627 outer_version: Option<&str>,
3628 show_def_docs: bool,
3629 use_absolute: Option<bool>,
3630 is_on_foreign_type: bool,
3631 show_default_items: bool,
3632 // This argument is used to reference same type with different paths to avoid duplication
3633 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3637 if render_mode == RenderMode::Normal {
3638 let id = cx.derive_id(match i.inner_impl().trait_ {
3640 if is_on_foreign_type {
3641 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3643 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3646 None => "impl".to_string(),
3648 let aliases = if aliases.is_empty() {
3651 format!(" aliases=\"{}\"", aliases.join(","))
3653 if let Some(use_absolute) = use_absolute {
3654 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3655 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3657 for it in &i.inner_impl().items {
3658 if let clean::TypedefItem(ref tydef, _) = it.inner {
3659 write!(w, "<span class=\"where fmt-newline\"> ");
3660 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3661 write!(w, ";</span>");
3665 write!(w, "</code>");
3669 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3672 i.inner_impl().print()
3675 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3676 let since = i.impl_item.stability.as_ref().and_then(|s| match s.level {
3677 StabilityLevel::Stable { since } => Some(since.as_str()),
3678 StabilityLevel::Unstable { .. } => None,
3680 render_stability_since_raw(w, since.as_deref(), outer_version);
3681 if let Some(l) = cx.src_href(&i.impl_item, cache) {
3684 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
3685 l, "goto source code"
3689 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3690 let mut ids = cx.id_map.borrow_mut();
3693 "<div class=\"docblock\">{}</div>",
3696 &i.impl_item.links(),
3700 &cx.shared.playground
3711 parent: Option<&clean::Item>,
3712 link: AssocItemLink<'_>,
3713 render_mode: RenderMode,
3714 is_default_item: bool,
3715 outer_version: Option<&str>,
3716 trait_: Option<&clean::Trait>,
3717 show_def_docs: bool,
3720 let item_type = item.type_();
3721 let name = item.name.as_ref().unwrap();
3723 let render_method_item = match render_mode {
3724 RenderMode::Normal => true,
3725 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3728 let (is_hidden, extra_class) =
3729 if (trait_.is_none() || item.doc_value().is_some() || item.inner.is_type_alias())
3737 clean::MethodItem(clean::Method { .. })
3738 | clean::TyMethodItem(clean::TyMethod { .. }) => {
3739 // Only render when the method is not static or we allow static methods
3740 if render_method_item {
3741 let id = cx.derive_id(format!("{}.{}", item_type, name));
3742 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3743 write!(w, "<code>");
3744 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3745 write!(w, "</code>");
3746 render_stability_since_raw(w, item.stable_since().as_deref(), outer_version);
3747 if let Some(l) = cx.src_href(item, cache) {
3750 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
3751 l, "goto source code"
3757 clean::TypedefItem(ref tydef, _) => {
3758 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3759 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3760 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3761 write!(w, "</code></h4>");
3763 clean::AssocConstItem(ref ty, ref default) => {
3764 let id = cx.derive_id(format!("{}.{}", item_type, name));
3765 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3766 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3767 write!(w, "</code>");
3768 render_stability_since_raw(w, item.stable_since().as_deref(), outer_version);
3769 if let Some(l) = cx.src_href(item, cache) {
3772 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
3773 l, "goto source code"
3778 clean::AssocTypeItem(ref bounds, ref default) => {
3779 let id = cx.derive_id(format!("{}.{}", item_type, name));
3780 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3781 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3782 write!(w, "</code></h4>");
3784 clean::StrippedItem(..) => return,
3785 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3788 if render_method_item {
3789 if !is_default_item {
3790 if let Some(t) = trait_ {
3791 // The trait item may have been stripped so we might not
3792 // find any documentation or stability for it.
3793 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3794 // We need the stability of the item from the trait
3795 // because impls can't have a stability.
3796 document_stability(w, cx, it, is_hidden, parent);
3797 if item.doc_value().is_some() {
3798 document_full(w, item, cx, "", is_hidden);
3799 } else if show_def_docs {
3800 // In case the item isn't documented,
3801 // provide short documentation from the trait.
3802 document_short(w, it, link, "", is_hidden);
3806 document_stability(w, cx, item, is_hidden, parent);
3808 document_full(w, item, cx, "", is_hidden);
3812 document_stability(w, cx, item, is_hidden, parent);
3814 document_short(w, item, link, "", is_hidden);
3820 let traits = &cache.traits;
3821 let trait_ = i.trait_did().map(|did| &traits[&did]);
3823 write!(w, "<div class=\"impl-items\">");
3824 for trait_item in &i.inner_impl().items {
3840 fn render_default_items(
3845 parent: Option<&clean::Item>,
3846 render_mode: RenderMode,
3847 outer_version: Option<&str>,
3848 show_def_docs: bool,
3851 for trait_item in &t.items {
3852 let n = trait_item.name.clone();
3853 if i.items.iter().any(|m| m.name == n) {
3856 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3857 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3875 // If we've implemented a trait, then also emit documentation for all
3876 // default items which weren't overridden in the implementation block.
3877 // We don't emit documentation for default items if they appear in the
3878 // Implementations on Foreign Types or Implementors sections.
3879 if show_default_items {
3880 if let Some(t) = trait_ {
3881 render_default_items(
3894 write!(w, "</div>");
3901 t: &clean::OpaqueTy,
3904 write!(w, "<pre class=\"rust opaque\">");
3905 render_attributes(w, it, false);
3908 "type {}{}{where_clause} = impl {bounds};</pre>",
3909 it.name.as_ref().unwrap(),
3911 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3912 bounds = bounds(&t.bounds, false)
3915 document(w, cx, it, None);
3917 // Render any items associated directly to this alias, as otherwise they
3918 // won't be visible anywhere in the docs. It would be nice to also show
3919 // associated items from the aliased type (see discussion in #32077), but
3920 // we need #14072 to make sense of the generics.
3921 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3924 fn item_trait_alias(
3928 t: &clean::TraitAlias,
3931 write!(w, "<pre class=\"rust trait-alias\">");
3932 render_attributes(w, it, false);
3935 "trait {}{}{} = {};</pre>",
3936 it.name.as_ref().unwrap(),
3938 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3939 bounds(&t.bounds, true)
3942 document(w, cx, it, None);
3944 // Render any items associated directly to this alias, as otherwise they
3945 // won't be visible anywhere in the docs. It would be nice to also show
3946 // associated items from the aliased type (see discussion in #32077), but
3947 // we need #14072 to make sense of the generics.
3948 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3951 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
3952 write!(w, "<pre class=\"rust typedef\">");
3953 render_attributes(w, it, false);
3956 "type {}{}{where_clause} = {type_};</pre>",
3957 it.name.as_ref().unwrap(),
3959 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3960 type_ = t.type_.print()
3963 document(w, cx, it, None);
3965 // Render any items associated directly to this alias, as otherwise they
3966 // won't be visible anywhere in the docs. It would be nice to also show
3967 // associated items from the aliased type (see discussion in #32077), but
3968 // we need #14072 to make sense of the generics.
3969 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3972 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
3973 writeln!(w, "<pre class=\"rust foreigntype\">extern {{");
3974 render_attributes(w, it, false);
3977 " {}type {};\n}}</pre>",
3978 it.visibility.print_with_space(),
3979 it.name.as_ref().unwrap(),
3982 document(w, cx, it, None);
3984 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3987 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
3988 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
3992 || it.is_primitive()
4000 "<p class=\"location\">{}{}</p>",
4002 clean::StructItem(..) => "Struct ",
4003 clean::TraitItem(..) => "Trait ",
4004 clean::PrimitiveItem(..) => "Primitive Type ",
4005 clean::UnionItem(..) => "Union ",
4006 clean::EnumItem(..) => "Enum ",
4007 clean::TypedefItem(..) => "Type Definition ",
4008 clean::ForeignTypeItem => "Foreign Type ",
4009 clean::ModuleItem(..) =>
4017 it.name.as_ref().unwrap()
4022 if let Some(ref version) = cache.crate_version {
4025 "<div class=\"block version\">\
4033 write!(buffer, "<div class=\"sidebar-elems\">");
4037 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4038 it.name.as_ref().expect("crates always have a name")
4042 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
4043 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
4044 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
4045 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
4046 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
4047 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
4048 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4049 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
4053 // The sidebar is designed to display sibling functions, modules and
4054 // other miscellaneous information. since there are lots of sibling
4055 // items (and that causes quadratic growth in large modules),
4056 // we refactor common parts into a shared JavaScript file per module.
4057 // still, we don't move everything into JS because we want to preserve
4058 // as much HTML as possible in order to allow non-JS-enabled browsers
4059 // to navigate the documentation (though slightly inefficiently).
4061 write!(buffer, "<p class=\"location\">");
4062 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4064 write!(buffer, "::<wbr>");
4068 "<a href=\"{}index.html\">{}</a>",
4069 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4073 write!(buffer, "</p>");
4075 // Sidebar refers to the enclosing module, not this module.
4076 let relpath = if it.is_mod() { "../" } else { "" };
4079 "<script>window.sidebarCurrent = {{\
4082 relpath: \"{path}\"\
4084 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4089 // There is no sidebar-items.js beyond the crate root path
4090 // FIXME maybe dynamic crate loading can be merged here
4092 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4094 // Closes sidebar-elems div.
4095 write!(buffer, "</div>");
4098 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4099 if used_links.insert(url.clone()) {
4103 while !used_links.insert(format!("{}-{}", url, add)) {
4106 format!("{}-{}", url, add)
4112 used_links: &mut FxHashSet<String>,
4117 .filter_map(|item| match item.name {
4118 Some(ref name) if !name.is_empty() && item.is_method() => {
4119 if !for_deref || should_render_item(item, deref_mut) {
4121 "<a href=\"#{}\">{}</a>",
4122 get_next_url(used_links, format!("method.{}", name)),
4131 .collect::<Vec<_>>()
4134 // The point is to url encode any potential character from a type with genericity.
4135 fn small_url_encode(s: &str) -> String {
4136 s.replace("<", "%3C")
4137 .replace(">", "%3E")
4138 .replace(" ", "%20")
4139 .replace("?", "%3F")
4140 .replace("'", "%27")
4141 .replace("&", "%26")
4142 .replace(",", "%2C")
4143 .replace(":", "%3A")
4144 .replace(";", "%3B")
4145 .replace("[", "%5B")
4146 .replace("]", "%5D")
4147 .replace("\"", "%22")
4150 fn sidebar_assoc_items(it: &clean::Item) -> String {
4151 let mut out = String::new();
4153 if let Some(v) = c.impls.get(&it.def_id) {
4154 let mut used_links = FxHashSet::default();
4157 let used_links_bor = &mut used_links;
4160 .filter(|i| i.inner_impl().trait_.is_none())
4161 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4162 .collect::<Vec<_>>();
4163 if !ret.is_empty() {
4164 // We want links' order to be reproducible so we don't use unstable sort.
4166 out.push_str(&format!(
4167 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4168 <div class=\"sidebar-links\">{}</div>",
4174 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4175 if let Some(impl_) = v
4177 .filter(|i| i.inner_impl().trait_.is_some())
4178 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4180 if let Some((target, real_target)) =
4181 impl_.inner_impl().items.iter().find_map(|item| match item.inner {
4182 clean::TypedefItem(ref t, true) => Some(match *t {
4183 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4184 _ => (&t.type_, &t.type_),
4191 .filter(|i| i.inner_impl().trait_.is_some())
4192 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4193 let inner_impl = target
4197 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4198 .and_then(|did| c.impls.get(&did));
4199 if let Some(impls) = inner_impl {
4200 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4201 out.push_str(&format!(
4202 "Methods from {}<Target={}>",
4205 impl_.inner_impl().trait_.as_ref().unwrap().print()
4207 Escape(&format!("{:#}", real_target.print()))
4209 out.push_str("</a>");
4212 .filter(|i| i.inner_impl().trait_.is_none())
4214 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4216 .collect::<Vec<_>>();
4217 // We want links' order to be reproducible so we don't use unstable sort.
4219 if !ret.is_empty() {
4220 out.push_str(&format!(
4221 "<div class=\"sidebar-links\">{}</div>",
4228 let format_impls = |impls: Vec<&Impl>| {
4229 let mut links = FxHashSet::default();
4234 let is_negative_impl = is_negative_impl(i.inner_impl());
4235 if let Some(ref i) = i.inner_impl().trait_ {
4236 let i_display = format!("{:#}", i.print());
4237 let out = Escape(&i_display);
4238 let encoded = small_url_encode(&format!("{:#}", i.print()));
4239 let generated = format!(
4240 "<a href=\"#impl-{}\">{}{}</a>",
4242 if is_negative_impl { "!" } else { "" },
4245 if links.insert(generated.clone()) { Some(generated) } else { None }
4250 .collect::<Vec<String>>();
4255 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4256 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4257 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4259 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4261 let concrete_format = format_impls(concrete);
4262 let synthetic_format = format_impls(synthetic);
4263 let blanket_format = format_impls(blanket_impl);
4265 if !concrete_format.is_empty() {
4267 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4268 Trait Implementations</a>",
4270 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4273 if !synthetic_format.is_empty() {
4275 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4276 Auto Trait Implementations</a>",
4278 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4281 if !blanket_format.is_empty() {
4283 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4284 Blanket Implementations</a>",
4286 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4294 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4295 let mut sidebar = String::new();
4296 let fields = get_struct_fields_name(&s.fields);
4298 if !fields.is_empty() {
4299 if let doctree::Plain = s.struct_type {
4300 sidebar.push_str(&format!(
4301 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4302 <div class=\"sidebar-links\">{}</div>",
4308 sidebar.push_str(&sidebar_assoc_items(it));
4310 if !sidebar.is_empty() {
4311 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4315 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4316 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4319 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4321 clean::ItemEnum::ImplItem(ref i) => {
4322 if let Some(ref trait_) = i.trait_ {
4324 format!("{:#}", i.for_.print()),
4325 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4335 fn is_negative_impl(i: &clean::Impl) -> bool {
4336 i.polarity == Some(clean::ImplPolarity::Negative)
4339 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4340 let mut sidebar = String::new();
4345 .filter_map(|m| match m.name {
4346 Some(ref name) if m.is_associated_type() => {
4347 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4351 .collect::<Vec<_>>();
4355 .filter_map(|m| match m.name {
4356 Some(ref name) if m.is_associated_const() => {
4357 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4361 .collect::<Vec<_>>();
4362 let mut required = t
4365 .filter_map(|m| match m.name {
4366 Some(ref name) if m.is_ty_method() => {
4367 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4371 .collect::<Vec<String>>();
4372 let mut provided = t
4375 .filter_map(|m| match m.name {
4376 Some(ref name) if m.is_method() => {
4377 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4381 .collect::<Vec<String>>();
4383 if !types.is_empty() {
4385 sidebar.push_str(&format!(
4386 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4387 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4391 if !consts.is_empty() {
4393 sidebar.push_str(&format!(
4394 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4395 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4399 if !required.is_empty() {
4401 sidebar.push_str(&format!(
4402 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4403 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4407 if !provided.is_empty() {
4409 sidebar.push_str(&format!(
4410 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4411 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4418 if let Some(implementors) = c.implementors.get(&it.def_id) {
4419 let mut res = implementors
4421 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4422 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4423 .collect::<Vec<_>>();
4425 if !res.is_empty() {
4427 sidebar.push_str(&format!(
4428 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4429 Implementations on Foreign Types</a>\
4430 <div class=\"sidebar-links\">{}</div>",
4432 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4433 .collect::<Vec<_>>()
4439 sidebar.push_str(&sidebar_assoc_items(it));
4441 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4444 "<a class=\"sidebar-title\" \
4445 href=\"#synthetic-implementors\">Auto Implementors</a>",
4449 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4452 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4453 let sidebar = sidebar_assoc_items(it);
4455 if !sidebar.is_empty() {
4456 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4460 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4461 let sidebar = sidebar_assoc_items(it);
4463 if !sidebar.is_empty() {
4464 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4468 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4469 let mut fields = fields
4471 .filter(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false })
4472 .filter_map(|f| match f.name {
4474 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4478 .collect::<Vec<_>>();
4483 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4484 let mut sidebar = String::new();
4485 let fields = get_struct_fields_name(&u.fields);
4487 if !fields.is_empty() {
4488 sidebar.push_str(&format!(
4489 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4490 <div class=\"sidebar-links\">{}</div>",
4495 sidebar.push_str(&sidebar_assoc_items(it));
4497 if !sidebar.is_empty() {
4498 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4502 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4503 let mut sidebar = String::new();
4505 let mut variants = e
4508 .filter_map(|v| match v.name {
4509 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4512 .collect::<Vec<_>>();
4513 if !variants.is_empty() {
4514 variants.sort_unstable();
4515 sidebar.push_str(&format!(
4516 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4517 <div class=\"sidebar-links\">{}</div>",
4522 sidebar.push_str(&sidebar_assoc_items(it));
4524 if !sidebar.is_empty() {
4525 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4529 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4531 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4532 ItemType::Module => ("modules", "Modules"),
4533 ItemType::Struct => ("structs", "Structs"),
4534 ItemType::Union => ("unions", "Unions"),
4535 ItemType::Enum => ("enums", "Enums"),
4536 ItemType::Function => ("functions", "Functions"),
4537 ItemType::Typedef => ("types", "Type Definitions"),
4538 ItemType::Static => ("statics", "Statics"),
4539 ItemType::Constant => ("constants", "Constants"),
4540 ItemType::Trait => ("traits", "Traits"),
4541 ItemType::Impl => ("impls", "Implementations"),
4542 ItemType::TyMethod => ("tymethods", "Type Methods"),
4543 ItemType::Method => ("methods", "Methods"),
4544 ItemType::StructField => ("fields", "Struct Fields"),
4545 ItemType::Variant => ("variants", "Variants"),
4546 ItemType::Macro => ("macros", "Macros"),
4547 ItemType::Primitive => ("primitives", "Primitive Types"),
4548 ItemType::AssocType => ("associated-types", "Associated Types"),
4549 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4550 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4551 ItemType::Keyword => ("keywords", "Keywords"),
4552 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4553 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4554 ItemType::ProcDerive => ("derives", "Derive Macros"),
4555 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4559 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4560 let mut sidebar = String::new();
4562 if items.iter().any(|it| {
4563 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4565 sidebar.push_str(&format!(
4566 "<li><a href=\"#{id}\">{name}</a></li>",
4572 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4573 // to print its headings
4575 ItemType::Primitive,
4589 ItemType::StructField,
4591 ItemType::AssocType,
4592 ItemType::AssocConst,
4593 ItemType::ForeignType,
4596 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4597 let (short, name) = item_ty_to_strs(&myty);
4598 sidebar.push_str(&format!(
4599 "<li><a href=\"#{id}\">{name}</a></li>",
4606 if !sidebar.is_empty() {
4607 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4611 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4612 let sidebar = sidebar_assoc_items(it);
4613 if !sidebar.is_empty() {
4614 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4618 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4619 wrap_into_docblock(w, |w| {
4620 w.write_str(&highlight::render_with_highlighting(
4627 document(w, cx, it, None)
4630 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4631 let name = it.name.as_ref().expect("proc-macros always have names");
4633 MacroKind::Bang => {
4634 write!(w, "<pre class=\"rust macro\">");
4635 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4636 write!(w, "</pre>");
4638 MacroKind::Attr => {
4639 write!(w, "<pre class=\"rust attr\">");
4640 write!(w, "#[{}]", name);
4641 write!(w, "</pre>");
4643 MacroKind::Derive => {
4644 write!(w, "<pre class=\"rust derive\">");
4645 write!(w, "#[derive({})]", name);
4646 if !m.helpers.is_empty() {
4647 writeln!(w, "\n{{");
4648 writeln!(w, " // Attributes available to this derive:");
4649 for attr in &m.helpers {
4650 writeln!(w, " #[{}]", attr);
4654 write!(w, "</pre>");
4657 document(w, cx, it, None)
4660 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4661 document(w, cx, it, None);
4662 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4665 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4666 document(w, cx, it, None)
4669 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4671 fn make_item_keywords(it: &clean::Item) -> String {
4672 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4675 /// Returns a list of all paths used in the type.
4676 /// This is used to help deduplicate imported impls
4677 /// for reexported types. If any of the contained
4678 /// types are re-exported, we don't use the corresponding
4679 /// entry from the js file, as inlining will have already
4680 /// picked up the impl
4681 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4682 let mut out = Vec::new();
4683 let mut visited = FxHashSet::default();
4684 let mut work = VecDeque::new();
4685 let cache = cache();
4687 work.push_back(first_ty);
4689 while let Some(ty) = work.pop_front() {
4690 if !visited.insert(ty.clone()) {
4695 clean::Type::ResolvedPath { did, .. } => {
4696 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4697 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4699 if let Some(path) = fqp {
4700 out.push(path.join("::"));
4703 clean::Type::Tuple(tys) => {
4704 work.extend(tys.into_iter());
4706 clean::Type::Slice(ty) => {
4707 work.push_back(*ty);
4709 clean::Type::Array(ty, _) => {
4710 work.push_back(*ty);
4712 clean::Type::RawPointer(_, ty) => {
4713 work.push_back(*ty);
4715 clean::Type::BorrowedRef { type_, .. } => {
4716 work.push_back(*type_);
4718 clean::Type::QPath { self_type, trait_, .. } => {
4719 work.push_back(*self_type);
4720 work.push_back(*trait_);