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.
33 use std::cell::{Cell, RefCell};
34 use std::cmp::Ordering;
35 use std::collections::{BTreeMap, VecDeque};
36 use std::default::Default;
38 use std::fmt::{self, Write};
39 use std::fs::{self, File};
40 use std::io::prelude::*;
41 use std::io::{self, BufReader};
42 use std::path::{Component, Path, PathBuf};
45 use std::string::ToString;
46 use std::sync::mpsc::{channel, Receiver};
49 use itertools::Itertools;
50 use rustc_ast_pretty::pprust;
51 use rustc_attr::{Deprecation, StabilityLevel};
52 use rustc_data_structures::flock;
53 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
55 use rustc_hir::def::CtorKind;
56 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
57 use rustc_hir::Mutability;
58 use rustc_middle::middle::stability;
59 use rustc_middle::ty::TyCtxt;
60 use rustc_session::Session;
61 use rustc_span::edition::Edition;
62 use rustc_span::hygiene::MacroKind;
63 use rustc_span::source_map::FileName;
64 use rustc_span::symbol::{kw, sym, Symbol};
65 use serde::ser::SerializeSeq;
66 use serde::{Serialize, Serializer};
68 use crate::clean::{self, AttributesExt, GetDefId, RenderedLink, SelfTy, TypeKind};
69 use crate::config::{RenderInfo, RenderOptions};
70 use crate::docfs::{DocFS, PathError};
71 use crate::error::Error;
72 use crate::formats::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::{
81 self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine,
83 use crate::html::sources;
84 use crate::html::{highlight, layout, static_files};
85 use cache::{build_index, ExternalLocation};
87 /// A pair of name and its optional document.
88 crate type NameDoc = (String, Option<String>);
90 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
91 crate::html::format::display_fn(move |f| {
92 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
96 /// Major driving force in all rustdoc rendering. This contains information
97 /// about where in the tree-like hierarchy rendering is occurring and controls
98 /// how the current page is being rendered.
100 /// It is intended that this context is a lightweight object which can be fairly
101 /// easily cloned because it is cloned per work-job (about once per item in the
104 crate struct Context<'tcx> {
105 /// Current hierarchy of components leading down to what's currently being
107 crate current: Vec<String>,
108 /// The current destination folder of where HTML artifacts should be placed.
109 /// This changes as the context descends into the module hierarchy.
111 /// A flag, which when `true`, will render pages which redirect to the
112 /// real location of an item. This is used to allow external links to
113 /// publicly reused items to redirect to the right location.
114 crate render_redirect_pages: bool,
115 /// The map used to ensure all generated 'id=' attributes are unique.
116 id_map: Rc<RefCell<IdMap>>,
117 /// Tracks section IDs for `Deref` targets so they match in both the main
118 /// body and the sidebar.
119 deref_id_map: Rc<RefCell<FxHashMap<DefId, String>>>,
120 crate shared: Arc<SharedContext<'tcx>>,
121 all: Rc<RefCell<AllTypes>>,
122 /// Storage for the errors produced while generating documentation so they
123 /// can be printed together at the end.
124 crate errors: Rc<Receiver<String>>,
125 crate cache: Rc<Cache>,
128 crate struct SharedContext<'tcx> {
129 crate tcx: TyCtxt<'tcx>,
130 /// The path to the crate root source minus the file name.
131 /// Used for simplifying paths to the highlighted source code files.
132 crate src_root: PathBuf,
133 /// This describes the layout of each page, and is not modified after
134 /// creation of the context (contains info like the favicon and added html).
135 crate layout: layout::Layout,
136 /// This flag indicates whether `[src]` links should be generated or not. If
137 /// the source files are present in the html rendering, then this will be
139 crate include_sources: bool,
140 /// The local file sources we've emitted and their respective url-paths.
141 crate local_sources: FxHashMap<PathBuf, String>,
142 /// Whether the collapsed pass ran
143 crate collapsed: bool,
144 /// The base-URL of the issue tracker for when an item has been tagged with
146 crate issue_tracker_base_url: Option<String>,
147 /// The directories that have already been created in this doc run. Used to reduce the number
148 /// of spurious `create_dir_all` calls.
149 crate created_dirs: RefCell<FxHashSet<PathBuf>>,
150 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
151 /// should be ordered alphabetically or in order of appearance (in the source code).
152 crate sort_modules_alphabetically: bool,
153 /// Additional CSS files to be added to the generated docs.
154 crate style_files: Vec<StylePath>,
155 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
157 crate resource_suffix: String,
158 /// Optional path string to be used to load static files on output pages. If not set, uses
159 /// combinations of `../` to reach the documentation root.
160 crate static_root_path: Option<String>,
161 /// The fs handle we are working with.
163 /// The default edition used to parse doctests.
164 crate edition: Edition,
165 crate codes: ErrorCodes,
166 playground: Option<markdown::Playground>,
169 impl<'tcx> Context<'tcx> {
170 fn path(&self, filename: &str) -> PathBuf {
171 // We use splitn vs Path::extension here because we might get a filename
172 // like `style.min.css` and we want to process that into
173 // `style-suffix.min.css`. Path::extension would just return `css`
174 // which would result in `style.min-suffix.css` which isn't what we
176 let (base, ext) = filename.split_once('.').unwrap();
177 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext);
178 self.dst.join(&filename)
181 fn tcx(&self) -> TyCtxt<'tcx> {
185 fn sess(&self) -> &Session {
186 &self.shared.tcx.sess
190 impl SharedContext<'_> {
191 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
192 let mut dirs = self.created_dirs.borrow_mut();
193 if !dirs.contains(dst) {
194 try_err!(self.fs.create_dir_all(dst), dst);
195 dirs.insert(dst.to_path_buf());
201 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
202 /// `collapsed_doc_value` of the given item.
203 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<String> {
204 if self.collapsed { item.collapsed_doc_value() } else { item.doc_value() }
208 // Helper structs for rendering items/sidebars and carrying along contextual
211 /// Struct representing one entry in the JS search index. These are all emitted
212 /// by hand to a large JS file at the end of cache-creation.
214 crate struct IndexItem {
219 crate parent: Option<DefId>,
220 crate parent_idx: Option<usize>,
221 crate search_type: Option<IndexItemFunctionType>,
224 impl Serialize for IndexItem {
225 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
230 self.parent.is_some(),
231 self.parent_idx.is_some(),
232 "`{}` is missing idx",
236 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
237 .serialize(serializer)
241 /// A type used for the search index.
243 crate struct RenderType {
246 name: Option<String>,
247 generics: Option<Vec<Generic>>,
250 impl Serialize for RenderType {
251 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
255 if let Some(name) = &self.name {
256 let mut seq = serializer.serialize_seq(None)?;
257 if let Some(id) = self.idx {
258 seq.serialize_element(&id)?;
260 seq.serialize_element(&name)?;
262 if let Some(generics) = &self.generics {
263 seq.serialize_element(&generics)?;
267 serializer.serialize_none()
272 /// A type used for the search index.
274 crate struct Generic {
276 defid: Option<DefId>,
280 impl Serialize for Generic {
281 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
285 if let Some(id) = self.idx {
286 serializer.serialize_some(&id)
288 serializer.serialize_some(&self.name)
293 /// Full type of functions/methods in the search index.
295 crate struct IndexItemFunctionType {
296 inputs: Vec<TypeWithKind>,
297 output: Option<Vec<TypeWithKind>>,
300 impl Serialize for IndexItemFunctionType {
301 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
305 // If we couldn't figure out a type, just write `null`.
306 let mut iter = self.inputs.iter();
307 if match self.output {
308 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
309 None => iter.any(|ref i| i.ty.name.is_none()),
311 serializer.serialize_none()
313 let mut seq = serializer.serialize_seq(None)?;
314 seq.serialize_element(&self.inputs)?;
315 if let Some(output) = &self.output {
316 if output.len() > 1 {
317 seq.serialize_element(&output)?;
319 seq.serialize_element(&output[0])?;
328 crate struct TypeWithKind {
333 impl From<(RenderType, TypeKind)> for TypeWithKind {
334 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
335 TypeWithKind { ty: x.0, kind: x.1 }
339 impl Serialize for TypeWithKind {
340 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
344 let mut seq = serializer.serialize_seq(None)?;
345 seq.serialize_element(&self.ty.name)?;
346 let x: ItemType = self.kind.into();
347 seq.serialize_element(&x)?;
352 #[derive(Debug, Clone)]
353 crate struct StylePath {
354 /// The path to the theme
356 /// What the `disabled` attribute should be set to in the HTML tag
357 crate disabled: bool,
360 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
362 crate const INITIAL_IDS: [&'static str; 15] = [
373 "synthetic-implementors",
375 "synthetic-implementors-list",
380 /// Generates the documentation for `crate` into the directory `dst`
381 impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
382 fn descr() -> &'static str {
387 mut krate: clean::Crate,
388 options: RenderOptions,
389 _render_info: RenderInfo,
393 ) -> Result<(Self, clean::Crate), Error> {
394 // need to save a copy of the options for rendering the index page
395 let md_opts = options.clone();
401 sort_modules_alphabetically,
407 generate_search_filter,
412 let src_root = match krate.src {
413 FileName::Real(ref p) => match p.local_path().parent() {
414 Some(p) => p.to_path_buf(),
415 None => PathBuf::new(),
419 // If user passed in `--playground-url` arg, we fill in crate name here
420 let mut playground = None;
421 if let Some(url) = playground_url {
423 Some(markdown::Playground { crate_name: Some(krate.name.to_string()), url });
425 let mut layout = layout::Layout {
427 favicon: String::new(),
430 krate: krate.name.to_string(),
431 css_file_extension: extension_css,
432 generate_search_filter,
434 let mut issue_tracker_base_url = None;
435 let mut include_sources = true;
437 // Crawl the crate attributes looking for attributes which control how we're
438 // going to emit HTML
439 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
440 for attr in attrs.lists(sym::doc) {
441 match (attr.name_or_empty(), attr.value_str()) {
442 (sym::html_favicon_url, Some(s)) => {
443 layout.favicon = s.to_string();
445 (sym::html_logo_url, Some(s)) => {
446 layout.logo = s.to_string();
448 (sym::html_playground_url, Some(s)) => {
449 playground = Some(markdown::Playground {
450 crate_name: Some(krate.name.to_string()),
454 (sym::issue_tracker_base_url, Some(s)) => {
455 issue_tracker_base_url = Some(s.to_string());
457 (sym::html_no_source, None) if attr.is_word() => {
458 include_sources = false;
464 let (sender, receiver) = channel();
465 let mut scx = SharedContext {
467 collapsed: krate.collapsed,
470 local_sources: Default::default(),
471 issue_tracker_base_url,
473 created_dirs: Default::default(),
474 sort_modules_alphabetically,
478 fs: DocFS::new(sender),
480 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
484 // Add the default themes to the `Vec` of stylepaths
486 // Note that these must be added before `sources::render` is called
487 // so that the resulting source pages are styled
489 // `light.css` is not disabled because it is the stylesheet that stays loaded
490 // by the browser as the theme stylesheet. The theme system (hackily) works by
491 // changing the href to this stylesheet. All other themes are disabled to
492 // prevent rule conflicts
493 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
494 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
495 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
498 scx.ensure_dir(&dst)?;
499 krate = sources::render(&dst, &mut scx, krate)?;
501 // Build our search index
502 let index = build_index(&krate, &mut cache, tcx);
504 let mut cx = Context {
507 render_redirect_pages: false,
508 id_map: Rc::new(RefCell::new(id_map)),
509 deref_id_map: Rc::new(RefCell::new(FxHashMap::default())),
510 shared: Arc::new(scx),
511 all: Rc::new(RefCell::new(AllTypes::new())),
512 errors: Rc::new(receiver),
513 cache: Rc::new(cache),
516 CURRENT_DEPTH.with(|s| s.set(0));
518 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
519 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
520 write_shared(&cx, &krate, index, &md_opts)?;
521 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
527 krate: &clean::Crate,
528 diag: &rustc_errors::Handler,
529 ) -> Result<(), Error> {
530 let final_file = self.dst.join(&*krate.name.as_str()).join("all.html");
531 let settings_file = self.dst.join("settings.html");
532 let crate_name = krate.name;
534 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
535 if !root_path.ends_with('/') {
538 let mut page = layout::Page {
539 title: "List of all items in this crate",
542 static_root_path: self.shared.static_root_path.as_deref(),
543 description: "List of all items in this crate",
544 keywords: BASIC_KEYWORDS,
545 resource_suffix: &self.shared.resource_suffix,
547 static_extra_scripts: &[],
549 let sidebar = if let Some(ref version) = self.cache.crate_version {
551 "<p class=\"location\">Crate {}</p>\
552 <div class=\"block version\">\
555 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
562 let all = self.all.replace(AllTypes::new());
563 let v = layout::render(
567 |buf: &mut Buffer| all.print(buf),
568 &self.shared.style_files,
570 self.shared.fs.write(&final_file, v.as_bytes())?;
572 // Generating settings page.
573 page.title = "Rustdoc settings";
574 page.description = "Settings of Rustdoc";
575 page.root_path = "./";
577 let mut style_files = self.shared.style_files.clone();
578 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
579 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
580 let v = layout::render(
585 self.shared.static_root_path.as_deref().unwrap_or("./"),
586 &self.shared.resource_suffix,
587 &self.shared.style_files,
591 self.shared.fs.write(&settings_file, v.as_bytes())?;
593 // Flush pending errors.
594 Arc::get_mut(&mut self.shared).unwrap().fs.close();
595 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
597 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
603 fn mod_item_in(&mut self, item: &clean::Item, item_name: &str) -> Result<(), Error> {
604 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
605 // if they contain impls for public types. These modules can also
606 // contain items such as publicly re-exported structures.
608 // External crates will provide links to these structures, so
609 // these modules are recursed into, but not rendered normally
610 // (a flag on the context).
611 if !self.render_redirect_pages {
612 self.render_redirect_pages = item.is_stripped();
614 let scx = &self.shared;
615 self.dst.push(item_name);
616 self.current.push(item_name.to_owned());
618 info!("Recursing into {}", self.dst.display());
620 let buf = self.render_item(item, false);
621 // buf will be empty if the module is stripped and there is no redirect for it
623 self.shared.ensure_dir(&self.dst)?;
624 let joint_dst = self.dst.join("index.html");
625 scx.fs.write(&joint_dst, buf.as_bytes())?;
628 // Render sidebar-items.js used throughout this module.
629 if !self.render_redirect_pages {
630 let module = match *item.kind {
631 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
634 let items = self.build_sidebar_items(module);
635 let js_dst = self.dst.join("sidebar-items.js");
636 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
637 scx.fs.write(&js_dst, &v)?;
642 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
643 info!("Recursed; leaving {}", self.dst.display());
645 // Go back to where we were at
651 fn item(&mut self, item: clean::Item) -> Result<(), Error> {
652 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
653 // if they contain impls for public types. These modules can also
654 // contain items such as publicly re-exported structures.
656 // External crates will provide links to these structures, so
657 // these modules are recursed into, but not rendered normally
658 // (a flag on the context).
659 if !self.render_redirect_pages {
660 self.render_redirect_pages = item.is_stripped();
663 let buf = self.render_item(&item, true);
664 // buf will be empty if the item is stripped and there is no redirect for it
666 let name = item.name.as_ref().unwrap();
667 let item_type = item.type_();
668 let file_name = &item_path(item_type, &name.as_str());
669 self.shared.ensure_dir(&self.dst)?;
670 let joint_dst = self.dst.join(file_name);
671 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
673 if !self.render_redirect_pages {
674 self.all.borrow_mut().append(full_path(self, &item), &item_type);
676 // If the item is a macro, redirect from the old macro URL (with !)
677 // to the new one (without).
678 if item_type == ItemType::Macro {
679 let redir_name = format!("{}.{}!.html", item_type, name);
680 let redir_dst = self.dst.join(redir_name);
681 let v = layout::redirect(file_name);
682 self.shared.fs.write(&redir_dst, v.as_bytes())?;
688 fn cache(&self) -> &Cache {
695 krate: &clean::Crate,
696 search_index: String,
697 options: &RenderOptions,
698 ) -> Result<(), Error> {
699 // Write out the shared files. Note that these are shared among all rustdoc
700 // docs placed in the output directory, so this needs to be a synchronized
701 // operation with respect to all other rustdocs running around.
702 let lock_file = cx.dst.join(".lock");
703 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
705 // Add all the static files. These may already exist, but we just
706 // overwrite them anyway to make sure that they're fresh and up-to-date.
710 cx.path("rustdoc.css"),
711 static_files::RUSTDOC_CSS,
712 options.enable_minification,
716 cx.path("settings.css"),
717 static_files::SETTINGS_CSS,
718 options.enable_minification,
722 cx.path("noscript.css"),
723 static_files::NOSCRIPT_CSS,
724 options.enable_minification,
727 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
728 // then we'll run over the "official" styles.
729 let mut themes: FxHashSet<String> = FxHashSet::default();
731 for entry in &cx.shared.style_files {
732 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
734 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
736 // Handle the official themes
738 "light" => write_minify(
740 cx.path("light.css"),
741 static_files::themes::LIGHT,
742 options.enable_minification,
744 "dark" => write_minify(
747 static_files::themes::DARK,
748 options.enable_minification,
750 "ayu" => write_minify(
753 static_files::themes::AYU,
754 options.enable_minification,
757 // Handle added third-party themes
758 let content = try_err!(fs::read(&entry.path), &entry.path);
761 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
765 themes.insert(theme.to_owned());
768 let write = |p, c| cx.shared.fs.write(p, c);
769 if (*cx.shared).layout.logo.is_empty() {
770 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
772 if (*cx.shared).layout.favicon.is_empty() {
773 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
774 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
775 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
777 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
778 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
779 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
781 let mut themes: Vec<&String> = themes.iter().collect();
783 // To avoid theme switch latencies as much as possible, we put everything theme related
784 // at the beginning of the html files into another js file.
785 let theme_js = format!(
786 r#"var themes = document.getElementById("theme-choices");
787 var themePicker = document.getElementById("theme-picker");
789 function showThemeButtonState() {{
790 themes.style.display = "block";
791 themePicker.style.borderBottomRightRadius = "0";
792 themePicker.style.borderBottomLeftRadius = "0";
795 function hideThemeButtonState() {{
796 themes.style.display = "none";
797 themePicker.style.borderBottomRightRadius = "3px";
798 themePicker.style.borderBottomLeftRadius = "3px";
801 function switchThemeButtonState() {{
802 if (themes.style.display === "block") {{
803 hideThemeButtonState();
805 showThemeButtonState();
809 function handleThemeButtonsBlur(e) {{
810 var active = document.activeElement;
811 var related = e.relatedTarget;
813 if (active.id !== "theme-picker" &&
814 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
816 (related.id !== "theme-picker" &&
817 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
818 hideThemeButtonState();
822 themePicker.onclick = switchThemeButtonState;
823 themePicker.onblur = handleThemeButtonsBlur;
824 {}.forEach(function(item) {{
825 var but = document.createElement("button");
826 but.textContent = item;
827 but.onclick = function(el) {{
828 switchTheme(currentTheme, mainTheme, item, true);
829 useSystemTheme(false);
831 but.onblur = handleThemeButtonsBlur;
832 themes.appendChild(but);
834 serde_json::to_string(&themes).unwrap()
837 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
841 static_files::MAIN_JS,
842 options.enable_minification,
846 cx.path("settings.js"),
847 static_files::SETTINGS_JS,
848 options.enable_minification,
850 if cx.shared.include_sources {
853 cx.path("source-script.js"),
854 static_files::sidebar::SOURCE_SCRIPT,
855 options.enable_minification,
862 cx.path("storage.js"),
864 "var resourcesSuffix = \"{}\";{}",
865 cx.shared.resource_suffix,
866 static_files::STORAGE_JS
868 options.enable_minification,
872 if let Some(ref css) = cx.shared.layout.css_file_extension {
873 let out = cx.path("theme.css");
874 let buffer = try_err!(fs::read_to_string(css), css);
875 if !options.enable_minification {
876 cx.shared.fs.write(&out, &buffer)?;
878 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
883 cx.path("normalize.css"),
884 static_files::NORMALIZE_CSS,
885 options.enable_minification,
887 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
888 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
889 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
890 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
891 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
892 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
893 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
894 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
895 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
896 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
897 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
898 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
899 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
901 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
902 let mut ret = Vec::new();
903 let mut krates = Vec::new();
906 let prefix = format!(r#"{}["{}"]"#, key, krate);
907 for line in BufReader::new(File::open(path)?).lines() {
909 if !line.starts_with(key) {
912 if line.starts_with(&prefix) {
915 ret.push(line.to_string());
917 line[key.len() + 2..]
920 .map(|s| s.to_owned())
921 .unwrap_or_else(String::new),
928 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
929 let mut ret = Vec::new();
930 let mut krates = Vec::new();
933 let prefix = format!("\"{}\"", krate);
934 for line in BufReader::new(File::open(path)?).lines() {
936 if !line.starts_with('"') {
939 if line.starts_with(&prefix) {
942 if line.ends_with(",\\") {
943 ret.push(line[..line.len() - 2].to_string());
945 // Ends with "\\" (it's the case for the last added crate line)
946 ret.push(line[..line.len() - 1].to_string());
950 .find(|s| !s.is_empty())
951 .map(|s| s.to_owned())
952 .unwrap_or_else(String::new),
959 use std::ffi::OsString;
964 children: FxHashMap<OsString, Hierarchy>,
965 elems: FxHashSet<OsString>,
969 fn new(elem: OsString) -> Hierarchy {
970 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
973 fn to_json_string(&self) -> String {
974 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
975 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
979 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
980 .collect::<Vec<_>>();
981 files.sort_unstable();
982 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
984 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
985 let files = files.join(",");
987 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
989 "{{\"name\":\"{name}\"{dirs}{files}}}",
990 name = self.elem.to_str().expect("invalid osstring conversion"),
997 if cx.shared.include_sources {
998 let mut hierarchy = Hierarchy::new(OsString::new());
1003 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
1005 let mut h = &mut hierarchy;
1006 let mut elems = source
1008 .filter_map(|s| match s {
1009 Component::Normal(s) => Some(s.to_owned()),
1014 let cur_elem = elems.next().expect("empty file path");
1015 if elems.peek().is_none() {
1016 h.elems.insert(cur_elem);
1019 let e = cur_elem.clone();
1020 h = h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1025 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1026 let (mut all_sources, _krates) =
1027 try_err!(collect(&dst, &krate.name.as_str(), "sourcesIndex"), &dst);
1028 all_sources.push(format!(
1029 "sourcesIndex[\"{}\"] = {};",
1031 hierarchy.to_json_string()
1035 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1036 all_sources.join("\n")
1038 cx.shared.fs.write(&dst, v.as_bytes())?;
1041 // Update the search index
1042 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1043 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name.as_str()), &dst);
1044 all_indexes.push(search_index);
1046 // Sort the indexes by crate so the file will be generated identically even
1047 // with rustdoc running in parallel.
1050 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1051 v.push_str(&all_indexes.join(",\\\n"));
1052 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1053 // search might start (if it's set into the URL for example).
1054 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1055 cx.shared.fs.write(&dst, &v)?;
1057 if options.enable_index_page {
1058 if let Some(index_page) = options.index_page.clone() {
1059 let mut md_opts = options.clone();
1060 md_opts.output = cx.dst.clone();
1061 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1063 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1064 .map_err(|e| Error::new(e, &index_page))?;
1066 let dst = cx.dst.join("index.html");
1067 let page = layout::Page {
1068 title: "Index of crates",
1071 static_root_path: cx.shared.static_root_path.as_deref(),
1072 description: "List of crates",
1073 keywords: BASIC_KEYWORDS,
1074 resource_suffix: &cx.shared.resource_suffix,
1076 static_extra_scripts: &[],
1078 krates.push(krate.name.to_string());
1082 let content = format!(
1083 "<h1 class=\"fqn\">\
1084 <span class=\"in-band\">List of all crates</span>\
1085 </h1><ul class=\"crate mod\">{}</ul>",
1090 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1091 ensure_trailing_slash(s),
1095 .collect::<String>()
1097 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1098 cx.shared.fs.write(&dst, v.as_bytes())?;
1102 // Update the list of all implementors for traits
1103 let dst = cx.dst.join("implementors");
1104 for (&did, imps) in &cx.cache.implementors {
1105 // Private modules can leak through to this phase of rustdoc, which
1106 // could contain implementations for otherwise private types. In some
1107 // rare cases we could find an implementation for an item which wasn't
1108 // indexed, so we just skip this step in that case.
1110 // FIXME: this is a vague explanation for why this can't be a `get`, in
1111 // theory it should be...
1112 let &(ref remote_path, remote_item_type) = match cx.cache.paths.get(&did) {
1114 None => match cx.cache.external_paths.get(&did) {
1120 #[derive(Serialize)]
1121 struct Implementor {
1127 let implementors = imps
1130 // If the trait and implementation are in the same crate, then
1131 // there's no need to emit information about it (there's inlining
1132 // going on). If they're in different crates then the crate defining
1133 // the trait will be interested in our implementation.
1135 // If the implementation is from another crate then that crate
1137 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1141 text: imp.inner_impl().print(cx.cache()).to_string(),
1142 synthetic: imp.inner_impl().synthetic,
1143 types: collect_paths_for_type(imp.inner_impl().for_.clone(), cx.cache()),
1147 .collect::<Vec<_>>();
1149 // Only create a js file if we have impls to add to it. If the trait is
1150 // documented locally though we always create the file to avoid dead
1152 if implementors.is_empty() && !cx.cache.paths.contains_key(&did) {
1156 let implementors = format!(
1157 r#"implementors["{}"] = {};"#,
1159 serde_json::to_string(&implementors).unwrap()
1162 let mut mydst = dst.clone();
1163 for part in &remote_path[..remote_path.len() - 1] {
1166 cx.shared.ensure_dir(&mydst)?;
1167 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1169 let (mut all_implementors, _) =
1170 try_err!(collect(&mydst, &krate.name.as_str(), "implementors"), &mydst);
1171 all_implementors.push(implementors);
1172 // Sort the implementors by crate so the file will be generated
1173 // identically even with rustdoc running in parallel.
1174 all_implementors.sort();
1176 let mut v = String::from("(function() {var implementors = {};\n");
1177 for implementor in &all_implementors {
1178 writeln!(v, "{}", *implementor).unwrap();
1181 "if (window.register_implementors) {\
1182 window.register_implementors(implementors);\
1184 window.pending_implementors = implementors;\
1188 cx.shared.fs.write(&mydst, &v)?;
1197 enable_minification: bool,
1198 ) -> Result<(), Error> {
1199 if enable_minification {
1200 if dst.extension() == Some(&OsStr::new("css")) {
1201 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1202 fs.write(dst, res.as_bytes())
1204 fs.write(dst, minifier::js::minify(contents).as_bytes())
1207 fs.write(dst, contents.as_bytes())
1211 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
1212 if let Some(l) = cx.src_href(item) {
1213 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
1217 #[derive(Debug, Eq, PartialEq, Hash)]
1224 fn new(mut url: String, name: String) -> ItemEntry {
1225 while url.starts_with('/') {
1228 ItemEntry { url, name }
1233 crate fn print(&self) -> impl fmt::Display + '_ {
1234 crate::html::format::display_fn(move |f| {
1235 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1240 impl PartialOrd for ItemEntry {
1241 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1242 Some(self.cmp(other))
1246 impl Ord for ItemEntry {
1247 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1248 self.name.cmp(&other.name)
1254 structs: FxHashSet<ItemEntry>,
1255 enums: FxHashSet<ItemEntry>,
1256 unions: FxHashSet<ItemEntry>,
1257 primitives: FxHashSet<ItemEntry>,
1258 traits: FxHashSet<ItemEntry>,
1259 macros: FxHashSet<ItemEntry>,
1260 functions: FxHashSet<ItemEntry>,
1261 typedefs: FxHashSet<ItemEntry>,
1262 opaque_tys: FxHashSet<ItemEntry>,
1263 statics: FxHashSet<ItemEntry>,
1264 constants: FxHashSet<ItemEntry>,
1265 keywords: FxHashSet<ItemEntry>,
1266 attributes: FxHashSet<ItemEntry>,
1267 derives: FxHashSet<ItemEntry>,
1268 trait_aliases: FxHashSet<ItemEntry>,
1272 fn new() -> AllTypes {
1273 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1275 structs: new_set(100),
1276 enums: new_set(100),
1277 unions: new_set(100),
1278 primitives: new_set(26),
1279 traits: new_set(100),
1280 macros: new_set(100),
1281 functions: new_set(100),
1282 typedefs: new_set(100),
1283 opaque_tys: new_set(100),
1284 statics: new_set(100),
1285 constants: new_set(100),
1286 keywords: new_set(100),
1287 attributes: new_set(100),
1288 derives: new_set(100),
1289 trait_aliases: new_set(100),
1293 fn append(&mut self, item_name: String, item_type: &ItemType) {
1294 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1295 if let Some(name) = url.pop() {
1296 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1298 let name = url.join("::");
1300 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1301 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1302 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1303 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1304 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1305 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1306 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1307 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1308 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1309 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1310 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1311 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1312 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1313 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1321 fn print(self, f: &mut Buffer) {
1322 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1324 let mut e: Vec<&ItemEntry> = e.iter().collect();
1326 write!(f, "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">", title, title, class);
1329 write!(f, "<li>{}</li>", s.print());
1332 f.write_str("</ul>");
1337 "<h1 class=\"fqn\">\
1338 <span class=\"in-band\">List of all items</span>\
1339 <span class=\"out-of-band\">\
1340 <span id=\"render-detail\">\
1341 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1342 title=\"collapse all docs\">\
1343 [<span class=\"inner\">−</span>]\
1347 <span class=\"in-band\">List of all items</span>\
1350 // Note: print_entries does not escape the title, because we know the current set of titles
1351 // don't require escaping.
1352 print_entries(f, &self.structs, "Structs", "structs");
1353 print_entries(f, &self.enums, "Enums", "enums");
1354 print_entries(f, &self.unions, "Unions", "unions");
1355 print_entries(f, &self.primitives, "Primitives", "primitives");
1356 print_entries(f, &self.traits, "Traits", "traits");
1357 print_entries(f, &self.macros, "Macros", "macros");
1358 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1359 print_entries(f, &self.derives, "Derive Macros", "derives");
1360 print_entries(f, &self.functions, "Functions", "functions");
1361 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1362 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1363 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1364 print_entries(f, &self.statics, "Statics", "statics");
1365 print_entries(f, &self.constants, "Constants", "constants")
1372 description: &'static str,
1373 sub_settings: Vec<Setting>,
1376 js_data_name: &'static str,
1377 description: &'static str,
1378 default_value: bool,
1381 js_data_name: &'static str,
1382 description: &'static str,
1383 default_value: &'static str,
1384 options: Vec<(String, String)>,
1389 fn display(&self, root_path: &str, suffix: &str) -> String {
1391 Setting::Section { description, ref sub_settings } => format!(
1392 "<div class=\"setting-line\">\
1393 <div class=\"title\">{}</div>\
1394 <div class=\"sub-settings\">{}</div>
1397 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1399 Setting::Toggle { js_data_name, description, default_value } => format!(
1400 "<div class=\"setting-line\">\
1401 <label class=\"toggle\">\
1402 <input type=\"checkbox\" id=\"{}\" {}>\
1403 <span class=\"slider\"></span>\
1408 if default_value { " checked" } else { "" },
1411 Setting::Select { js_data_name, description, default_value, ref options } => format!(
1412 "<div class=\"setting-line\">\
1414 <label class=\"select-wrapper\">\
1415 <select id=\"{}\" autocomplete=\"off\">{}</select>\
1416 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1424 "<option value=\"{}\" {}>{}</option>",
1426 if opt.0 == default_value { "selected" } else { "" },
1429 .collect::<String>(),
1437 impl From<(&'static str, &'static str, bool)> for Setting {
1438 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1439 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1443 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1444 fn from(values: (&'static str, Vec<T>)) -> Setting {
1446 description: values.0,
1447 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1452 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1453 let theme_names: Vec<(String, String)> = themes
1457 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1460 Ok((theme.clone(), theme))
1462 .collect::<Result<_, Error>>()?;
1464 // (id, explanation, default value)
1465 let settings: &[Setting] = &[
1467 "Theme preferences",
1469 Setting::from(("use-system-theme", "Use system theme", true)),
1471 js_data_name: "preferred-dark-theme",
1472 description: "Preferred dark theme",
1473 default_value: "dark",
1474 options: theme_names.clone(),
1477 js_data_name: "preferred-light-theme",
1478 description: "Preferred light theme",
1479 default_value: "light",
1480 options: theme_names,
1486 "Auto-hide item declarations",
1488 ("auto-hide-struct", "Auto-hide structs declaration", true),
1489 ("auto-hide-enum", "Auto-hide enums declaration", false),
1490 ("auto-hide-union", "Auto-hide unions declaration", true),
1491 ("auto-hide-trait", "Auto-hide traits declaration", true),
1492 ("auto-hide-macro", "Auto-hide macros declaration", false),
1496 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1497 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1498 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1500 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1501 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1503 ("line-numbers", "Show line numbers on code examples", false).into(),
1504 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1508 "<h1 class=\"fqn\">\
1509 <span class=\"in-band\">Rustdoc settings</span>\
1511 <div class=\"settings\">{}</div>\
1512 <script src=\"{}settings{}.js\"></script>",
1513 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1520 fn derive_id(&self, id: String) -> String {
1521 let mut map = self.id_map.borrow_mut();
1525 /// String representation of how to get back to the root path of the 'doc/'
1526 /// folder in terms of a relative URL.
1527 fn root_path(&self) -> String {
1528 "../".repeat(self.current.len())
1531 fn render_item(&self, it: &clean::Item, pushname: bool) -> String {
1532 // A little unfortunate that this is done like this, but it sure
1533 // does make formatting *a lot* nicer.
1534 CURRENT_DEPTH.with(|slot| {
1535 slot.set(self.current.len());
1538 let mut title = if it.is_primitive() || it.is_keyword() {
1539 // No need to include the namespace for primitive types and keywords
1542 self.current.join("::")
1545 if !title.is_empty() {
1546 title.push_str("::");
1548 title.push_str(&it.name.unwrap().as_str());
1550 title.push_str(" - Rust");
1551 let tyname = it.type_();
1552 let desc = if it.is_crate() {
1553 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1556 "API documentation for the Rust `{}` {} in crate `{}`.",
1557 it.name.as_ref().unwrap(),
1559 self.shared.layout.krate
1562 let keywords = make_item_keywords(it);
1563 let page = layout::Page {
1564 css_class: tyname.as_str(),
1565 root_path: &self.root_path(),
1566 static_root_path: self.shared.static_root_path.as_deref(),
1569 keywords: &keywords,
1570 resource_suffix: &self.shared.resource_suffix,
1572 static_extra_scripts: &[],
1576 self.id_map.borrow_mut().reset();
1577 self.id_map.borrow_mut().populate(&INITIAL_IDS);
1580 if !self.render_redirect_pages {
1582 &self.shared.layout,
1584 |buf: &mut _| print_sidebar(self, it, buf),
1585 |buf: &mut _| print_item(self, it, buf),
1586 &self.shared.style_files,
1589 let mut url = self.root_path();
1590 if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) {
1591 for name in &names[..names.len() - 1] {
1595 url.push_str(&item_path(ty, names.last().unwrap()));
1596 layout::redirect(&url)
1603 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1604 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1605 // BTreeMap instead of HashMap to get a sorted output
1606 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1607 for item in &m.items {
1608 if item.is_stripped() {
1612 let short = item.type_();
1613 let myname = match item.name {
1615 Some(ref s) => s.to_string(),
1617 let short = short.to_string();
1618 map.entry(short).or_default().push((
1620 Some(item.doc_value().map_or_else(String::new, |s| plain_text_summary(&s))),
1624 if self.shared.sort_modules_alphabetically {
1625 for items in map.values_mut() {
1632 /// Generates a url appropriate for an `href` attribute back to the source of
1635 /// The url generated, when clicked, will redirect the browser back to the
1636 /// original source code.
1638 /// If `None` is returned, then a source link couldn't be generated. This
1639 /// may happen, for example, with externally inlined items where the source
1640 /// of their crate documentation isn't known.
1641 fn src_href(&self, item: &clean::Item) -> Option<String> {
1642 let mut root = self.root_path();
1643 let mut path = String::new();
1644 let cnum = item.source.cnum(self.sess());
1646 // We can safely ignore synthetic `SourceFile`s.
1647 let file = match item.source.filename(self.sess()) {
1648 FileName::Real(ref path) => path.local_path().to_path_buf(),
1654 let (krate, path) = if cnum == LOCAL_CRATE {
1655 if let Some(path) = self.shared.local_sources.get(file) {
1656 (self.shared.layout.krate.as_str(), path)
1661 let (krate, src_root) = match *self.cache.extern_locations.get(&cnum)? {
1662 (name, ref src, ExternalLocation::Local) => (name, src),
1663 (name, ref src, ExternalLocation::Remote(ref s)) => {
1664 root = s.to_string();
1667 (_, _, ExternalLocation::Unknown) => return None,
1670 sources::clean_path(&src_root, file, false, |component| {
1671 path.push_str(&component.to_string_lossy());
1674 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1675 fname.push(".html");
1676 path.push_str(&fname.to_string_lossy());
1677 symbol = krate.as_str();
1681 let loline = item.source.lo(self.sess()).line;
1682 let hiline = item.source.hi(self.sess()).line;
1684 if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) };
1686 "{root}src/{krate}/{path}#{lines}",
1687 root = Escape(&root),
1695 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1697 F: FnOnce(&mut Buffer),
1699 w.write_str("<div class=\"docblock type-decl hidden-by-usual-hider\">");
1701 w.write_str("</div>")
1704 fn print_item(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
1705 debug_assert!(!item.is_stripped());
1706 // Write the breadcrumb trail header for the top
1707 buf.write_str("<h1 class=\"fqn\"><span class=\"in-band\">");
1708 let name = match *item.kind {
1709 clean::ModuleItem(ref m) => {
1716 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1717 clean::TraitItem(..) => "Trait ",
1718 clean::StructItem(..) => "Struct ",
1719 clean::UnionItem(..) => "Union ",
1720 clean::EnumItem(..) => "Enum ",
1721 clean::TypedefItem(..) => "Type Definition ",
1722 clean::MacroItem(..) => "Macro ",
1723 clean::ProcMacroItem(ref mac) => match mac.kind {
1724 MacroKind::Bang => "Macro ",
1725 MacroKind::Attr => "Attribute Macro ",
1726 MacroKind::Derive => "Derive Macro ",
1728 clean::PrimitiveItem(..) => "Primitive Type ",
1729 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1730 clean::ConstantItem(..) => "Constant ",
1731 clean::ForeignTypeItem => "Foreign Type ",
1732 clean::KeywordItem(..) => "Keyword ",
1733 clean::OpaqueTyItem(..) => "Opaque Type ",
1734 clean::TraitAliasItem(..) => "Trait Alias ",
1736 // We don't generate pages for any other type.
1740 buf.write_str(name);
1741 if !item.is_primitive() && !item.is_keyword() {
1742 let cur = &cx.current;
1743 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1744 for (i, component) in cur.iter().enumerate().take(amt) {
1747 "<a href=\"{}index.html\">{}</a>::<wbr>",
1748 "../".repeat(cur.len() - i - 1),
1753 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1755 buf.write_str("</span>"); // in-band
1756 buf.write_str("<span class=\"out-of-band\">");
1757 render_stability_since_raw(
1759 item.stable_since(cx.tcx()).as_deref(),
1760 item.const_stable_since(cx.tcx()).as_deref(),
1765 "<span id=\"render-detail\">\
1766 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1767 title=\"collapse all docs\">\
1768 [<span class=\"inner\">−</span>]\
1775 // When this item is part of a `crate use` in a downstream crate, the
1776 // [src] link in the downstream documentation will actually come back to
1777 // this page, and this link will be auto-clicked. The `id` attribute is
1778 // used to find the link to auto-click.
1779 if cx.shared.include_sources && !item.is_primitive() {
1780 write_srclink(cx, item, buf);
1783 buf.write_str("</span></h1>"); // out-of-band
1786 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1787 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1788 item_function(buf, cx, item, f)
1790 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
1791 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
1792 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
1793 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
1794 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t),
1795 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1796 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1797 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
1798 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1799 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1800 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
1801 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1802 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
1803 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
1805 // We don't generate pages for any other type.
1811 fn item_path(ty: ItemType, name: &str) -> String {
1813 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1814 _ => format!("{}.{}.html", ty, name),
1818 fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1819 let mut s = cx.current.join("::");
1821 s.push_str(&item.name.unwrap().as_str());
1825 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
1826 if let Some(ref name) = item.name {
1827 info!("Documenting {}", name);
1829 document_item_info(w, cx, item, false, parent);
1830 document_full(w, item, cx, "", false);
1833 /// Render md_text as markdown.
1838 links: Vec<RenderedLink>,
1842 let mut ids = cx.id_map.borrow_mut();
1845 "<div class=\"docblock{}\">{}{}</div>",
1846 if is_hidden { " hidden" } else { "" },
1854 &cx.shared.playground
1860 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1861 /// docs are longer, a "Read more" link is appended to the end.
1866 link: AssocItemLink<'_>,
1869 parent: Option<&clean::Item>,
1870 show_def_docs: bool,
1872 document_item_info(w, cx, item, is_hidden, parent);
1876 if let Some(s) = item.doc_value() {
1877 let mut summary_html = MarkdownSummaryLine(&s, &item.links(&cx.cache)).into_string();
1879 if s.contains('\n') {
1881 format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx.cache()));
1883 if let Some(idx) = summary_html.rfind("</p>") {
1884 summary_html.insert_str(idx, &link);
1886 summary_html.push_str(&link);
1892 "<div class='docblock{}'>{}{}</div>",
1893 if is_hidden { " hidden" } else { "" },
1897 } else if !prefix.is_empty() {
1900 "<div class=\"docblock{}\">{}</div>",
1901 if is_hidden { " hidden" } else { "" },
1914 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1915 debug!("Doc block: =====\n{}\n=====", s);
1916 render_markdown(w, cx, &*s, item.links(&cx.cache), prefix, is_hidden);
1917 } else if !prefix.is_empty() {
1919 w.write_str("<div class=\"docblock hidden\">");
1921 w.write_str("<div class=\"docblock\">");
1923 w.write_str(prefix);
1924 w.write_str("</div>");
1928 /// Add extra information about an item such as:
1932 /// * Required features (through the `doc_cfg` feature)
1933 fn document_item_info(
1938 parent: Option<&clean::Item>,
1940 let item_infos = short_item_info(item, cx, parent);
1941 if !item_infos.is_empty() {
1943 w.write_str("<div class=\"item-info hidden\">");
1945 w.write_str("<div class=\"item-info\">");
1947 for info in item_infos {
1950 w.write_str("</div>");
1954 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1955 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1958 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1959 if item.is_non_exhaustive() {
1960 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1961 if item.is_struct() {
1963 } else if item.is_enum() {
1965 } else if item.is_variant() {
1972 if item.is_struct() {
1974 "Non-exhaustive structs could have additional fields added in future. \
1975 Therefore, non-exhaustive structs cannot be constructed in external crates \
1976 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1977 matched against without a wildcard <code>..</code>; and \
1978 struct update syntax will not work.",
1980 } else if item.is_enum() {
1982 "Non-exhaustive enums could have additional variants added in future. \
1983 Therefore, when matching against variants of non-exhaustive enums, an \
1984 extra wildcard arm must be added to account for any future variants.",
1986 } else if item.is_variant() {
1988 "Non-exhaustive enum variants could have additional fields added in future. \
1989 Therefore, non-exhaustive enum variants cannot be constructed in external \
1990 crates and cannot be matched against.",
1994 "This type will require a wildcard arm in any match statements or constructors.",
1998 w.write_str("</div>");
2002 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
2003 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
2004 /// Takes a non-numeric and a numeric part from the given &str.
2005 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
2006 let i = s.find(|c: char| c.is_ascii_digit());
2007 let (a, b) = s.split_at(i.unwrap_or(s.len()));
2008 let i = b.find(|c: char| !c.is_ascii_digit());
2009 let (b, c) = b.split_at(i.unwrap_or(b.len()));
2014 while !lhs.is_empty() || !rhs.is_empty() {
2015 let (la, lb) = take_parts(&mut lhs);
2016 let (ra, rb) = take_parts(&mut rhs);
2017 // First process the non-numeric part.
2019 Ordering::Equal => (),
2022 // Then process the numeric part, if both sides have one (and they fit in a u64).
2023 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2025 Ordering::Equal => (),
2029 // Then process the numeric part again, but this time as strings.
2031 Ordering::Equal => (),
2039 fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) {
2040 document(w, cx, item, None);
2042 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2044 // the order of item types in the listing
2045 fn reorder(ty: ItemType) -> u8 {
2047 ItemType::ExternCrate => 0,
2048 ItemType::Import => 1,
2049 ItemType::Primitive => 2,
2050 ItemType::Module => 3,
2051 ItemType::Macro => 4,
2052 ItemType::Struct => 5,
2053 ItemType::Enum => 6,
2054 ItemType::Constant => 7,
2055 ItemType::Static => 8,
2056 ItemType::Trait => 9,
2057 ItemType::Function => 10,
2058 ItemType::Typedef => 12,
2059 ItemType::Union => 13,
2071 let ty1 = i1.type_();
2072 let ty2 = i2.type_();
2074 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2076 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
2077 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
2078 if let (Some(a), Some(b)) = (s1, s2) {
2079 match (a.is_stable(), b.is_stable()) {
2080 (true, true) | (false, false) => {}
2081 (false, true) => return Ordering::Less,
2082 (true, false) => return Ordering::Greater,
2085 let lhs = i1.name.unwrap_or(kw::Empty).as_str();
2086 let rhs = i2.name.unwrap_or(kw::Empty).as_str();
2087 compare_names(&lhs, &rhs)
2090 if cx.shared.sort_modules_alphabetically {
2091 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
2093 // This call is to remove re-export duplicates in cases such as:
2098 // crate trait Double { fn foo(); }
2102 // crate use foo::bar::*;
2103 // crate use foo::*;
2106 // `Double` will appear twice in the generated docs.
2108 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2109 // can be identical even if the elements are different (mostly in imports).
2110 // So in case this is an import, we keep everything by adding a "unique id"
2111 // (which is the position in the vector).
2112 indices.dedup_by_key(|i| {
2115 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2117 if items[*i].is_import() { *i } else { 0 },
2121 debug!("{:?}", indices);
2122 let mut curty = None;
2123 for &idx in &indices {
2124 let myitem = &items[idx];
2125 if myitem.is_stripped() {
2129 let myty = Some(myitem.type_());
2130 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2131 // Put `extern crate` and `use` re-exports in the same section.
2133 } else if myty != curty {
2134 if curty.is_some() {
2135 w.write_str("</table>");
2138 let (short, name) = item_ty_to_strs(&myty.unwrap());
2141 "<h2 id=\"{id}\" class=\"section-header\">\
2142 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2143 id = cx.derive_id(short.to_owned()),
2148 match *myitem.kind {
2149 clean::ExternCrateItem(ref name, ref src) => {
2150 use crate::html::format::anchor;
2153 Some(ref src) => write!(
2155 "<tr><td><code>{}extern crate {} as {};",
2156 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2157 anchor(myitem.def_id, &*src.as_str(), cx.cache()),
2162 "<tr><td><code>{}extern crate {};",
2163 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2164 anchor(myitem.def_id, &*name.as_str(), cx.cache())
2167 w.write_str("</code></td></tr>");
2170 clean::ImportItem(ref import) => {
2173 "<tr><td><code>{}{}</code></td></tr>",
2174 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2175 import.print(cx.cache())
2180 if myitem.name.is_none() {
2184 let unsafety_flag = match *myitem.kind {
2185 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2186 if func.header.unsafety == hir::Unsafety::Unsafe =>
2188 "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2193 let stab = myitem.stability_class(cx.tcx());
2194 let add = if stab.is_some() { " " } else { "" };
2196 let doc_value = myitem.doc_value().unwrap_or_default();
2199 "<tr class=\"{stab}{add}module-item\">\
2200 <td><a class=\"{class}\" href=\"{href}\" \
2201 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2202 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2204 name = *myitem.name.as_ref().unwrap(),
2205 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
2206 docs = MarkdownSummaryLine(&doc_value, &myitem.links(&cx.cache)).into_string(),
2207 class = myitem.type_(),
2209 stab = stab.unwrap_or_else(String::new),
2210 unsafety_flag = unsafety_flag,
2211 href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()),
2212 title = [full_path(cx, myitem), myitem.type_().to_string()]
2214 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2215 .collect::<Vec<_>>()
2222 if curty.is_some() {
2223 w.write_str("</table>");
2227 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
2228 /// at the module level.
2229 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
2230 let mut tags = String::new();
2232 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2233 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2236 // The trailing space after each tag is to space it properly against the rest of the docs.
2237 if let Some(depr) = &item.deprecation(tcx) {
2238 let mut message = "Deprecated";
2239 if !stability::deprecation_in_effect(
2240 depr.is_since_rustc_version,
2241 depr.since.map(|s| s.as_str()).as_deref(),
2243 message = "Deprecation planned";
2245 tags += &tag_html("deprecated", "", message);
2248 // The "rustc_private" crates are permanently unstable so it makes no sense
2249 // to render "unstable" everywhere.
2253 .map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2256 tags += &tag_html("unstable", "", "Experimental");
2259 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2260 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2261 (cfg, _) => cfg.as_deref().cloned(),
2264 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2265 if let Some(ref cfg) = cfg {
2266 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2272 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2273 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2274 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2275 (cfg, _) => cfg.as_deref().cloned(),
2279 "Portability {:?} - {:?} = {:?}",
2281 parent.and_then(|p| p.attrs.cfg.as_ref()),
2285 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2288 /// Render the stability, deprecation and portability information that is displayed at the top of
2289 /// the item's documentation.
2293 parent: Option<&clean::Item>,
2295 let mut extra_info = vec![];
2296 let error_codes = cx.shared.codes;
2298 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
2299 item.deprecation(cx.tcx())
2301 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2302 // but only display the future-deprecation messages for #[rustc_deprecated].
2303 let mut message = if let Some(since) = since {
2304 let since = &since.as_str();
2305 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2306 if *since == "TBD" {
2307 String::from("Deprecating in a future Rust version")
2309 format!("Deprecating in {}", Escape(since))
2312 format!("Deprecated since {}", Escape(since))
2315 String::from("Deprecated")
2318 if let Some(note) = note {
2319 let note = note.as_str();
2320 let mut ids = cx.id_map.borrow_mut();
2321 let html = MarkdownHtml(
2326 &cx.shared.playground,
2328 message.push_str(&format!(": {}", html.into_string()));
2330 extra_info.push(format!(
2331 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2336 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2337 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2338 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2339 .stability(cx.tcx())
2341 .filter(|stab| stab.feature != sym::rustc_private)
2342 .map(|stab| (stab.level, stab.feature))
2345 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2347 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2348 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2349 feature.push_str(&format!(
2350 " <a href=\"{url}{issue}\">#{issue}</a>",
2356 message.push_str(&format!(" ({})", feature));
2358 if let Some(unstable_reason) = reason {
2359 let mut ids = cx.id_map.borrow_mut();
2361 "<details><summary>{}</summary>{}</details>",
2364 &unstable_reason.as_str(),
2368 &cx.shared.playground,
2374 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2377 if let Some(portability) = portability(item, parent) {
2378 extra_info.push(portability);
2384 fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) {
2385 w.write_str("<pre class=\"rust const\">");
2386 render_attributes(w, it, false);
2390 "{vis}const {name}: {typ}",
2391 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2392 name = it.name.as_ref().unwrap(),
2393 typ = c.type_.print(cx.cache()),
2396 if c.value.is_some() || c.is_literal {
2397 write!(w, " = {expr};", expr = Escape(&c.expr));
2402 if let Some(value) = &c.value {
2404 let value_lowercase = value.to_lowercase();
2405 let expr_lowercase = c.expr.to_lowercase();
2407 if value_lowercase != expr_lowercase
2408 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2410 write!(w, " // {value}", value = Escape(value));
2415 w.write_str("</pre>");
2416 document(w, cx, it, None)
2419 fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
2420 w.write_str("<pre class=\"rust static\">");
2421 render_attributes(w, it, false);
2424 "{vis}static {mutability}{name}: {typ}</pre>",
2425 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2426 mutability = s.mutability.print_with_space(),
2427 name = it.name.as_ref().unwrap(),
2428 typ = s.type_.print(cx.cache())
2430 document(w, cx, it, None)
2433 fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
2434 let header_len = format!(
2435 "{}{}{}{}{:#}fn {}{:#}",
2436 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2437 f.header.constness.print_with_space(),
2438 f.header.asyncness.print_with_space(),
2439 f.header.unsafety.print_with_space(),
2440 print_abi_with_space(f.header.abi),
2441 it.name.as_ref().unwrap(),
2442 f.generics.print(cx.cache())
2445 w.write_str("<pre class=\"rust fn\">");
2446 render_attributes(w, it, false);
2449 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2450 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2451 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2452 constness = f.header.constness.print_with_space(),
2453 asyncness = f.header.asyncness.print_with_space(),
2454 unsafety = f.header.unsafety.print_with_space(),
2455 abi = print_abi_with_space(f.header.abi),
2456 name = it.name.as_ref().unwrap(),
2457 generics = f.generics.print(cx.cache()),
2459 WhereClause { gens: &f.generics, indent: 0, end_newline: true }.print(cx.cache()),
2460 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2462 spotlight = spotlight_decl(&f.decl, cx.cache()),
2464 document(w, cx, it, None)
2467 fn render_implementor(
2470 trait_: &clean::Item,
2472 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
2475 // If there's already another implementor that has the same abbridged name, use the
2476 // full path, for example in `std::iter::ExactSizeIterator`
2477 let use_absolute = match implementor.inner_impl().for_ {
2478 clean::ResolvedPath { ref path, is_generic: false, .. }
2479 | clean::BorrowedRef {
2480 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2482 } => implementor_dups[&path.last()].1,
2490 AssocItemLink::Anchor(None),
2492 trait_.stable_since(cx.tcx()).as_deref(),
2493 trait_.const_stable_since(cx.tcx()).as_deref(),
2506 containing_item: &clean::Item,
2508 let mut impls = traits
2511 let did = i.trait_did_full(cx.cache()).unwrap();
2512 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2513 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2521 containing_item.stable_since(cx.tcx()).as_deref(),
2522 containing_item.const_stable_since(cx.tcx()).as_deref(),
2531 .collect::<Vec<_>>();
2533 w.write_str(&impls.join(""));
2536 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cache: &Cache) -> String {
2537 let mut bounds = String::new();
2538 if !t_bounds.is_empty() {
2540 bounds.push_str(": ");
2542 for (i, p) in t_bounds.iter().enumerate() {
2544 bounds.push_str(" + ");
2546 bounds.push_str(&p.print(cache).to_string());
2552 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cache: &Cache) -> Ordering {
2553 let lhs = format!("{}", lhs.inner_impl().print(cache));
2554 let rhs = format!("{}", rhs.inner_impl().print(cache));
2556 // lhs and rhs are formatted as HTML, which may be unnecessary
2557 compare_names(&lhs, &rhs)
2560 fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) {
2561 let bounds = bounds(&t.bounds, false, cx.cache());
2562 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2563 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2564 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2565 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2567 // Output the trait definition
2568 wrap_into_docblock(w, |w| {
2569 w.write_str("<pre class=\"rust trait\">");
2570 render_attributes(w, it, true);
2573 "{}{}{}trait {}{}{}",
2574 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2575 t.unsafety.print_with_space(),
2576 if t.is_auto { "auto " } else { "" },
2577 it.name.as_ref().unwrap(),
2578 t.generics.print(cx.cache()),
2582 if !t.generics.where_predicates.is_empty() {
2583 let where_ = WhereClause { gens: &t.generics, indent: 0, end_newline: true };
2584 write!(w, "{}", where_.print(cx.cache()));
2589 if t.items.is_empty() {
2592 // FIXME: we should be using a derived_id for the Anchors here
2595 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2598 if !types.is_empty() && !consts.is_empty() {
2602 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2605 if !consts.is_empty() && !required.is_empty() {
2608 for (pos, m) in required.iter().enumerate() {
2609 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2612 if pos < required.len() - 1 {
2613 w.write_str("<div class=\"item-spacer\"></div>");
2616 if !required.is_empty() && !provided.is_empty() {
2619 for (pos, m) in provided.iter().enumerate() {
2620 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2622 clean::MethodItem(ref inner, _)
2623 if !inner.generics.where_predicates.is_empty() =>
2625 w.write_str(",\n { ... }\n");
2628 w.write_str(" { ... }\n");
2631 if pos < provided.len() - 1 {
2632 w.write_str("<div class=\"item-spacer\"></div>");
2637 w.write_str("</pre>")
2640 // Trait documentation
2641 document(w, cx, it, None);
2643 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2646 "<h2 id=\"{0}\" class=\"small-section-header\">\
2647 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2649 id, title, extra_content
2653 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2654 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2657 fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item) {
2658 let name = m.name.as_ref().unwrap();
2659 info!("Documenting {} on {:?}", name, t.name);
2660 let item_type = m.type_();
2661 let id = cx.derive_id(format!("{}.{}", item_type, name));
2662 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2663 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl, cx);
2664 w.write_str("</code>");
2665 render_stability_since(w, m, t, cx.tcx());
2666 write_srclink(cx, m, w);
2667 w.write_str("</h3>");
2668 document(w, cx, m, Some(t));
2671 if !types.is_empty() {
2672 write_small_section_header(
2676 "<div class=\"methods\">",
2679 trait_item(w, cx, t, it);
2681 write_loading_content(w, "</div>");
2684 if !consts.is_empty() {
2685 write_small_section_header(
2688 "Associated Constants",
2689 "<div class=\"methods\">",
2692 trait_item(w, cx, t, it);
2694 write_loading_content(w, "</div>");
2697 // Output the documentation for each function individually
2698 if !required.is_empty() {
2699 write_small_section_header(
2703 "<div class=\"methods\">",
2706 trait_item(w, cx, m, it);
2708 write_loading_content(w, "</div>");
2710 if !provided.is_empty() {
2711 write_small_section_header(
2715 "<div class=\"methods\">",
2718 trait_item(w, cx, m, it);
2720 write_loading_content(w, "</div>");
2723 // If there are methods directly on this trait object, render them here.
2724 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All);
2726 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2727 // The DefId is for the first Type found with that name. The bool is
2728 // if any Types with the same name but different DefId have been found.
2729 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
2730 for implementor in implementors {
2731 match implementor.inner_impl().for_ {
2732 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2733 | clean::BorrowedRef {
2734 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2737 let &mut (prev_did, ref mut has_duplicates) =
2738 implementor_dups.entry(path.last()).or_insert((did, false));
2739 if prev_did != did {
2740 *has_duplicates = true;
2747 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2750 .def_id_full(cx.cache())
2751 .map_or(true, |d| cx.cache.paths.contains_key(&d))
2754 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2755 local.iter().partition(|i| i.inner_impl().synthetic);
2757 synthetic.sort_by(|a, b| compare_impl(a, b, cx.cache()));
2758 concrete.sort_by(|a, b| compare_impl(a, b, cx.cache()));
2760 if !foreign.is_empty() {
2761 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2763 for implementor in foreign {
2764 let assoc_link = AssocItemLink::GotoSource(
2765 implementor.impl_item.def_id,
2766 &implementor.inner_impl().provided_trait_methods,
2775 implementor.impl_item.stable_since(cx.tcx()).as_deref(),
2776 implementor.impl_item.const_stable_since(cx.tcx()).as_deref(),
2784 write_loading_content(w, "");
2787 write_small_section_header(
2791 "<div class=\"item-list\" id=\"implementors-list\">",
2793 for implementor in concrete {
2794 render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
2796 write_loading_content(w, "</div>");
2799 write_small_section_header(
2801 "synthetic-implementors",
2802 "Auto implementors",
2803 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2805 for implementor in synthetic {
2812 &collect_paths_for_type(implementor.inner_impl().for_.clone(), &cx.cache),
2815 write_loading_content(w, "</div>");
2818 // even without any implementations to write in, we still want the heading and list, so the
2819 // implementors javascript file pulled in below has somewhere to write the impls into
2820 write_small_section_header(
2824 "<div class=\"item-list\" id=\"implementors-list\">",
2826 write_loading_content(w, "</div>");
2829 write_small_section_header(
2831 "synthetic-implementors",
2832 "Auto implementors",
2833 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2835 write_loading_content(w, "</div>");
2841 "<script type=\"text/javascript\" \
2842 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2844 root_path = vec![".."; cx.current.len()].join("/"),
2845 path = if it.def_id.is_local() {
2846 cx.current.join("/")
2848 let (ref path, _) = cx.cache.external_paths[&it.def_id];
2849 path[..path.len() - 1].join("/")
2852 name = *it.name.as_ref().unwrap()
2856 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cache: &Cache) -> String {
2857 use crate::formats::item_type::ItemType::*;
2859 let name = it.name.as_ref().unwrap();
2860 let ty = match it.type_() {
2861 Typedef | AssocType => AssocType,
2865 let anchor = format!("#{}.{}", ty, name);
2867 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2868 AssocItemLink::Anchor(None) => anchor,
2869 AssocItemLink::GotoSource(did, _) => {
2870 href(did, cache).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2879 _default: Option<&String>,
2880 link: AssocItemLink<'_>,
2886 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2888 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2889 naive_assoc_href(it, link, cx.cache()),
2890 it.name.as_ref().unwrap(),
2891 ty.print(cx.cache())
2898 bounds: &[clean::GenericBound],
2899 default: Option<&clean::Type>,
2900 link: AssocItemLink<'_>,
2906 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2908 naive_assoc_href(it, link, cache),
2909 it.name.as_ref().unwrap()
2911 if !bounds.is_empty() {
2912 write!(w, ": {}", print_generic_bounds(bounds, cache))
2914 if let Some(default) = default {
2915 write!(w, " = {}", default.print(cache))
2919 fn render_stability_since_raw(
2922 const_ver: Option<&str>,
2923 containing_ver: Option<&str>,
2924 containing_const_ver: Option<&str>,
2926 let ver = ver.filter(|inner| !inner.is_empty());
2927 let const_ver = const_ver.filter(|inner| !inner.is_empty());
2929 match (ver, const_ver) {
2930 (Some(v), Some(cv)) if const_ver != containing_const_ver => {
2933 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2937 (Some(v), _) if ver != containing_ver => {
2940 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2948 fn render_stability_since(
2951 containing_item: &clean::Item,
2954 render_stability_since_raw(
2956 item.stable_since(tcx).as_deref(),
2957 item.const_stable_since(tcx).as_deref(),
2958 containing_item.stable_since(tcx).as_deref(),
2959 containing_item.const_stable_since(tcx).as_deref(),
2963 fn render_assoc_item(
2966 link: AssocItemLink<'_>,
2973 header: hir::FnHeader,
2974 g: &clean::Generics,
2976 link: AssocItemLink<'_>,
2980 let name = meth.name.as_ref().unwrap();
2981 let anchor = format!("#{}.{}", meth.type_(), name);
2982 let href = match link {
2983 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2984 AssocItemLink::Anchor(None) => anchor,
2985 AssocItemLink::GotoSource(did, provided_methods) => {
2986 // We're creating a link from an impl-item to the corresponding
2987 // trait-item and need to map the anchored type accordingly.
2988 let ty = if provided_methods.contains(&name) {
2994 href(did, cx.cache()).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2997 let mut header_len = format!(
2998 "{}{}{}{}{}{:#}fn {}{:#}",
2999 meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
3000 header.constness.print_with_space(),
3001 header.asyncness.print_with_space(),
3002 header.unsafety.print_with_space(),
3003 print_default_space(meth.is_default()),
3004 print_abi_with_space(header.abi),
3009 let (indent, end_newline) = if parent == ItemType::Trait {
3015 render_attributes(w, meth, false);
3018 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
3019 {generics}{decl}{spotlight}{where_clause}",
3020 if parent == ItemType::Trait { " " } else { "" },
3021 meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
3022 header.constness.print_with_space(),
3023 header.asyncness.print_with_space(),
3024 header.unsafety.print_with_space(),
3025 print_default_space(meth.is_default()),
3026 print_abi_with_space(header.abi),
3029 generics = g.print(cx.cache()),
3030 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }
3032 spotlight = spotlight_decl(&d, cx.cache()),
3033 where_clause = WhereClause { gens: g, indent, end_newline }.print(cx.cache())
3037 clean::StrippedItem(..) => {}
3038 clean::TyMethodItem(ref m) => {
3039 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
3041 clean::MethodItem(ref m, _) => {
3042 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
3044 clean::AssocConstItem(ref ty, ref default) => assoc_const(
3050 if parent == ItemType::Trait { " " } else { "" },
3053 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3059 if parent == ItemType::Trait { " " } else { "" },
3062 _ => panic!("render_assoc_item called on non-associated-item"),
3066 fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) {
3067 wrap_into_docblock(w, |w| {
3068 w.write_str("<pre class=\"rust struct\">");
3069 render_attributes(w, it, true);
3070 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
3071 w.write_str("</pre>")
3074 document(w, cx, it, None);
3078 .filter_map(|f| match *f.kind {
3079 clean::StructFieldItem(ref ty) => Some((f, ty)),
3083 if let CtorKind::Fictive = s.struct_type {
3084 if fields.peek().is_some() {
3087 "<h2 id=\"fields\" class=\"fields small-section-header\">
3088 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3089 document_non_exhaustive_header(it)
3091 document_non_exhaustive(w, it);
3092 for (field, ty) in fields {
3093 let id = cx.derive_id(format!(
3095 ItemType::StructField,
3096 field.name.as_ref().unwrap()
3100 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3101 <a href=\"#{id}\" class=\"anchor field\"></a>\
3102 <code>{name}: {ty}</code>\
3104 item_type = ItemType::StructField,
3106 name = field.name.as_ref().unwrap(),
3107 ty = ty.print(cx.cache())
3109 document(w, cx, field, Some(it));
3113 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3116 fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
3117 wrap_into_docblock(w, |w| {
3118 w.write_str("<pre class=\"rust union\">");
3119 render_attributes(w, it, true);
3120 render_union(w, it, Some(&s.generics), &s.fields, "", true, cx);
3121 w.write_str("</pre>")
3124 document(w, cx, it, None);
3128 .filter_map(|f| match *f.kind {
3129 clean::StructFieldItem(ref ty) => Some((f, ty)),
3133 if fields.peek().is_some() {
3136 "<h2 id=\"fields\" class=\"fields small-section-header\">
3137 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3139 for (field, ty) in fields {
3140 let name = field.name.as_ref().expect("union field name");
3141 let id = format!("{}.{}", ItemType::StructField, name);
3144 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3145 <a href=\"#{id}\" class=\"anchor field\"></a>\
3146 <code>{name}: {ty}</code>\
3150 shortty = ItemType::StructField,
3151 ty = ty.print(cx.cache())
3153 if let Some(stability_class) = field.stability_class(cx.tcx()) {
3154 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3156 document(w, cx, field, Some(it));
3159 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3162 fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
3163 wrap_into_docblock(w, |w| {
3164 w.write_str("<pre class=\"rust enum\">");
3165 render_attributes(w, it, true);
3169 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3170 it.name.as_ref().unwrap(),
3171 e.generics.print(cx.cache()),
3172 WhereClause { gens: &e.generics, indent: 0, end_newline: true }.print(cx.cache())
3174 if e.variants.is_empty() && !e.variants_stripped {
3177 w.write_str(" {\n");
3178 for v in &e.variants {
3180 let name = v.name.as_ref().unwrap();
3182 clean::VariantItem(ref var) => match var {
3183 clean::Variant::CLike => write!(w, "{}", name),
3184 clean::Variant::Tuple(ref tys) => {
3185 write!(w, "{}(", name);
3186 for (i, ty) in tys.iter().enumerate() {
3188 w.write_str(", ")
3190 write!(w, "{}", ty.print(cx.cache()));
3194 clean::Variant::Struct(ref s) => {
3195 render_struct(w, v, None, s.struct_type, &s.fields, " ", false, cx);
3198 _ => unreachable!(),
3203 if e.variants_stripped {
3204 w.write_str(" // some variants omitted\n");
3208 w.write_str("</pre>")
3211 document(w, cx, it, None);
3212 if !e.variants.is_empty() {
3215 "<h2 id=\"variants\" class=\"variants small-section-header\">
3216 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3217 document_non_exhaustive_header(it)
3219 document_non_exhaustive(w, it);
3220 for variant in &e.variants {
3222 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3225 "<div id=\"{id}\" class=\"variant small-section-header\">\
3226 <a href=\"#{id}\" class=\"anchor field\"></a>\
3229 name = variant.name.as_ref().unwrap()
3231 if let clean::VariantItem(clean::Variant::Tuple(ref tys)) = *variant.kind {
3233 for (i, ty) in tys.iter().enumerate() {
3235 w.write_str(", ");
3237 write!(w, "{}", ty.print(cx.cache()));
3241 w.write_str("</code></div>");
3242 document(w, cx, variant, Some(it));
3243 document_non_exhaustive(w, variant);
3245 use crate::clean::Variant;
3246 if let clean::VariantItem(Variant::Struct(ref s)) = *variant.kind {
3247 let variant_id = cx.derive_id(format!(
3250 variant.name.as_ref().unwrap()
3252 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3255 "<h3>Fields of <b>{name}</b></h3><div>",
3256 name = variant.name.as_ref().unwrap()
3258 for field in &s.fields {
3259 use crate::clean::StructFieldItem;
3260 if let StructFieldItem(ref ty) = *field.kind {
3261 let id = cx.derive_id(format!(
3262 "variant.{}.field.{}",
3263 variant.name.as_ref().unwrap(),
3264 field.name.as_ref().unwrap()
3268 "<span id=\"{id}\" class=\"variant small-section-header\">\
3269 <a href=\"#{id}\" class=\"anchor field\"></a>\
3270 <code>{f}: {t}</code>\
3273 f = field.name.as_ref().unwrap(),
3274 t = ty.print(cx.cache())
3276 document(w, cx, field, Some(variant));
3279 w.write_str("</div></div>");
3281 render_stability_since(w, variant, it, cx.tcx());
3284 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3287 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3294 sym::non_exhaustive,
3297 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3298 // left padding. For example:
3300 // #[foo] <----- "top" attribute
3302 // #[bar] <---- not "top" attribute
3305 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3310 .filter_map(|attr| {
3311 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3312 Some(pprust::attribute_to_string(&attr))
3319 if !attrs.is_empty() {
3322 "<span class=\"docblock attributes{}\">{}</span>",
3323 if top { " top-attr" } else { "" },
3332 g: Option<&clean::Generics>,
3334 fields: &[clean::Item],
3342 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3343 if structhead { "struct " } else { "" },
3344 it.name.as_ref().unwrap()
3346 if let Some(g) = g {
3347 write!(w, "{}", g.print(cx.cache()))
3350 CtorKind::Fictive => {
3351 if let Some(g) = g {
3355 WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache())
3358 let mut has_visible_fields = false;
3360 for field in fields {
3361 if let clean::StructFieldItem(ref ty) = *field.kind {
3366 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3367 field.name.as_ref().unwrap(),
3368 ty.print(cx.cache())
3370 has_visible_fields = true;
3374 if has_visible_fields {
3375 if it.has_stripped_fields().unwrap() {
3376 write!(w, "\n{} // some fields omitted", tab);
3378 write!(w, "\n{}", tab);
3379 } else if it.has_stripped_fields().unwrap() {
3380 // If there are no visible fields we can just display
3381 // `{ /* fields omitted */ }` to save space.
3382 write!(w, " /* fields omitted */ ");
3388 for (i, field) in fields.iter().enumerate() {
3393 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3394 clean::StructFieldItem(ref ty) => {
3398 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3399 ty.print(cx.cache())
3402 _ => unreachable!(),
3406 if let Some(g) = g {
3410 WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache())
3415 CtorKind::Const => {
3416 // Needed for PhantomData.
3417 if let Some(g) = g {
3421 WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache())
3432 g: Option<&clean::Generics>,
3433 fields: &[clean::Item],
3441 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3442 if structhead { "union " } else { "" },
3443 it.name.as_ref().unwrap()
3445 if let Some(g) = g {
3446 write!(w, "{}", g.print(cx.cache()));
3447 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache()));
3450 write!(w, " {{\n{}", tab);
3451 for field in fields {
3452 if let clean::StructFieldItem(ref ty) = *field.kind {
3456 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3457 field.name.as_ref().unwrap(),
3458 ty.print(cx.cache()),
3464 if it.has_stripped_fields().unwrap() {
3465 write!(w, " // some fields omitted\n{}", tab);
3470 #[derive(Copy, Clone)]
3471 enum AssocItemLink<'a> {
3472 Anchor(Option<&'a str>),
3473 GotoSource(DefId, &'a FxHashSet<Symbol>),
3476 impl<'a> AssocItemLink<'a> {
3477 fn anchor(&self, id: &'a str) -> Self {
3479 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3480 ref other => *other,
3485 fn render_assoc_items(
3488 containing_item: &clean::Item,
3490 what: AssocItemRender<'_>,
3492 info!("Documenting associated items of {:?}", containing_item.name);
3493 let v = match cx.cache.impls.get(&it) {
3497 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3498 if !non_trait.is_empty() {
3499 let render_mode = match what {
3500 AssocItemRender::All => {
3502 "<h2 id=\"implementations\" class=\"small-section-header\">\
3503 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3508 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3509 let id = cx.derive_id(small_url_encode(format!(
3510 "deref-methods-{:#}",
3511 type_.print(cx.cache())
3513 debug!("Adding {} to deref id map", type_.print(cx.cache()));
3516 .insert(type_.def_id_full(cx.cache()).unwrap(), id.clone());
3519 "<h2 id=\"{id}\" class=\"small-section-header\">\
3520 Methods from {trait_}<Target = {type_}>\
3521 <a href=\"#{id}\" class=\"anchor\"></a>\
3524 trait_ = trait_.print(cx.cache()),
3525 type_ = type_.print(cx.cache()),
3527 RenderMode::ForDeref { mut_: deref_mut_ }
3530 for i in &non_trait {
3536 AssocItemLink::Anchor(None),
3538 containing_item.stable_since(cx.tcx()).as_deref(),
3539 containing_item.const_stable_since(cx.tcx()).as_deref(),
3548 if !traits.is_empty() {
3549 let deref_impl = traits
3551 .find(|t| t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did);
3552 if let Some(impl_) = deref_impl {
3553 let has_deref_mut = traits.iter().any(|t| {
3554 t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_mut_trait_did
3556 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
3559 // If we were already one level into rendering deref methods, we don't want to render
3560 // anything after recursing into any further deref methods above.
3561 if let AssocItemRender::DerefFor { .. } = what {
3565 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3566 traits.iter().partition(|t| t.inner_impl().synthetic);
3567 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3568 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3570 let mut impls = Buffer::empty_from(&w);
3571 render_impls(cx, &mut impls, &concrete, containing_item);
3572 let impls = impls.into_inner();
3573 if !impls.is_empty() {
3576 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3577 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3579 <div id=\"trait-implementations-list\">{}</div>",
3584 if !synthetic.is_empty() {
3586 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3587 Auto Trait Implementations\
3588 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3590 <div id=\"synthetic-implementations-list\">",
3592 render_impls(cx, w, &synthetic, containing_item);
3593 w.write_str("</div>");
3596 if !blanket_impl.is_empty() {
3598 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3599 Blanket Implementations\
3600 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3602 <div id=\"blanket-implementations-list\">",
3604 render_impls(cx, w, &blanket_impl, containing_item);
3605 w.write_str("</div>");
3610 fn render_deref_methods(
3614 container_item: &clean::Item,
3617 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3618 let (target, real_target) = impl_
3622 .find_map(|item| match *item.kind {
3623 clean::TypedefItem(ref t, true) => Some(match *t {
3624 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3625 _ => (&t.type_, &t.type_),
3629 .expect("Expected associated type binding");
3630 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
3632 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3633 if let Some(did) = target.def_id_full(cx.cache()) {
3634 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
3635 // `impl Deref<Target = S> for S`
3636 if did == type_did {
3637 // Avoid infinite cycles
3641 render_assoc_items(w, cx, container_item, did, what);
3643 if let Some(prim) = target.primitive_type() {
3644 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
3645 render_assoc_items(w, cx, container_item, did, what);
3651 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
3652 let self_type_opt = match *item.kind {
3653 clean::MethodItem(ref method, _) => method.decl.self_type(),
3654 clean::TyMethodItem(ref method) => method.decl.self_type(),
3658 if let Some(self_ty) = self_type_opt {
3659 let (by_mut_ref, by_box, by_value) = match self_ty {
3660 SelfTy::SelfBorrowed(_, mutability)
3661 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3662 (mutability == Mutability::Mut, false, false)
3664 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3665 (false, Some(did) == cache.owned_box_did, false)
3667 SelfTy::SelfValue => (false, false, true),
3668 _ => (false, false, false),
3671 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3677 fn spotlight_decl(decl: &clean::FnDecl, cache: &Cache) -> String {
3678 let mut out = Buffer::html();
3679 let mut trait_ = String::new();
3681 if let Some(did) = decl.output.def_id_full(cache) {
3682 if let Some(impls) = cache.impls.get(&did) {
3684 let impl_ = i.inner_impl();
3685 if impl_.trait_.def_id_full(cache).map_or(false, |d| cache.traits[&d].is_spotlight)
3690 "<h3 class=\"notable\">Notable traits for {}</h3>\
3691 <code class=\"content\">",
3692 impl_.for_.print(cache)
3694 trait_.push_str(&impl_.for_.print(cache).to_string());
3697 //use the "where" class here to make it small
3700 "<span class=\"where fmt-newline\">{}</span>",
3703 let t_did = impl_.trait_.def_id_full(cache).unwrap();
3704 for it in &impl_.items {
3705 if let clean::TypedefItem(ref tydef, _) = *it.kind {
3706 out.push_str("<span class=\"where fmt-newline\"> ");
3712 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3716 out.push_str(";</span>");
3724 if !out.is_empty() {
3727 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3728 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3730 out.push_str("</code></span></div></span></span>");
3740 parent: &clean::Item,
3741 link: AssocItemLink<'_>,
3742 render_mode: RenderMode,
3743 outer_version: Option<&str>,
3744 outer_const_version: Option<&str>,
3745 show_def_docs: bool,
3746 use_absolute: Option<bool>,
3747 is_on_foreign_type: bool,
3748 show_default_items: bool,
3749 // This argument is used to reference same type with different paths to avoid duplication
3750 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3753 let traits = &cx.cache.traits;
3754 let trait_ = i.trait_did_full(cx.cache()).map(|did| &traits[&did]);
3756 if render_mode == RenderMode::Normal {
3757 let id = cx.derive_id(match i.inner_impl().trait_ {
3759 if is_on_foreign_type {
3760 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx.cache())
3762 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx.cache()))))
3765 None => "impl".to_string(),
3767 let aliases = if aliases.is_empty() {
3770 format!(" aliases=\"{}\"", aliases.join(","))
3772 if let Some(use_absolute) = use_absolute {
3773 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3774 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute, cx.cache());
3776 for it in &i.inner_impl().items {
3777 if let clean::TypedefItem(ref tydef, _) = *it.kind {
3778 w.write_str("<span class=\"where fmt-newline\"> ");
3784 AssocItemLink::Anchor(None),
3788 w.write_str(";</span>");
3792 w.write_str("</code>");
3796 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3799 i.inner_impl().print(cx.cache())
3802 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3803 render_stability_since_raw(
3805 i.impl_item.stable_since(cx.tcx()).as_deref(),
3806 i.impl_item.const_stable_since(cx.tcx()).as_deref(),
3808 outer_const_version,
3810 write_srclink(cx, &i.impl_item, w);
3811 w.write_str("</h3>");
3813 if trait_.is_some() {
3814 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3815 write!(w, "<div class=\"item-info\">{}</div>", portability);
3819 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3820 let mut ids = cx.id_map.borrow_mut();
3823 "<div class=\"docblock\">{}</div>",
3826 &i.impl_item.links(&cx.cache),
3830 &cx.shared.playground
3841 parent: &clean::Item,
3842 link: AssocItemLink<'_>,
3843 render_mode: RenderMode,
3844 is_default_item: bool,
3845 outer_version: Option<&str>,
3846 outer_const_version: Option<&str>,
3847 trait_: Option<&clean::Trait>,
3848 show_def_docs: bool,
3850 let item_type = item.type_();
3851 let name = item.name.as_ref().unwrap();
3853 let render_method_item = match render_mode {
3854 RenderMode::Normal => true,
3855 RenderMode::ForDeref { mut_: deref_mut_ } => {
3856 should_render_item(&item, deref_mut_, &cx.cache)
3860 let (is_hidden, extra_class) =
3861 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3869 clean::MethodItem(..) | clean::TyMethodItem(_) => {
3870 // Only render when the method is not static or we allow static methods
3871 if render_method_item {
3872 let id = cx.derive_id(format!("{}.{}", item_type, name));
3873 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3874 w.write_str("<code>");
3875 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx);
3876 w.write_str("</code>");
3877 render_stability_since_raw(
3879 item.stable_since(cx.tcx()).as_deref(),
3880 item.const_stable_since(cx.tcx()).as_deref(),
3882 outer_const_version,
3884 write_srclink(cx, item, w);
3885 w.write_str("</h4>");
3888 clean::TypedefItem(ref tydef, _) => {
3889 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3890 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3900 w.write_str("</code></h4>");
3902 clean::AssocConstItem(ref ty, ref default) => {
3903 let id = cx.derive_id(format!("{}.{}", item_type, name));
3904 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3905 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "", cx);
3906 w.write_str("</code>");
3907 render_stability_since_raw(
3909 item.stable_since(cx.tcx()).as_deref(),
3910 item.const_stable_since(cx.tcx()).as_deref(),
3912 outer_const_version,
3914 write_srclink(cx, item, w);
3915 w.write_str("</h4>");
3917 clean::AssocTypeItem(ref bounds, ref default) => {
3918 let id = cx.derive_id(format!("{}.{}", item_type, name));
3919 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3920 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "", cx.cache());
3921 w.write_str("</code></h4>");
3923 clean::StrippedItem(..) => return,
3924 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3927 if render_method_item {
3928 if !is_default_item {
3929 if let Some(t) = trait_ {
3930 // The trait item may have been stripped so we might not
3931 // find any documentation or stability for it.
3932 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3933 // We need the stability of the item from the trait
3934 // because impls can't have a stability.
3935 if item.doc_value().is_some() {
3936 document_item_info(w, cx, it, is_hidden, Some(parent));
3937 document_full(w, item, cx, "", is_hidden);
3939 // In case the item isn't documented,
3940 // provide short documentation from the trait.
3954 document_item_info(w, cx, item, is_hidden, Some(parent));
3956 document_full(w, item, cx, "", is_hidden);
3960 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3965 w.write_str("<div class=\"impl-items\">");
3966 for trait_item in &i.inner_impl().items {
3971 if trait_.is_some() { &i.impl_item } else { parent },
3976 outer_const_version,
3982 fn render_default_items(
3987 parent: &clean::Item,
3988 render_mode: RenderMode,
3989 outer_version: Option<&str>,
3990 outer_const_version: Option<&str>,
3991 show_def_docs: bool,
3993 for trait_item in &t.items {
3994 let n = trait_item.name;
3995 if i.items.iter().any(|m| m.name == n) {
3998 let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
3999 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4010 outer_const_version,
4017 // If we've implemented a trait, then also emit documentation for all
4018 // default items which weren't overridden in the implementation block.
4019 // We don't emit documentation for default items if they appear in the
4020 // Implementations on Foreign Types or Implementors sections.
4021 if show_default_items {
4022 if let Some(t) = trait_ {
4023 render_default_items(
4031 outer_const_version,
4036 w.write_str("</div>");
4039 fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
4040 w.write_str("<pre class=\"rust opaque\">");
4041 render_attributes(w, it, false);
4044 "type {}{}{where_clause} = impl {bounds};</pre>",
4045 it.name.as_ref().unwrap(),
4046 t.generics.print(cx.cache()),
4048 WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4049 bounds = bounds(&t.bounds, false, cx.cache())
4052 document(w, cx, it, None);
4054 // Render any items associated directly to this alias, as otherwise they
4055 // won't be visible anywhere in the docs. It would be nice to also show
4056 // associated items from the aliased type (see discussion in #32077), but
4057 // we need #14072 to make sense of the generics.
4058 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4061 fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
4062 w.write_str("<pre class=\"rust trait-alias\">");
4063 render_attributes(w, it, false);
4066 "trait {}{}{} = {};</pre>",
4067 it.name.as_ref().unwrap(),
4068 t.generics.print(cx.cache()),
4069 WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4070 bounds(&t.bounds, true, cx.cache())
4073 document(w, cx, it, None);
4075 // Render any items associated directly to this alias, as otherwise they
4076 // won't be visible anywhere in the docs. It would be nice to also show
4077 // associated items from the aliased type (see discussion in #32077), but
4078 // we need #14072 to make sense of the generics.
4079 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4082 fn item_typedef(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
4083 w.write_str("<pre class=\"rust typedef\">");
4084 render_attributes(w, it, false);
4087 "type {}{}{where_clause} = {type_};</pre>",
4088 it.name.as_ref().unwrap(),
4089 t.generics.print(cx.cache()),
4091 WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4092 type_ = t.type_.print(cx.cache())
4095 document(w, cx, it, None);
4097 // Render any items associated directly to this alias, as otherwise they
4098 // won't be visible anywhere in the docs. It would be nice to also show
4099 // associated items from the aliased type (see discussion in #32077), but
4100 // we need #14072 to make sense of the generics.
4101 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4104 fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4105 w.write_str("<pre class=\"rust foreigntype\">extern {\n");
4106 render_attributes(w, it, false);
4109 " {}type {};\n}}</pre>",
4110 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
4111 it.name.as_ref().unwrap(),
4114 document(w, cx, it, None);
4116 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4119 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
4120 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4124 || it.is_primitive()
4132 "<p class=\"location\">{}{}</p>",
4134 clean::StructItem(..) => "Struct ",
4135 clean::TraitItem(..) => "Trait ",
4136 clean::PrimitiveItem(..) => "Primitive Type ",
4137 clean::UnionItem(..) => "Union ",
4138 clean::EnumItem(..) => "Enum ",
4139 clean::TypedefItem(..) => "Type Definition ",
4140 clean::ForeignTypeItem => "Foreign Type ",
4141 clean::ModuleItem(..) =>
4149 it.name.as_ref().unwrap()
4154 if let Some(ref version) = cx.cache.crate_version {
4157 "<div class=\"block version\">\
4165 buffer.write_str("<div class=\"sidebar-elems\">");
4169 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4170 it.name.as_ref().expect("crates always have a name")
4174 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
4175 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
4176 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
4177 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
4178 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
4179 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
4180 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4181 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
4185 // The sidebar is designed to display sibling functions, modules and
4186 // other miscellaneous information. since there are lots of sibling
4187 // items (and that causes quadratic growth in large modules),
4188 // we refactor common parts into a shared JavaScript file per module.
4189 // still, we don't move everything into JS because we want to preserve
4190 // as much HTML as possible in order to allow non-JS-enabled browsers
4191 // to navigate the documentation (though slightly inefficiently).
4193 buffer.write_str("<p class=\"location\">");
4194 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4196 buffer.write_str("::<wbr>");
4200 "<a href=\"{}index.html\">{}</a>",
4201 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4205 buffer.write_str("</p>");
4207 // Sidebar refers to the enclosing module, not this module.
4208 let relpath = if it.is_mod() { "../" } else { "" };
4211 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
4213 name = it.name.unwrap_or(kw::Empty),
4218 // There is no sidebar-items.js beyond the crate root path
4219 // FIXME maybe dynamic crate loading can be merged here
4221 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4223 // Closes sidebar-elems div.
4224 buffer.write_str("</div>");
4227 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4228 if used_links.insert(url.clone()) {
4232 while !used_links.insert(format!("{}-{}", url, add)) {
4235 format!("{}-{}", url, add)
4241 used_links: &mut FxHashSet<String>,
4247 .filter_map(|item| match item.name {
4248 Some(ref name) if !name.is_empty() && item.is_method() => {
4249 if !for_deref || should_render_item(item, deref_mut, cache) {
4251 "<a href=\"#{}\">{}</a>",
4252 get_next_url(used_links, format!("method.{}", name)),
4261 .collect::<Vec<_>>()
4264 // The point is to url encode any potential character from a type with genericity.
4265 fn small_url_encode(s: String) -> String {
4266 let mut st = String::new();
4267 let mut last_match = 0;
4268 for (idx, c) in s.char_indices() {
4269 let escaped = match c {
4285 st += &s[last_match..idx];
4287 // NOTE: we only expect single byte characters here - which is fine as long as we
4288 // only match single byte characters
4289 last_match = idx + 1;
4292 if last_match != 0 {
4293 st += &s[last_match..];
4300 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
4301 if let Some(v) = cx.cache.impls.get(&it.def_id) {
4302 let mut used_links = FxHashSet::default();
4305 let used_links_bor = &mut used_links;
4308 .filter(|i| i.inner_impl().trait_.is_none())
4309 .flat_map(move |i| {
4310 get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
4312 .collect::<Vec<_>>();
4313 if !ret.is_empty() {
4314 // We want links' order to be reproducible so we don't use unstable sort.
4318 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4319 <div class=\"sidebar-links\">",
4322 out.push_str(&line);
4324 out.push_str("</div>");
4328 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4329 if let Some(impl_) = v
4331 .filter(|i| i.inner_impl().trait_.is_some())
4332 .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did)
4334 sidebar_deref_methods(cx, out, impl_, v);
4336 let format_impls = |impls: Vec<&Impl>| {
4337 let mut links = FxHashSet::default();
4342 if let Some(ref i) = it.inner_impl().trait_ {
4343 let i_display = format!("{:#}", i.print(cx.cache()));
4344 let out = Escape(&i_display);
4345 let encoded = small_url_encode(format!("{:#}", i.print(cx.cache())));
4346 let generated = format!(
4347 "<a href=\"#impl-{}\">{}{}</a>",
4349 if it.inner_impl().negative_polarity { "!" } else { "" },
4352 if links.insert(generated.clone()) { Some(generated) } else { None }
4357 .collect::<Vec<String>>();
4362 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
4363 out.push_str("<div class=\"sidebar-links\">");
4365 out.push_str(&link);
4367 out.push_str("</div>");
4370 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4371 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4372 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4374 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4376 let concrete_format = format_impls(concrete);
4377 let synthetic_format = format_impls(synthetic);
4378 let blanket_format = format_impls(blanket_impl);
4380 if !concrete_format.is_empty() {
4382 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4383 Trait Implementations</a>",
4385 write_sidebar_links(out, concrete_format);
4388 if !synthetic_format.is_empty() {
4390 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4391 Auto Trait Implementations</a>",
4393 write_sidebar_links(out, synthetic_format);
4396 if !blanket_format.is_empty() {
4398 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4399 Blanket Implementations</a>",
4401 write_sidebar_links(out, blanket_format);
4407 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
4410 debug!("found Deref: {:?}", impl_);
4411 if let Some((target, real_target)) =
4412 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
4413 clean::TypedefItem(ref t, true) => Some(match *t {
4414 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4415 _ => (&t.type_, &t.type_),
4420 debug!("found target, real_target: {:?} {:?}", target, real_target);
4421 if let Some(did) = target.def_id_full(cx.cache()) {
4422 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
4423 // `impl Deref<Target = S> for S`
4424 if did == type_did {
4425 // Avoid infinite cycles
4432 .filter(|i| i.inner_impl().trait_.is_some())
4433 .any(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_mut_trait_did);
4434 let inner_impl = target
4435 .def_id_full(cx.cache())
4437 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
4439 .and_then(|did| c.impls.get(&did));
4440 if let Some(impls) = inner_impl {
4441 debug!("found inner_impl: {:?}", impls);
4442 let mut used_links = FxHashSet::default();
4445 .filter(|i| i.inner_impl().trait_.is_none())
4446 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
4447 .collect::<Vec<_>>();
4448 if !ret.is_empty() {
4449 let deref_id_map = cx.deref_id_map.borrow();
4450 let id = deref_id_map
4451 .get(&real_target.def_id_full(cx.cache()).unwrap())
4452 .expect("Deref section without derived id");
4455 "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}<Target={}></a>",
4457 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(c))),
4458 Escape(&format!("{:#}", real_target.print(c))),
4460 // We want links' order to be reproducible so we don't use unstable sort.
4462 out.push_str("<div class=\"sidebar-links\">");
4464 out.push_str(&link);
4466 out.push_str("</div>");
4470 // Recurse into any further impls that might exist for `target`
4471 if let Some(target_did) = target.def_id_full(cx.cache()) {
4472 if let Some(target_impls) = c.impls.get(&target_did) {
4473 if let Some(target_deref_impl) = target_impls
4475 .filter(|i| i.inner_impl().trait_.is_some())
4476 .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_trait_did)
4478 sidebar_deref_methods(cx, out, target_deref_impl, target_impls);
4485 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4486 let mut sidebar = Buffer::new();
4487 let fields = get_struct_fields_name(&s.fields);
4489 if !fields.is_empty() {
4490 if let CtorKind::Fictive = s.struct_type {
4492 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4493 <div class=\"sidebar-links\">",
4496 for field in fields {
4497 sidebar.push_str(&field);
4500 sidebar.push_str("</div>");
4504 sidebar_assoc_items(cx, &mut sidebar, it);
4506 if !sidebar.is_empty() {
4507 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4511 fn get_id_for_impl_on_foreign_type(
4513 trait_: &clean::Type,
4516 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cache), for_.print(cache)))
4519 fn extract_for_impl_name(item: &clean::Item, cache: &Cache) -> Option<(String, String)> {
4521 clean::ItemKind::ImplItem(ref i) => {
4522 if let Some(ref trait_) = i.trait_ {
4524 format!("{:#}", i.for_.print(cache)),
4525 get_id_for_impl_on_foreign_type(&i.for_, trait_, cache),
4535 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4536 buf.write_str("<div class=\"block items\">");
4538 fn print_sidebar_section(
4540 items: &[clean::Item],
4542 filter: impl Fn(&clean::Item) -> bool,
4543 write: impl Fn(&mut Buffer, &Symbol),
4546 let mut items = items
4548 .filter_map(|m| match m.name {
4549 Some(ref name) if filter(m) => Some(name),
4552 .collect::<Vec<_>>();
4554 if !items.is_empty() {
4556 out.push_str(before);
4557 for item in items.into_iter() {
4560 out.push_str(after);
4564 print_sidebar_section(
4567 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4568 Associated Types</a><div class=\"sidebar-links\">",
4569 |m| m.is_associated_type(),
4570 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
4574 print_sidebar_section(
4577 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4578 Associated Constants</a><div class=\"sidebar-links\">",
4579 |m| m.is_associated_const(),
4580 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
4584 print_sidebar_section(
4587 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4588 Required Methods</a><div class=\"sidebar-links\">",
4589 |m| m.is_ty_method(),
4590 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
4594 print_sidebar_section(
4597 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4598 Provided Methods</a><div class=\"sidebar-links\">",
4600 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
4604 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
4605 let mut res = implementors
4610 .def_id_full(cx.cache())
4611 .map_or(false, |d| !cx.cache.paths.contains_key(&d))
4613 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx.cache()))
4614 .collect::<Vec<_>>();
4616 if !res.is_empty() {
4619 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4620 Implementations on Foreign Types</a>\
4621 <div class=\"sidebar-links\">",
4623 for (name, id) in res.into_iter() {
4624 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
4626 buf.push_str("</div>");
4630 sidebar_assoc_items(cx, buf, it);
4632 buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4635 "<a class=\"sidebar-title\" \
4636 href=\"#synthetic-implementors\">Auto Implementors</a>",
4640 buf.push_str("</div>")
4643 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4644 let mut sidebar = Buffer::new();
4645 sidebar_assoc_items(cx, &mut sidebar, it);
4647 if !sidebar.is_empty() {
4648 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4652 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4653 let mut sidebar = Buffer::new();
4654 sidebar_assoc_items(cx, &mut sidebar, it);
4656 if !sidebar.is_empty() {
4657 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4661 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
4662 let mut fields = fields
4664 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
4666 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4668 .collect::<Vec<_>>();
4673 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4674 let mut sidebar = Buffer::new();
4675 let fields = get_struct_fields_name(&u.fields);
4677 if !fields.is_empty() {
4679 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4680 <div class=\"sidebar-links\">",
4683 for field in fields {
4684 sidebar.push_str(&field);
4687 sidebar.push_str("</div>");
4690 sidebar_assoc_items(cx, &mut sidebar, it);
4692 if !sidebar.is_empty() {
4693 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4697 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4698 let mut sidebar = Buffer::new();
4700 let mut variants = e
4703 .filter_map(|v| match v.name {
4704 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4707 .collect::<Vec<_>>();
4708 if !variants.is_empty() {
4709 variants.sort_unstable();
4710 sidebar.push_str(&format!(
4711 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4712 <div class=\"sidebar-links\">{}</div>",
4717 sidebar_assoc_items(cx, &mut sidebar, it);
4719 if !sidebar.is_empty() {
4720 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4724 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4726 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4727 ItemType::Module => ("modules", "Modules"),
4728 ItemType::Struct => ("structs", "Structs"),
4729 ItemType::Union => ("unions", "Unions"),
4730 ItemType::Enum => ("enums", "Enums"),
4731 ItemType::Function => ("functions", "Functions"),
4732 ItemType::Typedef => ("types", "Type Definitions"),
4733 ItemType::Static => ("statics", "Statics"),
4734 ItemType::Constant => ("constants", "Constants"),
4735 ItemType::Trait => ("traits", "Traits"),
4736 ItemType::Impl => ("impls", "Implementations"),
4737 ItemType::TyMethod => ("tymethods", "Type Methods"),
4738 ItemType::Method => ("methods", "Methods"),
4739 ItemType::StructField => ("fields", "Struct Fields"),
4740 ItemType::Variant => ("variants", "Variants"),
4741 ItemType::Macro => ("macros", "Macros"),
4742 ItemType::Primitive => ("primitives", "Primitive Types"),
4743 ItemType::AssocType => ("associated-types", "Associated Types"),
4744 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4745 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4746 ItemType::Keyword => ("keywords", "Keywords"),
4747 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4748 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4749 ItemType::ProcDerive => ("derives", "Derive Macros"),
4750 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4754 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4755 let mut sidebar = String::new();
4757 if items.iter().any(|it| {
4758 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4760 sidebar.push_str("<li><a href=\"#reexports\">Re-exports</a></li>");
4763 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4764 // to print its headings
4766 ItemType::Primitive,
4780 ItemType::StructField,
4782 ItemType::AssocType,
4783 ItemType::AssocConst,
4784 ItemType::ForeignType,
4787 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4788 let (short, name) = item_ty_to_strs(&myty);
4789 sidebar.push_str(&format!(
4790 "<li><a href=\"#{id}\">{name}</a></li>",
4797 if !sidebar.is_empty() {
4798 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4802 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4803 let mut sidebar = Buffer::new();
4804 sidebar_assoc_items(cx, &mut sidebar, it);
4806 if !sidebar.is_empty() {
4807 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4811 fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
4812 wrap_into_docblock(w, |w| {
4813 highlight::render_with_highlighting(
4819 it.source.span().edition(),
4822 document(w, cx, it, None)
4825 fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
4826 let name = it.name.as_ref().expect("proc-macros always have names");
4828 MacroKind::Bang => {
4829 w.push_str("<pre class=\"rust macro\">");
4830 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4831 w.push_str("</pre>");
4833 MacroKind::Attr => {
4834 w.push_str("<pre class=\"rust attr\">");
4835 write!(w, "#[{}]", name);
4836 w.push_str("</pre>");
4838 MacroKind::Derive => {
4839 w.push_str("<pre class=\"rust derive\">");
4840 write!(w, "#[derive({})]", name);
4841 if !m.helpers.is_empty() {
4842 w.push_str("\n{\n");
4843 w.push_str(" // Attributes available to this derive:\n");
4844 for attr in &m.helpers {
4845 writeln!(w, " #[{}]", attr);
4849 w.push_str("</pre>");
4852 document(w, cx, it, None)
4855 fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4856 document(w, cx, it, None);
4857 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4860 fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4861 document(w, cx, it, None)
4864 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4866 fn make_item_keywords(it: &clean::Item) -> String {
4867 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4870 /// Returns a list of all paths used in the type.
4871 /// This is used to help deduplicate imported impls
4872 /// for reexported types. If any of the contained
4873 /// types are re-exported, we don't use the corresponding
4874 /// entry from the js file, as inlining will have already
4875 /// picked up the impl
4876 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
4877 let mut out = Vec::new();
4878 let mut visited = FxHashSet::default();
4879 let mut work = VecDeque::new();
4881 work.push_back(first_ty);
4883 while let Some(ty) = work.pop_front() {
4884 if !visited.insert(ty.clone()) {
4889 clean::Type::ResolvedPath { did, .. } => {
4890 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4891 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4893 if let Some(path) = fqp {
4894 out.push(path.join("::"));
4897 clean::Type::Tuple(tys) => {
4898 work.extend(tys.into_iter());
4900 clean::Type::Slice(ty) => {
4901 work.push_back(*ty);
4903 clean::Type::Array(ty, _) => {
4904 work.push_back(*ty);
4906 clean::Type::RawPointer(_, ty) => {
4907 work.push_back(*ty);
4909 clean::Type::BorrowedRef { type_, .. } => {
4910 work.push_back(*type_);
4912 clean::Type::QPath { self_type, trait_, .. } => {
4913 work.push_back(*self_type);
4914 work.push_back(*trait_);