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::Function;
77 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
78 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
79 use crate::html::markdown::{
80 self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine,
82 use crate::html::sources;
83 use crate::html::{highlight, layout, static_files};
84 use cache::{build_index, ExternalLocation};
86 /// A pair of name and its optional document.
87 crate type NameDoc = (String, Option<String>);
89 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
90 crate::html::format::display_fn(move |f| {
91 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
95 /// Major driving force in all rustdoc rendering. This contains information
96 /// about where in the tree-like hierarchy rendering is occurring and controls
97 /// how the current page is being rendered.
99 /// It is intended that this context is a lightweight object which can be fairly
100 /// easily cloned because it is cloned per work-job (about once per item in the
103 crate struct Context<'tcx> {
104 /// Current hierarchy of components leading down to what's currently being
106 crate current: Vec<String>,
107 /// The current destination folder of where HTML artifacts should be placed.
108 /// This changes as the context descends into the module hierarchy.
110 /// A flag, which when `true`, will render pages which redirect to the
111 /// real location of an item. This is used to allow external links to
112 /// publicly reused items to redirect to the right location.
113 crate render_redirect_pages: bool,
114 /// The map used to ensure all generated 'id=' attributes are unique.
115 id_map: Rc<RefCell<IdMap>>,
116 /// Tracks section IDs for `Deref` targets so they match in both the main
117 /// body and the sidebar.
118 deref_id_map: Rc<RefCell<FxHashMap<DefId, String>>>,
119 crate shared: Arc<SharedContext<'tcx>>,
120 all: Rc<RefCell<AllTypes>>,
121 /// Storage for the errors produced while generating documentation so they
122 /// can be printed together at the end.
123 crate errors: Rc<Receiver<String>>,
124 crate cache: Rc<Cache>,
127 crate struct SharedContext<'tcx> {
128 crate tcx: TyCtxt<'tcx>,
129 /// The path to the crate root source minus the file name.
130 /// Used for simplifying paths to the highlighted source code files.
131 crate src_root: PathBuf,
132 /// This describes the layout of each page, and is not modified after
133 /// creation of the context (contains info like the favicon and added html).
134 crate layout: layout::Layout,
135 /// This flag indicates whether `[src]` links should be generated or not. If
136 /// the source files are present in the html rendering, then this will be
138 crate include_sources: bool,
139 /// The local file sources we've emitted and their respective url-paths.
140 crate local_sources: FxHashMap<PathBuf, String>,
141 /// Whether the collapsed pass ran
142 crate collapsed: bool,
143 /// The base-URL of the issue tracker for when an item has been tagged with
145 crate issue_tracker_base_url: Option<String>,
146 /// The directories that have already been created in this doc run. Used to reduce the number
147 /// of spurious `create_dir_all` calls.
148 crate created_dirs: RefCell<FxHashSet<PathBuf>>,
149 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
150 /// should be ordered alphabetically or in order of appearance (in the source code).
151 crate sort_modules_alphabetically: bool,
152 /// Additional CSS files to be added to the generated docs.
153 crate style_files: Vec<StylePath>,
154 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
156 crate resource_suffix: String,
157 /// Optional path string to be used to load static files on output pages. If not set, uses
158 /// combinations of `../` to reach the documentation root.
159 crate static_root_path: Option<String>,
160 /// The fs handle we are working with.
162 /// The default edition used to parse doctests.
163 crate edition: Edition,
164 crate codes: ErrorCodes,
165 playground: Option<markdown::Playground>,
168 impl<'tcx> Context<'tcx> {
169 fn path(&self, filename: &str) -> PathBuf {
170 // We use splitn vs Path::extension here because we might get a filename
171 // like `style.min.css` and we want to process that into
172 // `style-suffix.min.css`. Path::extension would just return `css`
173 // which would result in `style.min-suffix.css` which isn't what we
175 let (base, ext) = filename.split_once('.').unwrap();
176 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext);
177 self.dst.join(&filename)
180 fn tcx(&self) -> TyCtxt<'tcx> {
184 fn sess(&self) -> &'tcx Session {
185 &self.shared.tcx.sess
189 impl SharedContext<'_> {
190 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
191 let mut dirs = self.created_dirs.borrow_mut();
192 if !dirs.contains(dst) {
193 try_err!(self.fs.create_dir_all(dst), dst);
194 dirs.insert(dst.to_path_buf());
200 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
201 /// `collapsed_doc_value` of the given item.
202 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<String> {
203 if self.collapsed { item.collapsed_doc_value() } else { item.doc_value() }
207 // Helper structs for rendering items/sidebars and carrying along contextual
210 /// Struct representing one entry in the JS search index. These are all emitted
211 /// by hand to a large JS file at the end of cache-creation.
213 crate struct IndexItem {
218 crate parent: Option<DefId>,
219 crate parent_idx: Option<usize>,
220 crate search_type: Option<IndexItemFunctionType>,
223 impl Serialize for IndexItem {
224 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
229 self.parent.is_some(),
230 self.parent_idx.is_some(),
231 "`{}` is missing idx",
235 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
236 .serialize(serializer)
240 /// A type used for the search index.
242 crate struct RenderType {
245 name: Option<String>,
246 generics: Option<Vec<Generic>>,
249 impl Serialize for RenderType {
250 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
254 if let Some(name) = &self.name {
255 let mut seq = serializer.serialize_seq(None)?;
256 if let Some(id) = self.idx {
257 seq.serialize_element(&id)?;
259 seq.serialize_element(&name)?;
261 if let Some(generics) = &self.generics {
262 seq.serialize_element(&generics)?;
266 serializer.serialize_none()
271 /// A type used for the search index.
273 crate struct Generic {
275 defid: Option<DefId>,
279 impl Serialize for Generic {
280 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
284 if let Some(id) = self.idx {
285 serializer.serialize_some(&id)
287 serializer.serialize_some(&self.name)
292 /// Full type of functions/methods in the search index.
294 crate struct IndexItemFunctionType {
295 inputs: Vec<TypeWithKind>,
296 output: Option<Vec<TypeWithKind>>,
299 impl Serialize for IndexItemFunctionType {
300 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
304 // If we couldn't figure out a type, just write `null`.
305 let mut iter = self.inputs.iter();
306 if match self.output {
307 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
308 None => iter.any(|ref i| i.ty.name.is_none()),
310 serializer.serialize_none()
312 let mut seq = serializer.serialize_seq(None)?;
313 seq.serialize_element(&self.inputs)?;
314 if let Some(output) = &self.output {
315 if output.len() > 1 {
316 seq.serialize_element(&output)?;
318 seq.serialize_element(&output[0])?;
327 crate struct TypeWithKind {
332 impl From<(RenderType, TypeKind)> for TypeWithKind {
333 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
334 TypeWithKind { ty: x.0, kind: x.1 }
338 impl Serialize for TypeWithKind {
339 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
343 let mut seq = serializer.serialize_seq(None)?;
344 seq.serialize_element(&self.ty.name)?;
345 let x: ItemType = self.kind.into();
346 seq.serialize_element(&x)?;
351 #[derive(Debug, Clone)]
352 crate struct StylePath {
353 /// The path to the theme
355 /// What the `disabled` attribute should be set to in the HTML tag
356 crate disabled: bool,
359 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
361 crate const INITIAL_IDS: [&'static str; 15] = [
372 "synthetic-implementors",
374 "synthetic-implementors-list",
379 /// Generates the documentation for `crate` into the directory `dst`
380 impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
381 fn descr() -> &'static str {
386 mut krate: clean::Crate,
387 options: RenderOptions,
388 _render_info: RenderInfo,
392 ) -> Result<(Self, clean::Crate), Error> {
393 // need to save a copy of the options for rendering the index page
394 let md_opts = options.clone();
400 sort_modules_alphabetically,
406 generate_search_filter,
411 let src_root = match krate.src {
412 FileName::Real(ref p) => match p.local_path().parent() {
413 Some(p) => p.to_path_buf(),
414 None => PathBuf::new(),
418 // If user passed in `--playground-url` arg, we fill in crate name here
419 let mut playground = None;
420 if let Some(url) = playground_url {
422 Some(markdown::Playground { crate_name: Some(krate.name.to_string()), url });
424 let mut layout = layout::Layout {
426 favicon: String::new(),
429 krate: krate.name.to_string(),
430 css_file_extension: extension_css,
431 generate_search_filter,
433 let mut issue_tracker_base_url = None;
434 let mut include_sources = true;
436 // Crawl the crate attributes looking for attributes which control how we're
437 // going to emit HTML
438 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
439 for attr in attrs.lists(sym::doc) {
440 match (attr.name_or_empty(), attr.value_str()) {
441 (sym::html_favicon_url, Some(s)) => {
442 layout.favicon = s.to_string();
444 (sym::html_logo_url, Some(s)) => {
445 layout.logo = s.to_string();
447 (sym::html_playground_url, Some(s)) => {
448 playground = Some(markdown::Playground {
449 crate_name: Some(krate.name.to_string()),
453 (sym::issue_tracker_base_url, Some(s)) => {
454 issue_tracker_base_url = Some(s.to_string());
456 (sym::html_no_source, None) if attr.is_word() => {
457 include_sources = false;
463 let (sender, receiver) = channel();
464 let mut scx = SharedContext {
466 collapsed: krate.collapsed,
469 local_sources: Default::default(),
470 issue_tracker_base_url,
472 created_dirs: Default::default(),
473 sort_modules_alphabetically,
477 fs: DocFS::new(sender),
479 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
483 // Add the default themes to the `Vec` of stylepaths
485 // Note that these must be added before `sources::render` is called
486 // so that the resulting source pages are styled
488 // `light.css` is not disabled because it is the stylesheet that stays loaded
489 // by the browser as the theme stylesheet. The theme system (hackily) works by
490 // changing the href to this stylesheet. All other themes are disabled to
491 // prevent rule conflicts
492 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
493 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
494 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
497 scx.ensure_dir(&dst)?;
498 krate = sources::render(&dst, &mut scx, krate)?;
500 // Build our search index
501 let index = build_index(&krate, &mut cache, tcx);
503 let mut cx = Context {
506 render_redirect_pages: false,
507 id_map: Rc::new(RefCell::new(id_map)),
508 deref_id_map: Rc::new(RefCell::new(FxHashMap::default())),
509 shared: Arc::new(scx),
510 all: Rc::new(RefCell::new(AllTypes::new())),
511 errors: Rc::new(receiver),
512 cache: Rc::new(cache),
515 CURRENT_DEPTH.with(|s| s.set(0));
517 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
518 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
519 write_shared(&cx, &krate, index, &md_opts)?;
520 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
526 krate: &clean::Crate,
527 diag: &rustc_errors::Handler,
528 ) -> Result<(), Error> {
529 let final_file = self.dst.join(&*krate.name.as_str()).join("all.html");
530 let settings_file = self.dst.join("settings.html");
531 let crate_name = krate.name;
533 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
534 if !root_path.ends_with('/') {
537 let mut page = layout::Page {
538 title: "List of all items in this crate",
541 static_root_path: self.shared.static_root_path.as_deref(),
542 description: "List of all items in this crate",
543 keywords: BASIC_KEYWORDS,
544 resource_suffix: &self.shared.resource_suffix,
546 static_extra_scripts: &[],
548 let sidebar = if let Some(ref version) = self.cache.crate_version {
550 "<p class=\"location\">Crate {}</p>\
551 <div class=\"block version\">\
554 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
561 let all = self.all.replace(AllTypes::new());
562 let v = layout::render(
566 |buf: &mut Buffer| all.print(buf),
567 &self.shared.style_files,
569 self.shared.fs.write(&final_file, v.as_bytes())?;
571 // Generating settings page.
572 page.title = "Rustdoc settings";
573 page.description = "Settings of Rustdoc";
574 page.root_path = "./";
576 let mut style_files = self.shared.style_files.clone();
577 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
578 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
579 let v = layout::render(
584 self.shared.static_root_path.as_deref().unwrap_or("./"),
585 &self.shared.resource_suffix,
586 &self.shared.style_files,
590 self.shared.fs.write(&settings_file, v.as_bytes())?;
592 // Flush pending errors.
593 Arc::get_mut(&mut self.shared).unwrap().fs.close();
594 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
596 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
602 fn mod_item_in(&mut self, item: &clean::Item, item_name: &str) -> Result<(), Error> {
603 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
604 // if they contain impls for public types. These modules can also
605 // contain items such as publicly re-exported structures.
607 // External crates will provide links to these structures, so
608 // these modules are recursed into, but not rendered normally
609 // (a flag on the context).
610 if !self.render_redirect_pages {
611 self.render_redirect_pages = item.is_stripped();
613 let scx = &self.shared;
614 self.dst.push(item_name);
615 self.current.push(item_name.to_owned());
617 info!("Recursing into {}", self.dst.display());
619 let buf = self.render_item(item, false);
620 // buf will be empty if the module is stripped and there is no redirect for it
622 self.shared.ensure_dir(&self.dst)?;
623 let joint_dst = self.dst.join("index.html");
624 scx.fs.write(&joint_dst, buf.as_bytes())?;
627 // Render sidebar-items.js used throughout this module.
628 if !self.render_redirect_pages {
629 let module = match *item.kind {
630 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
633 let items = self.build_sidebar_items(module);
634 let js_dst = self.dst.join("sidebar-items.js");
635 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
636 scx.fs.write(&js_dst, &v)?;
641 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
642 info!("Recursed; leaving {}", self.dst.display());
644 // Go back to where we were at
650 fn item(&mut self, item: clean::Item) -> Result<(), Error> {
651 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
652 // if they contain impls for public types. These modules can also
653 // contain items such as publicly re-exported structures.
655 // External crates will provide links to these structures, so
656 // these modules are recursed into, but not rendered normally
657 // (a flag on the context).
658 if !self.render_redirect_pages {
659 self.render_redirect_pages = item.is_stripped();
662 let buf = self.render_item(&item, true);
663 // buf will be empty if the item is stripped and there is no redirect for it
665 let name = item.name.as_ref().unwrap();
666 let item_type = item.type_();
667 let file_name = &item_path(item_type, &name.as_str());
668 self.shared.ensure_dir(&self.dst)?;
669 let joint_dst = self.dst.join(file_name);
670 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
672 if !self.render_redirect_pages {
673 self.all.borrow_mut().append(full_path(self, &item), &item_type);
675 // If the item is a macro, redirect from the old macro URL (with !)
676 // to the new one (without).
677 if item_type == ItemType::Macro {
678 let redir_name = format!("{}.{}!.html", item_type, name);
679 let redir_dst = self.dst.join(redir_name);
680 let v = layout::redirect(file_name);
681 self.shared.fs.write(&redir_dst, v.as_bytes())?;
687 fn cache(&self) -> &Cache {
694 krate: &clean::Crate,
695 search_index: String,
696 options: &RenderOptions,
697 ) -> Result<(), Error> {
698 // Write out the shared files. Note that these are shared among all rustdoc
699 // docs placed in the output directory, so this needs to be a synchronized
700 // operation with respect to all other rustdocs running around.
701 let lock_file = cx.dst.join(".lock");
702 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
704 // Add all the static files. These may already exist, but we just
705 // overwrite them anyway to make sure that they're fresh and up-to-date.
709 cx.path("rustdoc.css"),
710 static_files::RUSTDOC_CSS,
711 options.enable_minification,
715 cx.path("settings.css"),
716 static_files::SETTINGS_CSS,
717 options.enable_minification,
721 cx.path("noscript.css"),
722 static_files::NOSCRIPT_CSS,
723 options.enable_minification,
726 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
727 // then we'll run over the "official" styles.
728 let mut themes: FxHashSet<String> = FxHashSet::default();
730 for entry in &cx.shared.style_files {
731 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
733 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
735 // Handle the official themes
737 "light" => write_minify(
739 cx.path("light.css"),
740 static_files::themes::LIGHT,
741 options.enable_minification,
743 "dark" => write_minify(
746 static_files::themes::DARK,
747 options.enable_minification,
749 "ayu" => write_minify(
752 static_files::themes::AYU,
753 options.enable_minification,
756 // Handle added third-party themes
757 let content = try_err!(fs::read(&entry.path), &entry.path);
760 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
764 themes.insert(theme.to_owned());
767 let write = |p, c| cx.shared.fs.write(p, c);
768 if (*cx.shared).layout.logo.is_empty() {
769 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
771 if (*cx.shared).layout.favicon.is_empty() {
772 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
773 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
774 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
776 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
777 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
778 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
780 let mut themes: Vec<&String> = themes.iter().collect();
782 // To avoid theme switch latencies as much as possible, we put everything theme related
783 // at the beginning of the html files into another js file.
784 let theme_js = format!(
785 r#"var themes = document.getElementById("theme-choices");
786 var themePicker = document.getElementById("theme-picker");
788 function showThemeButtonState() {{
789 themes.style.display = "block";
790 themePicker.style.borderBottomRightRadius = "0";
791 themePicker.style.borderBottomLeftRadius = "0";
794 function hideThemeButtonState() {{
795 themes.style.display = "none";
796 themePicker.style.borderBottomRightRadius = "3px";
797 themePicker.style.borderBottomLeftRadius = "3px";
800 function switchThemeButtonState() {{
801 if (themes.style.display === "block") {{
802 hideThemeButtonState();
804 showThemeButtonState();
808 function handleThemeButtonsBlur(e) {{
809 var active = document.activeElement;
810 var related = e.relatedTarget;
812 if (active.id !== "theme-picker" &&
813 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
815 (related.id !== "theme-picker" &&
816 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
817 hideThemeButtonState();
821 themePicker.onclick = switchThemeButtonState;
822 themePicker.onblur = handleThemeButtonsBlur;
823 {}.forEach(function(item) {{
824 var but = document.createElement("button");
825 but.textContent = item;
826 but.onclick = function(el) {{
827 switchTheme(currentTheme, mainTheme, item, true);
828 useSystemTheme(false);
830 but.onblur = handleThemeButtonsBlur;
831 themes.appendChild(but);
833 serde_json::to_string(&themes).unwrap()
836 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
840 static_files::MAIN_JS,
841 options.enable_minification,
845 cx.path("settings.js"),
846 static_files::SETTINGS_JS,
847 options.enable_minification,
849 if cx.shared.include_sources {
852 cx.path("source-script.js"),
853 static_files::sidebar::SOURCE_SCRIPT,
854 options.enable_minification,
861 cx.path("storage.js"),
863 "var resourcesSuffix = \"{}\";{}",
864 cx.shared.resource_suffix,
865 static_files::STORAGE_JS
867 options.enable_minification,
871 if let Some(ref css) = cx.shared.layout.css_file_extension {
872 let out = cx.path("theme.css");
873 let buffer = try_err!(fs::read_to_string(css), css);
874 if !options.enable_minification {
875 cx.shared.fs.write(&out, &buffer)?;
877 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
882 cx.path("normalize.css"),
883 static_files::NORMALIZE_CSS,
884 options.enable_minification,
886 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
887 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
888 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
889 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
890 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
891 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
892 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
893 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
894 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
895 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
896 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
897 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
898 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
900 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
901 let mut ret = Vec::new();
902 let mut krates = Vec::new();
905 let prefix = format!(r#"{}["{}"]"#, key, krate);
906 for line in BufReader::new(File::open(path)?).lines() {
908 if !line.starts_with(key) {
911 if line.starts_with(&prefix) {
914 ret.push(line.to_string());
916 line[key.len() + 2..]
919 .map(|s| s.to_owned())
920 .unwrap_or_else(String::new),
927 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
928 let mut ret = Vec::new();
929 let mut krates = Vec::new();
932 let prefix = format!("\"{}\"", krate);
933 for line in BufReader::new(File::open(path)?).lines() {
935 if !line.starts_with('"') {
938 if line.starts_with(&prefix) {
941 if line.ends_with(",\\") {
942 ret.push(line[..line.len() - 2].to_string());
944 // Ends with "\\" (it's the case for the last added crate line)
945 ret.push(line[..line.len() - 1].to_string());
949 .find(|s| !s.is_empty())
950 .map(|s| s.to_owned())
951 .unwrap_or_else(String::new),
958 use std::ffi::OsString;
963 children: FxHashMap<OsString, Hierarchy>,
964 elems: FxHashSet<OsString>,
968 fn new(elem: OsString) -> Hierarchy {
969 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
972 fn to_json_string(&self) -> String {
973 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
974 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
978 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
979 .collect::<Vec<_>>();
980 files.sort_unstable();
981 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
983 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
984 let files = files.join(",");
986 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
988 "{{\"name\":\"{name}\"{dirs}{files}}}",
989 name = self.elem.to_str().expect("invalid osstring conversion"),
996 if cx.shared.include_sources {
997 let mut hierarchy = Hierarchy::new(OsString::new());
1002 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
1004 let mut h = &mut hierarchy;
1005 let mut elems = source
1007 .filter_map(|s| match s {
1008 Component::Normal(s) => Some(s.to_owned()),
1013 let cur_elem = elems.next().expect("empty file path");
1014 if elems.peek().is_none() {
1015 h.elems.insert(cur_elem);
1018 let e = cur_elem.clone();
1019 h = h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1024 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1025 let (mut all_sources, _krates) =
1026 try_err!(collect(&dst, &krate.name.as_str(), "sourcesIndex"), &dst);
1027 all_sources.push(format!(
1028 "sourcesIndex[\"{}\"] = {};",
1030 hierarchy.to_json_string()
1034 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1035 all_sources.join("\n")
1037 cx.shared.fs.write(&dst, v.as_bytes())?;
1040 // Update the search index
1041 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1042 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name.as_str()), &dst);
1043 all_indexes.push(search_index);
1045 // Sort the indexes by crate so the file will be generated identically even
1046 // with rustdoc running in parallel.
1049 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1050 v.push_str(&all_indexes.join(",\\\n"));
1051 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1052 // search might start (if it's set into the URL for example).
1053 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1054 cx.shared.fs.write(&dst, &v)?;
1056 if options.enable_index_page {
1057 if let Some(index_page) = options.index_page.clone() {
1058 let mut md_opts = options.clone();
1059 md_opts.output = cx.dst.clone();
1060 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1062 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1063 .map_err(|e| Error::new(e, &index_page))?;
1065 let dst = cx.dst.join("index.html");
1066 let page = layout::Page {
1067 title: "Index of crates",
1070 static_root_path: cx.shared.static_root_path.as_deref(),
1071 description: "List of crates",
1072 keywords: BASIC_KEYWORDS,
1073 resource_suffix: &cx.shared.resource_suffix,
1075 static_extra_scripts: &[],
1077 krates.push(krate.name.to_string());
1081 let content = format!(
1082 "<h1 class=\"fqn\">\
1083 <span class=\"in-band\">List of all crates</span>\
1084 </h1><ul class=\"crate mod\">{}</ul>",
1089 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1090 ensure_trailing_slash(s),
1094 .collect::<String>()
1096 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1097 cx.shared.fs.write(&dst, v.as_bytes())?;
1101 // Update the list of all implementors for traits
1102 let dst = cx.dst.join("implementors");
1103 for (&did, imps) in &cx.cache.implementors {
1104 // Private modules can leak through to this phase of rustdoc, which
1105 // could contain implementations for otherwise private types. In some
1106 // rare cases we could find an implementation for an item which wasn't
1107 // indexed, so we just skip this step in that case.
1109 // FIXME: this is a vague explanation for why this can't be a `get`, in
1110 // theory it should be...
1111 let &(ref remote_path, remote_item_type) = match cx.cache.paths.get(&did) {
1113 None => match cx.cache.external_paths.get(&did) {
1119 #[derive(Serialize)]
1120 struct Implementor {
1126 let implementors = imps
1129 // If the trait and implementation are in the same crate, then
1130 // there's no need to emit information about it (there's inlining
1131 // going on). If they're in different crates then the crate defining
1132 // the trait will be interested in our implementation.
1134 // If the implementation is from another crate then that crate
1136 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1140 text: imp.inner_impl().print(cx.cache(), false).to_string(),
1141 synthetic: imp.inner_impl().synthetic,
1142 types: collect_paths_for_type(imp.inner_impl().for_.clone(), cx.cache()),
1146 .collect::<Vec<_>>();
1148 // Only create a js file if we have impls to add to it. If the trait is
1149 // documented locally though we always create the file to avoid dead
1151 if implementors.is_empty() && !cx.cache.paths.contains_key(&did) {
1155 let implementors = format!(
1156 r#"implementors["{}"] = {};"#,
1158 serde_json::to_string(&implementors).unwrap()
1161 let mut mydst = dst.clone();
1162 for part in &remote_path[..remote_path.len() - 1] {
1165 cx.shared.ensure_dir(&mydst)?;
1166 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1168 let (mut all_implementors, _) =
1169 try_err!(collect(&mydst, &krate.name.as_str(), "implementors"), &mydst);
1170 all_implementors.push(implementors);
1171 // Sort the implementors by crate so the file will be generated
1172 // identically even with rustdoc running in parallel.
1173 all_implementors.sort();
1175 let mut v = String::from("(function() {var implementors = {};\n");
1176 for implementor in &all_implementors {
1177 writeln!(v, "{}", *implementor).unwrap();
1180 "if (window.register_implementors) {\
1181 window.register_implementors(implementors);\
1183 window.pending_implementors = implementors;\
1187 cx.shared.fs.write(&mydst, &v)?;
1196 enable_minification: bool,
1197 ) -> Result<(), Error> {
1198 if enable_minification {
1199 if dst.extension() == Some(&OsStr::new("css")) {
1200 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1201 fs.write(dst, res.as_bytes())
1203 fs.write(dst, minifier::js::minify(contents).as_bytes())
1206 fs.write(dst, contents.as_bytes())
1210 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
1211 if let Some(l) = cx.src_href(item) {
1212 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
1216 #[derive(Debug, Eq, PartialEq, Hash)]
1223 fn new(mut url: String, name: String) -> ItemEntry {
1224 while url.starts_with('/') {
1227 ItemEntry { url, name }
1232 crate fn print(&self) -> impl fmt::Display + '_ {
1233 crate::html::format::display_fn(move |f| {
1234 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1239 impl PartialOrd for ItemEntry {
1240 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1241 Some(self.cmp(other))
1245 impl Ord for ItemEntry {
1246 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1247 self.name.cmp(&other.name)
1253 structs: FxHashSet<ItemEntry>,
1254 enums: FxHashSet<ItemEntry>,
1255 unions: FxHashSet<ItemEntry>,
1256 primitives: FxHashSet<ItemEntry>,
1257 traits: FxHashSet<ItemEntry>,
1258 macros: FxHashSet<ItemEntry>,
1259 functions: FxHashSet<ItemEntry>,
1260 typedefs: FxHashSet<ItemEntry>,
1261 opaque_tys: FxHashSet<ItemEntry>,
1262 statics: FxHashSet<ItemEntry>,
1263 constants: FxHashSet<ItemEntry>,
1264 keywords: FxHashSet<ItemEntry>,
1265 attributes: FxHashSet<ItemEntry>,
1266 derives: FxHashSet<ItemEntry>,
1267 trait_aliases: FxHashSet<ItemEntry>,
1271 fn new() -> AllTypes {
1272 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1274 structs: new_set(100),
1275 enums: new_set(100),
1276 unions: new_set(100),
1277 primitives: new_set(26),
1278 traits: new_set(100),
1279 macros: new_set(100),
1280 functions: new_set(100),
1281 typedefs: new_set(100),
1282 opaque_tys: new_set(100),
1283 statics: new_set(100),
1284 constants: new_set(100),
1285 keywords: new_set(100),
1286 attributes: new_set(100),
1287 derives: new_set(100),
1288 trait_aliases: new_set(100),
1292 fn append(&mut self, item_name: String, item_type: &ItemType) {
1293 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1294 if let Some(name) = url.pop() {
1295 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1297 let name = url.join("::");
1299 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1300 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1301 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1302 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1303 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1304 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1305 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1306 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1307 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1308 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1309 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1310 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1311 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1312 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1320 fn print(self, f: &mut Buffer) {
1321 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1323 let mut e: Vec<&ItemEntry> = e.iter().collect();
1325 write!(f, "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">", title, title, class);
1328 write!(f, "<li>{}</li>", s.print());
1331 f.write_str("</ul>");
1336 "<h1 class=\"fqn\">\
1337 <span class=\"in-band\">List of all items</span>\
1338 <span class=\"out-of-band\">\
1339 <span id=\"render-detail\">\
1340 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1341 title=\"collapse all docs\">\
1342 [<span class=\"inner\">−</span>]\
1346 <span class=\"in-band\">List of all items</span>\
1349 // Note: print_entries does not escape the title, because we know the current set of titles
1350 // don't require escaping.
1351 print_entries(f, &self.structs, "Structs", "structs");
1352 print_entries(f, &self.enums, "Enums", "enums");
1353 print_entries(f, &self.unions, "Unions", "unions");
1354 print_entries(f, &self.primitives, "Primitives", "primitives");
1355 print_entries(f, &self.traits, "Traits", "traits");
1356 print_entries(f, &self.macros, "Macros", "macros");
1357 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1358 print_entries(f, &self.derives, "Derive Macros", "derives");
1359 print_entries(f, &self.functions, "Functions", "functions");
1360 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1361 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1362 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1363 print_entries(f, &self.statics, "Statics", "statics");
1364 print_entries(f, &self.constants, "Constants", "constants")
1371 description: &'static str,
1372 sub_settings: Vec<Setting>,
1375 js_data_name: &'static str,
1376 description: &'static str,
1377 default_value: bool,
1380 js_data_name: &'static str,
1381 description: &'static str,
1382 default_value: &'static str,
1383 options: Vec<(String, String)>,
1388 fn display(&self, root_path: &str, suffix: &str) -> String {
1390 Setting::Section { description, ref sub_settings } => format!(
1391 "<div class=\"setting-line\">\
1392 <div class=\"title\">{}</div>\
1393 <div class=\"sub-settings\">{}</div>
1396 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1398 Setting::Toggle { js_data_name, description, default_value } => format!(
1399 "<div class=\"setting-line\">\
1400 <label class=\"toggle\">\
1401 <input type=\"checkbox\" id=\"{}\" {}>\
1402 <span class=\"slider\"></span>\
1407 if default_value { " checked" } else { "" },
1410 Setting::Select { js_data_name, description, default_value, ref options } => format!(
1411 "<div class=\"setting-line\">\
1413 <label class=\"select-wrapper\">\
1414 <select id=\"{}\" autocomplete=\"off\">{}</select>\
1415 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1423 "<option value=\"{}\" {}>{}</option>",
1425 if opt.0 == default_value { "selected" } else { "" },
1428 .collect::<String>(),
1436 impl From<(&'static str, &'static str, bool)> for Setting {
1437 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1438 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1442 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1443 fn from(values: (&'static str, Vec<T>)) -> Setting {
1445 description: values.0,
1446 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1451 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1452 let theme_names: Vec<(String, String)> = themes
1456 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1459 Ok((theme.clone(), theme))
1461 .collect::<Result<_, Error>>()?;
1463 // (id, explanation, default value)
1464 let settings: &[Setting] = &[
1466 "Theme preferences",
1468 Setting::from(("use-system-theme", "Use system theme", true)),
1470 js_data_name: "preferred-dark-theme",
1471 description: "Preferred dark theme",
1472 default_value: "dark",
1473 options: theme_names.clone(),
1476 js_data_name: "preferred-light-theme",
1477 description: "Preferred light theme",
1478 default_value: "light",
1479 options: theme_names,
1485 "Auto-hide item declarations",
1487 ("auto-hide-struct", "Auto-hide structs declaration", true),
1488 ("auto-hide-enum", "Auto-hide enums declaration", false),
1489 ("auto-hide-union", "Auto-hide unions declaration", true),
1490 ("auto-hide-trait", "Auto-hide traits declaration", true),
1491 ("auto-hide-macro", "Auto-hide macros declaration", false),
1495 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1496 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1497 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1499 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1500 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1502 ("line-numbers", "Show line numbers on code examples", false).into(),
1503 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1507 "<h1 class=\"fqn\">\
1508 <span class=\"in-band\">Rustdoc settings</span>\
1510 <div class=\"settings\">{}</div>\
1511 <script src=\"{}settings{}.js\"></script>",
1512 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1519 fn derive_id(&self, id: String) -> String {
1520 let mut map = self.id_map.borrow_mut();
1524 /// String representation of how to get back to the root path of the 'doc/'
1525 /// folder in terms of a relative URL.
1526 fn root_path(&self) -> String {
1527 "../".repeat(self.current.len())
1530 fn render_item(&self, it: &clean::Item, pushname: bool) -> String {
1531 // A little unfortunate that this is done like this, but it sure
1532 // does make formatting *a lot* nicer.
1533 CURRENT_DEPTH.with(|slot| {
1534 slot.set(self.current.len());
1537 let mut title = if it.is_primitive() || it.is_keyword() {
1538 // No need to include the namespace for primitive types and keywords
1541 self.current.join("::")
1544 if !title.is_empty() {
1545 title.push_str("::");
1547 title.push_str(&it.name.unwrap().as_str());
1549 title.push_str(" - Rust");
1550 let tyname = it.type_();
1551 let desc = it.doc_value().as_ref().map(|doc| plain_text_summary(&doc));
1552 let desc = if let Some(desc) = desc {
1554 } else if it.is_crate() {
1555 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1558 "API documentation for the Rust `{}` {} in crate `{}`.",
1559 it.name.as_ref().unwrap(),
1561 self.shared.layout.krate
1564 let keywords = make_item_keywords(it);
1565 let page = layout::Page {
1566 css_class: tyname.as_str(),
1567 root_path: &self.root_path(),
1568 static_root_path: self.shared.static_root_path.as_deref(),
1571 keywords: &keywords,
1572 resource_suffix: &self.shared.resource_suffix,
1574 static_extra_scripts: &[],
1578 self.id_map.borrow_mut().reset();
1579 self.id_map.borrow_mut().populate(&INITIAL_IDS);
1582 if !self.render_redirect_pages {
1584 &self.shared.layout,
1586 |buf: &mut _| print_sidebar(self, it, buf),
1587 |buf: &mut _| print_item(self, it, buf),
1588 &self.shared.style_files,
1591 let mut url = self.root_path();
1592 if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) {
1593 for name in &names[..names.len() - 1] {
1597 url.push_str(&item_path(ty, names.last().unwrap()));
1598 layout::redirect(&url)
1605 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1606 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1607 // BTreeMap instead of HashMap to get a sorted output
1608 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1609 for item in &m.items {
1610 if item.is_stripped() {
1614 let short = item.type_();
1615 let myname = match item.name {
1617 Some(ref s) => s.to_string(),
1619 let short = short.to_string();
1620 map.entry(short).or_default().push((
1622 Some(item.doc_value().map_or_else(String::new, |s| plain_text_summary(&s))),
1626 if self.shared.sort_modules_alphabetically {
1627 for items in map.values_mut() {
1634 /// Generates a url appropriate for an `href` attribute back to the source of
1637 /// The url generated, when clicked, will redirect the browser back to the
1638 /// original source code.
1640 /// If `None` is returned, then a source link couldn't be generated. This
1641 /// may happen, for example, with externally inlined items where the source
1642 /// of their crate documentation isn't known.
1643 fn src_href(&self, item: &clean::Item) -> Option<String> {
1644 if item.source.is_dummy() {
1647 let mut root = self.root_path();
1648 let mut path = String::new();
1649 let cnum = item.source.cnum(self.sess());
1651 // We can safely ignore synthetic `SourceFile`s.
1652 let file = match item.source.filename(self.sess()) {
1653 FileName::Real(ref path) => path.local_path().to_path_buf(),
1659 let (krate, path) = if cnum == LOCAL_CRATE {
1660 if let Some(path) = self.shared.local_sources.get(file) {
1661 (self.shared.layout.krate.as_str(), path)
1666 let (krate, src_root) = match *self.cache.extern_locations.get(&cnum)? {
1667 (name, ref src, ExternalLocation::Local) => (name, src),
1668 (name, ref src, ExternalLocation::Remote(ref s)) => {
1669 root = s.to_string();
1672 (_, _, ExternalLocation::Unknown) => return None,
1675 sources::clean_path(&src_root, file, false, |component| {
1676 path.push_str(&component.to_string_lossy());
1679 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1680 fname.push(".html");
1681 path.push_str(&fname.to_string_lossy());
1682 symbol = krate.as_str();
1686 let loline = item.source.lo(self.sess()).line;
1687 let hiline = item.source.hi(self.sess()).line;
1689 if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) };
1691 "{root}src/{krate}/{path}#{lines}",
1692 root = Escape(&root),
1700 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1702 F: FnOnce(&mut Buffer),
1704 w.write_str("<div class=\"docblock type-decl hidden-by-usual-hider\">");
1706 w.write_str("</div>")
1709 fn print_item(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
1710 debug_assert!(!item.is_stripped());
1711 // Write the breadcrumb trail header for the top
1712 buf.write_str("<h1 class=\"fqn\"><span class=\"in-band\">");
1713 let name = match *item.kind {
1714 clean::ModuleItem(ref m) => {
1721 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1722 clean::TraitItem(..) => "Trait ",
1723 clean::StructItem(..) => "Struct ",
1724 clean::UnionItem(..) => "Union ",
1725 clean::EnumItem(..) => "Enum ",
1726 clean::TypedefItem(..) => "Type Definition ",
1727 clean::MacroItem(..) => "Macro ",
1728 clean::ProcMacroItem(ref mac) => match mac.kind {
1729 MacroKind::Bang => "Macro ",
1730 MacroKind::Attr => "Attribute Macro ",
1731 MacroKind::Derive => "Derive Macro ",
1733 clean::PrimitiveItem(..) => "Primitive Type ",
1734 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1735 clean::ConstantItem(..) => "Constant ",
1736 clean::ForeignTypeItem => "Foreign Type ",
1737 clean::KeywordItem(..) => "Keyword ",
1738 clean::OpaqueTyItem(..) => "Opaque Type ",
1739 clean::TraitAliasItem(..) => "Trait Alias ",
1741 // We don't generate pages for any other type.
1745 buf.write_str(name);
1746 if !item.is_primitive() && !item.is_keyword() {
1747 let cur = &cx.current;
1748 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1749 for (i, component) in cur.iter().enumerate().take(amt) {
1752 "<a href=\"{}index.html\">{}</a>::<wbr>",
1753 "../".repeat(cur.len() - i - 1),
1758 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1760 buf.write_str("</span>"); // in-band
1761 buf.write_str("<span class=\"out-of-band\">");
1762 render_stability_since_raw(
1764 item.stable_since(cx.tcx()).as_deref(),
1765 item.const_stable_since(cx.tcx()).as_deref(),
1770 "<span id=\"render-detail\">\
1771 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1772 title=\"collapse all docs\">\
1773 [<span class=\"inner\">−</span>]\
1780 // When this item is part of a `crate use` in a downstream crate, the
1781 // [src] link in the downstream documentation will actually come back to
1782 // this page, and this link will be auto-clicked. The `id` attribute is
1783 // used to find the link to auto-click.
1784 if cx.shared.include_sources && !item.is_primitive() {
1785 write_srclink(cx, item, buf);
1788 buf.write_str("</span></h1>"); // out-of-band
1791 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1792 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1793 item_function(buf, cx, item, f)
1795 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
1796 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
1797 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
1798 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
1799 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t),
1800 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1801 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1802 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
1803 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1804 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1805 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
1806 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1807 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
1808 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
1810 // We don't generate pages for any other type.
1816 fn item_path(ty: ItemType, name: &str) -> String {
1818 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1819 _ => format!("{}.{}.html", ty, name),
1823 fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1824 let mut s = cx.current.join("::");
1826 s.push_str(&item.name.unwrap().as_str());
1830 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
1831 if let Some(ref name) = item.name {
1832 info!("Documenting {}", name);
1834 document_item_info(w, cx, item, false, parent);
1835 document_full(w, item, cx, "", false);
1838 /// Render md_text as markdown.
1843 links: Vec<RenderedLink>,
1847 let mut ids = cx.id_map.borrow_mut();
1850 "<div class=\"docblock{}\">{}{}</div>",
1851 if is_hidden { " hidden" } else { "" },
1859 &cx.shared.playground
1865 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1866 /// docs are longer, a "Read more" link is appended to the end.
1871 link: AssocItemLink<'_>,
1874 parent: Option<&clean::Item>,
1875 show_def_docs: bool,
1877 document_item_info(w, cx, item, is_hidden, parent);
1881 if let Some(s) = item.doc_value() {
1882 let mut summary_html = MarkdownSummaryLine(&s, &item.links(&cx.cache)).into_string();
1884 if s.contains('\n') {
1886 format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx.cache()));
1888 if let Some(idx) = summary_html.rfind("</p>") {
1889 summary_html.insert_str(idx, &link);
1891 summary_html.push_str(&link);
1897 "<div class='docblock{}'>{}{}</div>",
1898 if is_hidden { " hidden" } else { "" },
1902 } else if !prefix.is_empty() {
1905 "<div class=\"docblock{}\">{}</div>",
1906 if is_hidden { " hidden" } else { "" },
1919 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1920 debug!("Doc block: =====\n{}\n=====", s);
1921 render_markdown(w, cx, &*s, item.links(&cx.cache), prefix, is_hidden);
1922 } else if !prefix.is_empty() {
1924 w.write_str("<div class=\"docblock hidden\">");
1926 w.write_str("<div class=\"docblock\">");
1928 w.write_str(prefix);
1929 w.write_str("</div>");
1933 /// Add extra information about an item such as:
1937 /// * Required features (through the `doc_cfg` feature)
1938 fn document_item_info(
1943 parent: Option<&clean::Item>,
1945 let item_infos = short_item_info(item, cx, parent);
1946 if !item_infos.is_empty() {
1948 w.write_str("<div class=\"item-info hidden\">");
1950 w.write_str("<div class=\"item-info\">");
1952 for info in item_infos {
1955 w.write_str("</div>");
1959 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1960 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1963 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1964 if item.is_non_exhaustive() {
1965 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1966 if item.is_struct() {
1968 } else if item.is_enum() {
1970 } else if item.is_variant() {
1977 if item.is_struct() {
1979 "Non-exhaustive structs could have additional fields added in future. \
1980 Therefore, non-exhaustive structs cannot be constructed in external crates \
1981 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1982 matched against without a wildcard <code>..</code>; and \
1983 struct update syntax will not work.",
1985 } else if item.is_enum() {
1987 "Non-exhaustive enums could have additional variants added in future. \
1988 Therefore, when matching against variants of non-exhaustive enums, an \
1989 extra wildcard arm must be added to account for any future variants.",
1991 } else if item.is_variant() {
1993 "Non-exhaustive enum variants could have additional fields added in future. \
1994 Therefore, non-exhaustive enum variants cannot be constructed in external \
1995 crates and cannot be matched against.",
1999 "This type will require a wildcard arm in any match statements or constructors.",
2003 w.write_str("</div>");
2007 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
2008 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
2009 /// Takes a non-numeric and a numeric part from the given &str.
2010 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
2011 let i = s.find(|c: char| c.is_ascii_digit());
2012 let (a, b) = s.split_at(i.unwrap_or(s.len()));
2013 let i = b.find(|c: char| !c.is_ascii_digit());
2014 let (b, c) = b.split_at(i.unwrap_or(b.len()));
2019 while !lhs.is_empty() || !rhs.is_empty() {
2020 let (la, lb) = take_parts(&mut lhs);
2021 let (ra, rb) = take_parts(&mut rhs);
2022 // First process the non-numeric part.
2024 Ordering::Equal => (),
2027 // Then process the numeric part, if both sides have one (and they fit in a u64).
2028 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2030 Ordering::Equal => (),
2034 // Then process the numeric part again, but this time as strings.
2036 Ordering::Equal => (),
2044 fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) {
2045 document(w, cx, item, None);
2047 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2049 // the order of item types in the listing
2050 fn reorder(ty: ItemType) -> u8 {
2052 ItemType::ExternCrate => 0,
2053 ItemType::Import => 1,
2054 ItemType::Primitive => 2,
2055 ItemType::Module => 3,
2056 ItemType::Macro => 4,
2057 ItemType::Struct => 5,
2058 ItemType::Enum => 6,
2059 ItemType::Constant => 7,
2060 ItemType::Static => 8,
2061 ItemType::Trait => 9,
2062 ItemType::Function => 10,
2063 ItemType::Typedef => 12,
2064 ItemType::Union => 13,
2076 let ty1 = i1.type_();
2077 let ty2 = i2.type_();
2079 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2081 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
2082 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
2083 if let (Some(a), Some(b)) = (s1, s2) {
2084 match (a.is_stable(), b.is_stable()) {
2085 (true, true) | (false, false) => {}
2086 (false, true) => return Ordering::Less,
2087 (true, false) => return Ordering::Greater,
2090 let lhs = i1.name.unwrap_or(kw::Empty).as_str();
2091 let rhs = i2.name.unwrap_or(kw::Empty).as_str();
2092 compare_names(&lhs, &rhs)
2095 if cx.shared.sort_modules_alphabetically {
2096 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
2098 // This call is to remove re-export duplicates in cases such as:
2103 // crate trait Double { fn foo(); }
2107 // crate use foo::bar::*;
2108 // crate use foo::*;
2111 // `Double` will appear twice in the generated docs.
2113 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2114 // can be identical even if the elements are different (mostly in imports).
2115 // So in case this is an import, we keep everything by adding a "unique id"
2116 // (which is the position in the vector).
2117 indices.dedup_by_key(|i| {
2120 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2122 if items[*i].is_import() { *i } else { 0 },
2126 debug!("{:?}", indices);
2127 let mut curty = None;
2128 for &idx in &indices {
2129 let myitem = &items[idx];
2130 if myitem.is_stripped() {
2134 let myty = Some(myitem.type_());
2135 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2136 // Put `extern crate` and `use` re-exports in the same section.
2138 } else if myty != curty {
2139 if curty.is_some() {
2140 w.write_str("</table>");
2143 let (short, name) = item_ty_to_strs(&myty.unwrap());
2146 "<h2 id=\"{id}\" class=\"section-header\">\
2147 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2148 id = cx.derive_id(short.to_owned()),
2153 match *myitem.kind {
2154 clean::ExternCrateItem(ref name, ref src) => {
2155 use crate::html::format::anchor;
2158 Some(ref src) => write!(
2160 "<tr><td><code>{}extern crate {} as {};",
2161 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2162 anchor(myitem.def_id, &*src.as_str(), cx.cache()),
2167 "<tr><td><code>{}extern crate {};",
2168 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2169 anchor(myitem.def_id, &*name.as_str(), cx.cache())
2172 w.write_str("</code></td></tr>");
2175 clean::ImportItem(ref import) => {
2178 "<tr><td><code>{}{}</code></td></tr>",
2179 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2180 import.print(cx.cache())
2185 if myitem.name.is_none() {
2189 let unsafety_flag = match *myitem.kind {
2190 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2191 if func.header.unsafety == hir::Unsafety::Unsafe =>
2193 "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2198 let stab = myitem.stability_class(cx.tcx());
2199 let add = if stab.is_some() { " " } else { "" };
2201 let doc_value = myitem.doc_value().unwrap_or_default();
2204 "<tr class=\"{stab}{add}module-item\">\
2205 <td><a class=\"{class}\" href=\"{href}\" \
2206 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2207 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2209 name = *myitem.name.as_ref().unwrap(),
2210 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
2211 docs = MarkdownSummaryLine(&doc_value, &myitem.links(&cx.cache)).into_string(),
2212 class = myitem.type_(),
2214 stab = stab.unwrap_or_else(String::new),
2215 unsafety_flag = unsafety_flag,
2216 href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()),
2217 title = [full_path(cx, myitem), myitem.type_().to_string()]
2219 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2220 .collect::<Vec<_>>()
2227 if curty.is_some() {
2228 w.write_str("</table>");
2232 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
2233 /// at the module level.
2234 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
2235 let mut tags = String::new();
2237 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2238 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2241 // The trailing space after each tag is to space it properly against the rest of the docs.
2242 if let Some(depr) = &item.deprecation(tcx) {
2243 let mut message = "Deprecated";
2244 if !stability::deprecation_in_effect(
2245 depr.is_since_rustc_version,
2246 depr.since.map(|s| s.as_str()).as_deref(),
2248 message = "Deprecation planned";
2250 tags += &tag_html("deprecated", "", message);
2253 // The "rustc_private" crates are permanently unstable so it makes no sense
2254 // to render "unstable" everywhere.
2258 .map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2261 tags += &tag_html("unstable", "", "Experimental");
2264 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2265 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2266 (cfg, _) => cfg.as_deref().cloned(),
2269 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2270 if let Some(ref cfg) = cfg {
2271 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2277 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2278 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2279 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2280 (cfg, _) => cfg.as_deref().cloned(),
2284 "Portability {:?} - {:?} = {:?}",
2286 parent.and_then(|p| p.attrs.cfg.as_ref()),
2290 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2293 /// Render the stability, deprecation and portability information that is displayed at the top of
2294 /// the item's documentation.
2298 parent: Option<&clean::Item>,
2300 let mut extra_info = vec![];
2301 let error_codes = cx.shared.codes;
2303 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
2304 item.deprecation(cx.tcx())
2306 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2307 // but only display the future-deprecation messages for #[rustc_deprecated].
2308 let mut message = if let Some(since) = since {
2309 let since = &since.as_str();
2310 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2311 if *since == "TBD" {
2312 String::from("Deprecating in a future Rust version")
2314 format!("Deprecating in {}", Escape(since))
2317 format!("Deprecated since {}", Escape(since))
2320 String::from("Deprecated")
2323 if let Some(note) = note {
2324 let note = note.as_str();
2325 let mut ids = cx.id_map.borrow_mut();
2326 let html = MarkdownHtml(
2331 &cx.shared.playground,
2333 message.push_str(&format!(": {}", html.into_string()));
2335 extra_info.push(format!(
2336 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2341 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2342 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2343 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2344 .stability(cx.tcx())
2346 .filter(|stab| stab.feature != sym::rustc_private)
2347 .map(|stab| (stab.level, stab.feature))
2350 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2352 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2353 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2354 feature.push_str(&format!(
2355 " <a href=\"{url}{issue}\">#{issue}</a>",
2361 message.push_str(&format!(" ({})", feature));
2363 if let Some(unstable_reason) = reason {
2364 let mut ids = cx.id_map.borrow_mut();
2366 "<details><summary>{}</summary>{}</details>",
2369 &unstable_reason.as_str(),
2373 &cx.shared.playground,
2379 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2382 if let Some(portability) = portability(item, parent) {
2383 extra_info.push(portability);
2389 fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) {
2390 w.write_str("<pre class=\"rust const\">");
2391 render_attributes(w, it, false);
2395 "{vis}const {name}: {typ}",
2396 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2397 name = it.name.as_ref().unwrap(),
2398 typ = c.type_.print(cx.cache()),
2401 if c.value.is_some() || c.is_literal {
2402 write!(w, " = {expr};", expr = Escape(&c.expr));
2407 if let Some(value) = &c.value {
2409 let value_lowercase = value.to_lowercase();
2410 let expr_lowercase = c.expr.to_lowercase();
2412 if value_lowercase != expr_lowercase
2413 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2415 write!(w, " // {value}", value = Escape(value));
2420 w.write_str("</pre>");
2421 document(w, cx, it, None)
2424 fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
2425 w.write_str("<pre class=\"rust static\">");
2426 render_attributes(w, it, false);
2429 "{vis}static {mutability}{name}: {typ}</pre>",
2430 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2431 mutability = s.mutability.print_with_space(),
2432 name = it.name.as_ref().unwrap(),
2433 typ = s.type_.print(cx.cache())
2435 document(w, cx, it, None)
2438 fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
2439 let header_len = format!(
2440 "{}{}{}{}{:#}fn {}{:#}",
2441 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2442 f.header.constness.print_with_space(),
2443 f.header.asyncness.print_with_space(),
2444 f.header.unsafety.print_with_space(),
2445 print_abi_with_space(f.header.abi),
2446 it.name.as_ref().unwrap(),
2447 f.generics.print(cx.cache())
2450 w.write_str("<pre class=\"rust fn\">");
2451 render_attributes(w, it, false);
2454 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2455 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2456 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2457 constness = f.header.constness.print_with_space(),
2458 asyncness = f.header.asyncness.print_with_space(),
2459 unsafety = f.header.unsafety.print_with_space(),
2460 abi = print_abi_with_space(f.header.abi),
2461 name = it.name.as_ref().unwrap(),
2462 generics = f.generics.print(cx.cache()),
2464 WhereClause { gens: &f.generics, indent: 0, end_newline: true }.print(cx.cache()),
2465 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2467 spotlight = spotlight_decl(&f.decl, cx.cache()),
2469 document(w, cx, it, None)
2472 fn render_implementor(
2475 trait_: &clean::Item,
2477 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
2480 // If there's already another implementor that has the same abbridged name, use the
2481 // full path, for example in `std::iter::ExactSizeIterator`
2482 let use_absolute = match implementor.inner_impl().for_ {
2483 clean::ResolvedPath { ref path, is_generic: false, .. }
2484 | clean::BorrowedRef {
2485 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2487 } => implementor_dups[&path.last()].1,
2495 AssocItemLink::Anchor(None),
2497 trait_.stable_since(cx.tcx()).as_deref(),
2498 trait_.const_stable_since(cx.tcx()).as_deref(),
2511 containing_item: &clean::Item,
2513 let mut impls = traits
2516 let did = i.trait_did_full(cx.cache()).unwrap();
2517 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2518 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2526 containing_item.stable_since(cx.tcx()).as_deref(),
2527 containing_item.const_stable_since(cx.tcx()).as_deref(),
2536 .collect::<Vec<_>>();
2538 w.write_str(&impls.join(""));
2541 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cache: &Cache) -> String {
2542 let mut bounds = String::new();
2543 if !t_bounds.is_empty() {
2545 bounds.push_str(": ");
2547 for (i, p) in t_bounds.iter().enumerate() {
2549 bounds.push_str(" + ");
2551 bounds.push_str(&p.print(cache).to_string());
2557 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cache: &Cache) -> Ordering {
2558 let lhs = format!("{}", lhs.inner_impl().print(cache, false));
2559 let rhs = format!("{}", rhs.inner_impl().print(cache, false));
2561 // lhs and rhs are formatted as HTML, which may be unnecessary
2562 compare_names(&lhs, &rhs)
2565 fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) {
2566 let bounds = bounds(&t.bounds, false, cx.cache());
2567 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2568 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2569 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2570 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2572 // Output the trait definition
2573 wrap_into_docblock(w, |w| {
2574 w.write_str("<pre class=\"rust trait\">");
2575 render_attributes(w, it, true);
2578 "{}{}{}trait {}{}{}",
2579 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2580 t.unsafety.print_with_space(),
2581 if t.is_auto { "auto " } else { "" },
2582 it.name.as_ref().unwrap(),
2583 t.generics.print(cx.cache()),
2587 if !t.generics.where_predicates.is_empty() {
2588 let where_ = WhereClause { gens: &t.generics, indent: 0, end_newline: true };
2589 write!(w, "{}", where_.print(cx.cache()));
2594 if t.items.is_empty() {
2597 // FIXME: we should be using a derived_id for the Anchors here
2600 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2603 if !types.is_empty() && !consts.is_empty() {
2607 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2610 if !consts.is_empty() && !required.is_empty() {
2613 for (pos, m) in required.iter().enumerate() {
2614 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2617 if pos < required.len() - 1 {
2618 w.write_str("<div class=\"item-spacer\"></div>");
2621 if !required.is_empty() && !provided.is_empty() {
2624 for (pos, m) in provided.iter().enumerate() {
2625 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2627 clean::MethodItem(ref inner, _)
2628 if !inner.generics.where_predicates.is_empty() =>
2630 w.write_str(",\n { ... }\n");
2633 w.write_str(" { ... }\n");
2636 if pos < provided.len() - 1 {
2637 w.write_str("<div class=\"item-spacer\"></div>");
2642 w.write_str("</pre>")
2645 // Trait documentation
2646 document(w, cx, it, None);
2648 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2651 "<h2 id=\"{0}\" class=\"small-section-header\">\
2652 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2654 id, title, extra_content
2658 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2659 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2662 fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item) {
2663 let name = m.name.as_ref().unwrap();
2664 info!("Documenting {} on {:?}", name, t.name);
2665 let item_type = m.type_();
2666 let id = cx.derive_id(format!("{}.{}", item_type, name));
2667 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2668 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl, cx);
2669 w.write_str("</code>");
2670 render_stability_since(w, m, t, cx.tcx());
2671 write_srclink(cx, m, w);
2672 w.write_str("</h3>");
2673 document(w, cx, m, Some(t));
2676 if !types.is_empty() {
2677 write_small_section_header(
2681 "<div class=\"methods\">",
2684 trait_item(w, cx, t, it);
2686 write_loading_content(w, "</div>");
2689 if !consts.is_empty() {
2690 write_small_section_header(
2693 "Associated Constants",
2694 "<div class=\"methods\">",
2697 trait_item(w, cx, t, it);
2699 write_loading_content(w, "</div>");
2702 // Output the documentation for each function individually
2703 if !required.is_empty() {
2704 write_small_section_header(
2708 "<div class=\"methods\">",
2711 trait_item(w, cx, m, it);
2713 write_loading_content(w, "</div>");
2715 if !provided.is_empty() {
2716 write_small_section_header(
2720 "<div class=\"methods\">",
2723 trait_item(w, cx, m, it);
2725 write_loading_content(w, "</div>");
2728 // If there are methods directly on this trait object, render them here.
2729 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All);
2731 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2732 // The DefId is for the first Type found with that name. The bool is
2733 // if any Types with the same name but different DefId have been found.
2734 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
2735 for implementor in implementors {
2736 match implementor.inner_impl().for_ {
2737 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2738 | clean::BorrowedRef {
2739 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2742 let &mut (prev_did, ref mut has_duplicates) =
2743 implementor_dups.entry(path.last()).or_insert((did, false));
2744 if prev_did != did {
2745 *has_duplicates = true;
2752 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2755 .def_id_full(cx.cache())
2756 .map_or(true, |d| cx.cache.paths.contains_key(&d))
2759 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2760 local.iter().partition(|i| i.inner_impl().synthetic);
2762 synthetic.sort_by(|a, b| compare_impl(a, b, cx.cache()));
2763 concrete.sort_by(|a, b| compare_impl(a, b, cx.cache()));
2765 if !foreign.is_empty() {
2766 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2768 for implementor in foreign {
2769 let assoc_link = AssocItemLink::GotoSource(
2770 implementor.impl_item.def_id,
2771 &implementor.inner_impl().provided_trait_methods,
2780 implementor.impl_item.stable_since(cx.tcx()).as_deref(),
2781 implementor.impl_item.const_stable_since(cx.tcx()).as_deref(),
2789 write_loading_content(w, "");
2792 write_small_section_header(
2796 "<div class=\"item-list\" id=\"implementors-list\">",
2798 for implementor in concrete {
2799 render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
2801 write_loading_content(w, "</div>");
2804 write_small_section_header(
2806 "synthetic-implementors",
2807 "Auto implementors",
2808 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2810 for implementor in synthetic {
2817 &collect_paths_for_type(implementor.inner_impl().for_.clone(), &cx.cache),
2820 write_loading_content(w, "</div>");
2823 // even without any implementations to write in, we still want the heading and list, so the
2824 // implementors javascript file pulled in below has somewhere to write the impls into
2825 write_small_section_header(
2829 "<div class=\"item-list\" id=\"implementors-list\">",
2831 write_loading_content(w, "</div>");
2834 write_small_section_header(
2836 "synthetic-implementors",
2837 "Auto implementors",
2838 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2840 write_loading_content(w, "</div>");
2846 "<script type=\"text/javascript\" \
2847 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2849 root_path = vec![".."; cx.current.len()].join("/"),
2850 path = if it.def_id.is_local() {
2851 cx.current.join("/")
2853 let (ref path, _) = cx.cache.external_paths[&it.def_id];
2854 path[..path.len() - 1].join("/")
2857 name = *it.name.as_ref().unwrap()
2861 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cache: &Cache) -> String {
2862 use crate::formats::item_type::ItemType::*;
2864 let name = it.name.as_ref().unwrap();
2865 let ty = match it.type_() {
2866 Typedef | AssocType => AssocType,
2870 let anchor = format!("#{}.{}", ty, name);
2872 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2873 AssocItemLink::Anchor(None) => anchor,
2874 AssocItemLink::GotoSource(did, _) => {
2875 href(did, cache).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2884 _default: Option<&String>,
2885 link: AssocItemLink<'_>,
2891 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2893 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2894 naive_assoc_href(it, link, cx.cache()),
2895 it.name.as_ref().unwrap(),
2896 ty.print(cx.cache())
2903 bounds: &[clean::GenericBound],
2904 default: Option<&clean::Type>,
2905 link: AssocItemLink<'_>,
2911 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2913 naive_assoc_href(it, link, cache),
2914 it.name.as_ref().unwrap()
2916 if !bounds.is_empty() {
2917 write!(w, ": {}", print_generic_bounds(bounds, cache))
2919 if let Some(default) = default {
2920 write!(w, " = {}", default.print(cache))
2924 fn render_stability_since_raw(
2927 const_ver: Option<&str>,
2928 containing_ver: Option<&str>,
2929 containing_const_ver: Option<&str>,
2931 let ver = ver.filter(|inner| !inner.is_empty());
2932 let const_ver = const_ver.filter(|inner| !inner.is_empty());
2934 match (ver, const_ver) {
2935 (Some(v), Some(cv)) if const_ver != containing_const_ver => {
2938 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2942 (Some(v), _) if ver != containing_ver => {
2945 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2953 fn render_stability_since(
2956 containing_item: &clean::Item,
2959 render_stability_since_raw(
2961 item.stable_since(tcx).as_deref(),
2962 item.const_stable_since(tcx).as_deref(),
2963 containing_item.stable_since(tcx).as_deref(),
2964 containing_item.const_stable_since(tcx).as_deref(),
2968 fn render_assoc_item(
2971 link: AssocItemLink<'_>,
2978 header: hir::FnHeader,
2979 g: &clean::Generics,
2981 link: AssocItemLink<'_>,
2985 let name = meth.name.as_ref().unwrap();
2986 let anchor = format!("#{}.{}", meth.type_(), name);
2987 let href = match link {
2988 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2989 AssocItemLink::Anchor(None) => anchor,
2990 AssocItemLink::GotoSource(did, provided_methods) => {
2991 // We're creating a link from an impl-item to the corresponding
2992 // trait-item and need to map the anchored type accordingly.
2993 let ty = if provided_methods.contains(&name) {
2999 href(did, cx.cache()).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3002 let mut header_len = format!(
3003 "{}{}{}{}{}{:#}fn {}{:#}",
3004 meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
3005 header.constness.print_with_space(),
3006 header.asyncness.print_with_space(),
3007 header.unsafety.print_with_space(),
3008 print_default_space(meth.is_default()),
3009 print_abi_with_space(header.abi),
3014 let (indent, end_newline) = if parent == ItemType::Trait {
3020 render_attributes(w, meth, false);
3023 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
3024 {generics}{decl}{spotlight}{where_clause}",
3025 if parent == ItemType::Trait { " " } else { "" },
3026 meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
3027 header.constness.print_with_space(),
3028 header.asyncness.print_with_space(),
3029 header.unsafety.print_with_space(),
3030 print_default_space(meth.is_default()),
3031 print_abi_with_space(header.abi),
3034 generics = g.print(cx.cache()),
3035 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }
3037 spotlight = spotlight_decl(&d, cx.cache()),
3038 where_clause = WhereClause { gens: g, indent, end_newline }.print(cx.cache())
3042 clean::StrippedItem(..) => {}
3043 clean::TyMethodItem(ref m) => {
3044 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
3046 clean::MethodItem(ref m, _) => {
3047 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
3049 clean::AssocConstItem(ref ty, ref default) => assoc_const(
3055 if parent == ItemType::Trait { " " } else { "" },
3058 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3064 if parent == ItemType::Trait { " " } else { "" },
3067 _ => panic!("render_assoc_item called on non-associated-item"),
3071 fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) {
3072 wrap_into_docblock(w, |w| {
3073 w.write_str("<pre class=\"rust struct\">");
3074 render_attributes(w, it, true);
3075 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
3076 w.write_str("</pre>")
3079 document(w, cx, it, None);
3083 .filter_map(|f| match *f.kind {
3084 clean::StructFieldItem(ref ty) => Some((f, ty)),
3088 if let CtorKind::Fictive = s.struct_type {
3089 if fields.peek().is_some() {
3092 "<h2 id=\"fields\" class=\"fields small-section-header\">
3093 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3094 document_non_exhaustive_header(it)
3096 document_non_exhaustive(w, it);
3097 for (field, ty) in fields {
3098 let id = cx.derive_id(format!(
3100 ItemType::StructField,
3101 field.name.as_ref().unwrap()
3105 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3106 <a href=\"#{id}\" class=\"anchor field\"></a>\
3107 <code>{name}: {ty}</code>\
3109 item_type = ItemType::StructField,
3111 name = field.name.as_ref().unwrap(),
3112 ty = ty.print(cx.cache())
3114 document(w, cx, field, Some(it));
3118 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3121 fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
3122 wrap_into_docblock(w, |w| {
3123 w.write_str("<pre class=\"rust union\">");
3124 render_attributes(w, it, true);
3125 render_union(w, it, Some(&s.generics), &s.fields, "", true, cx);
3126 w.write_str("</pre>")
3129 document(w, cx, it, None);
3133 .filter_map(|f| match *f.kind {
3134 clean::StructFieldItem(ref ty) => Some((f, ty)),
3138 if fields.peek().is_some() {
3141 "<h2 id=\"fields\" class=\"fields small-section-header\">
3142 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3144 for (field, ty) in fields {
3145 let name = field.name.as_ref().expect("union field name");
3146 let id = format!("{}.{}", ItemType::StructField, name);
3149 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3150 <a href=\"#{id}\" class=\"anchor field\"></a>\
3151 <code>{name}: {ty}</code>\
3155 shortty = ItemType::StructField,
3156 ty = ty.print(cx.cache())
3158 if let Some(stability_class) = field.stability_class(cx.tcx()) {
3159 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3161 document(w, cx, field, Some(it));
3164 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3167 fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
3168 wrap_into_docblock(w, |w| {
3169 w.write_str("<pre class=\"rust enum\">");
3170 render_attributes(w, it, true);
3174 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3175 it.name.as_ref().unwrap(),
3176 e.generics.print(cx.cache()),
3177 WhereClause { gens: &e.generics, indent: 0, end_newline: true }.print(cx.cache())
3179 if e.variants.is_empty() && !e.variants_stripped {
3182 w.write_str(" {\n");
3183 for v in &e.variants {
3185 let name = v.name.as_ref().unwrap();
3187 clean::VariantItem(ref var) => match var {
3188 clean::Variant::CLike => write!(w, "{}", name),
3189 clean::Variant::Tuple(ref tys) => {
3190 write!(w, "{}(", name);
3191 for (i, ty) in tys.iter().enumerate() {
3193 w.write_str(", ")
3195 write!(w, "{}", ty.print(cx.cache()));
3199 clean::Variant::Struct(ref s) => {
3200 render_struct(w, v, None, s.struct_type, &s.fields, " ", false, cx);
3203 _ => unreachable!(),
3208 if e.variants_stripped {
3209 w.write_str(" // some variants omitted\n");
3213 w.write_str("</pre>")
3216 document(w, cx, it, None);
3217 if !e.variants.is_empty() {
3220 "<h2 id=\"variants\" class=\"variants small-section-header\">
3221 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3222 document_non_exhaustive_header(it)
3224 document_non_exhaustive(w, it);
3225 for variant in &e.variants {
3227 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3230 "<div id=\"{id}\" class=\"variant small-section-header\">\
3231 <a href=\"#{id}\" class=\"anchor field\"></a>\
3234 name = variant.name.as_ref().unwrap()
3236 if let clean::VariantItem(clean::Variant::Tuple(ref tys)) = *variant.kind {
3238 for (i, ty) in tys.iter().enumerate() {
3240 w.write_str(", ");
3242 write!(w, "{}", ty.print(cx.cache()));
3246 w.write_str("</code></div>");
3247 document(w, cx, variant, Some(it));
3248 document_non_exhaustive(w, variant);
3250 use crate::clean::Variant;
3251 if let clean::VariantItem(Variant::Struct(ref s)) = *variant.kind {
3252 let variant_id = cx.derive_id(format!(
3255 variant.name.as_ref().unwrap()
3257 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3260 "<h3>Fields of <b>{name}</b></h3><div>",
3261 name = variant.name.as_ref().unwrap()
3263 for field in &s.fields {
3264 use crate::clean::StructFieldItem;
3265 if let StructFieldItem(ref ty) = *field.kind {
3266 let id = cx.derive_id(format!(
3267 "variant.{}.field.{}",
3268 variant.name.as_ref().unwrap(),
3269 field.name.as_ref().unwrap()
3273 "<span id=\"{id}\" class=\"variant small-section-header\">\
3274 <a href=\"#{id}\" class=\"anchor field\"></a>\
3275 <code>{f}: {t}</code>\
3278 f = field.name.as_ref().unwrap(),
3279 t = ty.print(cx.cache())
3281 document(w, cx, field, Some(variant));
3284 w.write_str("</div></div>");
3286 render_stability_since(w, variant, it, cx.tcx());
3289 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3292 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3299 sym::non_exhaustive,
3302 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3303 // left padding. For example:
3305 // #[foo] <----- "top" attribute
3307 // #[bar] <---- not "top" attribute
3310 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3315 .filter_map(|attr| {
3316 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3317 Some(pprust::attribute_to_string(&attr))
3324 if !attrs.is_empty() {
3327 "<span class=\"docblock attributes{}\">{}</span>",
3328 if top { " top-attr" } else { "" },
3337 g: Option<&clean::Generics>,
3339 fields: &[clean::Item],
3347 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3348 if structhead { "struct " } else { "" },
3349 it.name.as_ref().unwrap()
3351 if let Some(g) = g {
3352 write!(w, "{}", g.print(cx.cache()))
3355 CtorKind::Fictive => {
3356 if let Some(g) = g {
3360 WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache())
3363 let mut has_visible_fields = false;
3365 for field in fields {
3366 if let clean::StructFieldItem(ref ty) = *field.kind {
3371 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3372 field.name.as_ref().unwrap(),
3373 ty.print(cx.cache())
3375 has_visible_fields = true;
3379 if has_visible_fields {
3380 if it.has_stripped_fields().unwrap() {
3381 write!(w, "\n{} // some fields omitted", tab);
3383 write!(w, "\n{}", tab);
3384 } else if it.has_stripped_fields().unwrap() {
3385 // If there are no visible fields we can just display
3386 // `{ /* fields omitted */ }` to save space.
3387 write!(w, " /* fields omitted */ ");
3393 for (i, field) in fields.iter().enumerate() {
3398 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3399 clean::StructFieldItem(ref ty) => {
3403 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3404 ty.print(cx.cache())
3407 _ => unreachable!(),
3411 if let Some(g) = g {
3415 WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache())
3420 CtorKind::Const => {
3421 // Needed for PhantomData.
3422 if let Some(g) = g {
3426 WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache())
3437 g: Option<&clean::Generics>,
3438 fields: &[clean::Item],
3446 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3447 if structhead { "union " } else { "" },
3448 it.name.as_ref().unwrap()
3450 if let Some(g) = g {
3451 write!(w, "{}", g.print(cx.cache()));
3452 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache()));
3455 write!(w, " {{\n{}", tab);
3456 for field in fields {
3457 if let clean::StructFieldItem(ref ty) = *field.kind {
3461 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3462 field.name.as_ref().unwrap(),
3463 ty.print(cx.cache()),
3469 if it.has_stripped_fields().unwrap() {
3470 write!(w, " // some fields omitted\n{}", tab);
3475 #[derive(Copy, Clone)]
3476 enum AssocItemLink<'a> {
3477 Anchor(Option<&'a str>),
3478 GotoSource(DefId, &'a FxHashSet<Symbol>),
3481 impl<'a> AssocItemLink<'a> {
3482 fn anchor(&self, id: &'a str) -> Self {
3484 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3485 ref other => *other,
3490 fn render_assoc_items(
3493 containing_item: &clean::Item,
3495 what: AssocItemRender<'_>,
3497 info!("Documenting associated items of {:?}", containing_item.name);
3498 let v = match cx.cache.impls.get(&it) {
3502 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3503 if !non_trait.is_empty() {
3504 let render_mode = match what {
3505 AssocItemRender::All => {
3507 "<h2 id=\"implementations\" class=\"small-section-header\">\
3508 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3513 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3514 let id = cx.derive_id(small_url_encode(format!(
3515 "deref-methods-{:#}",
3516 type_.print(cx.cache())
3518 debug!("Adding {} to deref id map", type_.print(cx.cache()));
3521 .insert(type_.def_id_full(cx.cache()).unwrap(), id.clone());
3524 "<h2 id=\"{id}\" class=\"small-section-header\">\
3525 Methods from {trait_}<Target = {type_}>\
3526 <a href=\"#{id}\" class=\"anchor\"></a>\
3529 trait_ = trait_.print(cx.cache()),
3530 type_ = type_.print(cx.cache()),
3532 RenderMode::ForDeref { mut_: deref_mut_ }
3535 for i in &non_trait {
3541 AssocItemLink::Anchor(None),
3543 containing_item.stable_since(cx.tcx()).as_deref(),
3544 containing_item.const_stable_since(cx.tcx()).as_deref(),
3553 if !traits.is_empty() {
3554 let deref_impl = traits
3556 .find(|t| t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did);
3557 if let Some(impl_) = deref_impl {
3558 let has_deref_mut = traits.iter().any(|t| {
3559 t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_mut_trait_did
3561 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
3564 // If we were already one level into rendering deref methods, we don't want to render
3565 // anything after recursing into any further deref methods above.
3566 if let AssocItemRender::DerefFor { .. } = what {
3570 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3571 traits.iter().partition(|t| t.inner_impl().synthetic);
3572 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3573 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3575 let mut impls = Buffer::empty_from(&w);
3576 render_impls(cx, &mut impls, &concrete, containing_item);
3577 let impls = impls.into_inner();
3578 if !impls.is_empty() {
3581 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3582 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3584 <div id=\"trait-implementations-list\">{}</div>",
3589 if !synthetic.is_empty() {
3591 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3592 Auto Trait Implementations\
3593 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3595 <div id=\"synthetic-implementations-list\">",
3597 render_impls(cx, w, &synthetic, containing_item);
3598 w.write_str("</div>");
3601 if !blanket_impl.is_empty() {
3603 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3604 Blanket Implementations\
3605 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3607 <div id=\"blanket-implementations-list\">",
3609 render_impls(cx, w, &blanket_impl, containing_item);
3610 w.write_str("</div>");
3615 fn render_deref_methods(
3619 container_item: &clean::Item,
3622 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3623 let (target, real_target) = impl_
3627 .find_map(|item| match *item.kind {
3628 clean::TypedefItem(ref t, true) => Some(match *t {
3629 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3630 _ => (&t.type_, &t.type_),
3634 .expect("Expected associated type binding");
3635 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
3637 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3638 if let Some(did) = target.def_id_full(cx.cache()) {
3639 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
3640 // `impl Deref<Target = S> for S`
3641 if did == type_did {
3642 // Avoid infinite cycles
3646 render_assoc_items(w, cx, container_item, did, what);
3648 if let Some(prim) = target.primitive_type() {
3649 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
3650 render_assoc_items(w, cx, container_item, did, what);
3656 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
3657 let self_type_opt = match *item.kind {
3658 clean::MethodItem(ref method, _) => method.decl.self_type(),
3659 clean::TyMethodItem(ref method) => method.decl.self_type(),
3663 if let Some(self_ty) = self_type_opt {
3664 let (by_mut_ref, by_box, by_value) = match self_ty {
3665 SelfTy::SelfBorrowed(_, mutability)
3666 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3667 (mutability == Mutability::Mut, false, false)
3669 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3670 (false, Some(did) == cache.owned_box_did, false)
3672 SelfTy::SelfValue => (false, false, true),
3673 _ => (false, false, false),
3676 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3682 fn spotlight_decl(decl: &clean::FnDecl, cache: &Cache) -> String {
3683 let mut out = Buffer::html();
3684 let mut trait_ = String::new();
3686 if let Some(did) = decl.output.def_id_full(cache) {
3687 if let Some(impls) = cache.impls.get(&did) {
3689 let impl_ = i.inner_impl();
3690 if impl_.trait_.def_id().map_or(false, |d| {
3691 cache.traits.get(&d).map(|t| t.is_spotlight).unwrap_or(false)
3696 "<h3 class=\"notable\">Notable traits for {}</h3>\
3697 <code class=\"content\">",
3698 impl_.for_.print(cache)
3700 trait_.push_str(&impl_.for_.print(cache).to_string());
3703 //use the "where" class here to make it small
3706 "<span class=\"where fmt-newline\">{}</span>",
3707 impl_.print(cache, false)
3709 let t_did = impl_.trait_.def_id_full(cache).unwrap();
3710 for it in &impl_.items {
3711 if let clean::TypedefItem(ref tydef, _) = *it.kind {
3712 out.push_str("<span class=\"where fmt-newline\"> ");
3718 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3722 out.push_str(";</span>");
3730 if !out.is_empty() {
3733 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3734 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3736 out.push_str("</code></span></div></span></span>");
3746 parent: &clean::Item,
3747 link: AssocItemLink<'_>,
3748 render_mode: RenderMode,
3749 outer_version: Option<&str>,
3750 outer_const_version: Option<&str>,
3751 show_def_docs: bool,
3752 use_absolute: Option<bool>,
3753 is_on_foreign_type: bool,
3754 show_default_items: bool,
3755 // This argument is used to reference same type with different paths to avoid duplication
3756 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3759 let traits = &cx.cache.traits;
3760 let trait_ = i.trait_did_full(cx.cache()).map(|did| &traits[&did]);
3762 if render_mode == RenderMode::Normal {
3763 let id = cx.derive_id(match i.inner_impl().trait_ {
3765 if is_on_foreign_type {
3766 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx.cache())
3768 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx.cache()))))
3771 None => "impl".to_string(),
3773 let aliases = if aliases.is_empty() {
3776 format!(" aliases=\"{}\"", aliases.join(","))
3778 if let Some(use_absolute) = use_absolute {
3779 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3780 write!(w, "{}", i.inner_impl().print(cx.cache(), use_absolute));
3782 for it in &i.inner_impl().items {
3783 if let clean::TypedefItem(ref tydef, _) = *it.kind {
3784 w.write_str("<span class=\"where fmt-newline\"> ");
3790 AssocItemLink::Anchor(None),
3794 w.write_str(";</span>");
3798 w.write_str("</code>");
3802 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3805 i.inner_impl().print(cx.cache(), false)
3808 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3809 render_stability_since_raw(
3811 i.impl_item.stable_since(cx.tcx()).as_deref(),
3812 i.impl_item.const_stable_since(cx.tcx()).as_deref(),
3814 outer_const_version,
3816 write_srclink(cx, &i.impl_item, w);
3817 w.write_str("</h3>");
3819 if trait_.is_some() {
3820 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3821 write!(w, "<div class=\"item-info\">{}</div>", portability);
3825 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3826 let mut ids = cx.id_map.borrow_mut();
3829 "<div class=\"docblock\">{}</div>",
3832 &i.impl_item.links(&cx.cache),
3836 &cx.shared.playground
3847 parent: &clean::Item,
3848 link: AssocItemLink<'_>,
3849 render_mode: RenderMode,
3850 is_default_item: bool,
3851 outer_version: Option<&str>,
3852 outer_const_version: Option<&str>,
3853 trait_: Option<&clean::Trait>,
3854 show_def_docs: bool,
3856 let item_type = item.type_();
3857 let name = item.name.as_ref().unwrap();
3859 let render_method_item = match render_mode {
3860 RenderMode::Normal => true,
3861 RenderMode::ForDeref { mut_: deref_mut_ } => {
3862 should_render_item(&item, deref_mut_, &cx.cache)
3866 let (is_hidden, extra_class) =
3867 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3875 clean::MethodItem(..) | clean::TyMethodItem(_) => {
3876 // Only render when the method is not static or we allow static methods
3877 if render_method_item {
3878 let id = cx.derive_id(format!("{}.{}", item_type, name));
3879 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3880 w.write_str("<code>");
3881 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx);
3882 w.write_str("</code>");
3883 render_stability_since_raw(
3885 item.stable_since(cx.tcx()).as_deref(),
3886 item.const_stable_since(cx.tcx()).as_deref(),
3888 outer_const_version,
3890 write_srclink(cx, item, w);
3891 w.write_str("</h4>");
3894 clean::TypedefItem(ref tydef, _) => {
3895 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3896 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3906 w.write_str("</code></h4>");
3908 clean::AssocConstItem(ref ty, ref default) => {
3909 let id = cx.derive_id(format!("{}.{}", item_type, name));
3910 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3911 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "", cx);
3912 w.write_str("</code>");
3913 render_stability_since_raw(
3915 item.stable_since(cx.tcx()).as_deref(),
3916 item.const_stable_since(cx.tcx()).as_deref(),
3918 outer_const_version,
3920 write_srclink(cx, item, w);
3921 w.write_str("</h4>");
3923 clean::AssocTypeItem(ref bounds, ref default) => {
3924 let id = cx.derive_id(format!("{}.{}", item_type, name));
3925 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3926 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "", cx.cache());
3927 w.write_str("</code></h4>");
3929 clean::StrippedItem(..) => return,
3930 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3933 if render_method_item {
3934 if !is_default_item {
3935 if let Some(t) = trait_ {
3936 // The trait item may have been stripped so we might not
3937 // find any documentation or stability for it.
3938 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3939 // We need the stability of the item from the trait
3940 // because impls can't have a stability.
3941 if item.doc_value().is_some() {
3942 document_item_info(w, cx, it, is_hidden, Some(parent));
3943 document_full(w, item, cx, "", is_hidden);
3945 // In case the item isn't documented,
3946 // provide short documentation from the trait.
3960 document_item_info(w, cx, item, is_hidden, Some(parent));
3962 document_full(w, item, cx, "", is_hidden);
3966 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3971 w.write_str("<div class=\"impl-items\">");
3972 for trait_item in &i.inner_impl().items {
3977 if trait_.is_some() { &i.impl_item } else { parent },
3982 outer_const_version,
3983 trait_.map(|t| &t.trait_),
3988 fn render_default_items(
3993 parent: &clean::Item,
3994 render_mode: RenderMode,
3995 outer_version: Option<&str>,
3996 outer_const_version: Option<&str>,
3997 show_def_docs: bool,
3999 for trait_item in &t.items {
4000 let n = trait_item.name;
4001 if i.items.iter().any(|m| m.name == n) {
4004 let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
4005 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4016 outer_const_version,
4023 // If we've implemented a trait, then also emit documentation for all
4024 // default items which weren't overridden in the implementation block.
4025 // We don't emit documentation for default items if they appear in the
4026 // Implementations on Foreign Types or Implementors sections.
4027 if show_default_items {
4028 if let Some(t) = trait_ {
4029 render_default_items(
4037 outer_const_version,
4042 w.write_str("</div>");
4045 fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
4046 w.write_str("<pre class=\"rust opaque\">");
4047 render_attributes(w, it, false);
4050 "type {}{}{where_clause} = impl {bounds};</pre>",
4051 it.name.as_ref().unwrap(),
4052 t.generics.print(cx.cache()),
4054 WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4055 bounds = bounds(&t.bounds, false, cx.cache())
4058 document(w, cx, it, None);
4060 // Render any items associated directly to this alias, as otherwise they
4061 // won't be visible anywhere in the docs. It would be nice to also show
4062 // associated items from the aliased type (see discussion in #32077), but
4063 // we need #14072 to make sense of the generics.
4064 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4067 fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
4068 w.write_str("<pre class=\"rust trait-alias\">");
4069 render_attributes(w, it, false);
4072 "trait {}{}{} = {};</pre>",
4073 it.name.as_ref().unwrap(),
4074 t.generics.print(cx.cache()),
4075 WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4076 bounds(&t.bounds, true, cx.cache())
4079 document(w, cx, it, None);
4081 // Render any items associated directly to this alias, as otherwise they
4082 // won't be visible anywhere in the docs. It would be nice to also show
4083 // associated items from the aliased type (see discussion in #32077), but
4084 // we need #14072 to make sense of the generics.
4085 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4088 fn item_typedef(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
4089 w.write_str("<pre class=\"rust typedef\">");
4090 render_attributes(w, it, false);
4093 "type {}{}{where_clause} = {type_};</pre>",
4094 it.name.as_ref().unwrap(),
4095 t.generics.print(cx.cache()),
4097 WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4098 type_ = t.type_.print(cx.cache())
4101 document(w, cx, it, None);
4103 // Render any items associated directly to this alias, as otherwise they
4104 // won't be visible anywhere in the docs. It would be nice to also show
4105 // associated items from the aliased type (see discussion in #32077), but
4106 // we need #14072 to make sense of the generics.
4107 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4110 fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4111 w.write_str("<pre class=\"rust foreigntype\">extern {\n");
4112 render_attributes(w, it, false);
4115 " {}type {};\n}}</pre>",
4116 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
4117 it.name.as_ref().unwrap(),
4120 document(w, cx, it, None);
4122 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4125 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
4126 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4130 || it.is_primitive()
4138 "<p class=\"location\">{}{}</p>",
4140 clean::StructItem(..) => "Struct ",
4141 clean::TraitItem(..) => "Trait ",
4142 clean::PrimitiveItem(..) => "Primitive Type ",
4143 clean::UnionItem(..) => "Union ",
4144 clean::EnumItem(..) => "Enum ",
4145 clean::TypedefItem(..) => "Type Definition ",
4146 clean::ForeignTypeItem => "Foreign Type ",
4147 clean::ModuleItem(..) =>
4155 it.name.as_ref().unwrap()
4160 if let Some(ref version) = cx.cache.crate_version {
4163 "<div class=\"block version\">\
4171 buffer.write_str("<div class=\"sidebar-elems\">");
4175 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4176 it.name.as_ref().expect("crates always have a name")
4180 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
4181 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
4182 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
4183 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
4184 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
4185 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
4186 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4187 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
4191 // The sidebar is designed to display sibling functions, modules and
4192 // other miscellaneous information. since there are lots of sibling
4193 // items (and that causes quadratic growth in large modules),
4194 // we refactor common parts into a shared JavaScript file per module.
4195 // still, we don't move everything into JS because we want to preserve
4196 // as much HTML as possible in order to allow non-JS-enabled browsers
4197 // to navigate the documentation (though slightly inefficiently).
4199 buffer.write_str("<p class=\"location\">");
4200 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4202 buffer.write_str("::<wbr>");
4206 "<a href=\"{}index.html\">{}</a>",
4207 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4211 buffer.write_str("</p>");
4213 // Sidebar refers to the enclosing module, not this module.
4214 let relpath = if it.is_mod() { "../" } else { "" };
4217 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
4219 name = it.name.unwrap_or(kw::Empty),
4224 // There is no sidebar-items.js beyond the crate root path
4225 // FIXME maybe dynamic crate loading can be merged here
4227 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4229 // Closes sidebar-elems div.
4230 buffer.write_str("</div>");
4233 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4234 if used_links.insert(url.clone()) {
4238 while !used_links.insert(format!("{}-{}", url, add)) {
4241 format!("{}-{}", url, add)
4247 used_links: &mut FxHashSet<String>,
4253 .filter_map(|item| match item.name {
4254 Some(ref name) if !name.is_empty() && item.is_method() => {
4255 if !for_deref || should_render_item(item, deref_mut, cache) {
4257 "<a href=\"#{}\">{}</a>",
4258 get_next_url(used_links, format!("method.{}", name)),
4267 .collect::<Vec<_>>()
4270 // The point is to url encode any potential character from a type with genericity.
4271 fn small_url_encode(s: String) -> String {
4272 let mut st = String::new();
4273 let mut last_match = 0;
4274 for (idx, c) in s.char_indices() {
4275 let escaped = match c {
4291 st += &s[last_match..idx];
4293 // NOTE: we only expect single byte characters here - which is fine as long as we
4294 // only match single byte characters
4295 last_match = idx + 1;
4298 if last_match != 0 {
4299 st += &s[last_match..];
4306 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
4307 if let Some(v) = cx.cache.impls.get(&it.def_id) {
4308 let mut used_links = FxHashSet::default();
4311 let used_links_bor = &mut used_links;
4314 .filter(|i| i.inner_impl().trait_.is_none())
4315 .flat_map(move |i| {
4316 get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
4318 .collect::<Vec<_>>();
4319 if !ret.is_empty() {
4320 // We want links' order to be reproducible so we don't use unstable sort.
4324 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4325 <div class=\"sidebar-links\">",
4328 out.push_str(&line);
4330 out.push_str("</div>");
4334 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4335 if let Some(impl_) = v
4337 .filter(|i| i.inner_impl().trait_.is_some())
4338 .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did)
4340 sidebar_deref_methods(cx, out, impl_, v);
4342 let format_impls = |impls: Vec<&Impl>| {
4343 let mut links = FxHashSet::default();
4348 if let Some(ref i) = it.inner_impl().trait_ {
4349 let i_display = format!("{:#}", i.print(cx.cache()));
4350 let out = Escape(&i_display);
4351 let encoded = small_url_encode(format!("{:#}", i.print(cx.cache())));
4352 let generated = format!(
4353 "<a href=\"#impl-{}\">{}{}</a>",
4355 if it.inner_impl().negative_polarity { "!" } else { "" },
4358 if links.insert(generated.clone()) { Some(generated) } else { None }
4363 .collect::<Vec<String>>();
4368 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
4369 out.push_str("<div class=\"sidebar-links\">");
4371 out.push_str(&link);
4373 out.push_str("</div>");
4376 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4377 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4378 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4380 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4382 let concrete_format = format_impls(concrete);
4383 let synthetic_format = format_impls(synthetic);
4384 let blanket_format = format_impls(blanket_impl);
4386 if !concrete_format.is_empty() {
4388 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4389 Trait Implementations</a>",
4391 write_sidebar_links(out, concrete_format);
4394 if !synthetic_format.is_empty() {
4396 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4397 Auto Trait Implementations</a>",
4399 write_sidebar_links(out, synthetic_format);
4402 if !blanket_format.is_empty() {
4404 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4405 Blanket Implementations</a>",
4407 write_sidebar_links(out, blanket_format);
4413 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
4416 debug!("found Deref: {:?}", impl_);
4417 if let Some((target, real_target)) =
4418 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
4419 clean::TypedefItem(ref t, true) => Some(match *t {
4420 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4421 _ => (&t.type_, &t.type_),
4426 debug!("found target, real_target: {:?} {:?}", target, real_target);
4427 if let Some(did) = target.def_id_full(cx.cache()) {
4428 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
4429 // `impl Deref<Target = S> for S`
4430 if did == type_did {
4431 // Avoid infinite cycles
4438 .filter(|i| i.inner_impl().trait_.is_some())
4439 .any(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_mut_trait_did);
4440 let inner_impl = target
4441 .def_id_full(cx.cache())
4443 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
4445 .and_then(|did| c.impls.get(&did));
4446 if let Some(impls) = inner_impl {
4447 debug!("found inner_impl: {:?}", impls);
4448 let mut used_links = FxHashSet::default();
4451 .filter(|i| i.inner_impl().trait_.is_none())
4452 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
4453 .collect::<Vec<_>>();
4454 if !ret.is_empty() {
4455 let deref_id_map = cx.deref_id_map.borrow();
4456 let id = deref_id_map
4457 .get(&real_target.def_id_full(cx.cache()).unwrap())
4458 .expect("Deref section without derived id");
4461 "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}<Target={}></a>",
4463 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(c))),
4464 Escape(&format!("{:#}", real_target.print(c))),
4466 // We want links' order to be reproducible so we don't use unstable sort.
4468 out.push_str("<div class=\"sidebar-links\">");
4470 out.push_str(&link);
4472 out.push_str("</div>");
4476 // Recurse into any further impls that might exist for `target`
4477 if let Some(target_did) = target.def_id_full(cx.cache()) {
4478 if let Some(target_impls) = c.impls.get(&target_did) {
4479 if let Some(target_deref_impl) = target_impls
4481 .filter(|i| i.inner_impl().trait_.is_some())
4482 .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_trait_did)
4484 sidebar_deref_methods(cx, out, target_deref_impl, target_impls);
4491 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4492 let mut sidebar = Buffer::new();
4493 let fields = get_struct_fields_name(&s.fields);
4495 if !fields.is_empty() {
4496 if let CtorKind::Fictive = s.struct_type {
4498 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4499 <div class=\"sidebar-links\">",
4502 for field in fields {
4503 sidebar.push_str(&field);
4506 sidebar.push_str("</div>");
4510 sidebar_assoc_items(cx, &mut sidebar, it);
4512 if !sidebar.is_empty() {
4513 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4517 fn get_id_for_impl_on_foreign_type(
4519 trait_: &clean::Type,
4522 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cache), for_.print(cache)))
4525 fn extract_for_impl_name(item: &clean::Item, cache: &Cache) -> Option<(String, String)> {
4527 clean::ItemKind::ImplItem(ref i) => {
4528 if let Some(ref trait_) = i.trait_ {
4530 format!("{:#}", i.for_.print(cache)),
4531 get_id_for_impl_on_foreign_type(&i.for_, trait_, cache),
4541 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4542 buf.write_str("<div class=\"block items\">");
4544 fn print_sidebar_section(
4546 items: &[clean::Item],
4548 filter: impl Fn(&clean::Item) -> bool,
4549 write: impl Fn(&mut Buffer, &Symbol),
4552 let mut items = items
4554 .filter_map(|m| match m.name {
4555 Some(ref name) if filter(m) => Some(name),
4558 .collect::<Vec<_>>();
4560 if !items.is_empty() {
4562 out.push_str(before);
4563 for item in items.into_iter() {
4566 out.push_str(after);
4570 print_sidebar_section(
4573 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4574 Associated Types</a><div class=\"sidebar-links\">",
4575 |m| m.is_associated_type(),
4576 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
4580 print_sidebar_section(
4583 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4584 Associated Constants</a><div class=\"sidebar-links\">",
4585 |m| m.is_associated_const(),
4586 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
4590 print_sidebar_section(
4593 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4594 Required Methods</a><div class=\"sidebar-links\">",
4595 |m| m.is_ty_method(),
4596 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
4600 print_sidebar_section(
4603 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4604 Provided Methods</a><div class=\"sidebar-links\">",
4606 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
4610 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
4611 let mut res = implementors
4616 .def_id_full(cx.cache())
4617 .map_or(false, |d| !cx.cache.paths.contains_key(&d))
4619 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx.cache()))
4620 .collect::<Vec<_>>();
4622 if !res.is_empty() {
4625 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4626 Implementations on Foreign Types</a>\
4627 <div class=\"sidebar-links\">",
4629 for (name, id) in res.into_iter() {
4630 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
4632 buf.push_str("</div>");
4636 sidebar_assoc_items(cx, buf, it);
4638 buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4641 "<a class=\"sidebar-title\" \
4642 href=\"#synthetic-implementors\">Auto Implementors</a>",
4646 buf.push_str("</div>")
4649 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4650 let mut sidebar = Buffer::new();
4651 sidebar_assoc_items(cx, &mut sidebar, it);
4653 if !sidebar.is_empty() {
4654 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4658 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4659 let mut sidebar = Buffer::new();
4660 sidebar_assoc_items(cx, &mut sidebar, it);
4662 if !sidebar.is_empty() {
4663 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4667 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
4668 let mut fields = fields
4670 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
4672 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4674 .collect::<Vec<_>>();
4679 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4680 let mut sidebar = Buffer::new();
4681 let fields = get_struct_fields_name(&u.fields);
4683 if !fields.is_empty() {
4685 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4686 <div class=\"sidebar-links\">",
4689 for field in fields {
4690 sidebar.push_str(&field);
4693 sidebar.push_str("</div>");
4696 sidebar_assoc_items(cx, &mut sidebar, it);
4698 if !sidebar.is_empty() {
4699 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4703 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4704 let mut sidebar = Buffer::new();
4706 let mut variants = e
4709 .filter_map(|v| match v.name {
4710 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4713 .collect::<Vec<_>>();
4714 if !variants.is_empty() {
4715 variants.sort_unstable();
4716 sidebar.push_str(&format!(
4717 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4718 <div class=\"sidebar-links\">{}</div>",
4723 sidebar_assoc_items(cx, &mut sidebar, it);
4725 if !sidebar.is_empty() {
4726 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4730 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4732 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4733 ItemType::Module => ("modules", "Modules"),
4734 ItemType::Struct => ("structs", "Structs"),
4735 ItemType::Union => ("unions", "Unions"),
4736 ItemType::Enum => ("enums", "Enums"),
4737 ItemType::Function => ("functions", "Functions"),
4738 ItemType::Typedef => ("types", "Type Definitions"),
4739 ItemType::Static => ("statics", "Statics"),
4740 ItemType::Constant => ("constants", "Constants"),
4741 ItemType::Trait => ("traits", "Traits"),
4742 ItemType::Impl => ("impls", "Implementations"),
4743 ItemType::TyMethod => ("tymethods", "Type Methods"),
4744 ItemType::Method => ("methods", "Methods"),
4745 ItemType::StructField => ("fields", "Struct Fields"),
4746 ItemType::Variant => ("variants", "Variants"),
4747 ItemType::Macro => ("macros", "Macros"),
4748 ItemType::Primitive => ("primitives", "Primitive Types"),
4749 ItemType::AssocType => ("associated-types", "Associated Types"),
4750 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4751 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4752 ItemType::Keyword => ("keywords", "Keywords"),
4753 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4754 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4755 ItemType::ProcDerive => ("derives", "Derive Macros"),
4756 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4760 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4761 let mut sidebar = String::new();
4763 if items.iter().any(|it| {
4764 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4766 sidebar.push_str("<li><a href=\"#reexports\">Re-exports</a></li>");
4769 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4770 // to print its headings
4772 ItemType::Primitive,
4786 ItemType::StructField,
4788 ItemType::AssocType,
4789 ItemType::AssocConst,
4790 ItemType::ForeignType,
4793 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4794 let (short, name) = item_ty_to_strs(&myty);
4795 sidebar.push_str(&format!(
4796 "<li><a href=\"#{id}\">{name}</a></li>",
4803 if !sidebar.is_empty() {
4804 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4808 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4809 let mut sidebar = Buffer::new();
4810 sidebar_assoc_items(cx, &mut sidebar, it);
4812 if !sidebar.is_empty() {
4813 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4817 fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
4818 wrap_into_docblock(w, |w| {
4819 highlight::render_with_highlighting(
4825 it.source.span().edition(),
4828 document(w, cx, it, None)
4831 fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
4832 let name = it.name.as_ref().expect("proc-macros always have names");
4834 MacroKind::Bang => {
4835 w.push_str("<pre class=\"rust macro\">");
4836 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4837 w.push_str("</pre>");
4839 MacroKind::Attr => {
4840 w.push_str("<pre class=\"rust attr\">");
4841 write!(w, "#[{}]", name);
4842 w.push_str("</pre>");
4844 MacroKind::Derive => {
4845 w.push_str("<pre class=\"rust derive\">");
4846 write!(w, "#[derive({})]", name);
4847 if !m.helpers.is_empty() {
4848 w.push_str("\n{\n");
4849 w.push_str(" // Attributes available to this derive:\n");
4850 for attr in &m.helpers {
4851 writeln!(w, " #[{}]", attr);
4855 w.push_str("</pre>");
4858 document(w, cx, it, None)
4861 fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4862 document(w, cx, it, None);
4863 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4866 fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4867 document(w, cx, it, None)
4870 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4872 fn make_item_keywords(it: &clean::Item) -> String {
4873 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4876 /// Returns a list of all paths used in the type.
4877 /// This is used to help deduplicate imported impls
4878 /// for reexported types. If any of the contained
4879 /// types are re-exported, we don't use the corresponding
4880 /// entry from the js file, as inlining will have already
4881 /// picked up the impl
4882 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
4883 let mut out = Vec::new();
4884 let mut visited = FxHashSet::default();
4885 let mut work = VecDeque::new();
4887 work.push_back(first_ty);
4889 while let Some(ty) = work.pop_front() {
4890 if !visited.insert(ty.clone()) {
4895 clean::Type::ResolvedPath { did, .. } => {
4896 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4897 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4899 if let Some(path) = fqp {
4900 out.push(path.join("::"));
4903 clean::Type::Tuple(tys) => {
4904 work.extend(tys.into_iter());
4906 clean::Type::Slice(ty) => {
4907 work.push_back(*ty);
4909 clean::Type::Array(ty, _) => {
4910 work.push_back(*ty);
4912 clean::Type::RawPointer(_, ty) => {
4913 work.push_back(*ty);
4915 clean::Type::BorrowedRef { type_, .. } => {
4916 work.push_back(*type_);
4918 clean::Type::QPath { self_type, trait_, .. } => {
4919 work.push_back(*self_type);
4920 work.push_back(*trait_);