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_id::{DefId, LOCAL_CRATE};
56 use rustc_hir::Mutability;
57 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};
72 use crate::error::Error;
73 use crate::formats::cache::{cache, Cache};
74 use crate::formats::item_type::ItemType;
75 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
76 use crate::html::escape::Escape;
77 use crate::html::format::fmt_impl_for_trait_page;
78 use crate::html::format::Function;
79 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
80 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
81 use crate::html::markdown::{
82 self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine,
84 use crate::html::sources;
85 use crate::html::{highlight, layout, static_files};
86 use cache::{build_index, ExternalLocation};
88 /// A pair of name and its optional document.
89 crate type NameDoc = (String, Option<String>);
91 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
92 crate::html::format::display_fn(move |f| {
93 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
97 /// Major driving force in all rustdoc rendering. This contains information
98 /// about where in the tree-like hierarchy rendering is occurring and controls
99 /// how the current page is being rendered.
101 /// It is intended that this context is a lightweight object which can be fairly
102 /// easily cloned because it is cloned per work-job (about once per item in the
105 crate struct Context<'tcx> {
106 /// Current hierarchy of components leading down to what's currently being
108 crate current: Vec<String>,
109 /// The current destination folder of where HTML artifacts should be placed.
110 /// This changes as the context descends into the module hierarchy.
112 /// A flag, which when `true`, will render pages which redirect to the
113 /// real location of an item. This is used to allow external links to
114 /// publicly reused items to redirect to the right location.
115 crate render_redirect_pages: bool,
116 /// The map used to ensure all generated 'id=' attributes are unique.
117 id_map: Rc<RefCell<IdMap>>,
118 /// Tracks section IDs for `Deref` targets so they match in both the main
119 /// body and the sidebar.
120 deref_id_map: Rc<RefCell<FxHashMap<DefId, String>>>,
121 crate shared: Arc<SharedContext<'tcx>>,
122 all: Rc<RefCell<AllTypes>>,
123 /// Storage for the errors produced while generating documentation so they
124 /// can be printed together at the end.
125 crate errors: Rc<Receiver<String>>,
128 crate struct SharedContext<'tcx> {
129 crate tcx: TyCtxt<'tcx>,
130 /// The path to the crate root source minus the file name.
131 /// Used for simplifying paths to the highlighted source code files.
132 crate src_root: PathBuf,
133 /// This describes the layout of each page, and is not modified after
134 /// creation of the context (contains info like the favicon and added html).
135 crate layout: layout::Layout,
136 /// This flag indicates whether `[src]` links should be generated or not. If
137 /// the source files are present in the html rendering, then this will be
139 crate include_sources: bool,
140 /// The local file sources we've emitted and their respective url-paths.
141 crate local_sources: FxHashMap<PathBuf, String>,
142 /// Whether the collapsed pass ran
143 crate collapsed: bool,
144 /// The base-URL of the issue tracker for when an item has been tagged with
146 crate issue_tracker_base_url: Option<String>,
147 /// The directories that have already been created in this doc run. Used to reduce the number
148 /// of spurious `create_dir_all` calls.
149 crate created_dirs: RefCell<FxHashSet<PathBuf>>,
150 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
151 /// should be ordered alphabetically or in order of appearance (in the source code).
152 crate sort_modules_alphabetically: bool,
153 /// Additional CSS files to be added to the generated docs.
154 crate style_files: Vec<StylePath>,
155 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
157 crate resource_suffix: String,
158 /// Optional path string to be used to load static files on output pages. If not set, uses
159 /// combinations of `../` to reach the documentation root.
160 crate static_root_path: Option<String>,
161 /// The fs handle we are working with.
163 /// The default edition used to parse doctests.
164 crate edition: Edition,
165 crate codes: ErrorCodes,
166 playground: Option<markdown::Playground>,
169 impl<'tcx> Context<'tcx> {
170 fn path(&self, filename: &str) -> PathBuf {
171 // We use splitn vs Path::extension here because we might get a filename
172 // like `style.min.css` and we want to process that into
173 // `style-suffix.min.css`. Path::extension would just return `css`
174 // which would result in `style.min-suffix.css` which isn't what we
176 let (base, ext) = filename.split_once('.').unwrap();
177 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext);
178 self.dst.join(&filename)
181 fn tcx(&self) -> TyCtxt<'tcx> {
185 fn sess(&self) -> &Session {
186 &self.shared.tcx.sess
190 impl SharedContext<'_> {
191 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
192 let mut dirs = self.created_dirs.borrow_mut();
193 if !dirs.contains(dst) {
194 try_err!(self.fs.create_dir_all(dst), dst);
195 dirs.insert(dst.to_path_buf());
201 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
202 /// `collapsed_doc_value` of the given item.
203 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<String> {
204 if self.collapsed { item.collapsed_doc_value() } else { item.doc_value() }
208 // Helper structs for rendering items/sidebars and carrying along contextual
211 /// Struct representing one entry in the JS search index. These are all emitted
212 /// by hand to a large JS file at the end of cache-creation.
214 crate struct IndexItem {
219 crate parent: Option<DefId>,
220 crate parent_idx: Option<usize>,
221 crate search_type: Option<IndexItemFunctionType>,
224 impl Serialize for IndexItem {
225 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
230 self.parent.is_some(),
231 self.parent_idx.is_some(),
232 "`{}` is missing idx",
236 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
237 .serialize(serializer)
241 /// A type used for the search index.
243 crate struct RenderType {
246 name: Option<String>,
247 generics: Option<Vec<Generic>>,
250 impl Serialize for RenderType {
251 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
255 if let Some(name) = &self.name {
256 let mut seq = serializer.serialize_seq(None)?;
257 if let Some(id) = self.idx {
258 seq.serialize_element(&id)?;
260 seq.serialize_element(&name)?;
262 if let Some(generics) = &self.generics {
263 seq.serialize_element(&generics)?;
267 serializer.serialize_none()
272 /// A type used for the search index.
274 crate struct Generic {
276 defid: Option<DefId>,
280 impl Serialize for Generic {
281 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
285 if let Some(id) = self.idx {
286 serializer.serialize_some(&id)
288 serializer.serialize_some(&self.name)
293 /// Full type of functions/methods in the search index.
295 crate struct IndexItemFunctionType {
296 inputs: Vec<TypeWithKind>,
297 output: Option<Vec<TypeWithKind>>,
300 impl Serialize for IndexItemFunctionType {
301 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
305 // If we couldn't figure out a type, just write `null`.
306 let mut iter = self.inputs.iter();
307 if match self.output {
308 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
309 None => iter.any(|ref i| i.ty.name.is_none()),
311 serializer.serialize_none()
313 let mut seq = serializer.serialize_seq(None)?;
314 seq.serialize_element(&self.inputs)?;
315 if let Some(output) = &self.output {
316 if output.len() > 1 {
317 seq.serialize_element(&output)?;
319 seq.serialize_element(&output[0])?;
328 crate struct TypeWithKind {
333 impl From<(RenderType, TypeKind)> for TypeWithKind {
334 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
335 TypeWithKind { ty: x.0, kind: x.1 }
339 impl Serialize for TypeWithKind {
340 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
344 let mut seq = serializer.serialize_seq(None)?;
345 seq.serialize_element(&self.ty.name)?;
346 let x: ItemType = self.kind.into();
347 seq.serialize_element(&x)?;
352 #[derive(Debug, Clone)]
353 crate struct StylePath {
354 /// The path to the theme
356 /// What the `disabled` attribute should be set to in the HTML tag
357 crate disabled: bool,
360 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
362 crate fn initial_ids() -> Vec<String> {
374 "synthetic-implementors",
376 "synthetic-implementors-list",
381 .map(|id| (String::from(*id)))
385 /// Generates the documentation for `crate` into the directory `dst`
386 impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
388 mut krate: clean::Crate,
389 options: RenderOptions,
390 _render_info: RenderInfo,
393 tcx: ty::TyCtxt<'tcx>,
394 ) -> Result<(Self, clean::Crate), Error> {
395 // need to save a copy of the options for rendering the index page
396 let md_opts = options.clone();
402 sort_modules_alphabetically,
408 generate_search_filter,
413 let src_root = match krate.src {
414 FileName::Real(ref p) => match p.local_path().parent() {
415 Some(p) => p.to_path_buf(),
416 None => PathBuf::new(),
420 // If user passed in `--playground-url` arg, we fill in crate name here
421 let mut playground = None;
422 if let Some(url) = playground_url {
424 Some(markdown::Playground { crate_name: Some(krate.name.to_string()), url });
426 let mut layout = layout::Layout {
428 favicon: String::new(),
431 krate: krate.name.to_string(),
432 css_file_extension: extension_css,
433 generate_search_filter,
435 let mut issue_tracker_base_url = None;
436 let mut include_sources = true;
438 // Crawl the crate attributes looking for attributes which control how we're
439 // going to emit HTML
440 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
441 for attr in attrs.lists(sym::doc) {
442 match (attr.name_or_empty(), attr.value_str()) {
443 (sym::html_favicon_url, Some(s)) => {
444 layout.favicon = s.to_string();
446 (sym::html_logo_url, Some(s)) => {
447 layout.logo = s.to_string();
449 (sym::html_playground_url, Some(s)) => {
450 playground = Some(markdown::Playground {
451 crate_name: Some(krate.name.to_string()),
455 (sym::issue_tracker_base_url, Some(s)) => {
456 issue_tracker_base_url = Some(s.to_string());
458 (sym::html_no_source, None) if attr.is_word() => {
459 include_sources = false;
465 let (sender, receiver) = channel();
466 let mut scx = SharedContext {
468 collapsed: krate.collapsed,
471 local_sources: Default::default(),
472 issue_tracker_base_url,
474 created_dirs: Default::default(),
475 sort_modules_alphabetically,
479 fs: DocFS::new(sender),
481 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
485 // Add the default themes to the `Vec` of stylepaths
487 // Note that these must be added before `sources::render` is called
488 // so that the resulting source pages are styled
490 // `light.css` is not disabled because it is the stylesheet that stays loaded
491 // by the browser as the theme stylesheet. The theme system (hackily) works by
492 // changing the href to this stylesheet. All other themes are disabled to
493 // prevent rule conflicts
494 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
495 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
496 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
499 scx.ensure_dir(&dst)?;
500 krate = sources::render(&dst, &mut scx, krate)?;
502 // Build our search index
503 let index = build_index(&krate, cache);
505 let cache = Arc::new(cache);
506 let mut cx = Context {
509 render_redirect_pages: false,
510 id_map: Rc::new(RefCell::new(id_map)),
511 deref_id_map: Rc::new(RefCell::new(FxHashMap::default())),
512 shared: Arc::new(scx),
513 all: Rc::new(RefCell::new(AllTypes::new())),
514 errors: Rc::new(receiver),
517 CURRENT_DEPTH.with(|s| s.set(0));
519 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
520 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
521 write_shared(&cx, &krate, index, &md_opts, &cache)?;
522 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
526 fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
527 Arc::get_mut(&mut self.shared).unwrap().fs.close();
528 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
530 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
536 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
537 let final_file = self.dst.join(&*krate.name.as_str()).join("all.html");
538 let settings_file = self.dst.join("settings.html");
539 let crate_name = krate.name;
541 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
542 if !root_path.ends_with('/') {
545 let mut page = layout::Page {
546 title: "List of all items in this crate",
549 static_root_path: self.shared.static_root_path.as_deref(),
550 description: "List of all items in this crate",
551 keywords: BASIC_KEYWORDS,
552 resource_suffix: &self.shared.resource_suffix,
554 static_extra_scripts: &[],
556 let sidebar = if let Some(ref version) = cache.crate_version {
558 "<p class=\"location\">Crate {}</p>\
559 <div class=\"block version\">\
562 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
569 let all = self.all.replace(AllTypes::new());
570 let v = layout::render(
574 |buf: &mut Buffer| all.print(buf),
575 &self.shared.style_files,
577 self.shared.fs.write(&final_file, v.as_bytes())?;
579 // Generating settings page.
580 page.title = "Rustdoc settings";
581 page.description = "Settings of Rustdoc";
582 page.root_path = "./";
584 let mut style_files = self.shared.style_files.clone();
585 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
586 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
587 let v = layout::render(
592 self.shared.static_root_path.as_deref().unwrap_or("./"),
593 &self.shared.resource_suffix,
594 &self.shared.style_files,
598 self.shared.fs.write(&settings_file, v.as_bytes())?;
607 ) -> Result<(), Error> {
608 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
609 // if they contain impls for public types. These modules can also
610 // contain items such as publicly re-exported structures.
612 // External crates will provide links to these structures, so
613 // these modules are recursed into, but not rendered normally
614 // (a flag on the context).
615 if !self.render_redirect_pages {
616 self.render_redirect_pages = item.is_stripped();
618 let scx = &self.shared;
619 self.dst.push(item_name);
620 self.current.push(item_name.to_owned());
622 info!("Recursing into {}", self.dst.display());
624 let buf = self.render_item(item, false, cache);
625 // buf will be empty if the module is stripped and there is no redirect for it
627 self.shared.ensure_dir(&self.dst)?;
628 let joint_dst = self.dst.join("index.html");
629 scx.fs.write(&joint_dst, buf.as_bytes())?;
632 // Render sidebar-items.js used throughout this module.
633 if !self.render_redirect_pages {
634 let module = match *item.kind {
635 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
638 let items = self.build_sidebar_items(module);
639 let js_dst = self.dst.join("sidebar-items.js");
640 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
641 scx.fs.write(&js_dst, &v)?;
646 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
647 info!("Recursed; leaving {}", self.dst.display());
649 // Go back to where we were at
655 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
656 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
657 // if they contain impls for public types. These modules can also
658 // contain items such as publicly re-exported structures.
660 // External crates will provide links to these structures, so
661 // these modules are recursed into, but not rendered normally
662 // (a flag on the context).
663 if !self.render_redirect_pages {
664 self.render_redirect_pages = item.is_stripped();
667 let buf = self.render_item(&item, true, cache);
668 // buf will be empty if the item is stripped and there is no redirect for it
670 let name = item.name.as_ref().unwrap();
671 let item_type = item.type_();
672 let file_name = &item_path(item_type, &name.as_str());
673 self.shared.ensure_dir(&self.dst)?;
674 let joint_dst = self.dst.join(file_name);
675 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
677 if !self.render_redirect_pages {
678 self.all.borrow_mut().append(full_path(self, &item), &item_type);
680 // If the item is a macro, redirect from the old macro URL (with !)
681 // to the new one (without).
682 if item_type == ItemType::Macro {
683 let redir_name = format!("{}.{}!.html", item_type, name);
684 let redir_dst = self.dst.join(redir_name);
685 let v = layout::redirect(file_name);
686 self.shared.fs.write(&redir_dst, v.as_bytes())?;
695 krate: &clean::Crate,
696 search_index: String,
697 options: &RenderOptions,
699 ) -> Result<(), Error> {
700 // Write out the shared files. Note that these are shared among all rustdoc
701 // docs placed in the output directory, so this needs to be a synchronized
702 // operation with respect to all other rustdocs running around.
703 let lock_file = cx.dst.join(".lock");
704 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
706 // Add all the static files. These may already exist, but we just
707 // overwrite them anyway to make sure that they're fresh and up-to-date.
711 cx.path("rustdoc.css"),
712 static_files::RUSTDOC_CSS,
713 options.enable_minification,
717 cx.path("settings.css"),
718 static_files::SETTINGS_CSS,
719 options.enable_minification,
723 cx.path("noscript.css"),
724 static_files::NOSCRIPT_CSS,
725 options.enable_minification,
728 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
729 // then we'll run over the "official" styles.
730 let mut themes: FxHashSet<String> = FxHashSet::default();
732 for entry in &cx.shared.style_files {
733 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
735 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
737 // Handle the official themes
739 "light" => write_minify(
741 cx.path("light.css"),
742 static_files::themes::LIGHT,
743 options.enable_minification,
745 "dark" => write_minify(
748 static_files::themes::DARK,
749 options.enable_minification,
751 "ayu" => write_minify(
754 static_files::themes::AYU,
755 options.enable_minification,
758 // Handle added third-party themes
759 let content = try_err!(fs::read(&entry.path), &entry.path);
762 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
766 themes.insert(theme.to_owned());
769 let write = |p, c| cx.shared.fs.write(p, c);
770 if (*cx.shared).layout.logo.is_empty() {
771 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
773 if (*cx.shared).layout.favicon.is_empty() {
774 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
775 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
776 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
778 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
779 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
780 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
782 let mut themes: Vec<&String> = themes.iter().collect();
784 // To avoid theme switch latencies as much as possible, we put everything theme related
785 // at the beginning of the html files into another js file.
786 let theme_js = format!(
787 r#"var themes = document.getElementById("theme-choices");
788 var themePicker = document.getElementById("theme-picker");
790 function showThemeButtonState() {{
791 themes.style.display = "block";
792 themePicker.style.borderBottomRightRadius = "0";
793 themePicker.style.borderBottomLeftRadius = "0";
796 function hideThemeButtonState() {{
797 themes.style.display = "none";
798 themePicker.style.borderBottomRightRadius = "3px";
799 themePicker.style.borderBottomLeftRadius = "3px";
802 function switchThemeButtonState() {{
803 if (themes.style.display === "block") {{
804 hideThemeButtonState();
806 showThemeButtonState();
810 function handleThemeButtonsBlur(e) {{
811 var active = document.activeElement;
812 var related = e.relatedTarget;
814 if (active.id !== "theme-picker" &&
815 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
817 (related.id !== "theme-picker" &&
818 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
819 hideThemeButtonState();
823 themePicker.onclick = switchThemeButtonState;
824 themePicker.onblur = handleThemeButtonsBlur;
825 {}.forEach(function(item) {{
826 var but = document.createElement("button");
827 but.textContent = item;
828 but.onclick = function(el) {{
829 switchTheme(currentTheme, mainTheme, item, true);
830 useSystemTheme(false);
832 but.onblur = handleThemeButtonsBlur;
833 themes.appendChild(but);
835 serde_json::to_string(&themes).unwrap()
838 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
842 static_files::MAIN_JS,
843 options.enable_minification,
847 cx.path("settings.js"),
848 static_files::SETTINGS_JS,
849 options.enable_minification,
851 if cx.shared.include_sources {
854 cx.path("source-script.js"),
855 static_files::sidebar::SOURCE_SCRIPT,
856 options.enable_minification,
863 cx.path("storage.js"),
865 "var resourcesSuffix = \"{}\";{}",
866 cx.shared.resource_suffix,
867 static_files::STORAGE_JS
869 options.enable_minification,
873 if let Some(ref css) = cx.shared.layout.css_file_extension {
874 let out = cx.path("theme.css");
875 let buffer = try_err!(fs::read_to_string(css), css);
876 if !options.enable_minification {
877 cx.shared.fs.write(&out, &buffer)?;
879 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
884 cx.path("normalize.css"),
885 static_files::NORMALIZE_CSS,
886 options.enable_minification,
888 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
889 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
890 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
891 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
892 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
893 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
894 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
895 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
896 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
897 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
898 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
899 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
900 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
902 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
903 let mut ret = Vec::new();
904 let mut krates = Vec::new();
907 for line in BufReader::new(File::open(path)?).lines() {
909 if !line.starts_with(key) {
912 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
915 ret.push(line.to_string());
917 line[key.len() + 2..]
920 .map(|s| s.to_owned())
921 .unwrap_or_else(String::new),
928 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
929 let mut ret = Vec::new();
930 let mut krates = Vec::new();
933 for line in BufReader::new(File::open(path)?).lines() {
935 if !line.starts_with('"') {
938 if line.starts_with(&format!("\"{}\"", krate)) {
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.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1020 h = h.children.get_mut(&cur_elem).expect("not found child");
1025 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1026 let (mut all_sources, _krates) =
1027 try_err!(collect(&dst, &krate.name.as_str(), "sourcesIndex"), &dst);
1028 all_sources.push(format!(
1029 "sourcesIndex[\"{}\"] = {};",
1031 hierarchy.to_json_string()
1035 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1036 all_sources.join("\n")
1038 cx.shared.fs.write(&dst, v.as_bytes())?;
1041 // Update the search index
1042 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1043 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name.as_str()), &dst);
1044 all_indexes.push(search_index);
1046 // Sort the indexes by crate so the file will be generated identically even
1047 // with rustdoc running in parallel.
1050 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1051 v.push_str(&all_indexes.join(",\\\n"));
1052 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1053 // search might start (if it's set into the URL for example).
1054 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1055 cx.shared.fs.write(&dst, &v)?;
1057 if options.enable_index_page {
1058 if let Some(index_page) = options.index_page.clone() {
1059 let mut md_opts = options.clone();
1060 md_opts.output = cx.dst.clone();
1061 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1063 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1064 .map_err(|e| Error::new(e, &index_page))?;
1066 let dst = cx.dst.join("index.html");
1067 let page = layout::Page {
1068 title: "Index of crates",
1071 static_root_path: cx.shared.static_root_path.as_deref(),
1072 description: "List of crates",
1073 keywords: BASIC_KEYWORDS,
1074 resource_suffix: &cx.shared.resource_suffix,
1076 static_extra_scripts: &[],
1078 krates.push(krate.name.to_string());
1082 let content = format!(
1083 "<h1 class=\"fqn\">\
1084 <span class=\"in-band\">List of all crates</span>\
1085 </h1><ul class=\"crate mod\">{}</ul>",
1090 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1091 ensure_trailing_slash(s),
1095 .collect::<String>()
1097 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1098 cx.shared.fs.write(&dst, v.as_bytes())?;
1102 // Update the list of all implementors for traits
1103 let dst = cx.dst.join("implementors");
1104 for (&did, imps) in &cache.implementors {
1105 // Private modules can leak through to this phase of rustdoc, which
1106 // could contain implementations for otherwise private types. In some
1107 // rare cases we could find an implementation for an item which wasn't
1108 // indexed, so we just skip this step in that case.
1110 // FIXME: this is a vague explanation for why this can't be a `get`, in
1111 // theory it should be...
1112 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1114 None => match cache.external_paths.get(&did) {
1120 #[derive(Serialize)]
1121 struct Implementor {
1127 let implementors = imps
1130 // If the trait and implementation are in the same crate, then
1131 // there's no need to emit information about it (there's inlining
1132 // going on). If they're in different crates then the crate defining
1133 // the trait will be interested in our implementation.
1135 // If the implementation is from another crate then that crate
1137 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1141 text: imp.inner_impl().print().to_string(),
1142 synthetic: imp.inner_impl().synthetic,
1143 types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1147 .collect::<Vec<_>>();
1149 // Only create a js file if we have impls to add to it. If the trait is
1150 // documented locally though we always create the file to avoid dead
1152 if implementors.is_empty() && !cache.paths.contains_key(&did) {
1156 let implementors = format!(
1157 r#"implementors["{}"] = {};"#,
1159 serde_json::to_string(&implementors).unwrap()
1162 let mut mydst = dst.clone();
1163 for part in &remote_path[..remote_path.len() - 1] {
1166 cx.shared.ensure_dir(&mydst)?;
1167 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1169 let (mut all_implementors, _) =
1170 try_err!(collect(&mydst, &krate.name.as_str(), "implementors"), &mydst);
1171 all_implementors.push(implementors);
1172 // Sort the implementors by crate so the file will be generated
1173 // identically even with rustdoc running in parallel.
1174 all_implementors.sort();
1176 let mut v = String::from("(function() {var implementors = {};\n");
1177 for implementor in &all_implementors {
1178 writeln!(v, "{}", *implementor).unwrap();
1181 "if (window.register_implementors) {\
1182 window.register_implementors(implementors);\
1184 window.pending_implementors = implementors;\
1188 cx.shared.fs.write(&mydst, &v)?;
1197 enable_minification: bool,
1198 ) -> Result<(), Error> {
1199 if enable_minification {
1200 if dst.extension() == Some(&OsStr::new("css")) {
1201 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1202 fs.write(dst, res.as_bytes())
1204 fs.write(dst, minifier::js::minify(contents).as_bytes())
1207 fs.write(dst, contents.as_bytes())
1211 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1212 if let Some(l) = cx.src_href(item, cache) {
1215 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
1216 l, "goto source code"
1221 #[derive(Debug, Eq, PartialEq, Hash)]
1228 fn new(mut url: String, name: String) -> ItemEntry {
1229 while url.starts_with('/') {
1232 ItemEntry { url, name }
1237 crate fn print(&self) -> impl fmt::Display + '_ {
1238 crate::html::format::display_fn(move |f| {
1239 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1244 impl PartialOrd for ItemEntry {
1245 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1246 Some(self.cmp(other))
1250 impl Ord for ItemEntry {
1251 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1252 self.name.cmp(&other.name)
1258 structs: FxHashSet<ItemEntry>,
1259 enums: FxHashSet<ItemEntry>,
1260 unions: FxHashSet<ItemEntry>,
1261 primitives: FxHashSet<ItemEntry>,
1262 traits: FxHashSet<ItemEntry>,
1263 macros: FxHashSet<ItemEntry>,
1264 functions: FxHashSet<ItemEntry>,
1265 typedefs: FxHashSet<ItemEntry>,
1266 opaque_tys: FxHashSet<ItemEntry>,
1267 statics: FxHashSet<ItemEntry>,
1268 constants: FxHashSet<ItemEntry>,
1269 keywords: FxHashSet<ItemEntry>,
1270 attributes: FxHashSet<ItemEntry>,
1271 derives: FxHashSet<ItemEntry>,
1272 trait_aliases: FxHashSet<ItemEntry>,
1276 fn new() -> AllTypes {
1277 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1279 structs: new_set(100),
1280 enums: new_set(100),
1281 unions: new_set(100),
1282 primitives: new_set(26),
1283 traits: new_set(100),
1284 macros: new_set(100),
1285 functions: new_set(100),
1286 typedefs: new_set(100),
1287 opaque_tys: new_set(100),
1288 statics: new_set(100),
1289 constants: new_set(100),
1290 keywords: new_set(100),
1291 attributes: new_set(100),
1292 derives: new_set(100),
1293 trait_aliases: new_set(100),
1297 fn append(&mut self, item_name: String, item_type: &ItemType) {
1298 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1299 if let Some(name) = url.pop() {
1300 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1302 let name = url.join("::");
1304 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1305 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1306 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1307 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1308 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1309 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1310 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1311 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1312 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1313 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1314 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1315 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1316 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1317 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1324 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1326 let mut e: Vec<&ItemEntry> = e.iter().collect();
1330 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">{}</ul>",
1334 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1340 fn print(self, f: &mut Buffer) {
1343 "<h1 class=\"fqn\">\
1344 <span class=\"out-of-band\">\
1345 <span id=\"render-detail\">\
1346 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1347 title=\"collapse all docs\">\
1348 [<span class=\"inner\">−</span>]\
1352 <span class=\"in-band\">List of all items</span>\
1355 print_entries(f, &self.structs, "Structs", "structs");
1356 print_entries(f, &self.enums, "Enums", "enums");
1357 print_entries(f, &self.unions, "Unions", "unions");
1358 print_entries(f, &self.primitives, "Primitives", "primitives");
1359 print_entries(f, &self.traits, "Traits", "traits");
1360 print_entries(f, &self.macros, "Macros", "macros");
1361 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1362 print_entries(f, &self.derives, "Derive Macros", "derives");
1363 print_entries(f, &self.functions, "Functions", "functions");
1364 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1365 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1366 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1367 print_entries(f, &self.statics, "Statics", "statics");
1368 print_entries(f, &self.constants, "Constants", "constants")
1375 description: &'static str,
1376 sub_settings: Vec<Setting>,
1379 js_data_name: &'static str,
1380 description: &'static str,
1381 default_value: bool,
1384 js_data_name: &'static str,
1385 description: &'static str,
1386 default_value: &'static str,
1387 options: Vec<(String, String)>,
1392 fn display(&self, root_path: &str, suffix: &str) -> String {
1394 Setting::Section { description, ref sub_settings } => format!(
1395 "<div class=\"setting-line\">\
1396 <div class=\"title\">{}</div>\
1397 <div class=\"sub-settings\">{}</div>
1400 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1402 Setting::Toggle { js_data_name, description, default_value } => format!(
1403 "<div class=\"setting-line\">\
1404 <label class=\"toggle\">\
1405 <input type=\"checkbox\" id=\"{}\" {}>\
1406 <span class=\"slider\"></span>\
1411 if default_value { " checked" } else { "" },
1414 Setting::Select { js_data_name, description, default_value, ref options } => format!(
1415 "<div class=\"setting-line\">\
1417 <label class=\"select-wrapper\">\
1418 <select id=\"{}\" autocomplete=\"off\">{}</select>\
1419 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1427 "<option value=\"{}\" {}>{}</option>",
1429 if opt.0 == default_value { "selected" } else { "" },
1432 .collect::<String>(),
1440 impl From<(&'static str, &'static str, bool)> for Setting {
1441 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1442 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1446 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1447 fn from(values: (&'static str, Vec<T>)) -> Setting {
1449 description: values.0,
1450 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1455 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1456 let theme_names: Vec<(String, String)> = themes
1460 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1463 Ok((theme.clone(), theme))
1465 .collect::<Result<_, Error>>()?;
1467 // (id, explanation, default value)
1468 let settings: &[Setting] = &[
1470 "Theme preferences",
1472 Setting::from(("use-system-theme", "Use system theme", true)),
1474 js_data_name: "preferred-dark-theme",
1475 description: "Preferred dark theme",
1476 default_value: "dark",
1477 options: theme_names.clone(),
1480 js_data_name: "preferred-light-theme",
1481 description: "Preferred light theme",
1482 default_value: "light",
1483 options: theme_names,
1489 "Auto-hide item declarations",
1491 ("auto-hide-struct", "Auto-hide structs declaration", true),
1492 ("auto-hide-enum", "Auto-hide enums declaration", false),
1493 ("auto-hide-union", "Auto-hide unions declaration", true),
1494 ("auto-hide-trait", "Auto-hide traits declaration", true),
1495 ("auto-hide-macro", "Auto-hide macros declaration", false),
1499 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1500 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1501 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1503 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1504 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1506 ("line-numbers", "Show line numbers on code examples", false).into(),
1507 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1511 "<h1 class=\"fqn\">\
1512 <span class=\"in-band\">Rustdoc settings</span>\
1514 <div class=\"settings\">{}</div>\
1515 <script src=\"{}settings{}.js\"></script>",
1516 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1523 fn derive_id(&self, id: String) -> String {
1524 let mut map = self.id_map.borrow_mut();
1528 /// String representation of how to get back to the root path of the 'doc/'
1529 /// folder in terms of a relative URL.
1530 fn root_path(&self) -> String {
1531 "../".repeat(self.current.len())
1534 fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1535 // A little unfortunate that this is done like this, but it sure
1536 // does make formatting *a lot* nicer.
1537 CURRENT_DEPTH.with(|slot| {
1538 slot.set(self.current.len());
1541 let mut title = if it.is_primitive() || it.is_keyword() {
1542 // No need to include the namespace for primitive types and keywords
1545 self.current.join("::")
1548 if !title.is_empty() {
1549 title.push_str("::");
1551 title.push_str(&it.name.unwrap().as_str());
1553 title.push_str(" - Rust");
1554 let tyname = it.type_();
1555 let desc = if it.is_crate() {
1556 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1559 "API documentation for the Rust `{}` {} in crate `{}`.",
1560 it.name.as_ref().unwrap(),
1562 self.shared.layout.krate
1565 let keywords = make_item_keywords(it);
1566 let page = layout::Page {
1567 css_class: tyname.as_str(),
1568 root_path: &self.root_path(),
1569 static_root_path: self.shared.static_root_path.as_deref(),
1572 keywords: &keywords,
1573 resource_suffix: &self.shared.resource_suffix,
1575 static_extra_scripts: &[],
1579 self.id_map.borrow_mut().reset();
1580 self.id_map.borrow_mut().populate(initial_ids());
1583 if !self.render_redirect_pages {
1585 &self.shared.layout,
1587 |buf: &mut _| print_sidebar(self, it, buf, cache),
1588 |buf: &mut _| print_item(self, it, buf, cache),
1589 &self.shared.style_files,
1592 let mut url = self.root_path();
1593 if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1594 for name in &names[..names.len() - 1] {
1598 url.push_str(&item_path(ty, names.last().unwrap()));
1599 layout::redirect(&url)
1606 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1607 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1608 // BTreeMap instead of HashMap to get a sorted output
1609 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1610 for item in &m.items {
1611 if item.is_stripped() {
1615 let short = item.type_();
1616 let myname = match item.name {
1618 Some(ref s) => s.to_string(),
1620 let short = short.to_string();
1621 map.entry(short).or_default().push((
1623 Some(item.doc_value().map_or_else(String::new, |s| plain_text_summary(&s))),
1627 if self.shared.sort_modules_alphabetically {
1628 for items in map.values_mut() {
1635 /// Generates a url appropriate for an `href` attribute back to the source of
1638 /// The url generated, when clicked, will redirect the browser back to the
1639 /// original source code.
1641 /// If `None` is returned, then a source link couldn't be generated. This
1642 /// may happen, for example, with externally inlined items where the source
1643 /// of their crate documentation isn't known.
1644 fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1645 let mut root = self.root_path();
1646 let mut path = String::new();
1647 let cnum = item.source.cnum(self.sess());
1649 // We can safely ignore synthetic `SourceFile`s.
1650 let file = match item.source.filename(self.sess()) {
1651 FileName::Real(ref path) => path.local_path().to_path_buf(),
1657 let (krate, path) = if cnum == LOCAL_CRATE {
1658 if let Some(path) = self.shared.local_sources.get(file) {
1659 (self.shared.layout.krate.as_str(), path)
1664 let (krate, src_root) = match *cache.extern_locations.get(&cnum)? {
1665 (name, ref src, ExternalLocation::Local) => (name, src),
1666 (name, ref src, ExternalLocation::Remote(ref s)) => {
1667 root = s.to_string();
1670 (_, _, ExternalLocation::Unknown) => return None,
1673 sources::clean_path(&src_root, file, false, |component| {
1674 path.push_str(&component.to_string_lossy());
1677 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1678 fname.push(".html");
1679 path.push_str(&fname.to_string_lossy());
1680 symbol = krate.as_str();
1684 let loline = item.source.lo(self.sess()).line;
1685 let hiline = item.source.hi(self.sess()).line;
1687 if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) };
1689 "{root}src/{krate}/{path}#{lines}",
1690 root = Escape(&root),
1698 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1700 F: FnOnce(&mut Buffer),
1702 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1707 fn print_item(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1708 debug_assert!(!item.is_stripped());
1709 // Write the breadcrumb trail header for the top
1710 write!(buf, "<h1 class=\"fqn\"><span class=\"out-of-band\">");
1711 render_stability_since_raw(
1713 item.stable_since(cx.tcx()).as_deref(),
1714 item.const_stable_since(cx.tcx()).as_deref(),
1720 "<span id=\"render-detail\">\
1721 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1722 title=\"collapse all docs\">\
1723 [<span class=\"inner\">−</span>]\
1730 // When this item is part of a `crate use` in a downstream crate, the
1731 // [src] link in the downstream documentation will actually come back to
1732 // this page, and this link will be auto-clicked. The `id` attribute is
1733 // used to find the link to auto-click.
1734 if cx.shared.include_sources && !item.is_primitive() {
1735 write_srclink(cx, item, buf, cache);
1738 write!(buf, "</span>"); // out-of-band
1739 write!(buf, "<span class=\"in-band\">");
1740 let name = match *item.kind {
1741 clean::ModuleItem(ref m) => {
1748 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1749 clean::TraitItem(..) => "Trait ",
1750 clean::StructItem(..) => "Struct ",
1751 clean::UnionItem(..) => "Union ",
1752 clean::EnumItem(..) => "Enum ",
1753 clean::TypedefItem(..) => "Type Definition ",
1754 clean::MacroItem(..) => "Macro ",
1755 clean::ProcMacroItem(ref mac) => match mac.kind {
1756 MacroKind::Bang => "Macro ",
1757 MacroKind::Attr => "Attribute Macro ",
1758 MacroKind::Derive => "Derive Macro ",
1760 clean::PrimitiveItem(..) => "Primitive Type ",
1761 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1762 clean::ConstantItem(..) => "Constant ",
1763 clean::ForeignTypeItem => "Foreign Type ",
1764 clean::KeywordItem(..) => "Keyword ",
1765 clean::OpaqueTyItem(..) => "Opaque Type ",
1766 clean::TraitAliasItem(..) => "Trait Alias ",
1768 // We don't generate pages for any other type.
1772 buf.write_str(name);
1773 if !item.is_primitive() && !item.is_keyword() {
1774 let cur = &cx.current;
1775 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1776 for (i, component) in cur.iter().enumerate().take(amt) {
1779 "<a href=\"{}index.html\">{}</a>::<wbr>",
1780 "../".repeat(cur.len() - i - 1),
1785 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1787 write!(buf, "</span></h1>"); // in-band
1790 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1791 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1792 item_function(buf, cx, item, f)
1794 clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1795 clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1796 clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1797 clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1798 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1799 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1800 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1801 clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1802 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1803 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1804 clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1805 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1806 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e, cache),
1807 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1809 // We don't generate pages for any other type.
1815 fn item_path(ty: ItemType, name: &str) -> String {
1817 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1818 _ => format!("{}.{}.html", ty, name),
1822 fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1823 let mut s = cx.current.join("::");
1825 s.push_str(&item.name.unwrap().as_str());
1829 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
1830 if let Some(ref name) = item.name {
1831 info!("Documenting {}", name);
1833 document_item_info(w, cx, item, false, parent);
1834 document_full(w, item, cx, "", false);
1837 /// Render md_text as markdown.
1842 links: Vec<RenderedLink>,
1846 let mut ids = cx.id_map.borrow_mut();
1849 "<div class=\"docblock{}\">{}{}</div>",
1850 if is_hidden { " hidden" } else { "" },
1858 &cx.shared.playground
1864 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1865 /// docs are longer, a "Read more" link is appended to the end.
1870 link: AssocItemLink<'_>,
1873 parent: Option<&clean::Item>,
1874 show_def_docs: bool,
1876 document_item_info(w, cx, item, is_hidden, parent);
1880 if let Some(s) = item.doc_value() {
1881 let mut summary_html = MarkdownSummaryLine(&s, &item.links()).into_string();
1883 if s.contains('\n') {
1884 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link));
1886 if let Some(idx) = summary_html.rfind("</p>") {
1887 summary_html.insert_str(idx, &link);
1889 summary_html.push_str(&link);
1895 "<div class='docblock{}'>{}{}</div>",
1896 if is_hidden { " hidden" } else { "" },
1900 } else if !prefix.is_empty() {
1903 "<div class=\"docblock{}\">{}</div>",
1904 if is_hidden { " hidden" } else { "" },
1917 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1918 debug!("Doc block: =====\n{}\n=====", s);
1919 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1920 } else if !prefix.is_empty() {
1923 "<div class=\"docblock{}\">{}</div>",
1924 if is_hidden { " hidden" } else { "" },
1930 /// Add extra information about an item such as:
1934 /// * Required features (through the `doc_cfg` feature)
1935 fn document_item_info(
1940 parent: Option<&clean::Item>,
1942 let item_infos = short_item_info(item, cx, parent);
1943 if !item_infos.is_empty() {
1944 write!(w, "<div class=\"item-info{}\">", if is_hidden { " hidden" } else { "" });
1945 for info in item_infos {
1946 write!(w, "{}", info);
1948 write!(w, "</div>");
1952 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1953 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1956 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1957 if item.is_non_exhaustive() {
1958 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1959 if item.is_struct() {
1961 } else if item.is_enum() {
1963 } else if item.is_variant() {
1970 if item.is_struct() {
1973 "Non-exhaustive structs could have additional fields added in future. \
1974 Therefore, non-exhaustive structs cannot be constructed in external crates \
1975 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1976 matched against without a wildcard <code>..</code>; and \
1977 struct update syntax will not work."
1979 } else if item.is_enum() {
1982 "Non-exhaustive enums could have additional variants added in future. \
1983 Therefore, when matching against variants of non-exhaustive enums, an \
1984 extra wildcard arm must be added to account for any future variants."
1986 } else if item.is_variant() {
1989 "Non-exhaustive enum variants could have additional fields added in future. \
1990 Therefore, non-exhaustive enum variants cannot be constructed in external \
1991 crates and cannot be matched against."
1996 "This type will require a wildcard arm in any match statements or constructors."
2000 write!(w, "</div>");
2004 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
2005 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
2006 /// Takes a non-numeric and a numeric part from the given &str.
2007 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
2008 let i = s.find(|c: char| c.is_ascii_digit());
2009 let (a, b) = s.split_at(i.unwrap_or(s.len()));
2010 let i = b.find(|c: char| !c.is_ascii_digit());
2011 let (b, c) = b.split_at(i.unwrap_or(b.len()));
2016 while !lhs.is_empty() || !rhs.is_empty() {
2017 let (la, lb) = take_parts(&mut lhs);
2018 let (ra, rb) = take_parts(&mut rhs);
2019 // First process the non-numeric part.
2021 Ordering::Equal => (),
2024 // Then process the numeric part, if both sides have one (and they fit in a u64).
2025 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2027 Ordering::Equal => (),
2031 // Then process the numeric part again, but this time as strings.
2033 Ordering::Equal => (),
2041 fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) {
2042 document(w, cx, item, None);
2044 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2046 // the order of item types in the listing
2047 fn reorder(ty: ItemType) -> u8 {
2049 ItemType::ExternCrate => 0,
2050 ItemType::Import => 1,
2051 ItemType::Primitive => 2,
2052 ItemType::Module => 3,
2053 ItemType::Macro => 4,
2054 ItemType::Struct => 5,
2055 ItemType::Enum => 6,
2056 ItemType::Constant => 7,
2057 ItemType::Static => 8,
2058 ItemType::Trait => 9,
2059 ItemType::Function => 10,
2060 ItemType::Typedef => 12,
2061 ItemType::Union => 13,
2073 let ty1 = i1.type_();
2074 let ty2 = i2.type_();
2076 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2078 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
2079 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
2080 if let (Some(a), Some(b)) = (s1, s2) {
2081 match (a.is_stable(), b.is_stable()) {
2082 (true, true) | (false, false) => {}
2083 (false, true) => return Ordering::Less,
2084 (true, false) => return Ordering::Greater,
2087 let lhs = i1.name.unwrap_or(kw::Empty).as_str();
2088 let rhs = i2.name.unwrap_or(kw::Empty).as_str();
2089 compare_names(&lhs, &rhs)
2092 if cx.shared.sort_modules_alphabetically {
2093 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
2095 // This call is to remove re-export duplicates in cases such as:
2100 // crate trait Double { fn foo(); }
2104 // crate use foo::bar::*;
2105 // crate use foo::*;
2108 // `Double` will appear twice in the generated docs.
2110 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2111 // can be identical even if the elements are different (mostly in imports).
2112 // So in case this is an import, we keep everything by adding a "unique id"
2113 // (which is the position in the vector).
2114 indices.dedup_by_key(|i| {
2117 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2119 if items[*i].is_import() { *i } else { 0 },
2123 debug!("{:?}", indices);
2124 let mut curty = None;
2125 for &idx in &indices {
2126 let myitem = &items[idx];
2127 if myitem.is_stripped() {
2131 let myty = Some(myitem.type_());
2132 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2133 // Put `extern crate` and `use` re-exports in the same section.
2135 } else if myty != curty {
2136 if curty.is_some() {
2137 write!(w, "</table>");
2140 let (short, name) = item_ty_to_strs(&myty.unwrap());
2143 "<h2 id=\"{id}\" class=\"section-header\">\
2144 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2145 id = cx.derive_id(short.to_owned()),
2150 match *myitem.kind {
2151 clean::ExternCrateItem(ref name, ref src) => {
2152 use crate::html::format::anchor;
2155 Some(ref src) => write!(
2157 "<tr><td><code>{}extern crate {} as {};",
2158 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id),
2159 anchor(myitem.def_id, &*src.as_str()),
2164 "<tr><td><code>{}extern crate {};",
2165 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id),
2166 anchor(myitem.def_id, &*name.as_str())
2169 write!(w, "</code></td></tr>");
2172 clean::ImportItem(ref import) => {
2175 "<tr><td><code>{}{}</code></td></tr>",
2176 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id),
2182 if myitem.name.is_none() {
2186 let unsafety_flag = match *myitem.kind {
2187 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2188 if func.header.unsafety == hir::Unsafety::Unsafe =>
2190 "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2195 let stab = myitem.stability_class(cx.tcx());
2196 let add = if stab.is_some() { " " } else { "" };
2198 let doc_value = myitem.doc_value().unwrap_or_default();
2201 "<tr class=\"{stab}{add}module-item\">\
2202 <td><a class=\"{class}\" href=\"{href}\" \
2203 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2204 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2206 name = *myitem.name.as_ref().unwrap(),
2207 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
2208 docs = MarkdownSummaryLine(&doc_value, &myitem.links()).into_string(),
2209 class = myitem.type_(),
2211 stab = stab.unwrap_or_else(String::new),
2212 unsafety_flag = unsafety_flag,
2213 href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()),
2214 title = [full_path(cx, myitem), myitem.type_().to_string()]
2216 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2217 .collect::<Vec<_>>()
2224 if curty.is_some() {
2225 write!(w, "</table>");
2229 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
2230 /// at the module level.
2231 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
2232 let mut tags = String::new();
2234 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2235 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2238 // The trailing space after each tag is to space it properly against the rest of the docs.
2239 if let Some(depr) = &item.deprecation(tcx) {
2240 let mut message = "Deprecated";
2241 if !stability::deprecation_in_effect(
2242 depr.is_since_rustc_version,
2243 depr.since.map(|s| s.as_str()).as_deref(),
2245 message = "Deprecation planned";
2247 tags += &tag_html("deprecated", "", message);
2250 // The "rustc_private" crates are permanently unstable so it makes no sense
2251 // to render "unstable" everywhere.
2255 .map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2258 tags += &tag_html("unstable", "", "Experimental");
2261 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2262 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2263 (cfg, _) => cfg.as_deref().cloned(),
2266 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2267 if let Some(ref cfg) = cfg {
2268 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2274 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2275 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2276 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2277 (cfg, _) => cfg.as_deref().cloned(),
2281 "Portability {:?} - {:?} = {:?}",
2283 parent.and_then(|p| p.attrs.cfg.as_ref()),
2287 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2290 /// Render the stability, deprecation and portability information that is displayed at the top of
2291 /// the item's documentation.
2295 parent: Option<&clean::Item>,
2297 let mut extra_info = vec![];
2298 let error_codes = cx.shared.codes;
2300 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
2301 item.deprecation(cx.tcx())
2303 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2304 // but only display the future-deprecation messages for #[rustc_deprecated].
2305 let mut message = if let Some(since) = since {
2306 let since = &since.as_str();
2307 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2308 if *since == "TBD" {
2309 String::from("Deprecating in a future Rust version")
2311 format!("Deprecating in {}", Escape(since))
2314 format!("Deprecated since {}", Escape(since))
2317 String::from("Deprecated")
2320 if let Some(note) = note {
2321 let note = note.as_str();
2322 let mut ids = cx.id_map.borrow_mut();
2323 let html = MarkdownHtml(
2328 &cx.shared.playground,
2330 message.push_str(&format!(": {}", html.into_string()));
2332 extra_info.push(format!(
2333 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2338 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2339 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2340 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2341 .stability(cx.tcx())
2343 .filter(|stab| stab.feature != sym::rustc_private)
2344 .map(|stab| (stab.level, stab.feature))
2347 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2349 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2350 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2351 feature.push_str(&format!(
2352 " <a href=\"{url}{issue}\">#{issue}</a>",
2358 message.push_str(&format!(" ({})", feature));
2360 if let Some(unstable_reason) = reason {
2361 let mut ids = cx.id_map.borrow_mut();
2363 "<details><summary>{}</summary>{}</details>",
2366 &unstable_reason.as_str(),
2370 &cx.shared.playground,
2376 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2379 if let Some(portability) = portability(item, parent) {
2380 extra_info.push(portability);
2386 fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) {
2387 write!(w, "<pre class=\"rust const\">");
2388 render_attributes(w, it, false);
2392 "{vis}const {name}: {typ}",
2393 vis = it.visibility.print_with_space(cx.tcx(), it.def_id),
2394 name = it.name.as_ref().unwrap(),
2395 typ = c.type_.print(),
2398 if c.value.is_some() || c.is_literal {
2399 write!(w, " = {expr};", expr = Escape(&c.expr));
2404 if let Some(value) = &c.value {
2406 let value_lowercase = value.to_lowercase();
2407 let expr_lowercase = c.expr.to_lowercase();
2409 if value_lowercase != expr_lowercase
2410 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2412 write!(w, " // {value}", value = Escape(value));
2417 write!(w, "</pre>");
2418 document(w, cx, it, None)
2421 fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
2422 write!(w, "<pre class=\"rust static\">");
2423 render_attributes(w, it, false);
2426 "{vis}static {mutability}{name}: {typ}</pre>",
2427 vis = it.visibility.print_with_space(cx.tcx(), it.def_id),
2428 mutability = s.mutability.print_with_space(),
2429 name = it.name.as_ref().unwrap(),
2430 typ = s.type_.print()
2432 document(w, cx, it, None)
2435 fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
2436 let header_len = format!(
2437 "{}{}{}{}{:#}fn {}{:#}",
2438 it.visibility.print_with_space(cx.tcx(), it.def_id),
2439 f.header.constness.print_with_space(),
2440 f.header.asyncness.print_with_space(),
2441 f.header.unsafety.print_with_space(),
2442 print_abi_with_space(f.header.abi),
2443 it.name.as_ref().unwrap(),
2447 write!(w, "<pre class=\"rust fn\">");
2448 render_attributes(w, it, false);
2451 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2452 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2453 vis = it.visibility.print_with_space(cx.tcx(), it.def_id),
2454 constness = f.header.constness.print_with_space(),
2455 asyncness = f.header.asyncness.print_with_space(),
2456 unsafety = f.header.unsafety.print_with_space(),
2457 abi = print_abi_with_space(f.header.abi),
2458 name = it.name.as_ref().unwrap(),
2459 generics = f.generics.print(),
2460 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2461 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2463 spotlight = spotlight_decl(&f.decl),
2465 document(w, cx, it, None)
2468 fn render_implementor(
2471 parent: &clean::Item,
2473 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
2477 // If there's already another implementor that has the same abbridged name, use the
2478 // full path, for example in `std::iter::ExactSizeIterator`
2479 let use_absolute = match implementor.inner_impl().for_ {
2480 clean::ResolvedPath { ref path, is_generic: false, .. }
2481 | clean::BorrowedRef {
2482 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2484 } => implementor_dups[&path.last()].1,
2492 AssocItemLink::Anchor(None),
2494 implementor.impl_item.stable_since(cx.tcx()).as_deref(),
2495 implementor.impl_item.const_stable_since(cx.tcx()).as_deref(),
2509 containing_item: &clean::Item,
2512 let mut impls = traits
2515 let did = i.trait_did().unwrap();
2516 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2517 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2525 containing_item.stable_since(cx.tcx()).as_deref(),
2526 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) -> 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().to_string());
2557 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2558 let lhs = format!("{}", lhs.inner_impl().print());
2559 let rhs = format!("{}", rhs.inner_impl().print());
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, cache: &Cache) {
2566 let bounds = bounds(&t.bounds, false);
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 write!(w, "<pre class=\"rust trait\">");
2575 render_attributes(w, it, true);
2578 "{}{}{}trait {}{}{}",
2579 it.visibility.print_with_space(cx.tcx(), it.def_id),
2580 t.unsafety.print_with_space(),
2581 if t.is_auto { "auto " } else { "" },
2582 it.name.as_ref().unwrap(),
2587 if !t.generics.where_predicates.is_empty() {
2588 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2593 if t.items.is_empty() {
2596 // FIXME: we should be using a derived_id for the Anchors here
2599 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2602 if !types.is_empty() && !consts.is_empty() {
2606 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2609 if !consts.is_empty() && !required.is_empty() {
2612 for (pos, m) in required.iter().enumerate() {
2613 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2616 if pos < required.len() - 1 {
2617 write!(w, "<div class=\"item-spacer\"></div>");
2620 if !required.is_empty() && !provided.is_empty() {
2623 for (pos, m) in provided.iter().enumerate() {
2624 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2626 clean::MethodItem(ref inner, _)
2627 if !inner.generics.where_predicates.is_empty() =>
2629 write!(w, ",\n {{ ... }}\n");
2632 write!(w, " {{ ... }}\n");
2635 if pos < provided.len() - 1 {
2636 write!(w, "<div class=\"item-spacer\"></div>");
2644 // Trait documentation
2645 document(w, cx, it, None);
2647 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2650 "<h2 id=\"{0}\" class=\"small-section-header\">\
2651 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2653 id, title, extra_content
2657 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2658 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2668 let name = m.name.as_ref().unwrap();
2669 info!("Documenting {} on {:?}", name, t.name);
2670 let item_type = m.type_();
2671 let id = cx.derive_id(format!("{}.{}", item_type, name));
2672 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2673 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl, cx);
2674 write!(w, "</code>");
2675 render_stability_since(w, m, t, cx.tcx());
2676 write_srclink(cx, m, w, cache);
2678 document(w, cx, m, Some(t));
2681 if !types.is_empty() {
2682 write_small_section_header(
2686 "<div class=\"methods\">",
2689 trait_item(w, cx, t, it, cache);
2691 write_loading_content(w, "</div>");
2694 if !consts.is_empty() {
2695 write_small_section_header(
2698 "Associated Constants",
2699 "<div class=\"methods\">",
2702 trait_item(w, cx, t, it, cache);
2704 write_loading_content(w, "</div>");
2707 // Output the documentation for each function individually
2708 if !required.is_empty() {
2709 write_small_section_header(
2713 "<div class=\"methods\">",
2716 trait_item(w, cx, m, it, cache);
2718 write_loading_content(w, "</div>");
2720 if !provided.is_empty() {
2721 write_small_section_header(
2725 "<div class=\"methods\">",
2728 trait_item(w, cx, m, it, cache);
2730 write_loading_content(w, "</div>");
2733 // If there are methods directly on this trait object, render them here.
2734 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2736 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2737 // The DefId is for the first Type found with that name. The bool is
2738 // if any Types with the same name but different DefId have been found.
2739 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
2740 for implementor in implementors {
2741 match implementor.inner_impl().for_ {
2742 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2743 | clean::BorrowedRef {
2744 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2747 let &mut (prev_did, ref mut has_duplicates) =
2748 implementor_dups.entry(path.last()).or_insert((did, false));
2749 if prev_did != did {
2750 *has_duplicates = true;
2757 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2758 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2761 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2762 local.iter().partition(|i| i.inner_impl().synthetic);
2764 synthetic.sort_by(compare_impl);
2765 concrete.sort_by(compare_impl);
2767 if !foreign.is_empty() {
2768 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2770 for implementor in foreign {
2771 let assoc_link = AssocItemLink::GotoSource(
2772 implementor.impl_item.def_id,
2773 &implementor.inner_impl().provided_trait_methods,
2782 implementor.impl_item.stable_since(cx.tcx()).as_deref(),
2783 implementor.impl_item.const_stable_since(cx.tcx()).as_deref(),
2792 write_loading_content(w, "");
2795 write_small_section_header(
2799 "<div class=\"item-list\" id=\"implementors-list\">",
2801 for implementor in concrete {
2802 render_implementor(cx, implementor, it, w, &implementor_dups, &[], cache);
2804 write_loading_content(w, "</div>");
2807 write_small_section_header(
2809 "synthetic-implementors",
2810 "Auto implementors",
2811 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2813 for implementor in synthetic {
2820 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2824 write_loading_content(w, "</div>");
2827 // even without any implementations to write in, we still want the heading and list, so the
2828 // implementors javascript file pulled in below has somewhere to write the impls into
2829 write_small_section_header(
2833 "<div class=\"item-list\" id=\"implementors-list\">",
2835 write_loading_content(w, "</div>");
2838 write_small_section_header(
2840 "synthetic-implementors",
2841 "Auto implementors",
2842 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2844 write_loading_content(w, "</div>");
2850 "<script type=\"text/javascript\" \
2851 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2853 root_path = vec![".."; cx.current.len()].join("/"),
2854 path = if it.def_id.is_local() {
2855 cx.current.join("/")
2857 let (ref path, _) = cache.external_paths[&it.def_id];
2858 path[..path.len() - 1].join("/")
2861 name = *it.name.as_ref().unwrap()
2865 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2866 use crate::formats::item_type::ItemType::*;
2868 let name = it.name.as_ref().unwrap();
2869 let ty = match it.type_() {
2870 Typedef | AssocType => AssocType,
2874 let anchor = format!("#{}.{}", ty, name);
2876 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2877 AssocItemLink::Anchor(None) => anchor,
2878 AssocItemLink::GotoSource(did, _) => {
2879 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2888 _default: Option<&String>,
2889 link: AssocItemLink<'_>,
2895 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2897 it.visibility.print_with_space(cx.tcx(), it.def_id),
2898 naive_assoc_href(it, link),
2899 it.name.as_ref().unwrap(),
2907 bounds: &[clean::GenericBound],
2908 default: Option<&clean::Type>,
2909 link: AssocItemLink<'_>,
2914 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2916 naive_assoc_href(it, link),
2917 it.name.as_ref().unwrap()
2919 if !bounds.is_empty() {
2920 write!(w, ": {}", print_generic_bounds(bounds))
2922 if let Some(default) = default {
2923 write!(w, " = {}", default.print())
2927 fn render_stability_since_raw(
2930 const_ver: Option<&str>,
2931 containing_ver: Option<&str>,
2932 containing_const_ver: Option<&str>,
2934 let ver = ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2936 let const_ver = const_ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2938 if let Some(v) = ver {
2939 if let Some(cv) = const_ver {
2940 if const_ver != containing_const_ver {
2943 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2946 } else if ver != containing_ver {
2949 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2954 if ver != containing_ver {
2957 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2965 fn render_stability_since(
2968 containing_item: &clean::Item,
2971 render_stability_since_raw(
2973 item.stable_since(tcx).as_deref(),
2974 item.const_stable_since(tcx).as_deref(),
2975 containing_item.stable_since(tcx).as_deref(),
2976 containing_item.const_stable_since(tcx).as_deref(),
2980 fn render_assoc_item(
2983 link: AssocItemLink<'_>,
2990 header: hir::FnHeader,
2991 g: &clean::Generics,
2993 link: AssocItemLink<'_>,
2997 let name = meth.name.as_ref().unwrap();
2998 let anchor = format!("#{}.{}", meth.type_(), name);
2999 let href = match link {
3000 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3001 AssocItemLink::Anchor(None) => anchor,
3002 AssocItemLink::GotoSource(did, provided_methods) => {
3003 // We're creating a link from an impl-item to the corresponding
3004 // trait-item and need to map the anchored type accordingly.
3005 let ty = if provided_methods.contains(&name) {
3011 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3014 let mut header_len = format!(
3015 "{}{}{}{}{}{:#}fn {}{:#}",
3016 meth.visibility.print_with_space(cx.tcx(), meth.def_id),
3017 header.constness.print_with_space(),
3018 header.asyncness.print_with_space(),
3019 header.unsafety.print_with_space(),
3020 print_default_space(meth.is_default()),
3021 print_abi_with_space(header.abi),
3026 let (indent, end_newline) = if parent == ItemType::Trait {
3032 render_attributes(w, meth, false);
3035 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
3036 {generics}{decl}{spotlight}{where_clause}",
3037 if parent == ItemType::Trait { " " } else { "" },
3038 meth.visibility.print_with_space(cx.tcx(), meth.def_id),
3039 header.constness.print_with_space(),
3040 header.asyncness.print_with_space(),
3041 header.unsafety.print_with_space(),
3042 print_default_space(meth.is_default()),
3043 print_abi_with_space(header.abi),
3046 generics = g.print(),
3047 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
3048 spotlight = spotlight_decl(&d),
3049 where_clause = WhereClause { gens: g, indent, end_newline }
3053 clean::StrippedItem(..) => {}
3054 clean::TyMethodItem(ref m) => {
3055 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
3057 clean::MethodItem(ref m, _) => {
3058 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
3060 clean::AssocConstItem(ref ty, ref default) => assoc_const(
3066 if parent == ItemType::Trait { " " } else { "" },
3069 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3075 if parent == ItemType::Trait { " " } else { "" },
3077 _ => panic!("render_assoc_item called on non-associated-item"),
3088 wrap_into_docblock(w, |w| {
3089 write!(w, "<pre class=\"rust struct\">");
3090 render_attributes(w, it, true);
3091 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
3095 document(w, cx, it, None);
3099 .filter_map(|f| match *f.kind {
3100 clean::StructFieldItem(ref ty) => Some((f, ty)),
3104 if let doctree::Plain = s.struct_type {
3105 if fields.peek().is_some() {
3108 "<h2 id=\"fields\" class=\"fields small-section-header\">
3109 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3110 document_non_exhaustive_header(it)
3112 document_non_exhaustive(w, it);
3113 for (field, ty) in fields {
3114 let id = cx.derive_id(format!(
3116 ItemType::StructField,
3117 field.name.as_ref().unwrap()
3121 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3122 <a href=\"#{id}\" class=\"anchor field\"></a>\
3123 <code>{name}: {ty}</code>\
3125 item_type = ItemType::StructField,
3127 name = field.name.as_ref().unwrap(),
3130 document(w, cx, field, Some(it));
3134 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3137 fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union, cache: &Cache) {
3138 wrap_into_docblock(w, |w| {
3139 write!(w, "<pre class=\"rust union\">");
3140 render_attributes(w, it, true);
3141 render_union(w, it, Some(&s.generics), &s.fields, "", true, cx);
3145 document(w, cx, it, None);
3149 .filter_map(|f| match *f.kind {
3150 clean::StructFieldItem(ref ty) => Some((f, ty)),
3154 if fields.peek().is_some() {
3157 "<h2 id=\"fields\" class=\"fields small-section-header\">
3158 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3160 for (field, ty) in fields {
3161 let name = field.name.as_ref().expect("union field name");
3162 let id = format!("{}.{}", ItemType::StructField, name);
3165 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3166 <a href=\"#{id}\" class=\"anchor field\"></a>\
3167 <code>{name}: {ty}</code>\
3171 shortty = ItemType::StructField,
3174 if let Some(stability_class) = field.stability_class(cx.tcx()) {
3175 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3177 document(w, cx, field, Some(it));
3180 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3183 fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
3184 wrap_into_docblock(w, |w| {
3185 write!(w, "<pre class=\"rust enum\">");
3186 render_attributes(w, it, true);
3190 it.visibility.print_with_space(cx.tcx(), it.def_id),
3191 it.name.as_ref().unwrap(),
3193 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
3195 if e.variants.is_empty() && !e.variants_stripped {
3199 for v in &e.variants {
3201 let name = v.name.as_ref().unwrap();
3203 clean::VariantItem(ref var) => match var {
3204 clean::Variant::CLike => write!(w, "{}", name),
3205 clean::Variant::Tuple(ref tys) => {
3206 write!(w, "{}(", name);
3207 for (i, ty) in tys.iter().enumerate() {
3209 write!(w, ", ")
3211 write!(w, "{}", ty.print());
3215 clean::Variant::Struct(ref s) => {
3216 render_struct(w, v, None, s.struct_type, &s.fields, " ", false, cx);
3219 _ => unreachable!(),
3224 if e.variants_stripped {
3225 write!(w, " // some variants omitted\n");
3232 document(w, cx, it, None);
3233 if !e.variants.is_empty() {
3236 "<h2 id=\"variants\" class=\"variants small-section-header\">
3237 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3238 document_non_exhaustive_header(it)
3240 document_non_exhaustive(w, it);
3241 for variant in &e.variants {
3243 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3246 "<div id=\"{id}\" class=\"variant small-section-header\">\
3247 <a href=\"#{id}\" class=\"anchor field\"></a>\
3250 name = variant.name.as_ref().unwrap()
3252 if let clean::VariantItem(clean::Variant::Tuple(ref tys)) = *variant.kind {
3254 for (i, ty) in tys.iter().enumerate() {
3256 write!(w, ", ");
3258 write!(w, "{}", ty.print());
3262 write!(w, "</code></div>");
3263 document(w, cx, variant, Some(it));
3264 document_non_exhaustive(w, variant);
3266 use crate::clean::Variant;
3267 if let clean::VariantItem(Variant::Struct(ref s)) = *variant.kind {
3268 let variant_id = cx.derive_id(format!(
3271 variant.name.as_ref().unwrap()
3273 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3276 "<h3>Fields of <b>{name}</b></h3><div>",
3277 name = variant.name.as_ref().unwrap()
3279 for field in &s.fields {
3280 use crate::clean::StructFieldItem;
3281 if let StructFieldItem(ref ty) = *field.kind {
3282 let id = cx.derive_id(format!(
3283 "variant.{}.field.{}",
3284 variant.name.as_ref().unwrap(),
3285 field.name.as_ref().unwrap()
3289 "<span id=\"{id}\" class=\"variant small-section-header\">\
3290 <a href=\"#{id}\" class=\"anchor field\"></a>\
3291 <code>{f}: {t}</code>\
3294 f = field.name.as_ref().unwrap(),
3297 document(w, cx, field, Some(variant));
3300 write!(w, "</div></div>");
3302 render_stability_since(w, variant, it, cx.tcx());
3305 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3308 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3315 sym::non_exhaustive,
3318 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3319 // left padding. For example:
3321 // #[foo] <----- "top" attribute
3323 // #[bar] <---- not "top" attribute
3326 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3331 .filter_map(|attr| {
3332 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3333 Some(pprust::attribute_to_string(&attr))
3340 if !attrs.is_empty() {
3343 "<span class=\"docblock attributes{}\">{}</span>",
3344 if top { " top-attr" } else { "" },
3353 g: Option<&clean::Generics>,
3354 ty: doctree::StructType,
3355 fields: &[clean::Item],
3363 it.visibility.print_with_space(cx.tcx(), it.def_id),
3364 if structhead { "struct " } else { "" },
3365 it.name.as_ref().unwrap()
3367 if let Some(g) = g {
3368 write!(w, "{}", g.print())
3372 if let Some(g) = g {
3373 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3375 let mut has_visible_fields = false;
3377 for field in fields {
3378 if let clean::StructFieldItem(ref ty) = *field.kind {
3383 field.visibility.print_with_space(cx.tcx(), field.def_id),
3384 field.name.as_ref().unwrap(),
3387 has_visible_fields = true;
3391 if has_visible_fields {
3392 if it.has_stripped_fields().unwrap() {
3393 write!(w, "\n{} // some fields omitted", tab);
3395 write!(w, "\n{}", tab);
3396 } else if it.has_stripped_fields().unwrap() {
3397 // If there are no visible fields we can just display
3398 // `{ /* fields omitted */ }` to save space.
3399 write!(w, " /* fields omitted */ ");
3405 for (i, field) in fields.iter().enumerate() {
3410 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3411 clean::StructFieldItem(ref ty) => {
3415 field.visibility.print_with_space(cx.tcx(), field.def_id),
3419 _ => unreachable!(),
3423 if let Some(g) = g {
3424 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3429 // Needed for PhantomData.
3430 if let Some(g) = g {
3431 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3441 g: Option<&clean::Generics>,
3442 fields: &[clean::Item],
3450 it.visibility.print_with_space(cx.tcx(), it.def_id),
3451 if structhead { "union " } else { "" },
3452 it.name.as_ref().unwrap()
3454 if let Some(g) = g {
3455 write!(w, "{}", g.print());
3456 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3459 write!(w, " {{\n{}", tab);
3460 for field in fields {
3461 if let clean::StructFieldItem(ref ty) = *field.kind {
3465 field.visibility.print_with_space(cx.tcx(), field.def_id),
3466 field.name.as_ref().unwrap(),
3473 if it.has_stripped_fields().unwrap() {
3474 write!(w, " // some fields omitted\n{}", tab);
3479 #[derive(Copy, Clone)]
3480 enum AssocItemLink<'a> {
3481 Anchor(Option<&'a str>),
3482 GotoSource(DefId, &'a FxHashSet<Symbol>),
3485 impl<'a> AssocItemLink<'a> {
3486 fn anchor(&self, id: &'a str) -> Self {
3488 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3489 ref other => *other,
3494 fn render_assoc_items(
3497 containing_item: &clean::Item,
3499 what: AssocItemRender<'_>,
3502 info!("Documenting associated items of {:?}", containing_item.name);
3503 let v = match cache.impls.get(&it) {
3507 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3508 if !non_trait.is_empty() {
3509 let render_mode = match what {
3510 AssocItemRender::All => {
3513 "<h2 id=\"implementations\" class=\"small-section-header\">\
3514 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3519 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3521 cx.derive_id(small_url_encode(&format!("deref-methods-{:#}", type_.print())));
3522 cx.deref_id_map.borrow_mut().insert(type_.def_id().unwrap(), id.clone());
3525 "<h2 id=\"{id}\" class=\"small-section-header\">\
3526 Methods from {trait_}<Target = {type_}>\
3527 <a href=\"#{id}\" class=\"anchor\"></a>\
3530 trait_ = trait_.print(),
3531 type_ = type_.print(),
3533 RenderMode::ForDeref { mut_: deref_mut_ }
3536 for i in &non_trait {
3542 AssocItemLink::Anchor(None),
3544 containing_item.stable_since(cx.tcx()).as_deref(),
3545 containing_item.const_stable_since(cx.tcx()).as_deref(),
3555 if !traits.is_empty() {
3557 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3558 if let Some(impl_) = deref_impl {
3560 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3561 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
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, cache);
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() {
3592 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3593 Auto Trait Implementations\
3594 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3596 <div id=\"synthetic-implementations-list\">"
3598 render_impls(cx, w, &synthetic, containing_item, cache);
3599 write!(w, "</div>");
3602 if !blanket_impl.is_empty() {
3605 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3606 Blanket Implementations\
3607 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3609 <div id=\"blanket-implementations-list\">"
3611 render_impls(cx, w, &blanket_impl, containing_item, cache);
3612 write!(w, "</div>");
3617 fn render_deref_methods(
3621 container_item: &clean::Item,
3625 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3626 let (target, real_target) = impl_
3630 .find_map(|item| match *item.kind {
3631 clean::TypedefItem(ref t, true) => Some(match *t {
3632 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3633 _ => (&t.type_, &t.type_),
3637 .expect("Expected associated type binding");
3639 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3640 if let Some(did) = target.def_id() {
3641 if let Some(type_did) = impl_.inner_impl().for_.def_id() {
3642 // `impl Deref<Target = S> for S`
3643 if did == type_did {
3644 // Avoid infinite cycles
3648 render_assoc_items(w, cx, container_item, did, what, cache);
3650 if let Some(prim) = target.primitive_type() {
3651 if let Some(&did) = cache.primitive_locations.get(&prim) {
3652 render_assoc_items(w, cx, container_item, did, what, cache);
3658 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3659 let self_type_opt = match *item.kind {
3660 clean::MethodItem(ref method, _) => method.decl.self_type(),
3661 clean::TyMethodItem(ref method) => method.decl.self_type(),
3665 if let Some(self_ty) = self_type_opt {
3666 let (by_mut_ref, by_box, by_value) = match self_ty {
3667 SelfTy::SelfBorrowed(_, mutability)
3668 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3669 (mutability == Mutability::Mut, false, false)
3671 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3672 (false, Some(did) == cache().owned_box_did, false)
3674 SelfTy::SelfValue => (false, false, true),
3675 _ => (false, false, false),
3678 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3684 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3685 let mut out = Buffer::html();
3686 let mut trait_ = String::new();
3688 if let Some(did) = decl.output.def_id() {
3690 if let Some(impls) = c.impls.get(&did) {
3692 let impl_ = i.inner_impl();
3693 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3695 out.push_str(&format!(
3696 "<h3 class=\"notable\">Notable traits for {}</h3>\
3697 <code class=\"content\">",
3700 trait_.push_str(&impl_.for_.print().to_string());
3703 //use the "where" class here to make it small
3704 out.push_str(&format!(
3705 "<span class=\"where fmt-newline\">{}</span>",
3708 let t_did = impl_.trait_.def_id().unwrap();
3709 for it in &impl_.items {
3710 if let clean::TypedefItem(ref tydef, _) = *it.kind {
3711 out.push_str("<span class=\"where fmt-newline\"> ");
3717 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3720 out.push_str(";</span>");
3728 if !out.is_empty() {
3731 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3732 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3734 out.push_str("</code></span></div></span></span>");
3744 parent: &clean::Item,
3745 link: AssocItemLink<'_>,
3746 render_mode: RenderMode,
3747 outer_version: Option<&str>,
3748 outer_const_version: Option<&str>,
3749 show_def_docs: bool,
3750 use_absolute: Option<bool>,
3751 is_on_foreign_type: bool,
3752 show_default_items: bool,
3753 // This argument is used to reference same type with different paths to avoid duplication
3754 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3758 let traits = &cache.traits;
3759 let trait_ = i.trait_did().map(|did| &traits[&did]);
3761 if render_mode == RenderMode::Normal {
3762 let id = cx.derive_id(match i.inner_impl().trait_ {
3764 if is_on_foreign_type {
3765 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3767 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3770 None => "impl".to_string(),
3772 let aliases = if aliases.is_empty() {
3775 format!(" aliases=\"{}\"", aliases.join(","))
3777 if let Some(use_absolute) = use_absolute {
3778 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3779 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3781 for it in &i.inner_impl().items {
3782 if let clean::TypedefItem(ref tydef, _) = *it.kind {
3783 write!(w, "<span class=\"where fmt-newline\"> ");
3784 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3785 write!(w, ";</span>");
3789 write!(w, "</code>");
3793 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3796 i.inner_impl().print()
3799 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3800 render_stability_since_raw(
3802 i.impl_item.stable_since(cx.tcx()).as_deref(),
3803 i.impl_item.const_stable_since(cx.tcx()).as_deref(),
3805 outer_const_version,
3807 write_srclink(cx, &i.impl_item, w, cache);
3810 if trait_.is_some() {
3811 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3812 write!(w, "<div class=\"item-info\">{}</div>", portability);
3816 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3817 let mut ids = cx.id_map.borrow_mut();
3820 "<div class=\"docblock\">{}</div>",
3823 &i.impl_item.links(),
3827 &cx.shared.playground
3838 parent: &clean::Item,
3839 link: AssocItemLink<'_>,
3840 render_mode: RenderMode,
3841 is_default_item: bool,
3842 outer_version: Option<&str>,
3843 outer_const_version: Option<&str>,
3844 trait_: Option<&clean::Trait>,
3845 show_def_docs: bool,
3848 let item_type = item.type_();
3849 let name = item.name.as_ref().unwrap();
3851 let render_method_item = match render_mode {
3852 RenderMode::Normal => true,
3853 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3856 let (is_hidden, extra_class) =
3857 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3865 clean::MethodItem(..) | clean::TyMethodItem(_) => {
3866 // Only render when the method is not static or we allow static methods
3867 if render_method_item {
3868 let id = cx.derive_id(format!("{}.{}", item_type, name));
3869 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3870 write!(w, "<code>");
3871 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx);
3872 write!(w, "</code>");
3873 render_stability_since_raw(
3875 item.stable_since(cx.tcx()).as_deref(),
3876 item.const_stable_since(cx.tcx()).as_deref(),
3878 outer_const_version,
3880 write_srclink(cx, item, w, cache);
3884 clean::TypedefItem(ref tydef, _) => {
3885 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3886 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3887 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3888 write!(w, "</code></h4>");
3890 clean::AssocConstItem(ref ty, ref default) => {
3891 let id = cx.derive_id(format!("{}.{}", item_type, name));
3892 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3893 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "", cx);
3894 write!(w, "</code>");
3895 render_stability_since_raw(
3897 item.stable_since(cx.tcx()).as_deref(),
3898 item.const_stable_since(cx.tcx()).as_deref(),
3900 outer_const_version,
3902 write_srclink(cx, item, w, cache);
3905 clean::AssocTypeItem(ref bounds, ref default) => {
3906 let id = cx.derive_id(format!("{}.{}", item_type, name));
3907 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3908 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3909 write!(w, "</code></h4>");
3911 clean::StrippedItem(..) => return,
3912 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3915 if render_method_item {
3916 if !is_default_item {
3917 if let Some(t) = trait_ {
3918 // The trait item may have been stripped so we might not
3919 // find any documentation or stability for it.
3920 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3921 // We need the stability of the item from the trait
3922 // because impls can't have a stability.
3923 if item.doc_value().is_some() {
3924 document_item_info(w, cx, it, is_hidden, Some(parent));
3925 document_full(w, item, cx, "", is_hidden);
3927 // In case the item isn't documented,
3928 // provide short documentation from the trait.
3942 document_item_info(w, cx, item, is_hidden, Some(parent));
3944 document_full(w, item, cx, "", is_hidden);
3948 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3953 write!(w, "<div class=\"impl-items\">");
3954 for trait_item in &i.inner_impl().items {
3959 if trait_.is_some() { &i.impl_item } else { parent },
3964 outer_const_version,
3971 fn render_default_items(
3976 parent: &clean::Item,
3977 render_mode: RenderMode,
3978 outer_version: Option<&str>,
3979 outer_const_version: Option<&str>,
3980 show_def_docs: bool,
3983 for trait_item in &t.items {
3984 let n = trait_item.name;
3985 if i.items.iter().any(|m| m.name == n) {
3988 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3989 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4000 outer_const_version,
4008 // If we've implemented a trait, then also emit documentation for all
4009 // default items which weren't overridden in the implementation block.
4010 // We don't emit documentation for default items if they appear in the
4011 // Implementations on Foreign Types or Implementors sections.
4012 if show_default_items {
4013 if let Some(t) = trait_ {
4014 render_default_items(
4022 outer_const_version,
4028 write!(w, "</div>");
4035 t: &clean::OpaqueTy,
4038 write!(w, "<pre class=\"rust opaque\">");
4039 render_attributes(w, it, false);
4042 "type {}{}{where_clause} = impl {bounds};</pre>",
4043 it.name.as_ref().unwrap(),
4045 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4046 bounds = bounds(&t.bounds, false)
4049 document(w, cx, it, None);
4051 // Render any items associated directly to this alias, as otherwise they
4052 // won't be visible anywhere in the docs. It would be nice to also show
4053 // associated items from the aliased type (see discussion in #32077), but
4054 // we need #14072 to make sense of the generics.
4055 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4058 fn item_trait_alias(
4062 t: &clean::TraitAlias,
4065 write!(w, "<pre class=\"rust trait-alias\">");
4066 render_attributes(w, it, false);
4069 "trait {}{}{} = {};</pre>",
4070 it.name.as_ref().unwrap(),
4072 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4073 bounds(&t.bounds, true)
4076 document(w, cx, it, None);
4078 // Render any items associated directly to this alias, as otherwise they
4079 // won't be visible anywhere in the docs. It would be nice to also show
4080 // associated items from the aliased type (see discussion in #32077), but
4081 // we need #14072 to make sense of the generics.
4082 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4092 write!(w, "<pre class=\"rust typedef\">");
4093 render_attributes(w, it, false);
4096 "type {}{}{where_clause} = {type_};</pre>",
4097 it.name.as_ref().unwrap(),
4099 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4100 type_ = t.type_.print()
4103 document(w, cx, it, None);
4105 // Render any items associated directly to this alias, as otherwise they
4106 // won't be visible anywhere in the docs. It would be nice to also show
4107 // associated items from the aliased type (see discussion in #32077), but
4108 // we need #14072 to make sense of the generics.
4109 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4112 fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, cache: &Cache) {
4113 writeln!(w, "<pre class=\"rust foreigntype\">extern {{");
4114 render_attributes(w, it, false);
4117 " {}type {};\n}}</pre>",
4118 it.visibility.print_with_space(cx.tcx(), it.def_id),
4119 it.name.as_ref().unwrap(),
4122 document(w, cx, it, None);
4124 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4127 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
4128 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4132 || it.is_primitive()
4140 "<p class=\"location\">{}{}</p>",
4142 clean::StructItem(..) => "Struct ",
4143 clean::TraitItem(..) => "Trait ",
4144 clean::PrimitiveItem(..) => "Primitive Type ",
4145 clean::UnionItem(..) => "Union ",
4146 clean::EnumItem(..) => "Enum ",
4147 clean::TypedefItem(..) => "Type Definition ",
4148 clean::ForeignTypeItem => "Foreign Type ",
4149 clean::ModuleItem(..) =>
4157 it.name.as_ref().unwrap()
4162 if let Some(ref version) = cache.crate_version {
4165 "<div class=\"block version\">\
4173 write!(buffer, "<div class=\"sidebar-elems\">");
4177 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4178 it.name.as_ref().expect("crates always have a name")
4182 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
4183 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
4184 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
4185 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
4186 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
4187 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
4188 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4189 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
4193 // The sidebar is designed to display sibling functions, modules and
4194 // other miscellaneous information. since there are lots of sibling
4195 // items (and that causes quadratic growth in large modules),
4196 // we refactor common parts into a shared JavaScript file per module.
4197 // still, we don't move everything into JS because we want to preserve
4198 // as much HTML as possible in order to allow non-JS-enabled browsers
4199 // to navigate the documentation (though slightly inefficiently).
4201 write!(buffer, "<p class=\"location\">");
4202 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4204 write!(buffer, "::<wbr>");
4208 "<a href=\"{}index.html\">{}</a>",
4209 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4213 write!(buffer, "</p>");
4215 // Sidebar refers to the enclosing module, not this module.
4216 let relpath = if it.is_mod() { "../" } else { "" };
4219 "<script>window.sidebarCurrent = {{\
4222 relpath: \"{path}\"\
4224 name = it.name.unwrap_or(kw::Empty),
4229 // There is no sidebar-items.js beyond the crate root path
4230 // FIXME maybe dynamic crate loading can be merged here
4232 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4234 // Closes sidebar-elems div.
4235 write!(buffer, "</div>");
4238 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4239 if used_links.insert(url.clone()) {
4243 while !used_links.insert(format!("{}-{}", url, add)) {
4246 format!("{}-{}", url, add)
4252 used_links: &mut FxHashSet<String>,
4257 .filter_map(|item| match item.name {
4258 Some(ref name) if !name.is_empty() && item.is_method() => {
4259 if !for_deref || should_render_item(item, deref_mut) {
4261 "<a href=\"#{}\">{}</a>",
4262 get_next_url(used_links, format!("method.{}", name)),
4271 .collect::<Vec<_>>()
4274 // The point is to url encode any potential character from a type with genericity.
4275 fn small_url_encode(s: &str) -> String {
4276 s.replace("<", "%3C")
4277 .replace(">", "%3E")
4278 .replace(" ", "%20")
4279 .replace("?", "%3F")
4280 .replace("'", "%27")
4281 .replace("&", "%26")
4282 .replace(",", "%2C")
4283 .replace(":", "%3A")
4284 .replace(";", "%3B")
4285 .replace("[", "%5B")
4286 .replace("]", "%5D")
4287 .replace("\"", "%22")
4290 fn sidebar_assoc_items(cx: &Context<'_>, it: &clean::Item) -> String {
4291 let mut out = String::new();
4293 if let Some(v) = c.impls.get(&it.def_id) {
4294 let mut used_links = FxHashSet::default();
4297 let used_links_bor = &mut used_links;
4300 .filter(|i| i.inner_impl().trait_.is_none())
4301 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4302 .collect::<Vec<_>>();
4303 if !ret.is_empty() {
4304 // We want links' order to be reproducible so we don't use unstable sort.
4306 out.push_str(&format!(
4307 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4308 <div class=\"sidebar-links\">{}</div>",
4314 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4315 if let Some(impl_) = v
4317 .filter(|i| i.inner_impl().trait_.is_some())
4318 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4320 out.push_str(&sidebar_deref_methods(cx, impl_, v));
4322 let format_impls = |impls: Vec<&Impl>| {
4323 let mut links = FxHashSet::default();
4328 if let Some(ref i) = it.inner_impl().trait_ {
4329 let i_display = format!("{:#}", i.print());
4330 let out = Escape(&i_display);
4331 let encoded = small_url_encode(&format!("{:#}", i.print()));
4332 let generated = format!(
4333 "<a href=\"#impl-{}\">{}{}</a>",
4335 if it.inner_impl().negative_polarity { "!" } else { "" },
4338 if links.insert(generated.clone()) { Some(generated) } else { None }
4343 .collect::<Vec<String>>();
4348 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4349 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4350 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4352 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4354 let concrete_format = format_impls(concrete);
4355 let synthetic_format = format_impls(synthetic);
4356 let blanket_format = format_impls(blanket_impl);
4358 if !concrete_format.is_empty() {
4360 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4361 Trait Implementations</a>",
4363 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4366 if !synthetic_format.is_empty() {
4368 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4369 Auto Trait Implementations</a>",
4371 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4374 if !blanket_format.is_empty() {
4376 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4377 Blanket Implementations</a>",
4379 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4387 fn sidebar_deref_methods(cx: &Context<'_>, impl_: &Impl, v: &Vec<Impl>) -> String {
4388 let mut out = String::new();
4391 debug!("found Deref: {:?}", impl_);
4392 if let Some((target, real_target)) =
4393 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
4394 clean::TypedefItem(ref t, true) => Some(match *t {
4395 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4396 _ => (&t.type_, &t.type_),
4401 debug!("found target, real_target: {:?} {:?}", target, real_target);
4404 .filter(|i| i.inner_impl().trait_.is_some())
4405 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4406 let inner_impl = target
4409 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
4411 .and_then(|did| c.impls.get(&did));
4412 if let Some(impls) = inner_impl {
4413 debug!("found inner_impl: {:?}", impls);
4414 let mut used_links = FxHashSet::default();
4417 .filter(|i| i.inner_impl().trait_.is_none())
4418 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut))
4419 .collect::<Vec<_>>();
4420 if !ret.is_empty() {
4421 let deref_id_map = cx.deref_id_map.borrow();
4422 let id = deref_id_map
4423 .get(&real_target.def_id().unwrap())
4424 .expect("Deref section without derived id");
4425 out.push_str(&format!(
4426 "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}<Target={}></a>",
4428 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print())),
4429 Escape(&format!("{:#}", real_target.print())),
4431 // We want links' order to be reproducible so we don't use unstable sort.
4433 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret.join("")));
4437 // Recurse into any further impls that might exist for `target`
4438 if let Some(target_did) = target.def_id() {
4439 if let Some(target_impls) = c.impls.get(&target_did) {
4440 if let Some(target_deref_impl) = target_impls
4442 .filter(|i| i.inner_impl().trait_.is_some())
4443 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4445 if let Some(type_did) = impl_.inner_impl().for_.def_id() {
4446 // `impl Deref<Target = S> for S`
4447 if target_did == type_did {
4448 // Avoid infinite cycles
4452 out.push_str(&sidebar_deref_methods(cx, target_deref_impl, target_impls));
4461 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4462 let mut sidebar = String::new();
4463 let fields = get_struct_fields_name(&s.fields);
4465 if !fields.is_empty() {
4466 if let doctree::Plain = s.struct_type {
4467 sidebar.push_str(&format!(
4468 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4469 <div class=\"sidebar-links\">{}</div>",
4475 sidebar.push_str(&sidebar_assoc_items(cx, it));
4477 if !sidebar.is_empty() {
4478 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4482 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4483 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4486 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4488 clean::ItemKind::ImplItem(ref i) => {
4489 if let Some(ref trait_) = i.trait_ {
4491 format!("{:#}", i.for_.print()),
4492 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4502 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4503 let mut sidebar = String::new();
4508 .filter_map(|m| match m.name {
4509 Some(ref name) if m.is_associated_type() => {
4510 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4514 .collect::<Vec<_>>();
4518 .filter_map(|m| match m.name {
4519 Some(ref name) if m.is_associated_const() => {
4520 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4524 .collect::<Vec<_>>();
4525 let mut required = t
4528 .filter_map(|m| match m.name {
4529 Some(ref name) if m.is_ty_method() => {
4530 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4534 .collect::<Vec<String>>();
4535 let mut provided = t
4538 .filter_map(|m| match m.name {
4539 Some(ref name) if m.is_method() => {
4540 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4544 .collect::<Vec<String>>();
4546 if !types.is_empty() {
4548 sidebar.push_str(&format!(
4549 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4550 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4554 if !consts.is_empty() {
4556 sidebar.push_str(&format!(
4557 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4558 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4562 if !required.is_empty() {
4564 sidebar.push_str(&format!(
4565 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4566 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4570 if !provided.is_empty() {
4572 sidebar.push_str(&format!(
4573 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4574 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4581 if let Some(implementors) = c.implementors.get(&it.def_id) {
4582 let mut res = implementors
4584 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4585 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4586 .collect::<Vec<_>>();
4588 if !res.is_empty() {
4590 sidebar.push_str(&format!(
4591 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4592 Implementations on Foreign Types</a>\
4593 <div class=\"sidebar-links\">{}</div>",
4595 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4596 .collect::<Vec<_>>()
4602 sidebar.push_str(&sidebar_assoc_items(cx, it));
4604 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4607 "<a class=\"sidebar-title\" \
4608 href=\"#synthetic-implementors\">Auto Implementors</a>",
4612 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4615 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4616 let sidebar = sidebar_assoc_items(cx, it);
4618 if !sidebar.is_empty() {
4619 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4623 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4624 let sidebar = sidebar_assoc_items(cx, it);
4626 if !sidebar.is_empty() {
4627 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4631 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4632 let mut fields = fields
4634 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
4635 .filter_map(|f| match f.name {
4637 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4641 .collect::<Vec<_>>();
4646 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4647 let mut sidebar = String::new();
4648 let fields = get_struct_fields_name(&u.fields);
4650 if !fields.is_empty() {
4651 sidebar.push_str(&format!(
4652 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4653 <div class=\"sidebar-links\">{}</div>",
4658 sidebar.push_str(&sidebar_assoc_items(cx, it));
4660 if !sidebar.is_empty() {
4661 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4665 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4666 let mut sidebar = String::new();
4668 let mut variants = e
4671 .filter_map(|v| match v.name {
4672 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4675 .collect::<Vec<_>>();
4676 if !variants.is_empty() {
4677 variants.sort_unstable();
4678 sidebar.push_str(&format!(
4679 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4680 <div class=\"sidebar-links\">{}</div>",
4685 sidebar.push_str(&sidebar_assoc_items(cx, it));
4687 if !sidebar.is_empty() {
4688 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4692 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4694 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4695 ItemType::Module => ("modules", "Modules"),
4696 ItemType::Struct => ("structs", "Structs"),
4697 ItemType::Union => ("unions", "Unions"),
4698 ItemType::Enum => ("enums", "Enums"),
4699 ItemType::Function => ("functions", "Functions"),
4700 ItemType::Typedef => ("types", "Type Definitions"),
4701 ItemType::Static => ("statics", "Statics"),
4702 ItemType::Constant => ("constants", "Constants"),
4703 ItemType::Trait => ("traits", "Traits"),
4704 ItemType::Impl => ("impls", "Implementations"),
4705 ItemType::TyMethod => ("tymethods", "Type Methods"),
4706 ItemType::Method => ("methods", "Methods"),
4707 ItemType::StructField => ("fields", "Struct Fields"),
4708 ItemType::Variant => ("variants", "Variants"),
4709 ItemType::Macro => ("macros", "Macros"),
4710 ItemType::Primitive => ("primitives", "Primitive Types"),
4711 ItemType::AssocType => ("associated-types", "Associated Types"),
4712 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4713 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4714 ItemType::Keyword => ("keywords", "Keywords"),
4715 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4716 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4717 ItemType::ProcDerive => ("derives", "Derive Macros"),
4718 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4722 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4723 let mut sidebar = String::new();
4725 if items.iter().any(|it| {
4726 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4728 sidebar.push_str(&format!(
4729 "<li><a href=\"#{id}\">{name}</a></li>",
4735 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4736 // to print its headings
4738 ItemType::Primitive,
4752 ItemType::StructField,
4754 ItemType::AssocType,
4755 ItemType::AssocConst,
4756 ItemType::ForeignType,
4759 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4760 let (short, name) = item_ty_to_strs(&myty);
4761 sidebar.push_str(&format!(
4762 "<li><a href=\"#{id}\">{name}</a></li>",
4769 if !sidebar.is_empty() {
4770 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4774 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4775 let sidebar = sidebar_assoc_items(cx, it);
4776 if !sidebar.is_empty() {
4777 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4781 fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
4782 wrap_into_docblock(w, |w| {
4783 w.write_str(&highlight::render_with_highlighting(
4788 it.source.span().edition(),
4791 document(w, cx, it, None)
4794 fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
4795 let name = it.name.as_ref().expect("proc-macros always have names");
4797 MacroKind::Bang => {
4798 write!(w, "<pre class=\"rust macro\">");
4799 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4800 write!(w, "</pre>");
4802 MacroKind::Attr => {
4803 write!(w, "<pre class=\"rust attr\">");
4804 write!(w, "#[{}]", name);
4805 write!(w, "</pre>");
4807 MacroKind::Derive => {
4808 write!(w, "<pre class=\"rust derive\">");
4809 write!(w, "#[derive({})]", name);
4810 if !m.helpers.is_empty() {
4811 writeln!(w, "\n{{");
4812 writeln!(w, " // Attributes available to this derive:");
4813 for attr in &m.helpers {
4814 writeln!(w, " #[{}]", attr);
4818 write!(w, "</pre>");
4821 document(w, cx, it, None)
4824 fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, cache: &Cache) {
4825 document(w, cx, it, None);
4826 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4829 fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4830 document(w, cx, it, None)
4833 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4835 fn make_item_keywords(it: &clean::Item) -> String {
4836 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4839 /// Returns a list of all paths used in the type.
4840 /// This is used to help deduplicate imported impls
4841 /// for reexported types. If any of the contained
4842 /// types are re-exported, we don't use the corresponding
4843 /// entry from the js file, as inlining will have already
4844 /// picked up the impl
4845 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4846 let mut out = Vec::new();
4847 let mut visited = FxHashSet::default();
4848 let mut work = VecDeque::new();
4849 let cache = cache();
4851 work.push_back(first_ty);
4853 while let Some(ty) = work.pop_front() {
4854 if !visited.insert(ty.clone()) {
4859 clean::Type::ResolvedPath { did, .. } => {
4860 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4861 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4863 if let Some(path) = fqp {
4864 out.push(path.join("::"));
4867 clean::Type::Tuple(tys) => {
4868 work.extend(tys.into_iter());
4870 clean::Type::Slice(ty) => {
4871 work.push_back(*ty);
4873 clean::Type::Array(ty, _) => {
4874 work.push_back(*ty);
4876 clean::Type::RawPointer(_, ty) => {
4877 work.push_back(*ty);
4879 clean::Type::BorrowedRef { type_, .. } => {
4880 work.push_back(*type_);
4882 clean::Type::QPath { self_type, trait_, .. } => {
4883 work.push_back(*self_type);
4884 work.push_back(*trait_);