1 // ignore-tidy-filelength
3 //! Rustdoc's HTML rendering module.
5 //! This modules contains the bulk of the logic necessary for rendering a
6 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
7 //! rendering process is largely driven by the `format!` syntax extension to
8 //! perform all I/O into files and streams.
10 //! The rendering process is largely driven by the `Context` and `Cache`
11 //! structures. The cache is pre-populated by crawling the crate in question,
12 //! and then it is shared among the various rendering threads. The cache is meant
13 //! to be a fairly large structure not implementing `Clone` (because it's shared
14 //! among threads). The context, however, should be a lightweight structure. This
15 //! is cloned per-thread and contains information about what is currently being
18 //! In order to speed up rendering (mostly because of markdown rendering), the
19 //! rendering process has been parallelized. This parallelization is only
20 //! exposed through the `crate` method on the context, and then also from the
21 //! fact that the shared cache is stored in TLS (and must be accessed as such).
23 //! In addition to rendering the crate itself, this module is also responsible
24 //! for creating the corresponding search index and source file renderings.
25 //! These threads are not parallelized (they haven't been a bottleneck yet), and
26 //! both occur before the crate is rendered.
33 use std::cell::{Cell, RefCell};
34 use std::cmp::Ordering;
35 use std::collections::{BTreeMap, VecDeque};
36 use std::default::Default;
38 use std::fmt::{self, Write};
39 use std::fs::{self, File};
40 use std::io::prelude::*;
41 use std::io::{self, BufReader};
42 use std::path::{Component, Path, PathBuf};
45 use std::string::ToString;
46 use std::sync::mpsc::{channel, Receiver};
49 use itertools::Itertools;
50 use rustc_ast_pretty::pprust;
51 use rustc_attr::{Deprecation, StabilityLevel};
52 use rustc_data_structures::flock;
53 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
55 use rustc_hir::def::CtorKind;
56 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
57 use rustc_hir::Mutability;
58 use rustc_middle::middle::stability;
59 use rustc_middle::ty::TyCtxt;
60 use rustc_session::Session;
61 use rustc_span::edition::Edition;
62 use rustc_span::hygiene::MacroKind;
63 use rustc_span::source_map::FileName;
64 use rustc_span::symbol::{kw, sym, Symbol};
65 use serde::ser::SerializeSeq;
66 use serde::{Serialize, Serializer};
68 use crate::clean::{self, AttributesExt, GetDefId, RenderedLink, SelfTy, TypeKind};
69 use crate::config::{RenderInfo, RenderOptions};
70 use crate::docfs::{DocFS, PathError};
71 use crate::error::Error;
72 use crate::formats::cache::Cache;
73 use crate::formats::item_type::ItemType;
74 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
75 use crate::html::escape::Escape;
76 use crate::html::format::Function;
77 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
78 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
79 use crate::html::markdown::{
80 self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine,
82 use crate::html::sources;
83 use crate::html::{highlight, layout, static_files};
84 use cache::{build_index, ExternalLocation};
86 /// A pair of name and its optional document.
87 crate type NameDoc = (String, Option<String>);
89 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
90 crate::html::format::display_fn(move |f| {
91 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
95 /// Major driving force in all rustdoc rendering. This contains information
96 /// about where in the tree-like hierarchy rendering is occurring and controls
97 /// how the current page is being rendered.
99 /// It is intended that this context is a lightweight object which can be fairly
100 /// easily cloned because it is cloned per work-job (about once per item in the
103 crate struct Context<'tcx> {
104 /// Current hierarchy of components leading down to what's currently being
106 crate current: Vec<String>,
107 /// The current destination folder of where HTML artifacts should be placed.
108 /// This changes as the context descends into the module hierarchy.
110 /// A flag, which when `true`, will render pages which redirect to the
111 /// real location of an item. This is used to allow external links to
112 /// publicly reused items to redirect to the right location.
113 crate render_redirect_pages: bool,
114 /// The map used to ensure all generated 'id=' attributes are unique.
115 id_map: Rc<RefCell<IdMap>>,
116 /// Tracks section IDs for `Deref` targets so they match in both the main
117 /// body and the sidebar.
118 deref_id_map: Rc<RefCell<FxHashMap<DefId, String>>>,
119 crate shared: Arc<SharedContext<'tcx>>,
120 all: Rc<RefCell<AllTypes>>,
121 /// Storage for the errors produced while generating documentation so they
122 /// can be printed together at the end.
123 crate errors: Rc<Receiver<String>>,
124 crate cache: Rc<Cache>,
127 crate struct SharedContext<'tcx> {
128 crate tcx: TyCtxt<'tcx>,
129 /// The path to the crate root source minus the file name.
130 /// Used for simplifying paths to the highlighted source code files.
131 crate src_root: PathBuf,
132 /// This describes the layout of each page, and is not modified after
133 /// creation of the context (contains info like the favicon and added html).
134 crate layout: layout::Layout,
135 /// This flag indicates whether `[src]` links should be generated or not. If
136 /// the source files are present in the html rendering, then this will be
138 crate include_sources: bool,
139 /// The local file sources we've emitted and their respective url-paths.
140 crate local_sources: FxHashMap<PathBuf, String>,
141 /// Whether the collapsed pass ran
142 crate collapsed: bool,
143 /// The base-URL of the issue tracker for when an item has been tagged with
145 crate issue_tracker_base_url: Option<String>,
146 /// The directories that have already been created in this doc run. Used to reduce the number
147 /// of spurious `create_dir_all` calls.
148 crate created_dirs: RefCell<FxHashSet<PathBuf>>,
149 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
150 /// should be ordered alphabetically or in order of appearance (in the source code).
151 crate sort_modules_alphabetically: bool,
152 /// Additional CSS files to be added to the generated docs.
153 crate style_files: Vec<StylePath>,
154 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
156 crate resource_suffix: String,
157 /// Optional path string to be used to load static files on output pages. If not set, uses
158 /// combinations of `../` to reach the documentation root.
159 crate static_root_path: Option<String>,
160 /// The fs handle we are working with.
162 /// The default edition used to parse doctests.
163 crate edition: Edition,
164 crate codes: ErrorCodes,
165 playground: Option<markdown::Playground>,
168 impl<'tcx> Context<'tcx> {
169 fn path(&self, filename: &str) -> PathBuf {
170 // We use splitn vs Path::extension here because we might get a filename
171 // like `style.min.css` and we want to process that into
172 // `style-suffix.min.css`. Path::extension would just return `css`
173 // which would result in `style.min-suffix.css` which isn't what we
175 let (base, ext) = filename.split_once('.').unwrap();
176 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext);
177 self.dst.join(&filename)
180 fn tcx(&self) -> TyCtxt<'tcx> {
184 fn sess(&self) -> &Session {
185 &self.shared.tcx.sess
189 impl SharedContext<'_> {
190 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
191 let mut dirs = self.created_dirs.borrow_mut();
192 if !dirs.contains(dst) {
193 try_err!(self.fs.create_dir_all(dst), dst);
194 dirs.insert(dst.to_path_buf());
200 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
201 /// `collapsed_doc_value` of the given item.
202 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<String> {
203 if self.collapsed { item.collapsed_doc_value() } else { item.doc_value() }
207 // Helper structs for rendering items/sidebars and carrying along contextual
210 /// Struct representing one entry in the JS search index. These are all emitted
211 /// by hand to a large JS file at the end of cache-creation.
213 crate struct IndexItem {
218 crate parent: Option<DefId>,
219 crate parent_idx: Option<usize>,
220 crate search_type: Option<IndexItemFunctionType>,
223 impl Serialize for IndexItem {
224 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
229 self.parent.is_some(),
230 self.parent_idx.is_some(),
231 "`{}` is missing idx",
235 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
236 .serialize(serializer)
240 /// A type used for the search index.
242 crate struct RenderType {
245 name: Option<String>,
246 generics: Option<Vec<Generic>>,
249 impl Serialize for RenderType {
250 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
254 if let Some(name) = &self.name {
255 let mut seq = serializer.serialize_seq(None)?;
256 if let Some(id) = self.idx {
257 seq.serialize_element(&id)?;
259 seq.serialize_element(&name)?;
261 if let Some(generics) = &self.generics {
262 seq.serialize_element(&generics)?;
266 serializer.serialize_none()
271 /// A type used for the search index.
273 crate struct Generic {
275 defid: Option<DefId>,
279 impl Serialize for Generic {
280 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
284 if let Some(id) = self.idx {
285 serializer.serialize_some(&id)
287 serializer.serialize_some(&self.name)
292 /// Full type of functions/methods in the search index.
294 crate struct IndexItemFunctionType {
295 inputs: Vec<TypeWithKind>,
296 output: Option<Vec<TypeWithKind>>,
299 impl Serialize for IndexItemFunctionType {
300 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
304 // If we couldn't figure out a type, just write `null`.
305 let mut iter = self.inputs.iter();
306 if match self.output {
307 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
308 None => iter.any(|ref i| i.ty.name.is_none()),
310 serializer.serialize_none()
312 let mut seq = serializer.serialize_seq(None)?;
313 seq.serialize_element(&self.inputs)?;
314 if let Some(output) = &self.output {
315 if output.len() > 1 {
316 seq.serialize_element(&output)?;
318 seq.serialize_element(&output[0])?;
327 crate struct TypeWithKind {
332 impl From<(RenderType, TypeKind)> for TypeWithKind {
333 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
334 TypeWithKind { ty: x.0, kind: x.1 }
338 impl Serialize for TypeWithKind {
339 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
343 let mut seq = serializer.serialize_seq(None)?;
344 seq.serialize_element(&self.ty.name)?;
345 let x: ItemType = self.kind.into();
346 seq.serialize_element(&x)?;
351 #[derive(Debug, Clone)]
352 crate struct StylePath {
353 /// The path to the theme
355 /// What the `disabled` attribute should be set to in the HTML tag
356 crate disabled: bool,
359 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
361 crate const INITIAL_IDS: [&'static str; 15] = [
372 "synthetic-implementors",
374 "synthetic-implementors-list",
379 /// Generates the documentation for `crate` into the directory `dst`
380 impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
381 fn descr() -> &'static str {
386 mut krate: clean::Crate,
387 options: RenderOptions,
388 _render_info: RenderInfo,
392 ) -> Result<(Self, clean::Crate), Error> {
393 // need to save a copy of the options for rendering the index page
394 let md_opts = options.clone();
400 sort_modules_alphabetically,
406 generate_search_filter,
411 let src_root = match krate.src {
412 FileName::Real(ref p) => match p.local_path().parent() {
413 Some(p) => p.to_path_buf(),
414 None => PathBuf::new(),
418 // If user passed in `--playground-url` arg, we fill in crate name here
419 let mut playground = None;
420 if let Some(url) = playground_url {
422 Some(markdown::Playground { crate_name: Some(krate.name.to_string()), url });
424 let mut layout = layout::Layout {
426 favicon: String::new(),
429 krate: krate.name.to_string(),
430 css_file_extension: extension_css,
431 generate_search_filter,
433 let mut issue_tracker_base_url = None;
434 let mut include_sources = true;
436 // Crawl the crate attributes looking for attributes which control how we're
437 // going to emit HTML
438 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
439 for attr in attrs.lists(sym::doc) {
440 match (attr.name_or_empty(), attr.value_str()) {
441 (sym::html_favicon_url, Some(s)) => {
442 layout.favicon = s.to_string();
444 (sym::html_logo_url, Some(s)) => {
445 layout.logo = s.to_string();
447 (sym::html_playground_url, Some(s)) => {
448 playground = Some(markdown::Playground {
449 crate_name: Some(krate.name.to_string()),
453 (sym::issue_tracker_base_url, Some(s)) => {
454 issue_tracker_base_url = Some(s.to_string());
456 (sym::html_no_source, None) if attr.is_word() => {
457 include_sources = false;
463 let (sender, receiver) = channel();
464 let mut scx = SharedContext {
466 collapsed: krate.collapsed,
469 local_sources: Default::default(),
470 issue_tracker_base_url,
472 created_dirs: Default::default(),
473 sort_modules_alphabetically,
477 fs: DocFS::new(sender),
479 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
483 // Add the default themes to the `Vec` of stylepaths
485 // Note that these must be added before `sources::render` is called
486 // so that the resulting source pages are styled
488 // `light.css` is not disabled because it is the stylesheet that stays loaded
489 // by the browser as the theme stylesheet. The theme system (hackily) works by
490 // changing the href to this stylesheet. All other themes are disabled to
491 // prevent rule conflicts
492 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
493 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
494 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
497 scx.ensure_dir(&dst)?;
498 krate = sources::render(&dst, &mut scx, krate)?;
500 // Build our search index
501 let index = build_index(&krate, &mut cache, tcx);
503 let mut cx = Context {
506 render_redirect_pages: false,
507 id_map: Rc::new(RefCell::new(id_map)),
508 deref_id_map: Rc::new(RefCell::new(FxHashMap::default())),
509 shared: Arc::new(scx),
510 all: Rc::new(RefCell::new(AllTypes::new())),
511 errors: Rc::new(receiver),
512 cache: Rc::new(cache),
515 CURRENT_DEPTH.with(|s| s.set(0));
517 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
518 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
519 write_shared(&cx, &krate, index, &md_opts)?;
520 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
526 krate: &clean::Crate,
527 diag: &rustc_errors::Handler,
528 ) -> Result<(), Error> {
529 let final_file = self.dst.join(&*krate.name.as_str()).join("all.html");
530 let settings_file = self.dst.join("settings.html");
531 let crate_name = krate.name;
533 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
534 if !root_path.ends_with('/') {
537 let mut page = layout::Page {
538 title: "List of all items in this crate",
541 static_root_path: self.shared.static_root_path.as_deref(),
542 description: "List of all items in this crate",
543 keywords: BASIC_KEYWORDS,
544 resource_suffix: &self.shared.resource_suffix,
546 static_extra_scripts: &[],
548 let sidebar = if let Some(ref version) = self.cache.crate_version {
550 "<p class=\"location\">Crate {}</p>\
551 <div class=\"block version\">\
554 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
561 let all = self.all.replace(AllTypes::new());
562 let v = layout::render(
566 |buf: &mut Buffer| all.print(buf),
567 &self.shared.style_files,
569 self.shared.fs.write(&final_file, v.as_bytes())?;
571 // Generating settings page.
572 page.title = "Rustdoc settings";
573 page.description = "Settings of Rustdoc";
574 page.root_path = "./";
576 let mut style_files = self.shared.style_files.clone();
577 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
578 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
579 let v = layout::render(
584 self.shared.static_root_path.as_deref().unwrap_or("./"),
585 &self.shared.resource_suffix,
586 &self.shared.style_files,
590 self.shared.fs.write(&settings_file, v.as_bytes())?;
592 // Flush pending errors.
593 Arc::get_mut(&mut self.shared).unwrap().fs.close();
594 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
596 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
602 fn mod_item_in(&mut self, item: &clean::Item, item_name: &str) -> Result<(), Error> {
603 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
604 // if they contain impls for public types. These modules can also
605 // contain items such as publicly re-exported structures.
607 // External crates will provide links to these structures, so
608 // these modules are recursed into, but not rendered normally
609 // (a flag on the context).
610 if !self.render_redirect_pages {
611 self.render_redirect_pages = item.is_stripped();
613 let scx = &self.shared;
614 self.dst.push(item_name);
615 self.current.push(item_name.to_owned());
617 info!("Recursing into {}", self.dst.display());
619 let buf = self.render_item(item, false);
620 // buf will be empty if the module is stripped and there is no redirect for it
622 self.shared.ensure_dir(&self.dst)?;
623 let joint_dst = self.dst.join("index.html");
624 scx.fs.write(&joint_dst, buf.as_bytes())?;
627 // Render sidebar-items.js used throughout this module.
628 if !self.render_redirect_pages {
629 let module = match *item.kind {
630 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
633 let items = self.build_sidebar_items(module);
634 let js_dst = self.dst.join("sidebar-items.js");
635 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
636 scx.fs.write(&js_dst, &v)?;
641 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
642 info!("Recursed; leaving {}", self.dst.display());
644 // Go back to where we were at
650 fn item(&mut self, item: clean::Item) -> Result<(), Error> {
651 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
652 // if they contain impls for public types. These modules can also
653 // contain items such as publicly re-exported structures.
655 // External crates will provide links to these structures, so
656 // these modules are recursed into, but not rendered normally
657 // (a flag on the context).
658 if !self.render_redirect_pages {
659 self.render_redirect_pages = item.is_stripped();
662 let buf = self.render_item(&item, true);
663 // buf will be empty if the item is stripped and there is no redirect for it
665 let name = item.name.as_ref().unwrap();
666 let item_type = item.type_();
667 let file_name = &item_path(item_type, &name.as_str());
668 self.shared.ensure_dir(&self.dst)?;
669 let joint_dst = self.dst.join(file_name);
670 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
672 if !self.render_redirect_pages {
673 self.all.borrow_mut().append(full_path(self, &item), &item_type);
675 // If the item is a macro, redirect from the old macro URL (with !)
676 // to the new one (without).
677 if item_type == ItemType::Macro {
678 let redir_name = format!("{}.{}!.html", item_type, name);
679 let redir_dst = self.dst.join(redir_name);
680 let v = layout::redirect(file_name);
681 self.shared.fs.write(&redir_dst, v.as_bytes())?;
687 fn cache(&self) -> &Cache {
694 krate: &clean::Crate,
695 search_index: String,
696 options: &RenderOptions,
697 ) -> Result<(), Error> {
698 // Write out the shared files. Note that these are shared among all rustdoc
699 // docs placed in the output directory, so this needs to be a synchronized
700 // operation with respect to all other rustdocs running around.
701 let lock_file = cx.dst.join(".lock");
702 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
704 // Add all the static files. These may already exist, but we just
705 // overwrite them anyway to make sure that they're fresh and up-to-date.
709 cx.path("rustdoc.css"),
710 static_files::RUSTDOC_CSS,
711 options.enable_minification,
715 cx.path("settings.css"),
716 static_files::SETTINGS_CSS,
717 options.enable_minification,
721 cx.path("noscript.css"),
722 static_files::NOSCRIPT_CSS,
723 options.enable_minification,
726 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
727 // then we'll run over the "official" styles.
728 let mut themes: FxHashSet<String> = FxHashSet::default();
730 for entry in &cx.shared.style_files {
731 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
733 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
735 // Handle the official themes
737 "light" => write_minify(
739 cx.path("light.css"),
740 static_files::themes::LIGHT,
741 options.enable_minification,
743 "dark" => write_minify(
746 static_files::themes::DARK,
747 options.enable_minification,
749 "ayu" => write_minify(
752 static_files::themes::AYU,
753 options.enable_minification,
756 // Handle added third-party themes
757 let content = try_err!(fs::read(&entry.path), &entry.path);
760 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
764 themes.insert(theme.to_owned());
767 let write = |p, c| cx.shared.fs.write(p, c);
768 if (*cx.shared).layout.logo.is_empty() {
769 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
771 if (*cx.shared).layout.favicon.is_empty() {
772 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
773 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
774 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
776 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
777 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
778 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
780 let mut themes: Vec<&String> = themes.iter().collect();
782 // To avoid theme switch latencies as much as possible, we put everything theme related
783 // at the beginning of the html files into another js file.
784 let theme_js = format!(
785 r#"var themes = document.getElementById("theme-choices");
786 var themePicker = document.getElementById("theme-picker");
788 function showThemeButtonState() {{
789 themes.style.display = "block";
790 themePicker.style.borderBottomRightRadius = "0";
791 themePicker.style.borderBottomLeftRadius = "0";
794 function hideThemeButtonState() {{
795 themes.style.display = "none";
796 themePicker.style.borderBottomRightRadius = "3px";
797 themePicker.style.borderBottomLeftRadius = "3px";
800 function switchThemeButtonState() {{
801 if (themes.style.display === "block") {{
802 hideThemeButtonState();
804 showThemeButtonState();
808 function handleThemeButtonsBlur(e) {{
809 var active = document.activeElement;
810 var related = e.relatedTarget;
812 if (active.id !== "theme-picker" &&
813 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
815 (related.id !== "theme-picker" &&
816 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
817 hideThemeButtonState();
821 themePicker.onclick = switchThemeButtonState;
822 themePicker.onblur = handleThemeButtonsBlur;
823 {}.forEach(function(item) {{
824 var but = document.createElement("button");
825 but.textContent = item;
826 but.onclick = function(el) {{
827 switchTheme(currentTheme, mainTheme, item, true);
828 useSystemTheme(false);
830 but.onblur = handleThemeButtonsBlur;
831 themes.appendChild(but);
833 serde_json::to_string(&themes).unwrap()
836 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
840 static_files::MAIN_JS,
841 options.enable_minification,
845 cx.path("settings.js"),
846 static_files::SETTINGS_JS,
847 options.enable_minification,
849 if cx.shared.include_sources {
852 cx.path("source-script.js"),
853 static_files::sidebar::SOURCE_SCRIPT,
854 options.enable_minification,
861 cx.path("storage.js"),
863 "var resourcesSuffix = \"{}\";{}",
864 cx.shared.resource_suffix,
865 static_files::STORAGE_JS
867 options.enable_minification,
871 if let Some(ref css) = cx.shared.layout.css_file_extension {
872 let out = cx.path("theme.css");
873 let buffer = try_err!(fs::read_to_string(css), css);
874 if !options.enable_minification {
875 cx.shared.fs.write(&out, &buffer)?;
877 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
882 cx.path("normalize.css"),
883 static_files::NORMALIZE_CSS,
884 options.enable_minification,
886 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
887 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
888 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
889 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
890 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
891 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
892 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
893 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
894 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
895 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
896 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
897 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
898 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
900 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
901 let mut ret = Vec::new();
902 let mut krates = Vec::new();
905 let prefix = format!(r#"{}["{}"]"#, key, krate);
906 for line in BufReader::new(File::open(path)?).lines() {
908 if !line.starts_with(key) {
911 if line.starts_with(&prefix) {
914 ret.push(line.to_string());
916 line[key.len() + 2..]
919 .map(|s| s.to_owned())
920 .unwrap_or_else(String::new),
927 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
928 let mut ret = Vec::new();
929 let mut krates = Vec::new();
932 let prefix = format!("\"{}\"", krate);
933 for line in BufReader::new(File::open(path)?).lines() {
935 if !line.starts_with('"') {
938 if line.starts_with(&prefix) {
941 if line.ends_with(",\\") {
942 ret.push(line[..line.len() - 2].to_string());
944 // Ends with "\\" (it's the case for the last added crate line)
945 ret.push(line[..line.len() - 1].to_string());
949 .find(|s| !s.is_empty())
950 .map(|s| s.to_owned())
951 .unwrap_or_else(String::new),
958 use std::ffi::OsString;
963 children: FxHashMap<OsString, Hierarchy>,
964 elems: FxHashSet<OsString>,
968 fn new(elem: OsString) -> Hierarchy {
969 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
972 fn to_json_string(&self) -> String {
973 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
974 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
978 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
979 .collect::<Vec<_>>();
980 files.sort_unstable();
981 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
983 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
984 let files = files.join(",");
986 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
988 "{{\"name\":\"{name}\"{dirs}{files}}}",
989 name = self.elem.to_str().expect("invalid osstring conversion"),
996 if cx.shared.include_sources {
997 let mut hierarchy = Hierarchy::new(OsString::new());
1002 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
1004 let mut h = &mut hierarchy;
1005 let mut elems = source
1007 .filter_map(|s| match s {
1008 Component::Normal(s) => Some(s.to_owned()),
1013 let cur_elem = elems.next().expect("empty file path");
1014 if elems.peek().is_none() {
1015 h.elems.insert(cur_elem);
1018 let e = cur_elem.clone();
1019 h = h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1024 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1025 let (mut all_sources, _krates) =
1026 try_err!(collect(&dst, &krate.name.as_str(), "sourcesIndex"), &dst);
1027 all_sources.push(format!(
1028 "sourcesIndex[\"{}\"] = {};",
1030 hierarchy.to_json_string()
1034 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1035 all_sources.join("\n")
1037 cx.shared.fs.write(&dst, v.as_bytes())?;
1040 // Update the search index
1041 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1042 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name.as_str()), &dst);
1043 all_indexes.push(search_index);
1045 // Sort the indexes by crate so the file will be generated identically even
1046 // with rustdoc running in parallel.
1049 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1050 v.push_str(&all_indexes.join(",\\\n"));
1051 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1052 // search might start (if it's set into the URL for example).
1053 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1054 cx.shared.fs.write(&dst, &v)?;
1056 if options.enable_index_page {
1057 if let Some(index_page) = options.index_page.clone() {
1058 let mut md_opts = options.clone();
1059 md_opts.output = cx.dst.clone();
1060 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1062 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1063 .map_err(|e| Error::new(e, &index_page))?;
1065 let dst = cx.dst.join("index.html");
1066 let page = layout::Page {
1067 title: "Index of crates",
1070 static_root_path: cx.shared.static_root_path.as_deref(),
1071 description: "List of crates",
1072 keywords: BASIC_KEYWORDS,
1073 resource_suffix: &cx.shared.resource_suffix,
1075 static_extra_scripts: &[],
1077 krates.push(krate.name.to_string());
1081 let content = format!(
1082 "<h1 class=\"fqn\">\
1083 <span class=\"in-band\">List of all crates</span>\
1084 </h1><ul class=\"crate mod\">{}</ul>",
1089 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1090 ensure_trailing_slash(s),
1094 .collect::<String>()
1096 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1097 cx.shared.fs.write(&dst, v.as_bytes())?;
1101 // Update the list of all implementors for traits
1102 let dst = cx.dst.join("implementors");
1103 for (&did, imps) in &cx.cache.implementors {
1104 // Private modules can leak through to this phase of rustdoc, which
1105 // could contain implementations for otherwise private types. In some
1106 // rare cases we could find an implementation for an item which wasn't
1107 // indexed, so we just skip this step in that case.
1109 // FIXME: this is a vague explanation for why this can't be a `get`, in
1110 // theory it should be...
1111 let &(ref remote_path, remote_item_type) = match cx.cache.paths.get(&did) {
1113 None => match cx.cache.external_paths.get(&did) {
1119 #[derive(Serialize)]
1120 struct Implementor {
1126 let implementors = imps
1129 // If the trait and implementation are in the same crate, then
1130 // there's no need to emit information about it (there's inlining
1131 // going on). If they're in different crates then the crate defining
1132 // the trait will be interested in our implementation.
1134 // If the implementation is from another crate then that crate
1136 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1140 text: imp.inner_impl().print(cx.cache(), false).to_string(),
1141 synthetic: imp.inner_impl().synthetic,
1142 types: collect_paths_for_type(imp.inner_impl().for_.clone(), cx.cache()),
1146 .collect::<Vec<_>>();
1148 // Only create a js file if we have impls to add to it. If the trait is
1149 // documented locally though we always create the file to avoid dead
1151 if implementors.is_empty() && !cx.cache.paths.contains_key(&did) {
1155 let implementors = format!(
1156 r#"implementors["{}"] = {};"#,
1158 serde_json::to_string(&implementors).unwrap()
1161 let mut mydst = dst.clone();
1162 for part in &remote_path[..remote_path.len() - 1] {
1165 cx.shared.ensure_dir(&mydst)?;
1166 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1168 let (mut all_implementors, _) =
1169 try_err!(collect(&mydst, &krate.name.as_str(), "implementors"), &mydst);
1170 all_implementors.push(implementors);
1171 // Sort the implementors by crate so the file will be generated
1172 // identically even with rustdoc running in parallel.
1173 all_implementors.sort();
1175 let mut v = String::from("(function() {var implementors = {};\n");
1176 for implementor in &all_implementors {
1177 writeln!(v, "{}", *implementor).unwrap();
1180 "if (window.register_implementors) {\
1181 window.register_implementors(implementors);\
1183 window.pending_implementors = implementors;\
1187 cx.shared.fs.write(&mydst, &v)?;
1196 enable_minification: bool,
1197 ) -> Result<(), Error> {
1198 if enable_minification {
1199 if dst.extension() == Some(&OsStr::new("css")) {
1200 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1201 fs.write(dst, res.as_bytes())
1203 fs.write(dst, minifier::js::minify(contents).as_bytes())
1206 fs.write(dst, contents.as_bytes())
1210 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
1211 if let Some(l) = cx.src_href(item) {
1212 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
1216 #[derive(Debug, Eq, PartialEq, Hash)]
1223 fn new(mut url: String, name: String) -> ItemEntry {
1224 while url.starts_with('/') {
1227 ItemEntry { url, name }
1232 crate fn print(&self) -> impl fmt::Display + '_ {
1233 crate::html::format::display_fn(move |f| {
1234 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1239 impl PartialOrd for ItemEntry {
1240 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1241 Some(self.cmp(other))
1245 impl Ord for ItemEntry {
1246 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1247 self.name.cmp(&other.name)
1253 structs: FxHashSet<ItemEntry>,
1254 enums: FxHashSet<ItemEntry>,
1255 unions: FxHashSet<ItemEntry>,
1256 primitives: FxHashSet<ItemEntry>,
1257 traits: FxHashSet<ItemEntry>,
1258 macros: FxHashSet<ItemEntry>,
1259 functions: FxHashSet<ItemEntry>,
1260 typedefs: FxHashSet<ItemEntry>,
1261 opaque_tys: FxHashSet<ItemEntry>,
1262 statics: FxHashSet<ItemEntry>,
1263 constants: FxHashSet<ItemEntry>,
1264 keywords: FxHashSet<ItemEntry>,
1265 attributes: FxHashSet<ItemEntry>,
1266 derives: FxHashSet<ItemEntry>,
1267 trait_aliases: FxHashSet<ItemEntry>,
1271 fn new() -> AllTypes {
1272 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1274 structs: new_set(100),
1275 enums: new_set(100),
1276 unions: new_set(100),
1277 primitives: new_set(26),
1278 traits: new_set(100),
1279 macros: new_set(100),
1280 functions: new_set(100),
1281 typedefs: new_set(100),
1282 opaque_tys: new_set(100),
1283 statics: new_set(100),
1284 constants: new_set(100),
1285 keywords: new_set(100),
1286 attributes: new_set(100),
1287 derives: new_set(100),
1288 trait_aliases: new_set(100),
1292 fn append(&mut self, item_name: String, item_type: &ItemType) {
1293 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1294 if let Some(name) = url.pop() {
1295 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1297 let name = url.join("::");
1299 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1300 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1301 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1302 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1303 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1304 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1305 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1306 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1307 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1308 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1309 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1310 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1311 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1312 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1320 fn print(self, f: &mut Buffer) {
1321 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1323 let mut e: Vec<&ItemEntry> = e.iter().collect();
1325 write!(f, "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">", title, title, class);
1328 write!(f, "<li>{}</li>", s.print());
1331 f.write_str("</ul>");
1336 "<h1 class=\"fqn\">\
1337 <span class=\"in-band\">List of all items</span>\
1338 <span class=\"out-of-band\">\
1339 <span id=\"render-detail\">\
1340 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1341 title=\"collapse all docs\">\
1342 [<span class=\"inner\">−</span>]\
1346 <span class=\"in-band\">List of all items</span>\
1349 // Note: print_entries does not escape the title, because we know the current set of titles
1350 // don't require escaping.
1351 print_entries(f, &self.structs, "Structs", "structs");
1352 print_entries(f, &self.enums, "Enums", "enums");
1353 print_entries(f, &self.unions, "Unions", "unions");
1354 print_entries(f, &self.primitives, "Primitives", "primitives");
1355 print_entries(f, &self.traits, "Traits", "traits");
1356 print_entries(f, &self.macros, "Macros", "macros");
1357 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1358 print_entries(f, &self.derives, "Derive Macros", "derives");
1359 print_entries(f, &self.functions, "Functions", "functions");
1360 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1361 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1362 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1363 print_entries(f, &self.statics, "Statics", "statics");
1364 print_entries(f, &self.constants, "Constants", "constants")
1371 description: &'static str,
1372 sub_settings: Vec<Setting>,
1375 js_data_name: &'static str,
1376 description: &'static str,
1377 default_value: bool,
1380 js_data_name: &'static str,
1381 description: &'static str,
1382 default_value: &'static str,
1383 options: Vec<(String, String)>,
1388 fn display(&self, root_path: &str, suffix: &str) -> String {
1390 Setting::Section { description, ref sub_settings } => format!(
1391 "<div class=\"setting-line\">\
1392 <div class=\"title\">{}</div>\
1393 <div class=\"sub-settings\">{}</div>
1396 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1398 Setting::Toggle { js_data_name, description, default_value } => format!(
1399 "<div class=\"setting-line\">\
1400 <label class=\"toggle\">\
1401 <input type=\"checkbox\" id=\"{}\" {}>\
1402 <span class=\"slider\"></span>\
1407 if default_value { " checked" } else { "" },
1410 Setting::Select { js_data_name, description, default_value, ref options } => format!(
1411 "<div class=\"setting-line\">\
1413 <label class=\"select-wrapper\">\
1414 <select id=\"{}\" autocomplete=\"off\">{}</select>\
1415 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1423 "<option value=\"{}\" {}>{}</option>",
1425 if opt.0 == default_value { "selected" } else { "" },
1428 .collect::<String>(),
1436 impl From<(&'static str, &'static str, bool)> for Setting {
1437 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1438 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1442 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1443 fn from(values: (&'static str, Vec<T>)) -> Setting {
1445 description: values.0,
1446 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1451 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1452 let theme_names: Vec<(String, String)> = themes
1456 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1459 Ok((theme.clone(), theme))
1461 .collect::<Result<_, Error>>()?;
1463 // (id, explanation, default value)
1464 let settings: &[Setting] = &[
1466 "Theme preferences",
1468 Setting::from(("use-system-theme", "Use system theme", true)),
1470 js_data_name: "preferred-dark-theme",
1471 description: "Preferred dark theme",
1472 default_value: "dark",
1473 options: theme_names.clone(),
1476 js_data_name: "preferred-light-theme",
1477 description: "Preferred light theme",
1478 default_value: "light",
1479 options: theme_names,
1485 "Auto-hide item declarations",
1487 ("auto-hide-struct", "Auto-hide structs declaration", true),
1488 ("auto-hide-enum", "Auto-hide enums declaration", false),
1489 ("auto-hide-union", "Auto-hide unions declaration", true),
1490 ("auto-hide-trait", "Auto-hide traits declaration", true),
1491 ("auto-hide-macro", "Auto-hide macros declaration", false),
1495 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1496 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1497 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1499 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1500 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1502 ("line-numbers", "Show line numbers on code examples", false).into(),
1503 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1507 "<h1 class=\"fqn\">\
1508 <span class=\"in-band\">Rustdoc settings</span>\
1510 <div class=\"settings\">{}</div>\
1511 <script src=\"{}settings{}.js\"></script>",
1512 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1519 fn derive_id(&self, id: String) -> String {
1520 let mut map = self.id_map.borrow_mut();
1524 /// String representation of how to get back to the root path of the 'doc/'
1525 /// folder in terms of a relative URL.
1526 fn root_path(&self) -> String {
1527 "../".repeat(self.current.len())
1530 fn render_item(&self, it: &clean::Item, pushname: bool) -> String {
1531 // A little unfortunate that this is done like this, but it sure
1532 // does make formatting *a lot* nicer.
1533 CURRENT_DEPTH.with(|slot| {
1534 slot.set(self.current.len());
1537 let mut title = if it.is_primitive() || it.is_keyword() {
1538 // No need to include the namespace for primitive types and keywords
1541 self.current.join("::")
1544 if !title.is_empty() {
1545 title.push_str("::");
1547 title.push_str(&it.name.unwrap().as_str());
1549 title.push_str(" - Rust");
1550 let tyname = it.type_();
1551 let desc = if it.is_crate() {
1552 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1555 "API documentation for the Rust `{}` {} in crate `{}`.",
1556 it.name.as_ref().unwrap(),
1558 self.shared.layout.krate
1561 let keywords = make_item_keywords(it);
1562 let page = layout::Page {
1563 css_class: tyname.as_str(),
1564 root_path: &self.root_path(),
1565 static_root_path: self.shared.static_root_path.as_deref(),
1568 keywords: &keywords,
1569 resource_suffix: &self.shared.resource_suffix,
1571 static_extra_scripts: &[],
1575 self.id_map.borrow_mut().reset();
1576 self.id_map.borrow_mut().populate(&INITIAL_IDS);
1579 if !self.render_redirect_pages {
1581 &self.shared.layout,
1583 |buf: &mut _| print_sidebar(self, it, buf),
1584 |buf: &mut _| print_item(self, it, buf),
1585 &self.shared.style_files,
1588 let mut url = self.root_path();
1589 if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) {
1590 for name in &names[..names.len() - 1] {
1594 url.push_str(&item_path(ty, names.last().unwrap()));
1595 layout::redirect(&url)
1602 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1603 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1604 // BTreeMap instead of HashMap to get a sorted output
1605 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1606 for item in &m.items {
1607 if item.is_stripped() {
1611 let short = item.type_();
1612 let myname = match item.name {
1614 Some(ref s) => s.to_string(),
1616 let short = short.to_string();
1617 map.entry(short).or_default().push((
1619 Some(item.doc_value().map_or_else(String::new, |s| plain_text_summary(&s))),
1623 if self.shared.sort_modules_alphabetically {
1624 for items in map.values_mut() {
1631 /// Generates a url appropriate for an `href` attribute back to the source of
1634 /// The url generated, when clicked, will redirect the browser back to the
1635 /// original source code.
1637 /// If `None` is returned, then a source link couldn't be generated. This
1638 /// may happen, for example, with externally inlined items where the source
1639 /// of their crate documentation isn't known.
1640 fn src_href(&self, item: &clean::Item) -> Option<String> {
1641 let mut root = self.root_path();
1642 let mut path = String::new();
1643 let cnum = item.source.cnum(self.sess());
1645 // We can safely ignore synthetic `SourceFile`s.
1646 let file = match item.source.filename(self.sess()) {
1647 FileName::Real(ref path) => path.local_path().to_path_buf(),
1653 let (krate, path) = if cnum == LOCAL_CRATE {
1654 if let Some(path) = self.shared.local_sources.get(file) {
1655 (self.shared.layout.krate.as_str(), path)
1660 let (krate, src_root) = match *self.cache.extern_locations.get(&cnum)? {
1661 (name, ref src, ExternalLocation::Local) => (name, src),
1662 (name, ref src, ExternalLocation::Remote(ref s)) => {
1663 root = s.to_string();
1666 (_, _, ExternalLocation::Unknown) => return None,
1669 sources::clean_path(&src_root, file, false, |component| {
1670 path.push_str(&component.to_string_lossy());
1673 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1674 fname.push(".html");
1675 path.push_str(&fname.to_string_lossy());
1676 symbol = krate.as_str();
1680 let loline = item.source.lo(self.sess()).line;
1681 let hiline = item.source.hi(self.sess()).line;
1683 if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) };
1685 "{root}src/{krate}/{path}#{lines}",
1686 root = Escape(&root),
1694 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1696 F: FnOnce(&mut Buffer),
1698 w.write_str("<div class=\"docblock type-decl hidden-by-usual-hider\">");
1700 w.write_str("</div>")
1703 fn print_item(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
1704 debug_assert!(!item.is_stripped());
1705 // Write the breadcrumb trail header for the top
1706 buf.write_str("<h1 class=\"fqn\"><span class=\"in-band\">");
1707 let name = match *item.kind {
1708 clean::ModuleItem(ref m) => {
1715 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1716 clean::TraitItem(..) => "Trait ",
1717 clean::StructItem(..) => "Struct ",
1718 clean::UnionItem(..) => "Union ",
1719 clean::EnumItem(..) => "Enum ",
1720 clean::TypedefItem(..) => "Type Definition ",
1721 clean::MacroItem(..) => "Macro ",
1722 clean::ProcMacroItem(ref mac) => match mac.kind {
1723 MacroKind::Bang => "Macro ",
1724 MacroKind::Attr => "Attribute Macro ",
1725 MacroKind::Derive => "Derive Macro ",
1727 clean::PrimitiveItem(..) => "Primitive Type ",
1728 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1729 clean::ConstantItem(..) => "Constant ",
1730 clean::ForeignTypeItem => "Foreign Type ",
1731 clean::KeywordItem(..) => "Keyword ",
1732 clean::OpaqueTyItem(..) => "Opaque Type ",
1733 clean::TraitAliasItem(..) => "Trait Alias ",
1735 // We don't generate pages for any other type.
1739 buf.write_str(name);
1740 if !item.is_primitive() && !item.is_keyword() {
1741 let cur = &cx.current;
1742 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1743 for (i, component) in cur.iter().enumerate().take(amt) {
1746 "<a href=\"{}index.html\">{}</a>::<wbr>",
1747 "../".repeat(cur.len() - i - 1),
1752 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1754 buf.write_str("</span>"); // in-band
1755 buf.write_str("<span class=\"out-of-band\">");
1756 render_stability_since_raw(
1758 item.stable_since(cx.tcx()).as_deref(),
1759 item.const_stable_since(cx.tcx()).as_deref(),
1764 "<span id=\"render-detail\">\
1765 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1766 title=\"collapse all docs\">\
1767 [<span class=\"inner\">−</span>]\
1774 // When this item is part of a `crate use` in a downstream crate, the
1775 // [src] link in the downstream documentation will actually come back to
1776 // this page, and this link will be auto-clicked. The `id` attribute is
1777 // used to find the link to auto-click.
1778 if cx.shared.include_sources && !item.is_primitive() {
1779 write_srclink(cx, item, buf);
1782 buf.write_str("</span></h1>"); // out-of-band
1785 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1786 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1787 item_function(buf, cx, item, f)
1789 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
1790 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
1791 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
1792 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
1793 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t),
1794 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1795 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1796 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
1797 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1798 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1799 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
1800 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1801 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
1802 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
1804 // We don't generate pages for any other type.
1810 fn item_path(ty: ItemType, name: &str) -> String {
1812 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1813 _ => format!("{}.{}.html", ty, name),
1817 fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1818 let mut s = cx.current.join("::");
1820 s.push_str(&item.name.unwrap().as_str());
1824 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
1825 if let Some(ref name) = item.name {
1826 info!("Documenting {}", name);
1828 document_item_info(w, cx, item, false, parent);
1829 document_full(w, item, cx, "", false);
1832 /// Render md_text as markdown.
1837 links: Vec<RenderedLink>,
1841 let mut ids = cx.id_map.borrow_mut();
1844 "<div class=\"docblock{}\">{}{}</div>",
1845 if is_hidden { " hidden" } else { "" },
1853 &cx.shared.playground
1859 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1860 /// docs are longer, a "Read more" link is appended to the end.
1865 link: AssocItemLink<'_>,
1868 parent: Option<&clean::Item>,
1869 show_def_docs: bool,
1871 document_item_info(w, cx, item, is_hidden, parent);
1875 if let Some(s) = item.doc_value() {
1876 let mut summary_html = MarkdownSummaryLine(&s, &item.links(&cx.cache)).into_string();
1878 if s.contains('\n') {
1880 format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx.cache()));
1882 if let Some(idx) = summary_html.rfind("</p>") {
1883 summary_html.insert_str(idx, &link);
1885 summary_html.push_str(&link);
1891 "<div class='docblock{}'>{}{}</div>",
1892 if is_hidden { " hidden" } else { "" },
1896 } else if !prefix.is_empty() {
1899 "<div class=\"docblock{}\">{}</div>",
1900 if is_hidden { " hidden" } else { "" },
1913 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1914 debug!("Doc block: =====\n{}\n=====", s);
1915 render_markdown(w, cx, &*s, item.links(&cx.cache), prefix, is_hidden);
1916 } else if !prefix.is_empty() {
1918 w.write_str("<div class=\"docblock hidden\">");
1920 w.write_str("<div class=\"docblock\">");
1922 w.write_str(prefix);
1923 w.write_str("</div>");
1927 /// Add extra information about an item such as:
1931 /// * Required features (through the `doc_cfg` feature)
1932 fn document_item_info(
1937 parent: Option<&clean::Item>,
1939 let item_infos = short_item_info(item, cx, parent);
1940 if !item_infos.is_empty() {
1942 w.write_str("<div class=\"item-info hidden\">");
1944 w.write_str("<div class=\"item-info\">");
1946 for info in item_infos {
1949 w.write_str("</div>");
1953 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1954 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1957 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1958 if item.is_non_exhaustive() {
1959 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1960 if item.is_struct() {
1962 } else if item.is_enum() {
1964 } else if item.is_variant() {
1971 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() {
1981 "Non-exhaustive enums could have additional variants added in future. \
1982 Therefore, when matching against variants of non-exhaustive enums, an \
1983 extra wildcard arm must be added to account for any future variants.",
1985 } else if item.is_variant() {
1987 "Non-exhaustive enum variants could have additional fields added in future. \
1988 Therefore, non-exhaustive enum variants cannot be constructed in external \
1989 crates and cannot be matched against.",
1993 "This type will require a wildcard arm in any match statements or constructors.",
1997 w.write_str("</div>");
2001 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
2002 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
2003 /// Takes a non-numeric and a numeric part from the given &str.
2004 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
2005 let i = s.find(|c: char| c.is_ascii_digit());
2006 let (a, b) = s.split_at(i.unwrap_or(s.len()));
2007 let i = b.find(|c: char| !c.is_ascii_digit());
2008 let (b, c) = b.split_at(i.unwrap_or(b.len()));
2013 while !lhs.is_empty() || !rhs.is_empty() {
2014 let (la, lb) = take_parts(&mut lhs);
2015 let (ra, rb) = take_parts(&mut rhs);
2016 // First process the non-numeric part.
2018 Ordering::Equal => (),
2021 // Then process the numeric part, if both sides have one (and they fit in a u64).
2022 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2024 Ordering::Equal => (),
2028 // Then process the numeric part again, but this time as strings.
2030 Ordering::Equal => (),
2038 fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) {
2039 document(w, cx, item, None);
2041 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2043 // the order of item types in the listing
2044 fn reorder(ty: ItemType) -> u8 {
2046 ItemType::ExternCrate => 0,
2047 ItemType::Import => 1,
2048 ItemType::Primitive => 2,
2049 ItemType::Module => 3,
2050 ItemType::Macro => 4,
2051 ItemType::Struct => 5,
2052 ItemType::Enum => 6,
2053 ItemType::Constant => 7,
2054 ItemType::Static => 8,
2055 ItemType::Trait => 9,
2056 ItemType::Function => 10,
2057 ItemType::Typedef => 12,
2058 ItemType::Union => 13,
2070 let ty1 = i1.type_();
2071 let ty2 = i2.type_();
2073 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2075 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
2076 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
2077 if let (Some(a), Some(b)) = (s1, s2) {
2078 match (a.is_stable(), b.is_stable()) {
2079 (true, true) | (false, false) => {}
2080 (false, true) => return Ordering::Less,
2081 (true, false) => return Ordering::Greater,
2084 let lhs = i1.name.unwrap_or(kw::Empty).as_str();
2085 let rhs = i2.name.unwrap_or(kw::Empty).as_str();
2086 compare_names(&lhs, &rhs)
2089 if cx.shared.sort_modules_alphabetically {
2090 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
2092 // This call is to remove re-export duplicates in cases such as:
2097 // crate trait Double { fn foo(); }
2101 // crate use foo::bar::*;
2102 // crate use foo::*;
2105 // `Double` will appear twice in the generated docs.
2107 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2108 // can be identical even if the elements are different (mostly in imports).
2109 // So in case this is an import, we keep everything by adding a "unique id"
2110 // (which is the position in the vector).
2111 indices.dedup_by_key(|i| {
2114 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2116 if items[*i].is_import() { *i } else { 0 },
2120 debug!("{:?}", indices);
2121 let mut curty = None;
2122 for &idx in &indices {
2123 let myitem = &items[idx];
2124 if myitem.is_stripped() {
2128 let myty = Some(myitem.type_());
2129 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2130 // Put `extern crate` and `use` re-exports in the same section.
2132 } else if myty != curty {
2133 if curty.is_some() {
2134 w.write_str("</table>");
2137 let (short, name) = item_ty_to_strs(&myty.unwrap());
2140 "<h2 id=\"{id}\" class=\"section-header\">\
2141 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2142 id = cx.derive_id(short.to_owned()),
2147 match *myitem.kind {
2148 clean::ExternCrateItem(ref name, ref src) => {
2149 use crate::html::format::anchor;
2152 Some(ref src) => write!(
2154 "<tr><td><code>{}extern crate {} as {};",
2155 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2156 anchor(myitem.def_id, &*src.as_str(), cx.cache()),
2161 "<tr><td><code>{}extern crate {};",
2162 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2163 anchor(myitem.def_id, &*name.as_str(), cx.cache())
2166 w.write_str("</code></td></tr>");
2169 clean::ImportItem(ref import) => {
2172 "<tr><td><code>{}{}</code></td></tr>",
2173 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
2174 import.print(cx.cache())
2179 if myitem.name.is_none() {
2183 let unsafety_flag = match *myitem.kind {
2184 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2185 if func.header.unsafety == hir::Unsafety::Unsafe =>
2187 "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2192 let stab = myitem.stability_class(cx.tcx());
2193 let add = if stab.is_some() { " " } else { "" };
2195 let doc_value = myitem.doc_value().unwrap_or_default();
2198 "<tr class=\"{stab}{add}module-item\">\
2199 <td><a class=\"{class}\" href=\"{href}\" \
2200 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2201 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2203 name = *myitem.name.as_ref().unwrap(),
2204 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
2205 docs = MarkdownSummaryLine(&doc_value, &myitem.links(&cx.cache)).into_string(),
2206 class = myitem.type_(),
2208 stab = stab.unwrap_or_else(String::new),
2209 unsafety_flag = unsafety_flag,
2210 href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()),
2211 title = [full_path(cx, myitem), myitem.type_().to_string()]
2213 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2214 .collect::<Vec<_>>()
2221 if curty.is_some() {
2222 w.write_str("</table>");
2226 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
2227 /// at the module level.
2228 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
2229 let mut tags = String::new();
2231 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2232 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2235 // The trailing space after each tag is to space it properly against the rest of the docs.
2236 if let Some(depr) = &item.deprecation(tcx) {
2237 let mut message = "Deprecated";
2238 if !stability::deprecation_in_effect(
2239 depr.is_since_rustc_version,
2240 depr.since.map(|s| s.as_str()).as_deref(),
2242 message = "Deprecation planned";
2244 tags += &tag_html("deprecated", "", message);
2247 // The "rustc_private" crates are permanently unstable so it makes no sense
2248 // to render "unstable" everywhere.
2252 .map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2255 tags += &tag_html("unstable", "", "Experimental");
2258 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2259 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2260 (cfg, _) => cfg.as_deref().cloned(),
2263 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2264 if let Some(ref cfg) = cfg {
2265 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2271 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2272 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2273 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2274 (cfg, _) => cfg.as_deref().cloned(),
2278 "Portability {:?} - {:?} = {:?}",
2280 parent.and_then(|p| p.attrs.cfg.as_ref()),
2284 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2287 /// Render the stability, deprecation and portability information that is displayed at the top of
2288 /// the item's documentation.
2292 parent: Option<&clean::Item>,
2294 let mut extra_info = vec![];
2295 let error_codes = cx.shared.codes;
2297 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
2298 item.deprecation(cx.tcx())
2300 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2301 // but only display the future-deprecation messages for #[rustc_deprecated].
2302 let mut message = if let Some(since) = since {
2303 let since = &since.as_str();
2304 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2305 if *since == "TBD" {
2306 String::from("Deprecating in a future Rust version")
2308 format!("Deprecating in {}", Escape(since))
2311 format!("Deprecated since {}", Escape(since))
2314 String::from("Deprecated")
2317 if let Some(note) = note {
2318 let note = note.as_str();
2319 let mut ids = cx.id_map.borrow_mut();
2320 let html = MarkdownHtml(
2325 &cx.shared.playground,
2327 message.push_str(&format!(": {}", html.into_string()));
2329 extra_info.push(format!(
2330 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2335 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2336 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2337 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2338 .stability(cx.tcx())
2340 .filter(|stab| stab.feature != sym::rustc_private)
2341 .map(|stab| (stab.level, stab.feature))
2344 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2346 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2347 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2348 feature.push_str(&format!(
2349 " <a href=\"{url}{issue}\">#{issue}</a>",
2355 message.push_str(&format!(" ({})", feature));
2357 if let Some(unstable_reason) = reason {
2358 let mut ids = cx.id_map.borrow_mut();
2360 "<details><summary>{}</summary>{}</details>",
2363 &unstable_reason.as_str(),
2367 &cx.shared.playground,
2373 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2376 if let Some(portability) = portability(item, parent) {
2377 extra_info.push(portability);
2383 fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) {
2384 w.write_str("<pre class=\"rust const\">");
2385 render_attributes(w, it, false);
2389 "{vis}const {name}: {typ}",
2390 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2391 name = it.name.as_ref().unwrap(),
2392 typ = c.type_.print(cx.cache()),
2395 if c.value.is_some() || c.is_literal {
2396 write!(w, " = {expr};", expr = Escape(&c.expr));
2401 if let Some(value) = &c.value {
2403 let value_lowercase = value.to_lowercase();
2404 let expr_lowercase = c.expr.to_lowercase();
2406 if value_lowercase != expr_lowercase
2407 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2409 write!(w, " // {value}", value = Escape(value));
2414 w.write_str("</pre>");
2415 document(w, cx, it, None)
2418 fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
2419 w.write_str("<pre class=\"rust static\">");
2420 render_attributes(w, it, false);
2423 "{vis}static {mutability}{name}: {typ}</pre>",
2424 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2425 mutability = s.mutability.print_with_space(),
2426 name = it.name.as_ref().unwrap(),
2427 typ = s.type_.print(cx.cache())
2429 document(w, cx, it, None)
2432 fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
2433 let header_len = format!(
2434 "{}{}{}{}{:#}fn {}{:#}",
2435 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2436 f.header.constness.print_with_space(),
2437 f.header.asyncness.print_with_space(),
2438 f.header.unsafety.print_with_space(),
2439 print_abi_with_space(f.header.abi),
2440 it.name.as_ref().unwrap(),
2441 f.generics.print(cx.cache())
2444 w.write_str("<pre class=\"rust fn\">");
2445 render_attributes(w, it, false);
2448 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2449 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2450 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2451 constness = f.header.constness.print_with_space(),
2452 asyncness = f.header.asyncness.print_with_space(),
2453 unsafety = f.header.unsafety.print_with_space(),
2454 abi = print_abi_with_space(f.header.abi),
2455 name = it.name.as_ref().unwrap(),
2456 generics = f.generics.print(cx.cache()),
2458 WhereClause { gens: &f.generics, indent: 0, end_newline: true }.print(cx.cache()),
2459 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2461 spotlight = spotlight_decl(&f.decl, cx.cache()),
2463 document(w, cx, it, None)
2466 fn render_implementor(
2469 trait_: &clean::Item,
2471 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
2474 // If there's already another implementor that has the same abbridged name, use the
2475 // full path, for example in `std::iter::ExactSizeIterator`
2476 let use_absolute = match implementor.inner_impl().for_ {
2477 clean::ResolvedPath { ref path, is_generic: false, .. }
2478 | clean::BorrowedRef {
2479 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2481 } => implementor_dups[&path.last()].1,
2489 AssocItemLink::Anchor(None),
2491 trait_.stable_since(cx.tcx()).as_deref(),
2492 trait_.const_stable_since(cx.tcx()).as_deref(),
2505 containing_item: &clean::Item,
2507 let mut impls = traits
2510 let did = i.trait_did_full(cx.cache()).unwrap();
2511 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2512 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2520 containing_item.stable_since(cx.tcx()).as_deref(),
2521 containing_item.const_stable_since(cx.tcx()).as_deref(),
2530 .collect::<Vec<_>>();
2532 w.write_str(&impls.join(""));
2535 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cache: &Cache) -> String {
2536 let mut bounds = String::new();
2537 if !t_bounds.is_empty() {
2539 bounds.push_str(": ");
2541 for (i, p) in t_bounds.iter().enumerate() {
2543 bounds.push_str(" + ");
2545 bounds.push_str(&p.print(cache).to_string());
2551 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cache: &Cache) -> Ordering {
2552 let lhs = format!("{}", lhs.inner_impl().print(cache, false));
2553 let rhs = format!("{}", rhs.inner_impl().print(cache, false));
2555 // lhs and rhs are formatted as HTML, which may be unnecessary
2556 compare_names(&lhs, &rhs)
2559 fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) {
2560 let bounds = bounds(&t.bounds, false, cx.cache());
2561 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2562 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2563 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2564 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2566 // Output the trait definition
2567 wrap_into_docblock(w, |w| {
2568 w.write_str("<pre class=\"rust trait\">");
2569 render_attributes(w, it, true);
2572 "{}{}{}trait {}{}{}",
2573 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2574 t.unsafety.print_with_space(),
2575 if t.is_auto { "auto " } else { "" },
2576 it.name.as_ref().unwrap(),
2577 t.generics.print(cx.cache()),
2581 if !t.generics.where_predicates.is_empty() {
2582 let where_ = WhereClause { gens: &t.generics, indent: 0, end_newline: true };
2583 write!(w, "{}", where_.print(cx.cache()));
2588 if t.items.is_empty() {
2591 // FIXME: we should be using a derived_id for the Anchors here
2594 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2597 if !types.is_empty() && !consts.is_empty() {
2601 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2604 if !consts.is_empty() && !required.is_empty() {
2607 for (pos, m) in required.iter().enumerate() {
2608 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2611 if pos < required.len() - 1 {
2612 w.write_str("<div class=\"item-spacer\"></div>");
2615 if !required.is_empty() && !provided.is_empty() {
2618 for (pos, m) in provided.iter().enumerate() {
2619 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
2621 clean::MethodItem(ref inner, _)
2622 if !inner.generics.where_predicates.is_empty() =>
2624 w.write_str(",\n { ... }\n");
2627 w.write_str(" { ... }\n");
2630 if pos < provided.len() - 1 {
2631 w.write_str("<div class=\"item-spacer\"></div>");
2636 w.write_str("</pre>")
2639 // Trait documentation
2640 document(w, cx, it, None);
2642 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2645 "<h2 id=\"{0}\" class=\"small-section-header\">\
2646 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2648 id, title, extra_content
2652 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2653 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2656 fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item) {
2657 let name = m.name.as_ref().unwrap();
2658 info!("Documenting {} on {:?}", name, t.name);
2659 let item_type = m.type_();
2660 let id = cx.derive_id(format!("{}.{}", item_type, name));
2661 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2662 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl, cx);
2663 w.write_str("</code>");
2664 render_stability_since(w, m, t, cx.tcx());
2665 write_srclink(cx, m, w);
2666 w.write_str("</h3>");
2667 document(w, cx, m, Some(t));
2670 if !types.is_empty() {
2671 write_small_section_header(
2675 "<div class=\"methods\">",
2678 trait_item(w, cx, t, it);
2680 write_loading_content(w, "</div>");
2683 if !consts.is_empty() {
2684 write_small_section_header(
2687 "Associated Constants",
2688 "<div class=\"methods\">",
2691 trait_item(w, cx, t, it);
2693 write_loading_content(w, "</div>");
2696 // Output the documentation for each function individually
2697 if !required.is_empty() {
2698 write_small_section_header(
2702 "<div class=\"methods\">",
2705 trait_item(w, cx, m, it);
2707 write_loading_content(w, "</div>");
2709 if !provided.is_empty() {
2710 write_small_section_header(
2714 "<div class=\"methods\">",
2717 trait_item(w, cx, m, it);
2719 write_loading_content(w, "</div>");
2722 // If there are methods directly on this trait object, render them here.
2723 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All);
2725 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2726 // The DefId is for the first Type found with that name. The bool is
2727 // if any Types with the same name but different DefId have been found.
2728 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
2729 for implementor in implementors {
2730 match implementor.inner_impl().for_ {
2731 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2732 | clean::BorrowedRef {
2733 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2736 let &mut (prev_did, ref mut has_duplicates) =
2737 implementor_dups.entry(path.last()).or_insert((did, false));
2738 if prev_did != did {
2739 *has_duplicates = true;
2746 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2749 .def_id_full(cx.cache())
2750 .map_or(true, |d| cx.cache.paths.contains_key(&d))
2753 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2754 local.iter().partition(|i| i.inner_impl().synthetic);
2756 synthetic.sort_by(|a, b| compare_impl(a, b, cx.cache()));
2757 concrete.sort_by(|a, b| compare_impl(a, b, cx.cache()));
2759 if !foreign.is_empty() {
2760 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2762 for implementor in foreign {
2763 let assoc_link = AssocItemLink::GotoSource(
2764 implementor.impl_item.def_id,
2765 &implementor.inner_impl().provided_trait_methods,
2774 implementor.impl_item.stable_since(cx.tcx()).as_deref(),
2775 implementor.impl_item.const_stable_since(cx.tcx()).as_deref(),
2783 write_loading_content(w, "");
2786 write_small_section_header(
2790 "<div class=\"item-list\" id=\"implementors-list\">",
2792 for implementor in concrete {
2793 render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
2795 write_loading_content(w, "</div>");
2798 write_small_section_header(
2800 "synthetic-implementors",
2801 "Auto implementors",
2802 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2804 for implementor in synthetic {
2811 &collect_paths_for_type(implementor.inner_impl().for_.clone(), &cx.cache),
2814 write_loading_content(w, "</div>");
2817 // even without any implementations to write in, we still want the heading and list, so the
2818 // implementors javascript file pulled in below has somewhere to write the impls into
2819 write_small_section_header(
2823 "<div class=\"item-list\" id=\"implementors-list\">",
2825 write_loading_content(w, "</div>");
2828 write_small_section_header(
2830 "synthetic-implementors",
2831 "Auto implementors",
2832 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2834 write_loading_content(w, "</div>");
2840 "<script type=\"text/javascript\" \
2841 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2843 root_path = vec![".."; cx.current.len()].join("/"),
2844 path = if it.def_id.is_local() {
2845 cx.current.join("/")
2847 let (ref path, _) = cx.cache.external_paths[&it.def_id];
2848 path[..path.len() - 1].join("/")
2851 name = *it.name.as_ref().unwrap()
2855 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cache: &Cache) -> String {
2856 use crate::formats::item_type::ItemType::*;
2858 let name = it.name.as_ref().unwrap();
2859 let ty = match it.type_() {
2860 Typedef | AssocType => AssocType,
2864 let anchor = format!("#{}.{}", ty, name);
2866 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2867 AssocItemLink::Anchor(None) => anchor,
2868 AssocItemLink::GotoSource(did, _) => {
2869 href(did, cache).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2878 _default: Option<&String>,
2879 link: AssocItemLink<'_>,
2885 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2887 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
2888 naive_assoc_href(it, link, cx.cache()),
2889 it.name.as_ref().unwrap(),
2890 ty.print(cx.cache())
2897 bounds: &[clean::GenericBound],
2898 default: Option<&clean::Type>,
2899 link: AssocItemLink<'_>,
2905 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2907 naive_assoc_href(it, link, cache),
2908 it.name.as_ref().unwrap()
2910 if !bounds.is_empty() {
2911 write!(w, ": {}", print_generic_bounds(bounds, cache))
2913 if let Some(default) = default {
2914 write!(w, " = {}", default.print(cache))
2918 fn render_stability_since_raw(
2921 const_ver: Option<&str>,
2922 containing_ver: Option<&str>,
2923 containing_const_ver: Option<&str>,
2925 let ver = ver.filter(|inner| !inner.is_empty());
2926 let const_ver = const_ver.filter(|inner| !inner.is_empty());
2928 match (ver, const_ver) {
2929 (Some(v), Some(cv)) if const_ver != containing_const_ver => {
2932 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2936 (Some(v), _) if ver != containing_ver => {
2939 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2947 fn render_stability_since(
2950 containing_item: &clean::Item,
2953 render_stability_since_raw(
2955 item.stable_since(tcx).as_deref(),
2956 item.const_stable_since(tcx).as_deref(),
2957 containing_item.stable_since(tcx).as_deref(),
2958 containing_item.const_stable_since(tcx).as_deref(),
2962 fn render_assoc_item(
2965 link: AssocItemLink<'_>,
2972 header: hir::FnHeader,
2973 g: &clean::Generics,
2975 link: AssocItemLink<'_>,
2979 let name = meth.name.as_ref().unwrap();
2980 let anchor = format!("#{}.{}", meth.type_(), name);
2981 let href = match link {
2982 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2983 AssocItemLink::Anchor(None) => anchor,
2984 AssocItemLink::GotoSource(did, provided_methods) => {
2985 // We're creating a link from an impl-item to the corresponding
2986 // trait-item and need to map the anchored type accordingly.
2987 let ty = if provided_methods.contains(&name) {
2993 href(did, cx.cache()).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2996 let mut header_len = format!(
2997 "{}{}{}{}{}{:#}fn {}{:#}",
2998 meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
2999 header.constness.print_with_space(),
3000 header.asyncness.print_with_space(),
3001 header.unsafety.print_with_space(),
3002 print_default_space(meth.is_default()),
3003 print_abi_with_space(header.abi),
3008 let (indent, end_newline) = if parent == ItemType::Trait {
3014 render_attributes(w, meth, false);
3017 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
3018 {generics}{decl}{spotlight}{where_clause}",
3019 if parent == ItemType::Trait { " " } else { "" },
3020 meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
3021 header.constness.print_with_space(),
3022 header.asyncness.print_with_space(),
3023 header.unsafety.print_with_space(),
3024 print_default_space(meth.is_default()),
3025 print_abi_with_space(header.abi),
3028 generics = g.print(cx.cache()),
3029 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }
3031 spotlight = spotlight_decl(&d, cx.cache()),
3032 where_clause = WhereClause { gens: g, indent, end_newline }.print(cx.cache())
3036 clean::StrippedItem(..) => {}
3037 clean::TyMethodItem(ref m) => {
3038 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
3040 clean::MethodItem(ref m, _) => {
3041 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
3043 clean::AssocConstItem(ref ty, ref default) => assoc_const(
3049 if parent == ItemType::Trait { " " } else { "" },
3052 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3058 if parent == ItemType::Trait { " " } else { "" },
3061 _ => panic!("render_assoc_item called on non-associated-item"),
3065 fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) {
3066 wrap_into_docblock(w, |w| {
3067 w.write_str("<pre class=\"rust struct\">");
3068 render_attributes(w, it, true);
3069 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
3070 w.write_str("</pre>")
3073 document(w, cx, it, None);
3077 .filter_map(|f| match *f.kind {
3078 clean::StructFieldItem(ref ty) => Some((f, ty)),
3082 if let CtorKind::Fictive = s.struct_type {
3083 if fields.peek().is_some() {
3086 "<h2 id=\"fields\" class=\"fields small-section-header\">
3087 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3088 document_non_exhaustive_header(it)
3090 document_non_exhaustive(w, it);
3091 for (field, ty) in fields {
3092 let id = cx.derive_id(format!(
3094 ItemType::StructField,
3095 field.name.as_ref().unwrap()
3099 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3100 <a href=\"#{id}\" class=\"anchor field\"></a>\
3101 <code>{name}: {ty}</code>\
3103 item_type = ItemType::StructField,
3105 name = field.name.as_ref().unwrap(),
3106 ty = ty.print(cx.cache())
3108 document(w, cx, field, Some(it));
3112 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3115 fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
3116 wrap_into_docblock(w, |w| {
3117 w.write_str("<pre class=\"rust union\">");
3118 render_attributes(w, it, true);
3119 render_union(w, it, Some(&s.generics), &s.fields, "", true, cx);
3120 w.write_str("</pre>")
3123 document(w, cx, it, None);
3127 .filter_map(|f| match *f.kind {
3128 clean::StructFieldItem(ref ty) => Some((f, ty)),
3132 if fields.peek().is_some() {
3135 "<h2 id=\"fields\" class=\"fields small-section-header\">
3136 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3138 for (field, ty) in fields {
3139 let name = field.name.as_ref().expect("union field name");
3140 let id = format!("{}.{}", ItemType::StructField, name);
3143 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3144 <a href=\"#{id}\" class=\"anchor field\"></a>\
3145 <code>{name}: {ty}</code>\
3149 shortty = ItemType::StructField,
3150 ty = ty.print(cx.cache())
3152 if let Some(stability_class) = field.stability_class(cx.tcx()) {
3153 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3155 document(w, cx, field, Some(it));
3158 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3161 fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
3162 wrap_into_docblock(w, |w| {
3163 w.write_str("<pre class=\"rust enum\">");
3164 render_attributes(w, it, true);
3168 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3169 it.name.as_ref().unwrap(),
3170 e.generics.print(cx.cache()),
3171 WhereClause { gens: &e.generics, indent: 0, end_newline: true }.print(cx.cache())
3173 if e.variants.is_empty() && !e.variants_stripped {
3176 w.write_str(" {\n");
3177 for v in &e.variants {
3179 let name = v.name.as_ref().unwrap();
3181 clean::VariantItem(ref var) => match var {
3182 clean::Variant::CLike => write!(w, "{}", name),
3183 clean::Variant::Tuple(ref tys) => {
3184 write!(w, "{}(", name);
3185 for (i, ty) in tys.iter().enumerate() {
3187 w.write_str(", ")
3189 write!(w, "{}", ty.print(cx.cache()));
3193 clean::Variant::Struct(ref s) => {
3194 render_struct(w, v, None, s.struct_type, &s.fields, " ", false, cx);
3197 _ => unreachable!(),
3202 if e.variants_stripped {
3203 w.write_str(" // some variants omitted\n");
3207 w.write_str("</pre>")
3210 document(w, cx, it, None);
3211 if !e.variants.is_empty() {
3214 "<h2 id=\"variants\" class=\"variants small-section-header\">
3215 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3216 document_non_exhaustive_header(it)
3218 document_non_exhaustive(w, it);
3219 for variant in &e.variants {
3221 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3224 "<div id=\"{id}\" class=\"variant small-section-header\">\
3225 <a href=\"#{id}\" class=\"anchor field\"></a>\
3228 name = variant.name.as_ref().unwrap()
3230 if let clean::VariantItem(clean::Variant::Tuple(ref tys)) = *variant.kind {
3232 for (i, ty) in tys.iter().enumerate() {
3234 w.write_str(", ");
3236 write!(w, "{}", ty.print(cx.cache()));
3240 w.write_str("</code></div>");
3241 document(w, cx, variant, Some(it));
3242 document_non_exhaustive(w, variant);
3244 use crate::clean::Variant;
3245 if let clean::VariantItem(Variant::Struct(ref s)) = *variant.kind {
3246 let variant_id = cx.derive_id(format!(
3249 variant.name.as_ref().unwrap()
3251 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3254 "<h3>Fields of <b>{name}</b></h3><div>",
3255 name = variant.name.as_ref().unwrap()
3257 for field in &s.fields {
3258 use crate::clean::StructFieldItem;
3259 if let StructFieldItem(ref ty) = *field.kind {
3260 let id = cx.derive_id(format!(
3261 "variant.{}.field.{}",
3262 variant.name.as_ref().unwrap(),
3263 field.name.as_ref().unwrap()
3267 "<span id=\"{id}\" class=\"variant small-section-header\">\
3268 <a href=\"#{id}\" class=\"anchor field\"></a>\
3269 <code>{f}: {t}</code>\
3272 f = field.name.as_ref().unwrap(),
3273 t = ty.print(cx.cache())
3275 document(w, cx, field, Some(variant));
3278 w.write_str("</div></div>");
3280 render_stability_since(w, variant, it, cx.tcx());
3283 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3286 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3293 sym::non_exhaustive,
3296 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3297 // left padding. For example:
3299 // #[foo] <----- "top" attribute
3301 // #[bar] <---- not "top" attribute
3304 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3309 .filter_map(|attr| {
3310 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3311 Some(pprust::attribute_to_string(&attr))
3318 if !attrs.is_empty() {
3321 "<span class=\"docblock attributes{}\">{}</span>",
3322 if top { " top-attr" } else { "" },
3331 g: Option<&clean::Generics>,
3333 fields: &[clean::Item],
3341 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3342 if structhead { "struct " } else { "" },
3343 it.name.as_ref().unwrap()
3345 if let Some(g) = g {
3346 write!(w, "{}", g.print(cx.cache()))
3349 CtorKind::Fictive => {
3350 if let Some(g) = g {
3354 WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache())
3357 let mut has_visible_fields = false;
3359 for field in fields {
3360 if let clean::StructFieldItem(ref ty) = *field.kind {
3365 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3366 field.name.as_ref().unwrap(),
3367 ty.print(cx.cache())
3369 has_visible_fields = true;
3373 if has_visible_fields {
3374 if it.has_stripped_fields().unwrap() {
3375 write!(w, "\n{} // some fields omitted", tab);
3377 write!(w, "\n{}", tab);
3378 } else if it.has_stripped_fields().unwrap() {
3379 // If there are no visible fields we can just display
3380 // `{ /* fields omitted */ }` to save space.
3381 write!(w, " /* fields omitted */ ");
3387 for (i, field) in fields.iter().enumerate() {
3392 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3393 clean::StructFieldItem(ref ty) => {
3397 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3398 ty.print(cx.cache())
3401 _ => unreachable!(),
3405 if let Some(g) = g {
3409 WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache())
3414 CtorKind::Const => {
3415 // Needed for PhantomData.
3416 if let Some(g) = g {
3420 WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache())
3431 g: Option<&clean::Generics>,
3432 fields: &[clean::Item],
3440 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
3441 if structhead { "union " } else { "" },
3442 it.name.as_ref().unwrap()
3444 if let Some(g) = g {
3445 write!(w, "{}", g.print(cx.cache()));
3446 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache()));
3449 write!(w, " {{\n{}", tab);
3450 for field in fields {
3451 if let clean::StructFieldItem(ref ty) = *field.kind {
3455 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
3456 field.name.as_ref().unwrap(),
3457 ty.print(cx.cache()),
3463 if it.has_stripped_fields().unwrap() {
3464 write!(w, " // some fields omitted\n{}", tab);
3469 #[derive(Copy, Clone)]
3470 enum AssocItemLink<'a> {
3471 Anchor(Option<&'a str>),
3472 GotoSource(DefId, &'a FxHashSet<Symbol>),
3475 impl<'a> AssocItemLink<'a> {
3476 fn anchor(&self, id: &'a str) -> Self {
3478 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3479 ref other => *other,
3484 fn render_assoc_items(
3487 containing_item: &clean::Item,
3489 what: AssocItemRender<'_>,
3491 info!("Documenting associated items of {:?}", containing_item.name);
3492 let v = match cx.cache.impls.get(&it) {
3496 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3497 if !non_trait.is_empty() {
3498 let render_mode = match what {
3499 AssocItemRender::All => {
3501 "<h2 id=\"implementations\" class=\"small-section-header\">\
3502 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3507 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3508 let id = cx.derive_id(small_url_encode(format!(
3509 "deref-methods-{:#}",
3510 type_.print(cx.cache())
3512 debug!("Adding {} to deref id map", type_.print(cx.cache()));
3515 .insert(type_.def_id_full(cx.cache()).unwrap(), id.clone());
3518 "<h2 id=\"{id}\" class=\"small-section-header\">\
3519 Methods from {trait_}<Target = {type_}>\
3520 <a href=\"#{id}\" class=\"anchor\"></a>\
3523 trait_ = trait_.print(cx.cache()),
3524 type_ = type_.print(cx.cache()),
3526 RenderMode::ForDeref { mut_: deref_mut_ }
3529 for i in &non_trait {
3535 AssocItemLink::Anchor(None),
3537 containing_item.stable_since(cx.tcx()).as_deref(),
3538 containing_item.const_stable_since(cx.tcx()).as_deref(),
3547 if !traits.is_empty() {
3548 let deref_impl = traits
3550 .find(|t| t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did);
3551 if let Some(impl_) = deref_impl {
3552 let has_deref_mut = traits.iter().any(|t| {
3553 t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_mut_trait_did
3555 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
3558 // If we were already one level into rendering deref methods, we don't want to render
3559 // anything after recursing into any further deref methods above.
3560 if let AssocItemRender::DerefFor { .. } = what {
3564 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3565 traits.iter().partition(|t| t.inner_impl().synthetic);
3566 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3567 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3569 let mut impls = Buffer::empty_from(&w);
3570 render_impls(cx, &mut impls, &concrete, containing_item);
3571 let impls = impls.into_inner();
3572 if !impls.is_empty() {
3575 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3576 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3578 <div id=\"trait-implementations-list\">{}</div>",
3583 if !synthetic.is_empty() {
3585 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3586 Auto Trait Implementations\
3587 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3589 <div id=\"synthetic-implementations-list\">",
3591 render_impls(cx, w, &synthetic, containing_item);
3592 w.write_str("</div>");
3595 if !blanket_impl.is_empty() {
3597 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3598 Blanket Implementations\
3599 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3601 <div id=\"blanket-implementations-list\">",
3603 render_impls(cx, w, &blanket_impl, containing_item);
3604 w.write_str("</div>");
3609 fn render_deref_methods(
3613 container_item: &clean::Item,
3616 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3617 let (target, real_target) = impl_
3621 .find_map(|item| match *item.kind {
3622 clean::TypedefItem(ref t, true) => Some(match *t {
3623 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3624 _ => (&t.type_, &t.type_),
3628 .expect("Expected associated type binding");
3629 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
3631 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3632 if let Some(did) = target.def_id_full(cx.cache()) {
3633 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
3634 // `impl Deref<Target = S> for S`
3635 if did == type_did {
3636 // Avoid infinite cycles
3640 render_assoc_items(w, cx, container_item, did, what);
3642 if let Some(prim) = target.primitive_type() {
3643 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
3644 render_assoc_items(w, cx, container_item, did, what);
3650 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
3651 let self_type_opt = match *item.kind {
3652 clean::MethodItem(ref method, _) => method.decl.self_type(),
3653 clean::TyMethodItem(ref method) => method.decl.self_type(),
3657 if let Some(self_ty) = self_type_opt {
3658 let (by_mut_ref, by_box, by_value) = match self_ty {
3659 SelfTy::SelfBorrowed(_, mutability)
3660 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3661 (mutability == Mutability::Mut, false, false)
3663 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3664 (false, Some(did) == cache.owned_box_did, false)
3666 SelfTy::SelfValue => (false, false, true),
3667 _ => (false, false, false),
3670 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3676 fn spotlight_decl(decl: &clean::FnDecl, cache: &Cache) -> String {
3677 let mut out = Buffer::html();
3678 let mut trait_ = String::new();
3680 if let Some(did) = decl.output.def_id_full(cache) {
3681 if let Some(impls) = cache.impls.get(&did) {
3683 let impl_ = i.inner_impl();
3684 if impl_.trait_.def_id_full(cache).map_or(false, |d| cache.traits[&d].is_spotlight)
3689 "<h3 class=\"notable\">Notable traits for {}</h3>\
3690 <code class=\"content\">",
3691 impl_.for_.print(cache)
3693 trait_.push_str(&impl_.for_.print(cache).to_string());
3696 //use the "where" class here to make it small
3699 "<span class=\"where fmt-newline\">{}</span>",
3700 impl_.print(cache, false)
3702 let t_did = impl_.trait_.def_id_full(cache).unwrap();
3703 for it in &impl_.items {
3704 if let clean::TypedefItem(ref tydef, _) = *it.kind {
3705 out.push_str("<span class=\"where fmt-newline\"> ");
3711 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3715 out.push_str(";</span>");
3723 if !out.is_empty() {
3726 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3727 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3729 out.push_str("</code></span></div></span></span>");
3739 parent: &clean::Item,
3740 link: AssocItemLink<'_>,
3741 render_mode: RenderMode,
3742 outer_version: Option<&str>,
3743 outer_const_version: Option<&str>,
3744 show_def_docs: bool,
3745 use_absolute: Option<bool>,
3746 is_on_foreign_type: bool,
3747 show_default_items: bool,
3748 // This argument is used to reference same type with different paths to avoid duplication
3749 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3752 let traits = &cx.cache.traits;
3753 let trait_ = i.trait_did_full(cx.cache()).map(|did| &traits[&did]);
3755 if render_mode == RenderMode::Normal {
3756 let id = cx.derive_id(match i.inner_impl().trait_ {
3758 if is_on_foreign_type {
3759 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx.cache())
3761 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx.cache()))))
3764 None => "impl".to_string(),
3766 let aliases = if aliases.is_empty() {
3769 format!(" aliases=\"{}\"", aliases.join(","))
3771 if let Some(use_absolute) = use_absolute {
3772 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3773 write!(w, "{}", i.inner_impl().print(cx.cache(), use_absolute));
3775 for it in &i.inner_impl().items {
3776 if let clean::TypedefItem(ref tydef, _) = *it.kind {
3777 w.write_str("<span class=\"where fmt-newline\"> ");
3783 AssocItemLink::Anchor(None),
3787 w.write_str(";</span>");
3791 w.write_str("</code>");
3795 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3798 i.inner_impl().print(cx.cache(), false)
3801 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3802 render_stability_since_raw(
3804 i.impl_item.stable_since(cx.tcx()).as_deref(),
3805 i.impl_item.const_stable_since(cx.tcx()).as_deref(),
3807 outer_const_version,
3809 write_srclink(cx, &i.impl_item, w);
3810 w.write_str("</h3>");
3812 if trait_.is_some() {
3813 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3814 write!(w, "<div class=\"item-info\">{}</div>", portability);
3818 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3819 let mut ids = cx.id_map.borrow_mut();
3822 "<div class=\"docblock\">{}</div>",
3825 &i.impl_item.links(&cx.cache),
3829 &cx.shared.playground
3840 parent: &clean::Item,
3841 link: AssocItemLink<'_>,
3842 render_mode: RenderMode,
3843 is_default_item: bool,
3844 outer_version: Option<&str>,
3845 outer_const_version: Option<&str>,
3846 trait_: Option<&clean::Trait>,
3847 show_def_docs: bool,
3849 let item_type = item.type_();
3850 let name = item.name.as_ref().unwrap();
3852 let render_method_item = match render_mode {
3853 RenderMode::Normal => true,
3854 RenderMode::ForDeref { mut_: deref_mut_ } => {
3855 should_render_item(&item, deref_mut_, &cx.cache)
3859 let (is_hidden, extra_class) =
3860 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3868 clean::MethodItem(..) | clean::TyMethodItem(_) => {
3869 // Only render when the method is not static or we allow static methods
3870 if render_method_item {
3871 let id = cx.derive_id(format!("{}.{}", item_type, name));
3872 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3873 w.write_str("<code>");
3874 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx);
3875 w.write_str("</code>");
3876 render_stability_since_raw(
3878 item.stable_since(cx.tcx()).as_deref(),
3879 item.const_stable_since(cx.tcx()).as_deref(),
3881 outer_const_version,
3883 write_srclink(cx, item, w);
3884 w.write_str("</h4>");
3887 clean::TypedefItem(ref tydef, _) => {
3888 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3889 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3899 w.write_str("</code></h4>");
3901 clean::AssocConstItem(ref ty, ref default) => {
3902 let id = cx.derive_id(format!("{}.{}", item_type, name));
3903 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3904 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "", cx);
3905 w.write_str("</code>");
3906 render_stability_since_raw(
3908 item.stable_since(cx.tcx()).as_deref(),
3909 item.const_stable_since(cx.tcx()).as_deref(),
3911 outer_const_version,
3913 write_srclink(cx, item, w);
3914 w.write_str("</h4>");
3916 clean::AssocTypeItem(ref bounds, ref default) => {
3917 let id = cx.derive_id(format!("{}.{}", item_type, name));
3918 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3919 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "", cx.cache());
3920 w.write_str("</code></h4>");
3922 clean::StrippedItem(..) => return,
3923 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3926 if render_method_item {
3927 if !is_default_item {
3928 if let Some(t) = trait_ {
3929 // The trait item may have been stripped so we might not
3930 // find any documentation or stability for it.
3931 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3932 // We need the stability of the item from the trait
3933 // because impls can't have a stability.
3934 if item.doc_value().is_some() {
3935 document_item_info(w, cx, it, is_hidden, Some(parent));
3936 document_full(w, item, cx, "", is_hidden);
3938 // In case the item isn't documented,
3939 // provide short documentation from the trait.
3953 document_item_info(w, cx, item, is_hidden, Some(parent));
3955 document_full(w, item, cx, "", is_hidden);
3959 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3964 w.write_str("<div class=\"impl-items\">");
3965 for trait_item in &i.inner_impl().items {
3970 if trait_.is_some() { &i.impl_item } else { parent },
3975 outer_const_version,
3981 fn render_default_items(
3986 parent: &clean::Item,
3987 render_mode: RenderMode,
3988 outer_version: Option<&str>,
3989 outer_const_version: Option<&str>,
3990 show_def_docs: bool,
3992 for trait_item in &t.items {
3993 let n = trait_item.name;
3994 if i.items.iter().any(|m| m.name == n) {
3997 let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
3998 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4009 outer_const_version,
4016 // If we've implemented a trait, then also emit documentation for all
4017 // default items which weren't overridden in the implementation block.
4018 // We don't emit documentation for default items if they appear in the
4019 // Implementations on Foreign Types or Implementors sections.
4020 if show_default_items {
4021 if let Some(t) = trait_ {
4022 render_default_items(
4030 outer_const_version,
4035 w.write_str("</div>");
4038 fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
4039 w.write_str("<pre class=\"rust opaque\">");
4040 render_attributes(w, it, false);
4043 "type {}{}{where_clause} = impl {bounds};</pre>",
4044 it.name.as_ref().unwrap(),
4045 t.generics.print(cx.cache()),
4047 WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4048 bounds = bounds(&t.bounds, false, cx.cache())
4051 document(w, cx, it, None);
4053 // Render any items associated directly to this alias, as otherwise they
4054 // won't be visible anywhere in the docs. It would be nice to also show
4055 // associated items from the aliased type (see discussion in #32077), but
4056 // we need #14072 to make sense of the generics.
4057 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4060 fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
4061 w.write_str("<pre class=\"rust trait-alias\">");
4062 render_attributes(w, it, false);
4065 "trait {}{}{} = {};</pre>",
4066 it.name.as_ref().unwrap(),
4067 t.generics.print(cx.cache()),
4068 WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4069 bounds(&t.bounds, true, cx.cache())
4072 document(w, cx, it, None);
4074 // Render any items associated directly to this alias, as otherwise they
4075 // won't be visible anywhere in the docs. It would be nice to also show
4076 // associated items from the aliased type (see discussion in #32077), but
4077 // we need #14072 to make sense of the generics.
4078 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4081 fn item_typedef(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
4082 w.write_str("<pre class=\"rust typedef\">");
4083 render_attributes(w, it, false);
4086 "type {}{}{where_clause} = {type_};</pre>",
4087 it.name.as_ref().unwrap(),
4088 t.generics.print(cx.cache()),
4090 WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()),
4091 type_ = t.type_.print(cx.cache())
4094 document(w, cx, it, None);
4096 // Render any items associated directly to this alias, as otherwise they
4097 // won't be visible anywhere in the docs. It would be nice to also show
4098 // associated items from the aliased type (see discussion in #32077), but
4099 // we need #14072 to make sense of the generics.
4100 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4103 fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4104 w.write_str("<pre class=\"rust foreigntype\">extern {\n");
4105 render_attributes(w, it, false);
4108 " {}type {};\n}}</pre>",
4109 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
4110 it.name.as_ref().unwrap(),
4113 document(w, cx, it, None);
4115 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4118 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
4119 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4123 || it.is_primitive()
4131 "<p class=\"location\">{}{}</p>",
4133 clean::StructItem(..) => "Struct ",
4134 clean::TraitItem(..) => "Trait ",
4135 clean::PrimitiveItem(..) => "Primitive Type ",
4136 clean::UnionItem(..) => "Union ",
4137 clean::EnumItem(..) => "Enum ",
4138 clean::TypedefItem(..) => "Type Definition ",
4139 clean::ForeignTypeItem => "Foreign Type ",
4140 clean::ModuleItem(..) =>
4148 it.name.as_ref().unwrap()
4153 if let Some(ref version) = cx.cache.crate_version {
4156 "<div class=\"block version\">\
4164 buffer.write_str("<div class=\"sidebar-elems\">");
4168 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4169 it.name.as_ref().expect("crates always have a name")
4173 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
4174 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
4175 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
4176 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
4177 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
4178 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
4179 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4180 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
4184 // The sidebar is designed to display sibling functions, modules and
4185 // other miscellaneous information. since there are lots of sibling
4186 // items (and that causes quadratic growth in large modules),
4187 // we refactor common parts into a shared JavaScript file per module.
4188 // still, we don't move everything into JS because we want to preserve
4189 // as much HTML as possible in order to allow non-JS-enabled browsers
4190 // to navigate the documentation (though slightly inefficiently).
4192 buffer.write_str("<p class=\"location\">");
4193 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4195 buffer.write_str("::<wbr>");
4199 "<a href=\"{}index.html\">{}</a>",
4200 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4204 buffer.write_str("</p>");
4206 // Sidebar refers to the enclosing module, not this module.
4207 let relpath = if it.is_mod() { "../" } else { "" };
4210 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
4212 name = it.name.unwrap_or(kw::Empty),
4217 // There is no sidebar-items.js beyond the crate root path
4218 // FIXME maybe dynamic crate loading can be merged here
4220 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4222 // Closes sidebar-elems div.
4223 buffer.write_str("</div>");
4226 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4227 if used_links.insert(url.clone()) {
4231 while !used_links.insert(format!("{}-{}", url, add)) {
4234 format!("{}-{}", url, add)
4240 used_links: &mut FxHashSet<String>,
4246 .filter_map(|item| match item.name {
4247 Some(ref name) if !name.is_empty() && item.is_method() => {
4248 if !for_deref || should_render_item(item, deref_mut, cache) {
4250 "<a href=\"#{}\">{}</a>",
4251 get_next_url(used_links, format!("method.{}", name)),
4260 .collect::<Vec<_>>()
4263 // The point is to url encode any potential character from a type with genericity.
4264 fn small_url_encode(s: String) -> String {
4265 let mut st = String::new();
4266 let mut last_match = 0;
4267 for (idx, c) in s.char_indices() {
4268 let escaped = match c {
4284 st += &s[last_match..idx];
4286 // NOTE: we only expect single byte characters here - which is fine as long as we
4287 // only match single byte characters
4288 last_match = idx + 1;
4291 if last_match != 0 {
4292 st += &s[last_match..];
4299 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
4300 if let Some(v) = cx.cache.impls.get(&it.def_id) {
4301 let mut used_links = FxHashSet::default();
4304 let used_links_bor = &mut used_links;
4307 .filter(|i| i.inner_impl().trait_.is_none())
4308 .flat_map(move |i| {
4309 get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
4311 .collect::<Vec<_>>();
4312 if !ret.is_empty() {
4313 // We want links' order to be reproducible so we don't use unstable sort.
4317 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4318 <div class=\"sidebar-links\">",
4321 out.push_str(&line);
4323 out.push_str("</div>");
4327 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4328 if let Some(impl_) = v
4330 .filter(|i| i.inner_impl().trait_.is_some())
4331 .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did)
4333 sidebar_deref_methods(cx, out, impl_, v);
4335 let format_impls = |impls: Vec<&Impl>| {
4336 let mut links = FxHashSet::default();
4341 if let Some(ref i) = it.inner_impl().trait_ {
4342 let i_display = format!("{:#}", i.print(cx.cache()));
4343 let out = Escape(&i_display);
4344 let encoded = small_url_encode(format!("{:#}", i.print(cx.cache())));
4345 let generated = format!(
4346 "<a href=\"#impl-{}\">{}{}</a>",
4348 if it.inner_impl().negative_polarity { "!" } else { "" },
4351 if links.insert(generated.clone()) { Some(generated) } else { None }
4356 .collect::<Vec<String>>();
4361 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
4362 out.push_str("<div class=\"sidebar-links\">");
4364 out.push_str(&link);
4366 out.push_str("</div>");
4369 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4370 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4371 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4373 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4375 let concrete_format = format_impls(concrete);
4376 let synthetic_format = format_impls(synthetic);
4377 let blanket_format = format_impls(blanket_impl);
4379 if !concrete_format.is_empty() {
4381 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4382 Trait Implementations</a>",
4384 write_sidebar_links(out, concrete_format);
4387 if !synthetic_format.is_empty() {
4389 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4390 Auto Trait Implementations</a>",
4392 write_sidebar_links(out, synthetic_format);
4395 if !blanket_format.is_empty() {
4397 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4398 Blanket Implementations</a>",
4400 write_sidebar_links(out, blanket_format);
4406 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
4409 debug!("found Deref: {:?}", impl_);
4410 if let Some((target, real_target)) =
4411 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
4412 clean::TypedefItem(ref t, true) => Some(match *t {
4413 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4414 _ => (&t.type_, &t.type_),
4419 debug!("found target, real_target: {:?} {:?}", target, real_target);
4420 if let Some(did) = target.def_id_full(cx.cache()) {
4421 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
4422 // `impl Deref<Target = S> for S`
4423 if did == type_did {
4424 // Avoid infinite cycles
4431 .filter(|i| i.inner_impl().trait_.is_some())
4432 .any(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_mut_trait_did);
4433 let inner_impl = target
4434 .def_id_full(cx.cache())
4436 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
4438 .and_then(|did| c.impls.get(&did));
4439 if let Some(impls) = inner_impl {
4440 debug!("found inner_impl: {:?}", impls);
4441 let mut used_links = FxHashSet::default();
4444 .filter(|i| i.inner_impl().trait_.is_none())
4445 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
4446 .collect::<Vec<_>>();
4447 if !ret.is_empty() {
4448 let deref_id_map = cx.deref_id_map.borrow();
4449 let id = deref_id_map
4450 .get(&real_target.def_id_full(cx.cache()).unwrap())
4451 .expect("Deref section without derived id");
4454 "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}<Target={}></a>",
4456 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(c))),
4457 Escape(&format!("{:#}", real_target.print(c))),
4459 // We want links' order to be reproducible so we don't use unstable sort.
4461 out.push_str("<div class=\"sidebar-links\">");
4463 out.push_str(&link);
4465 out.push_str("</div>");
4469 // Recurse into any further impls that might exist for `target`
4470 if let Some(target_did) = target.def_id_full(cx.cache()) {
4471 if let Some(target_impls) = c.impls.get(&target_did) {
4472 if let Some(target_deref_impl) = target_impls
4474 .filter(|i| i.inner_impl().trait_.is_some())
4475 .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_trait_did)
4477 sidebar_deref_methods(cx, out, target_deref_impl, target_impls);
4484 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4485 let mut sidebar = Buffer::new();
4486 let fields = get_struct_fields_name(&s.fields);
4488 if !fields.is_empty() {
4489 if let CtorKind::Fictive = s.struct_type {
4491 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4492 <div class=\"sidebar-links\">",
4495 for field in fields {
4496 sidebar.push_str(&field);
4499 sidebar.push_str("</div>");
4503 sidebar_assoc_items(cx, &mut sidebar, it);
4505 if !sidebar.is_empty() {
4506 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4510 fn get_id_for_impl_on_foreign_type(
4512 trait_: &clean::Type,
4515 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cache), for_.print(cache)))
4518 fn extract_for_impl_name(item: &clean::Item, cache: &Cache) -> Option<(String, String)> {
4520 clean::ItemKind::ImplItem(ref i) => {
4521 if let Some(ref trait_) = i.trait_ {
4523 format!("{:#}", i.for_.print(cache)),
4524 get_id_for_impl_on_foreign_type(&i.for_, trait_, cache),
4534 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4535 buf.write_str("<div class=\"block items\">");
4537 fn print_sidebar_section(
4539 items: &[clean::Item],
4541 filter: impl Fn(&clean::Item) -> bool,
4542 write: impl Fn(&mut Buffer, &Symbol),
4545 let mut items = items
4547 .filter_map(|m| match m.name {
4548 Some(ref name) if filter(m) => Some(name),
4551 .collect::<Vec<_>>();
4553 if !items.is_empty() {
4555 out.push_str(before);
4556 for item in items.into_iter() {
4559 out.push_str(after);
4563 print_sidebar_section(
4566 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4567 Associated Types</a><div class=\"sidebar-links\">",
4568 |m| m.is_associated_type(),
4569 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
4573 print_sidebar_section(
4576 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4577 Associated Constants</a><div class=\"sidebar-links\">",
4578 |m| m.is_associated_const(),
4579 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
4583 print_sidebar_section(
4586 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4587 Required Methods</a><div class=\"sidebar-links\">",
4588 |m| m.is_ty_method(),
4589 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
4593 print_sidebar_section(
4596 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4597 Provided Methods</a><div class=\"sidebar-links\">",
4599 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
4603 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
4604 let mut res = implementors
4609 .def_id_full(cx.cache())
4610 .map_or(false, |d| !cx.cache.paths.contains_key(&d))
4612 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx.cache()))
4613 .collect::<Vec<_>>();
4615 if !res.is_empty() {
4618 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4619 Implementations on Foreign Types</a>\
4620 <div class=\"sidebar-links\">",
4622 for (name, id) in res.into_iter() {
4623 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
4625 buf.push_str("</div>");
4629 sidebar_assoc_items(cx, buf, it);
4631 buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4634 "<a class=\"sidebar-title\" \
4635 href=\"#synthetic-implementors\">Auto Implementors</a>",
4639 buf.push_str("</div>")
4642 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4643 let mut sidebar = Buffer::new();
4644 sidebar_assoc_items(cx, &mut sidebar, it);
4646 if !sidebar.is_empty() {
4647 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4651 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4652 let mut sidebar = Buffer::new();
4653 sidebar_assoc_items(cx, &mut sidebar, it);
4655 if !sidebar.is_empty() {
4656 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4660 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
4661 let mut fields = fields
4663 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
4665 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4667 .collect::<Vec<_>>();
4672 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4673 let mut sidebar = Buffer::new();
4674 let fields = get_struct_fields_name(&u.fields);
4676 if !fields.is_empty() {
4678 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4679 <div class=\"sidebar-links\">",
4682 for field in fields {
4683 sidebar.push_str(&field);
4686 sidebar.push_str("</div>");
4689 sidebar_assoc_items(cx, &mut sidebar, it);
4691 if !sidebar.is_empty() {
4692 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4696 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4697 let mut sidebar = Buffer::new();
4699 let mut variants = e
4702 .filter_map(|v| match v.name {
4703 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4706 .collect::<Vec<_>>();
4707 if !variants.is_empty() {
4708 variants.sort_unstable();
4709 sidebar.push_str(&format!(
4710 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4711 <div class=\"sidebar-links\">{}</div>",
4716 sidebar_assoc_items(cx, &mut sidebar, it);
4718 if !sidebar.is_empty() {
4719 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4723 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4725 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4726 ItemType::Module => ("modules", "Modules"),
4727 ItemType::Struct => ("structs", "Structs"),
4728 ItemType::Union => ("unions", "Unions"),
4729 ItemType::Enum => ("enums", "Enums"),
4730 ItemType::Function => ("functions", "Functions"),
4731 ItemType::Typedef => ("types", "Type Definitions"),
4732 ItemType::Static => ("statics", "Statics"),
4733 ItemType::Constant => ("constants", "Constants"),
4734 ItemType::Trait => ("traits", "Traits"),
4735 ItemType::Impl => ("impls", "Implementations"),
4736 ItemType::TyMethod => ("tymethods", "Type Methods"),
4737 ItemType::Method => ("methods", "Methods"),
4738 ItemType::StructField => ("fields", "Struct Fields"),
4739 ItemType::Variant => ("variants", "Variants"),
4740 ItemType::Macro => ("macros", "Macros"),
4741 ItemType::Primitive => ("primitives", "Primitive Types"),
4742 ItemType::AssocType => ("associated-types", "Associated Types"),
4743 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4744 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4745 ItemType::Keyword => ("keywords", "Keywords"),
4746 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4747 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4748 ItemType::ProcDerive => ("derives", "Derive Macros"),
4749 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4753 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4754 let mut sidebar = String::new();
4756 if items.iter().any(|it| {
4757 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4759 sidebar.push_str("<li><a href=\"#reexports\">Re-exports</a></li>");
4762 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4763 // to print its headings
4765 ItemType::Primitive,
4779 ItemType::StructField,
4781 ItemType::AssocType,
4782 ItemType::AssocConst,
4783 ItemType::ForeignType,
4786 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4787 let (short, name) = item_ty_to_strs(&myty);
4788 sidebar.push_str(&format!(
4789 "<li><a href=\"#{id}\">{name}</a></li>",
4796 if !sidebar.is_empty() {
4797 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4801 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
4802 let mut sidebar = Buffer::new();
4803 sidebar_assoc_items(cx, &mut sidebar, it);
4805 if !sidebar.is_empty() {
4806 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
4810 fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
4811 wrap_into_docblock(w, |w| {
4812 highlight::render_with_highlighting(
4818 it.source.span().edition(),
4821 document(w, cx, it, None)
4824 fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
4825 let name = it.name.as_ref().expect("proc-macros always have names");
4827 MacroKind::Bang => {
4828 w.push_str("<pre class=\"rust macro\">");
4829 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4830 w.push_str("</pre>");
4832 MacroKind::Attr => {
4833 w.push_str("<pre class=\"rust attr\">");
4834 write!(w, "#[{}]", name);
4835 w.push_str("</pre>");
4837 MacroKind::Derive => {
4838 w.push_str("<pre class=\"rust derive\">");
4839 write!(w, "#[derive({})]", name);
4840 if !m.helpers.is_empty() {
4841 w.push_str("\n{\n");
4842 w.push_str(" // Attributes available to this derive:\n");
4843 for attr in &m.helpers {
4844 writeln!(w, " #[{}]", attr);
4848 w.push_str("</pre>");
4851 document(w, cx, it, None)
4854 fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4855 document(w, cx, it, None);
4856 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4859 fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
4860 document(w, cx, it, None)
4863 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4865 fn make_item_keywords(it: &clean::Item) -> String {
4866 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4869 /// Returns a list of all paths used in the type.
4870 /// This is used to help deduplicate imported impls
4871 /// for reexported types. If any of the contained
4872 /// types are re-exported, we don't use the corresponding
4873 /// entry from the js file, as inlining will have already
4874 /// picked up the impl
4875 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
4876 let mut out = Vec::new();
4877 let mut visited = FxHashSet::default();
4878 let mut work = VecDeque::new();
4880 work.push_back(first_ty);
4882 while let Some(ty) = work.pop_front() {
4883 if !visited.insert(ty.clone()) {
4888 clean::Type::ResolvedPath { did, .. } => {
4889 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4890 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4892 if let Some(path) = fqp {
4893 out.push(path.join("::"));
4896 clean::Type::Tuple(tys) => {
4897 work.extend(tys.into_iter());
4899 clean::Type::Slice(ty) => {
4900 work.push_back(*ty);
4902 clean::Type::Array(ty, _) => {
4903 work.push_back(*ty);
4905 clean::Type::RawPointer(_, ty) => {
4906 work.push_back(*ty);
4908 clean::Type::BorrowedRef { type_, .. } => {
4909 work.push_back(*type_);
4911 clean::Type::QPath { self_type, trait_, .. } => {
4912 work.push_back(*self_type);
4913 work.push_back(*trait_);