1 // ignore-tidy-filelength
3 //! Rustdoc's HTML rendering module.
5 //! This modules contains the bulk of the logic necessary for rendering a
6 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
7 //! rendering process is largely driven by the `format!` syntax extension to
8 //! perform all I/O into files and streams.
10 //! The rendering process is largely driven by the `Context` and `Cache`
11 //! structures. The cache is pre-populated by crawling the crate in question,
12 //! and then it is shared among the various rendering threads. The cache is meant
13 //! to be a fairly large structure not implementing `Clone` (because it's shared
14 //! among threads). The context, however, should be a lightweight structure. This
15 //! is cloned per-thread and contains information about what is currently being
18 //! In order to speed up rendering (mostly because of markdown rendering), the
19 //! rendering process has been parallelized. This parallelization is only
20 //! exposed through the `crate` method on the context, and then also from the
21 //! fact that the shared cache is stored in TLS (and must be accessed as such).
23 //! In addition to rendering the crate itself, this module is also responsible
24 //! for creating the corresponding search index and source file renderings.
25 //! These threads are not parallelized (they haven't been a bottleneck yet), and
26 //! both occur before the crate is rendered.
34 use std::cell::{Cell, RefCell};
35 use std::cmp::Ordering;
36 use std::collections::{BTreeMap, VecDeque};
37 use std::default::Default;
39 use std::fmt::{self, Write};
40 use std::fs::{self, File};
41 use std::io::prelude::*;
42 use std::io::{self, BufReader};
43 use std::path::{Component, Path, PathBuf};
46 use std::string::ToString;
47 use std::sync::mpsc::{channel, Receiver};
50 use itertools::Itertools;
51 use rustc_ast_pretty::pprust;
52 use rustc_attr::StabilityLevel;
53 use rustc_data_structures::flock;
54 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
56 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
57 use rustc_hir::Mutability;
58 use rustc_middle::middle::stability;
59 use rustc_span::edition::Edition;
60 use rustc_span::hygiene::MacroKind;
61 use rustc_span::source_map::FileName;
62 use rustc_span::symbol::{sym, Symbol};
63 use serde::ser::SerializeSeq;
64 use serde::{Serialize, Serializer};
66 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, RenderedLink, SelfTy, TypeKind};
67 use crate::config::{RenderInfo, RenderOptions};
68 use crate::docfs::{DocFS, PathError};
70 use crate::error::Error;
71 use crate::formats::cache::{cache, Cache};
72 use crate::formats::item_type::ItemType;
73 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
74 use crate::html::escape::Escape;
75 use crate::html::format::fmt_impl_for_trait_page;
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 { write!(f, "{}", 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 {
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 crate shared: Arc<SharedContext>,
117 all: Rc<RefCell<AllTypes>>,
118 /// Storage for the errors produced while generating documentation so they
119 /// can be printed together at the end.
120 crate errors: Rc<Receiver<String>>,
123 crate struct SharedContext {
124 /// The path to the crate root source minus the file name.
125 /// Used for simplifying paths to the highlighted source code files.
126 crate src_root: PathBuf,
127 /// This describes the layout of each page, and is not modified after
128 /// creation of the context (contains info like the favicon and added html).
129 crate layout: layout::Layout,
130 /// This flag indicates whether `[src]` links should be generated or not. If
131 /// the source files are present in the html rendering, then this will be
133 crate include_sources: bool,
134 /// The local file sources we've emitted and their respective url-paths.
135 crate local_sources: FxHashMap<PathBuf, String>,
136 /// Whether the collapsed pass ran
137 crate collapsed: bool,
138 /// The base-URL of the issue tracker for when an item has been tagged with
140 crate issue_tracker_base_url: Option<String>,
141 /// The directories that have already been created in this doc run. Used to reduce the number
142 /// of spurious `create_dir_all` calls.
143 crate created_dirs: RefCell<FxHashSet<PathBuf>>,
144 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
145 /// should be ordered alphabetically or in order of appearance (in the source code).
146 crate sort_modules_alphabetically: bool,
147 /// Additional CSS files to be added to the generated docs.
148 crate style_files: Vec<StylePath>,
149 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
151 crate resource_suffix: String,
152 /// Optional path string to be used to load static files on output pages. If not set, uses
153 /// combinations of `../` to reach the documentation root.
154 crate static_root_path: Option<String>,
155 /// The fs handle we are working with.
157 /// The default edition used to parse doctests.
158 crate edition: Edition,
159 crate codes: ErrorCodes,
160 playground: Option<markdown::Playground>,
164 fn path(&self, filename: &str) -> PathBuf {
165 // We use splitn vs Path::extension here because we might get a filename
166 // like `style.min.css` and we want to process that into
167 // `style-suffix.min.css`. Path::extension would just return `css`
168 // which would result in `style.min-suffix.css` which isn't what we
170 let (base, ext) = filename.split_once('.').unwrap();
171 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext);
172 self.dst.join(&filename)
177 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
178 let mut dirs = self.created_dirs.borrow_mut();
179 if !dirs.contains(dst) {
180 try_err!(self.fs.create_dir_all(dst), dst);
181 dirs.insert(dst.to_path_buf());
187 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
188 /// `collapsed_doc_value` of the given item.
189 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
191 item.collapsed_doc_value().map(|s| s.into())
193 item.doc_value().map(|s| s.into())
198 // Helper structs for rendering items/sidebars and carrying along contextual
201 /// Struct representing one entry in the JS search index. These are all emitted
202 /// by hand to a large JS file at the end of cache-creation.
204 crate struct IndexItem {
209 crate parent: Option<DefId>,
210 crate parent_idx: Option<usize>,
211 crate search_type: Option<IndexItemFunctionType>,
214 impl Serialize for IndexItem {
215 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
220 self.parent.is_some(),
221 self.parent_idx.is_some(),
222 "`{}` is missing idx",
226 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
227 .serialize(serializer)
231 /// A type used for the search index.
233 crate struct RenderType {
236 name: Option<String>,
237 generics: Option<Vec<Generic>>,
240 impl Serialize for RenderType {
241 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
245 if let Some(name) = &self.name {
246 let mut seq = serializer.serialize_seq(None)?;
247 if let Some(id) = self.idx {
248 seq.serialize_element(&id)?;
250 seq.serialize_element(&name)?;
252 if let Some(generics) = &self.generics {
253 seq.serialize_element(&generics)?;
257 serializer.serialize_none()
262 /// A type used for the search index.
264 crate struct Generic {
266 defid: Option<DefId>,
270 impl Serialize for Generic {
271 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
275 if let Some(id) = self.idx {
276 serializer.serialize_some(&id)
278 serializer.serialize_some(&self.name)
283 /// Full type of functions/methods in the search index.
285 crate struct IndexItemFunctionType {
286 inputs: Vec<TypeWithKind>,
287 output: Option<Vec<TypeWithKind>>,
290 impl Serialize for IndexItemFunctionType {
291 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
295 // If we couldn't figure out a type, just write `null`.
296 let mut iter = self.inputs.iter();
297 if match self.output {
298 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
299 None => iter.any(|ref i| i.ty.name.is_none()),
301 serializer.serialize_none()
303 let mut seq = serializer.serialize_seq(None)?;
304 seq.serialize_element(&self.inputs)?;
305 if let Some(output) = &self.output {
306 if output.len() > 1 {
307 seq.serialize_element(&output)?;
309 seq.serialize_element(&output[0])?;
318 crate struct TypeWithKind {
323 impl From<(RenderType, TypeKind)> for TypeWithKind {
324 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
325 TypeWithKind { ty: x.0, kind: x.1 }
329 impl Serialize for TypeWithKind {
330 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
334 let mut seq = serializer.serialize_seq(None)?;
335 seq.serialize_element(&self.ty.name)?;
336 let x: ItemType = self.kind.into();
337 seq.serialize_element(&x)?;
342 #[derive(Debug, Clone)]
343 crate struct StylePath {
344 /// The path to the theme
346 /// What the `disabled` attribute should be set to in the HTML tag
347 crate disabled: bool,
350 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
352 crate fn initial_ids() -> Vec<String> {
364 "synthetic-implementors",
366 "synthetic-implementors-list",
372 .map(|id| (String::from(*id)))
376 /// Generates the documentation for `crate` into the directory `dst`
377 impl FormatRenderer for Context {
379 mut krate: clean::Crate,
380 options: RenderOptions,
381 _render_info: RenderInfo,
384 ) -> Result<(Context, clean::Crate), Error> {
385 // need to save a copy of the options for rendering the index page
386 let md_opts = options.clone();
392 sort_modules_alphabetically,
398 generate_search_filter,
403 let src_root = match krate.src {
404 FileName::Real(ref p) => match p.local_path().parent() {
405 Some(p) => p.to_path_buf(),
406 None => PathBuf::new(),
410 // If user passed in `--playground-url` arg, we fill in crate name here
411 let mut playground = None;
412 if let Some(url) = playground_url {
413 playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url });
415 let mut layout = layout::Layout {
417 favicon: String::new(),
420 krate: krate.name.clone(),
421 css_file_extension: extension_css,
422 generate_search_filter,
424 let mut issue_tracker_base_url = None;
425 let mut include_sources = true;
427 // Crawl the crate attributes looking for attributes which control how we're
428 // going to emit HTML
429 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
430 for attr in attrs.lists(sym::doc) {
431 match (attr.name_or_empty(), attr.value_str()) {
432 (sym::html_favicon_url, Some(s)) => {
433 layout.favicon = s.to_string();
435 (sym::html_logo_url, Some(s)) => {
436 layout.logo = s.to_string();
438 (sym::html_playground_url, Some(s)) => {
439 playground = Some(markdown::Playground {
440 crate_name: Some(krate.name.clone()),
444 (sym::issue_tracker_base_url, Some(s)) => {
445 issue_tracker_base_url = Some(s.to_string());
447 (sym::html_no_source, None) if attr.is_word() => {
448 include_sources = false;
454 let (sender, receiver) = channel();
455 let mut scx = SharedContext {
456 collapsed: krate.collapsed,
459 local_sources: Default::default(),
460 issue_tracker_base_url,
462 created_dirs: Default::default(),
463 sort_modules_alphabetically,
467 fs: DocFS::new(sender),
469 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
473 // Add the default themes to the `Vec` of stylepaths
475 // Note that these must be added before `sources::render` is called
476 // so that the resulting source pages are styled
478 // `light.css` is not disabled because it is the stylesheet that stays loaded
479 // by the browser as the theme stylesheet. The theme system (hackily) works by
480 // changing the href to this stylesheet. All other themes are disabled to
481 // prevent rule conflicts
482 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
483 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
484 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
487 scx.ensure_dir(&dst)?;
488 krate = sources::render(&dst, &mut scx, krate)?;
490 // Build our search index
491 let index = build_index(&krate, cache);
493 let cache = Arc::new(cache);
494 let mut cx = Context {
497 render_redirect_pages: false,
498 id_map: Rc::new(RefCell::new(id_map)),
499 shared: Arc::new(scx),
500 all: Rc::new(RefCell::new(AllTypes::new())),
501 errors: Rc::new(receiver),
504 CURRENT_DEPTH.with(|s| s.set(0));
506 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
507 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
508 write_shared(&cx, &krate, index, &md_opts, &cache)?;
509 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
513 fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
514 Arc::get_mut(&mut self.shared).unwrap().fs.close();
515 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
517 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
523 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
524 let final_file = self.dst.join(&krate.name).join("all.html");
525 let settings_file = self.dst.join("settings.html");
526 let crate_name = krate.name.clone();
528 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
529 if !root_path.ends_with('/') {
532 let mut page = layout::Page {
533 title: "List of all items in this crate",
536 static_root_path: self.shared.static_root_path.as_deref(),
537 description: "List of all items in this crate",
538 keywords: BASIC_KEYWORDS,
539 resource_suffix: &self.shared.resource_suffix,
541 static_extra_scripts: &[],
543 let sidebar = if let Some(ref version) = cache.crate_version {
545 "<p class=\"location\">Crate {}</p>\
546 <div class=\"block version\">\
549 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
556 let all = self.all.replace(AllTypes::new());
557 let v = layout::render(
561 |buf: &mut Buffer| all.print(buf),
562 &self.shared.style_files,
564 self.shared.fs.write(&final_file, v.as_bytes())?;
566 // Generating settings page.
567 page.title = "Rustdoc settings";
568 page.description = "Settings of Rustdoc";
569 page.root_path = "./";
571 let mut style_files = self.shared.style_files.clone();
572 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
573 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
574 let v = layout::render(
579 self.shared.static_root_path.as_deref().unwrap_or("./"),
580 &self.shared.resource_suffix,
581 &self.shared.style_files,
585 self.shared.fs.write(&settings_file, v.as_bytes())?;
594 ) -> Result<(), Error> {
595 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
596 // if they contain impls for public types. These modules can also
597 // contain items such as publicly re-exported structures.
599 // External crates will provide links to these structures, so
600 // these modules are recursed into, but not rendered normally
601 // (a flag on the context).
602 if !self.render_redirect_pages {
603 self.render_redirect_pages = item.is_stripped();
605 let scx = &self.shared;
606 self.dst.push(item_name);
607 self.current.push(item_name.to_owned());
609 info!("Recursing into {}", self.dst.display());
611 let buf = self.render_item(item, false, cache);
612 // buf will be empty if the module is stripped and there is no redirect for it
614 self.shared.ensure_dir(&self.dst)?;
615 let joint_dst = self.dst.join("index.html");
616 scx.fs.write(&joint_dst, buf.as_bytes())?;
619 // Render sidebar-items.js used throughout this module.
620 if !self.render_redirect_pages {
621 let module = match item.kind {
622 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
625 let items = self.build_sidebar_items(module);
626 let js_dst = self.dst.join("sidebar-items.js");
627 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
628 scx.fs.write(&js_dst, &v)?;
633 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
634 info!("Recursed; leaving {}", self.dst.display());
636 // Go back to where we were at
642 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
643 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
644 // if they contain impls for public types. These modules can also
645 // contain items such as publicly re-exported structures.
647 // External crates will provide links to these structures, so
648 // these modules are recursed into, but not rendered normally
649 // (a flag on the context).
650 if !self.render_redirect_pages {
651 self.render_redirect_pages = item.is_stripped();
654 let buf = self.render_item(&item, true, cache);
655 // buf will be empty if the item is stripped and there is no redirect for it
657 let name = item.name.as_ref().unwrap();
658 let item_type = item.type_();
659 let file_name = &item_path(item_type, name);
660 self.shared.ensure_dir(&self.dst)?;
661 let joint_dst = self.dst.join(file_name);
662 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
664 if !self.render_redirect_pages {
665 self.all.borrow_mut().append(full_path(self, &item), &item_type);
667 // If the item is a macro, redirect from the old macro URL (with !)
668 // to the new one (without).
669 if item_type == ItemType::Macro {
670 let redir_name = format!("{}.{}!.html", item_type, name);
671 let redir_dst = self.dst.join(redir_name);
672 let v = layout::redirect(file_name);
673 self.shared.fs.write(&redir_dst, v.as_bytes())?;
682 krate: &clean::Crate,
683 search_index: String,
684 options: &RenderOptions,
686 ) -> Result<(), Error> {
687 // Write out the shared files. Note that these are shared among all rustdoc
688 // docs placed in the output directory, so this needs to be a synchronized
689 // operation with respect to all other rustdocs running around.
690 let lock_file = cx.dst.join(".lock");
691 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
693 // Add all the static files. These may already exist, but we just
694 // overwrite them anyway to make sure that they're fresh and up-to-date.
698 cx.path("rustdoc.css"),
699 static_files::RUSTDOC_CSS,
700 options.enable_minification,
704 cx.path("settings.css"),
705 static_files::SETTINGS_CSS,
706 options.enable_minification,
710 cx.path("noscript.css"),
711 static_files::NOSCRIPT_CSS,
712 options.enable_minification,
715 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
716 // then we'll run over the "official" styles.
717 let mut themes: FxHashSet<String> = FxHashSet::default();
719 for entry in &cx.shared.style_files {
720 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
722 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
724 // Handle the official themes
726 "light" => write_minify(
728 cx.path("light.css"),
729 static_files::themes::LIGHT,
730 options.enable_minification,
732 "dark" => write_minify(
735 static_files::themes::DARK,
736 options.enable_minification,
738 "ayu" => write_minify(
741 static_files::themes::AYU,
742 options.enable_minification,
745 // Handle added third-party themes
746 let content = try_err!(fs::read(&entry.path), &entry.path);
749 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
753 themes.insert(theme.to_owned());
756 let write = |p, c| cx.shared.fs.write(p, c);
757 if (*cx.shared).layout.logo.is_empty() {
758 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
760 if (*cx.shared).layout.favicon.is_empty() {
761 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
762 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
763 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
765 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
766 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
767 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
769 let mut themes: Vec<&String> = themes.iter().collect();
771 // To avoid theme switch latencies as much as possible, we put everything theme related
772 // at the beginning of the html files into another js file.
773 let theme_js = format!(
774 r#"var themes = document.getElementById("theme-choices");
775 var themePicker = document.getElementById("theme-picker");
777 function showThemeButtonState() {{
778 themes.style.display = "block";
779 themePicker.style.borderBottomRightRadius = "0";
780 themePicker.style.borderBottomLeftRadius = "0";
783 function hideThemeButtonState() {{
784 themes.style.display = "none";
785 themePicker.style.borderBottomRightRadius = "3px";
786 themePicker.style.borderBottomLeftRadius = "3px";
789 function switchThemeButtonState() {{
790 if (themes.style.display === "block") {{
791 hideThemeButtonState();
793 showThemeButtonState();
797 function handleThemeButtonsBlur(e) {{
798 var active = document.activeElement;
799 var related = e.relatedTarget;
801 if (active.id !== "theme-picker" &&
802 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
804 (related.id !== "theme-picker" &&
805 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
806 hideThemeButtonState();
810 themePicker.onclick = switchThemeButtonState;
811 themePicker.onblur = handleThemeButtonsBlur;
812 {}.forEach(function(item) {{
813 var but = document.createElement("button");
814 but.textContent = item;
815 but.onclick = function(el) {{
816 switchTheme(currentTheme, mainTheme, item, true);
817 useSystemTheme(false);
819 but.onblur = handleThemeButtonsBlur;
820 themes.appendChild(but);
822 serde_json::to_string(&themes).unwrap()
825 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
829 static_files::MAIN_JS,
830 options.enable_minification,
834 cx.path("settings.js"),
835 static_files::SETTINGS_JS,
836 options.enable_minification,
838 if cx.shared.include_sources {
841 cx.path("source-script.js"),
842 static_files::sidebar::SOURCE_SCRIPT,
843 options.enable_minification,
850 cx.path("storage.js"),
852 "var resourcesSuffix = \"{}\";{}",
853 cx.shared.resource_suffix,
854 static_files::STORAGE_JS
856 options.enable_minification,
860 if let Some(ref css) = cx.shared.layout.css_file_extension {
861 let out = cx.path("theme.css");
862 let buffer = try_err!(fs::read_to_string(css), css);
863 if !options.enable_minification {
864 cx.shared.fs.write(&out, &buffer)?;
866 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
871 cx.path("normalize.css"),
872 static_files::NORMALIZE_CSS,
873 options.enable_minification,
875 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
876 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
877 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
878 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
879 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
880 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
881 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
882 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
883 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
884 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
885 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
886 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
887 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
889 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
890 let mut ret = Vec::new();
891 let mut krates = Vec::new();
894 for line in BufReader::new(File::open(path)?).lines() {
896 if !line.starts_with(key) {
899 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
902 ret.push(line.to_string());
904 line[key.len() + 2..]
907 .map(|s| s.to_owned())
908 .unwrap_or_else(String::new),
915 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
916 let mut ret = Vec::new();
917 let mut krates = Vec::new();
920 for line in BufReader::new(File::open(path)?).lines() {
922 if !line.starts_with('"') {
925 if line.starts_with(&format!("\"{}\"", krate)) {
928 if line.ends_with(",\\") {
929 ret.push(line[..line.len() - 2].to_string());
931 // Ends with "\\" (it's the case for the last added crate line)
932 ret.push(line[..line.len() - 1].to_string());
936 .find(|s| !s.is_empty())
937 .map(|s| s.to_owned())
938 .unwrap_or_else(String::new),
945 use std::ffi::OsString;
950 children: FxHashMap<OsString, Hierarchy>,
951 elems: FxHashSet<OsString>,
955 fn new(elem: OsString) -> Hierarchy {
956 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
959 fn to_json_string(&self) -> String {
960 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
961 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
965 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
966 .collect::<Vec<_>>();
967 files.sort_unstable_by(|a, b| a.cmp(b));
968 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
970 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
971 let files = files.join(",");
973 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
975 "{{\"name\":\"{name}\"{dirs}{files}}}",
976 name = self.elem.to_str().expect("invalid osstring conversion"),
983 if cx.shared.include_sources {
984 let mut hierarchy = Hierarchy::new(OsString::new());
989 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
991 let mut h = &mut hierarchy;
992 let mut elems = source
994 .filter_map(|s| match s {
995 Component::Normal(s) => Some(s.to_owned()),
1000 let cur_elem = elems.next().expect("empty file path");
1001 if elems.peek().is_none() {
1002 h.elems.insert(cur_elem);
1005 let e = cur_elem.clone();
1006 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1007 h = h.children.get_mut(&cur_elem).expect("not found child");
1012 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1013 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1014 all_sources.push(format!(
1015 "sourcesIndex[\"{}\"] = {};",
1017 hierarchy.to_json_string()
1021 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1022 all_sources.join("\n")
1024 cx.shared.fs.write(&dst, v.as_bytes())?;
1027 // Update the search index
1028 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1029 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name), &dst);
1030 all_indexes.push(search_index);
1032 // Sort the indexes by crate so the file will be generated identically even
1033 // with rustdoc running in parallel.
1036 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1037 v.push_str(&all_indexes.join(",\\\n"));
1038 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1039 // search might start (if it's set into the URL for example).
1040 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1041 cx.shared.fs.write(&dst, &v)?;
1043 if options.enable_index_page {
1044 if let Some(index_page) = options.index_page.clone() {
1045 let mut md_opts = options.clone();
1046 md_opts.output = cx.dst.clone();
1047 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1049 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1050 .map_err(|e| Error::new(e, &index_page))?;
1052 let dst = cx.dst.join("index.html");
1053 let page = layout::Page {
1054 title: "Index of crates",
1057 static_root_path: cx.shared.static_root_path.as_deref(),
1058 description: "List of crates",
1059 keywords: BASIC_KEYWORDS,
1060 resource_suffix: &cx.shared.resource_suffix,
1062 static_extra_scripts: &[],
1064 krates.push(krate.name.clone());
1068 let content = format!(
1069 "<h1 class=\"fqn\">\
1070 <span class=\"in-band\">List of all crates</span>\
1071 </h1><ul class=\"crate mod\">{}</ul>",
1076 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1077 ensure_trailing_slash(s),
1081 .collect::<String>()
1083 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1084 cx.shared.fs.write(&dst, v.as_bytes())?;
1088 // Update the list of all implementors for traits
1089 let dst = cx.dst.join("implementors");
1090 for (&did, imps) in &cache.implementors {
1091 // Private modules can leak through to this phase of rustdoc, which
1092 // could contain implementations for otherwise private types. In some
1093 // rare cases we could find an implementation for an item which wasn't
1094 // indexed, so we just skip this step in that case.
1096 // FIXME: this is a vague explanation for why this can't be a `get`, in
1097 // theory it should be...
1098 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1100 None => match cache.external_paths.get(&did) {
1106 #[derive(Serialize)]
1107 struct Implementor {
1113 let implementors = imps
1116 // If the trait and implementation are in the same crate, then
1117 // there's no need to emit information about it (there's inlining
1118 // going on). If they're in different crates then the crate defining
1119 // the trait will be interested in our implementation.
1121 // If the implementation is from another crate then that crate
1123 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1127 text: imp.inner_impl().print().to_string(),
1128 synthetic: imp.inner_impl().synthetic,
1129 types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1133 .collect::<Vec<_>>();
1135 // Only create a js file if we have impls to add to it. If the trait is
1136 // documented locally though we always create the file to avoid dead
1138 if implementors.is_empty() && !cache.paths.contains_key(&did) {
1142 let implementors = format!(
1143 r#"implementors["{}"] = {};"#,
1145 serde_json::to_string(&implementors).unwrap()
1148 let mut mydst = dst.clone();
1149 for part in &remote_path[..remote_path.len() - 1] {
1152 cx.shared.ensure_dir(&mydst)?;
1153 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1155 let (mut all_implementors, _) =
1156 try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1157 all_implementors.push(implementors);
1158 // Sort the implementors by crate so the file will be generated
1159 // identically even with rustdoc running in parallel.
1160 all_implementors.sort();
1162 let mut v = String::from("(function() {var implementors = {};\n");
1163 for implementor in &all_implementors {
1164 writeln!(v, "{}", *implementor).unwrap();
1167 "if (window.register_implementors) {\
1168 window.register_implementors(implementors);\
1170 window.pending_implementors = implementors;\
1174 cx.shared.fs.write(&mydst, &v)?;
1183 enable_minification: bool,
1184 ) -> Result<(), Error> {
1185 if enable_minification {
1186 if dst.extension() == Some(&OsStr::new("css")) {
1187 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1188 fs.write(dst, res.as_bytes())
1190 fs.write(dst, minifier::js::minify(contents).as_bytes())
1193 fs.write(dst, contents.as_bytes())
1197 fn write_srclink(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1198 if let Some(l) = cx.src_href(item, cache) {
1201 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
1202 l, "goto source code"
1207 #[derive(Debug, Eq, PartialEq, Hash)]
1214 fn new(mut url: String, name: String) -> ItemEntry {
1215 while url.starts_with('/') {
1218 ItemEntry { url, name }
1223 crate fn print(&self) -> impl fmt::Display + '_ {
1224 crate::html::format::display_fn(move |f| {
1225 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1230 impl PartialOrd for ItemEntry {
1231 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1232 Some(self.cmp(other))
1236 impl Ord for ItemEntry {
1237 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1238 self.name.cmp(&other.name)
1244 structs: FxHashSet<ItemEntry>,
1245 enums: FxHashSet<ItemEntry>,
1246 unions: FxHashSet<ItemEntry>,
1247 primitives: FxHashSet<ItemEntry>,
1248 traits: FxHashSet<ItemEntry>,
1249 macros: FxHashSet<ItemEntry>,
1250 functions: FxHashSet<ItemEntry>,
1251 typedefs: FxHashSet<ItemEntry>,
1252 opaque_tys: FxHashSet<ItemEntry>,
1253 statics: FxHashSet<ItemEntry>,
1254 constants: FxHashSet<ItemEntry>,
1255 keywords: FxHashSet<ItemEntry>,
1256 attributes: FxHashSet<ItemEntry>,
1257 derives: FxHashSet<ItemEntry>,
1258 trait_aliases: FxHashSet<ItemEntry>,
1262 fn new() -> AllTypes {
1263 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1265 structs: new_set(100),
1266 enums: new_set(100),
1267 unions: new_set(100),
1268 primitives: new_set(26),
1269 traits: new_set(100),
1270 macros: new_set(100),
1271 functions: new_set(100),
1272 typedefs: new_set(100),
1273 opaque_tys: new_set(100),
1274 statics: new_set(100),
1275 constants: new_set(100),
1276 keywords: new_set(100),
1277 attributes: new_set(100),
1278 derives: new_set(100),
1279 trait_aliases: new_set(100),
1283 fn append(&mut self, item_name: String, item_type: &ItemType) {
1284 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1285 if let Some(name) = url.pop() {
1286 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1288 let name = url.join("::");
1290 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1291 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1292 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1293 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1294 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1295 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1296 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1297 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1298 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1299 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1300 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1301 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1302 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1303 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1310 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1312 let mut e: Vec<&ItemEntry> = e.iter().collect();
1316 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">{}</ul>",
1320 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1326 fn print(self, f: &mut Buffer) {
1329 "<h1 class=\"fqn\">\
1330 <span class=\"out-of-band\">\
1331 <span id=\"render-detail\">\
1332 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1333 title=\"collapse all docs\">\
1334 [<span class=\"inner\">−</span>]\
1338 <span class=\"in-band\">List of all items</span>\
1341 print_entries(f, &self.structs, "Structs", "structs");
1342 print_entries(f, &self.enums, "Enums", "enums");
1343 print_entries(f, &self.unions, "Unions", "unions");
1344 print_entries(f, &self.primitives, "Primitives", "primitives");
1345 print_entries(f, &self.traits, "Traits", "traits");
1346 print_entries(f, &self.macros, "Macros", "macros");
1347 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1348 print_entries(f, &self.derives, "Derive Macros", "derives");
1349 print_entries(f, &self.functions, "Functions", "functions");
1350 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1351 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1352 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1353 print_entries(f, &self.statics, "Statics", "statics");
1354 print_entries(f, &self.constants, "Constants", "constants")
1361 description: &'static str,
1362 sub_settings: Vec<Setting>,
1365 js_data_name: &'static str,
1366 description: &'static str,
1367 default_value: bool,
1370 js_data_name: &'static str,
1371 description: &'static str,
1372 default_value: &'static str,
1373 options: Vec<(String, String)>,
1378 fn display(&self, root_path: &str, suffix: &str) -> String {
1380 Setting::Section { description, ref sub_settings } => format!(
1381 "<div class=\"setting-line\">\
1382 <div class=\"title\">{}</div>\
1383 <div class=\"sub-settings\">{}</div>
1386 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1388 Setting::Toggle { js_data_name, description, default_value } => format!(
1389 "<div class=\"setting-line\">\
1390 <label class=\"toggle\">\
1391 <input type=\"checkbox\" id=\"{}\" {}>\
1392 <span class=\"slider\"></span>\
1397 if default_value { " checked" } else { "" },
1400 Setting::Select { js_data_name, description, default_value, ref options } => format!(
1401 "<div class=\"setting-line\">\
1403 <label class=\"select-wrapper\">\
1404 <select id=\"{}\" autocomplete=\"off\">{}</select>\
1405 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1413 "<option value=\"{}\" {}>{}</option>",
1415 if &opt.0 == default_value { "selected" } else { "" },
1418 .collect::<String>(),
1426 impl From<(&'static str, &'static str, bool)> for Setting {
1427 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1428 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1432 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1433 fn from(values: (&'static str, Vec<T>)) -> Setting {
1435 description: values.0,
1436 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1441 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1442 let theme_names: Vec<(String, String)> = themes
1446 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1449 Ok((theme.clone(), theme))
1451 .collect::<Result<_, Error>>()?;
1453 // (id, explanation, default value)
1454 let settings: &[Setting] = &[
1456 "Theme preferences",
1458 Setting::from(("use-system-theme", "Use system theme", true)),
1460 js_data_name: "preferred-dark-theme",
1461 description: "Preferred dark theme",
1462 default_value: "dark",
1463 options: theme_names.clone(),
1466 js_data_name: "preferred-light-theme",
1467 description: "Preferred light theme",
1468 default_value: "light",
1469 options: theme_names,
1475 "Auto-hide item declarations",
1477 ("auto-hide-struct", "Auto-hide structs declaration", true),
1478 ("auto-hide-enum", "Auto-hide enums declaration", false),
1479 ("auto-hide-union", "Auto-hide unions declaration", true),
1480 ("auto-hide-trait", "Auto-hide traits declaration", true),
1481 ("auto-hide-macro", "Auto-hide macros declaration", false),
1485 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1486 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1487 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1489 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1490 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1492 ("line-numbers", "Show line numbers on code examples", false).into(),
1493 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1497 "<h1 class=\"fqn\">\
1498 <span class=\"in-band\">Rustdoc settings</span>\
1500 <div class=\"settings\">{}</div>\
1501 <script src=\"{}settings{}.js\"></script>",
1502 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1509 fn derive_id(&self, id: String) -> String {
1510 let mut map = self.id_map.borrow_mut();
1514 /// String representation of how to get back to the root path of the 'doc/'
1515 /// folder in terms of a relative URL.
1516 fn root_path(&self) -> String {
1517 "../".repeat(self.current.len())
1520 fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1521 // A little unfortunate that this is done like this, but it sure
1522 // does make formatting *a lot* nicer.
1523 CURRENT_DEPTH.with(|slot| {
1524 slot.set(self.current.len());
1527 let mut title = if it.is_primitive() || it.is_keyword() {
1528 // No need to include the namespace for primitive types and keywords
1531 self.current.join("::")
1534 if !title.is_empty() {
1535 title.push_str("::");
1537 title.push_str(it.name.as_ref().unwrap());
1539 title.push_str(" - Rust");
1540 let tyname = it.type_();
1541 let desc = if it.is_crate() {
1542 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1545 "API documentation for the Rust `{}` {} in crate `{}`.",
1546 it.name.as_ref().unwrap(),
1548 self.shared.layout.krate
1551 let keywords = make_item_keywords(it);
1552 let page = layout::Page {
1553 css_class: tyname.as_str(),
1554 root_path: &self.root_path(),
1555 static_root_path: self.shared.static_root_path.as_deref(),
1558 keywords: &keywords,
1559 resource_suffix: &self.shared.resource_suffix,
1561 static_extra_scripts: &[],
1565 self.id_map.borrow_mut().reset();
1566 self.id_map.borrow_mut().populate(initial_ids());
1569 if !self.render_redirect_pages {
1571 &self.shared.layout,
1573 |buf: &mut _| print_sidebar(self, it, buf, cache),
1574 |buf: &mut _| print_item(self, it, buf, cache),
1575 &self.shared.style_files,
1578 let mut url = self.root_path();
1579 if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1580 for name in &names[..names.len() - 1] {
1584 url.push_str(&item_path(ty, names.last().unwrap()));
1585 layout::redirect(&url)
1592 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1593 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1594 // BTreeMap instead of HashMap to get a sorted output
1595 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1596 for item in &m.items {
1597 if item.is_stripped() {
1601 let short = item.type_();
1602 let myname = match item.name {
1604 Some(ref s) => s.to_string(),
1606 let short = short.to_string();
1607 map.entry(short).or_default().push((
1609 Some(item.doc_value().map_or_else(|| String::new(), plain_text_summary)),
1613 if self.shared.sort_modules_alphabetically {
1614 for items in map.values_mut() {
1621 /// Generates a url appropriate for an `href` attribute back to the source of
1624 /// The url generated, when clicked, will redirect the browser back to the
1625 /// original source code.
1627 /// If `None` is returned, then a source link couldn't be generated. This
1628 /// may happen, for example, with externally inlined items where the source
1629 /// of their crate documentation isn't known.
1630 fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1631 let mut root = self.root_path();
1633 let mut path = String::new();
1635 // We can safely ignore synthetic `SourceFile`s.
1636 let file = match item.source.filename {
1637 FileName::Real(ref path) => path.local_path().to_path_buf(),
1642 let (krate, path) = if item.source.cnum == LOCAL_CRATE {
1643 if let Some(path) = self.shared.local_sources.get(file) {
1644 (&self.shared.layout.krate, path)
1649 let (krate, src_root) = match *cache.extern_locations.get(&item.source.cnum)? {
1650 (ref name, ref src, ExternalLocation::Local) => (name, src),
1651 (ref name, ref src, ExternalLocation::Remote(ref s)) => {
1652 root = s.to_string();
1655 (_, _, ExternalLocation::Unknown) => return None,
1658 sources::clean_path(&src_root, file, false, |component| {
1659 path.push_str(&component.to_string_lossy());
1662 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1663 fname.push(".html");
1664 path.push_str(&fname.to_string_lossy());
1668 let lines = if item.source.loline == item.source.hiline {
1669 item.source.loline.to_string()
1671 format!("{}-{}", item.source.loline, item.source.hiline)
1674 "{root}src/{krate}/{path}#{lines}",
1675 root = Escape(&root),
1683 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1685 F: FnOnce(&mut Buffer),
1687 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1692 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1693 debug_assert!(!item.is_stripped());
1694 // Write the breadcrumb trail header for the top
1695 write!(buf, "<h1 class=\"fqn\"><span class=\"out-of-band\">");
1696 render_stability_since_raw(
1698 item.stable_since().as_deref(),
1699 item.const_stable_since().as_deref(),
1705 "<span id=\"render-detail\">\
1706 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1707 title=\"collapse all docs\">\
1708 [<span class=\"inner\">−</span>]\
1715 // When this item is part of a `crate use` in a downstream crate, the
1716 // [src] link in the downstream documentation will actually come back to
1717 // this page, and this link will be auto-clicked. The `id` attribute is
1718 // used to find the link to auto-click.
1719 if cx.shared.include_sources && !item.is_primitive() {
1720 write_srclink(cx, item, buf, cache);
1723 write!(buf, "</span>"); // out-of-band
1724 write!(buf, "<span class=\"in-band\">");
1725 let name = match item.kind {
1726 clean::ModuleItem(ref m) => {
1733 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1734 clean::TraitItem(..) => "Trait ",
1735 clean::StructItem(..) => "Struct ",
1736 clean::UnionItem(..) => "Union ",
1737 clean::EnumItem(..) => "Enum ",
1738 clean::TypedefItem(..) => "Type Definition ",
1739 clean::MacroItem(..) => "Macro ",
1740 clean::ProcMacroItem(ref mac) => match mac.kind {
1741 MacroKind::Bang => "Macro ",
1742 MacroKind::Attr => "Attribute Macro ",
1743 MacroKind::Derive => "Derive Macro ",
1745 clean::PrimitiveItem(..) => "Primitive Type ",
1746 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1747 clean::ConstantItem(..) => "Constant ",
1748 clean::ForeignTypeItem => "Foreign Type ",
1749 clean::KeywordItem(..) => "Keyword ",
1750 clean::OpaqueTyItem(..) => "Opaque Type ",
1751 clean::TraitAliasItem(..) => "Trait Alias ",
1753 // We don't generate pages for any other type.
1757 buf.write_str(name);
1758 if !item.is_primitive() && !item.is_keyword() {
1759 let cur = &cx.current;
1760 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1761 for (i, component) in cur.iter().enumerate().take(amt) {
1764 "<a href=\"{}index.html\">{}</a>::<wbr>",
1765 "../".repeat(cur.len() - i - 1),
1770 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1772 write!(buf, "</span></h1>"); // in-band
1775 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1776 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1777 item_function(buf, cx, item, f)
1779 clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1780 clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1781 clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1782 clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1783 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1784 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1785 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1786 clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1787 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1788 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1789 clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1790 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1791 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e, cache),
1792 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1794 // We don't generate pages for any other type.
1800 fn item_path(ty: ItemType, name: &str) -> String {
1802 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1803 _ => format!("{}.{}.html", ty, name),
1807 fn full_path(cx: &Context, item: &clean::Item) -> String {
1808 let mut s = cx.current.join("::");
1810 s.push_str(item.name.as_ref().unwrap());
1814 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item, parent: Option<&clean::Item>) {
1815 if let Some(ref name) = item.name {
1816 info!("Documenting {}", name);
1818 document_item_info(w, cx, item, false, parent);
1819 document_full(w, item, cx, "", false);
1822 /// Render md_text as markdown.
1827 links: Vec<RenderedLink>,
1831 let mut ids = cx.id_map.borrow_mut();
1834 "<div class=\"docblock{}\">{}{}</div>",
1835 if is_hidden { " hidden" } else { "" },
1843 &cx.shared.playground
1849 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1850 /// docs are longer, a "Read more" link is appended to the end.
1855 link: AssocItemLink<'_>,
1858 parent: Option<&clean::Item>,
1859 show_def_docs: bool,
1861 document_item_info(w, cx, item, is_hidden, parent);
1865 if let Some(s) = item.doc_value() {
1866 let mut summary_html = MarkdownSummaryLine(s, &item.links()).into_string();
1868 if s.contains('\n') {
1869 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link));
1871 if let Some(idx) = summary_html.rfind("</p>") {
1872 summary_html.insert_str(idx, &link);
1874 summary_html.push_str(&link);
1880 "<div class='docblock{}'>{}{}</div>",
1881 if is_hidden { " hidden" } else { "" },
1885 } else if !prefix.is_empty() {
1888 "<div class=\"docblock{}\">{}</div>",
1889 if is_hidden { " hidden" } else { "" },
1895 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1896 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1897 debug!("Doc block: =====\n{}\n=====", s);
1898 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1899 } else if !prefix.is_empty() {
1902 "<div class=\"docblock{}\">{}</div>",
1903 if is_hidden { " hidden" } else { "" },
1909 /// Add extra information about an item such as:
1913 /// * Required features (through the `doc_cfg` feature)
1914 fn document_item_info(
1919 parent: Option<&clean::Item>,
1921 let item_infos = short_item_info(item, cx, parent);
1922 if !item_infos.is_empty() {
1923 write!(w, "<div class=\"item-info{}\">", if is_hidden { " hidden" } else { "" });
1924 for info in item_infos {
1925 write!(w, "{}", info);
1927 write!(w, "</div>");
1931 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1932 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1935 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1936 if item.is_non_exhaustive() {
1937 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1938 if item.is_struct() {
1940 } else if item.is_enum() {
1942 } else if item.is_variant() {
1949 if item.is_struct() {
1952 "Non-exhaustive structs could have additional fields added in future. \
1953 Therefore, non-exhaustive structs cannot be constructed in external crates \
1954 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1955 matched against without a wildcard <code>..</code>; and \
1956 struct update syntax will not work."
1958 } else if item.is_enum() {
1961 "Non-exhaustive enums could have additional variants added in future. \
1962 Therefore, when matching against variants of non-exhaustive enums, an \
1963 extra wildcard arm must be added to account for any future variants."
1965 } else if item.is_variant() {
1968 "Non-exhaustive enum variants could have additional fields added in future. \
1969 Therefore, non-exhaustive enum variants cannot be constructed in external \
1970 crates and cannot be matched against."
1975 "This type will require a wildcard arm in any match statements or constructors."
1979 write!(w, "</div>");
1983 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1984 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1985 /// Takes a non-numeric and a numeric part from the given &str.
1986 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1987 let i = s.find(|c: char| c.is_ascii_digit());
1988 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1989 let i = b.find(|c: char| !c.is_ascii_digit());
1990 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1995 while !lhs.is_empty() || !rhs.is_empty() {
1996 let (la, lb) = take_parts(&mut lhs);
1997 let (ra, rb) = take_parts(&mut rhs);
1998 // First process the non-numeric part.
2000 Ordering::Equal => (),
2003 // Then process the numeric part, if both sides have one (and they fit in a u64).
2004 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2006 Ordering::Equal => (),
2010 // Then process the numeric part again, but this time as strings.
2012 Ordering::Equal => (),
2020 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
2021 document(w, cx, item, None);
2023 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2025 // the order of item types in the listing
2026 fn reorder(ty: ItemType) -> u8 {
2028 ItemType::ExternCrate => 0,
2029 ItemType::Import => 1,
2030 ItemType::Primitive => 2,
2031 ItemType::Module => 3,
2032 ItemType::Macro => 4,
2033 ItemType::Struct => 5,
2034 ItemType::Enum => 6,
2035 ItemType::Constant => 7,
2036 ItemType::Static => 8,
2037 ItemType::Trait => 9,
2038 ItemType::Function => 10,
2039 ItemType::Typedef => 12,
2040 ItemType::Union => 13,
2045 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2046 let ty1 = i1.type_();
2047 let ty2 = i2.type_();
2049 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2051 let s1 = i1.stability.as_ref().map(|s| s.level);
2052 let s2 = i2.stability.as_ref().map(|s| s.level);
2053 if let (Some(a), Some(b)) = (s1, s2) {
2054 match (a.is_stable(), b.is_stable()) {
2055 (true, true) | (false, false) => {}
2056 (false, true) => return Ordering::Less,
2057 (true, false) => return Ordering::Greater,
2060 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2061 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2062 compare_names(lhs, rhs)
2065 if cx.shared.sort_modules_alphabetically {
2066 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2068 // This call is to remove re-export duplicates in cases such as:
2073 // crate trait Double { fn foo(); }
2077 // crate use foo::bar::*;
2078 // crate use foo::*;
2081 // `Double` will appear twice in the generated docs.
2083 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2084 // can be identical even if the elements are different (mostly in imports).
2085 // So in case this is an import, we keep everything by adding a "unique id"
2086 // (which is the position in the vector).
2087 indices.dedup_by_key(|i| {
2090 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2092 if items[*i].is_import() { *i } else { 0 },
2096 debug!("{:?}", indices);
2097 let mut curty = None;
2098 for &idx in &indices {
2099 let myitem = &items[idx];
2100 if myitem.is_stripped() {
2104 let myty = Some(myitem.type_());
2105 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2106 // Put `extern crate` and `use` re-exports in the same section.
2108 } else if myty != curty {
2109 if curty.is_some() {
2110 write!(w, "</table>");
2113 let (short, name) = item_ty_to_strs(&myty.unwrap());
2116 "<h2 id=\"{id}\" class=\"section-header\">\
2117 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2118 id = cx.derive_id(short.to_owned()),
2124 clean::ExternCrateItem(ref name, ref src) => {
2125 use crate::html::format::anchor;
2128 Some(ref src) => write!(
2130 "<tr><td><code>{}extern crate {} as {};",
2131 myitem.visibility.print_with_space(),
2132 anchor(myitem.def_id, src),
2137 "<tr><td><code>{}extern crate {};",
2138 myitem.visibility.print_with_space(),
2139 anchor(myitem.def_id, name)
2142 write!(w, "</code></td></tr>");
2145 clean::ImportItem(ref import) => {
2148 "<tr><td><code>{}{}</code></td></tr>",
2149 myitem.visibility.print_with_space(),
2155 if myitem.name.is_none() {
2159 let unsafety_flag = match myitem.kind {
2160 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2161 if func.header.unsafety == hir::Unsafety::Unsafe =>
2163 "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2168 let stab = myitem.stability_class();
2169 let add = if stab.is_some() { " " } else { "" };
2171 let doc_value = myitem.doc_value().unwrap_or("");
2174 "<tr class=\"{stab}{add}module-item\">\
2175 <td><a class=\"{class}\" href=\"{href}\" \
2176 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2177 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2179 name = *myitem.name.as_ref().unwrap(),
2180 stab_tags = extra_info_tags(myitem, item),
2181 docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2182 class = myitem.type_(),
2184 stab = stab.unwrap_or_else(String::new),
2185 unsafety_flag = unsafety_flag,
2186 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2187 title = [full_path(cx, myitem), myitem.type_().to_string()]
2189 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2190 .collect::<Vec<_>>()
2197 if curty.is_some() {
2198 write!(w, "</table>");
2202 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
2203 /// at the module level.
2204 fn extra_info_tags(item: &clean::Item, parent: &clean::Item) -> String {
2205 let mut tags = String::new();
2207 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2208 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2211 // The trailing space after each tag is to space it properly against the rest of the docs.
2212 if let Some(depr) = &item.deprecation {
2213 let mut message = "Deprecated";
2214 if !stability::deprecation_in_effect(depr.is_since_rustc_version, depr.since.as_deref()) {
2215 message = "Deprecation planned";
2217 tags += &tag_html("deprecated", "", message);
2220 // The "rustc_private" crates are permanently unstable so it makes no sense
2221 // to render "unstable" everywhere.
2222 if item.stability.as_ref().map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2225 tags += &tag_html("unstable", "", "Experimental");
2228 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2229 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2230 (cfg, _) => cfg.as_deref().cloned(),
2233 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2234 if let Some(ref cfg) = cfg {
2235 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2241 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2242 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2243 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2244 (cfg, _) => cfg.as_deref().cloned(),
2248 "Portability {:?} - {:?} = {:?}",
2250 parent.and_then(|p| p.attrs.cfg.as_ref()),
2254 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2257 /// Render the stability, deprecation and portability information that is displayed at the top of
2258 /// the item's documentation.
2259 fn short_item_info(item: &clean::Item, cx: &Context, parent: Option<&clean::Item>) -> Vec<String> {
2260 let mut extra_info = vec![];
2261 let error_codes = cx.shared.codes;
2263 if let Some(Deprecation { ref note, ref since, is_since_rustc_version }) = item.deprecation {
2264 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2265 // but only display the future-deprecation messages for #[rustc_deprecated].
2266 let mut message = if let Some(since) = since {
2267 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2268 format!("Deprecating in {}", Escape(&since))
2270 format!("Deprecated since {}", Escape(&since))
2273 String::from("Deprecated")
2276 if let Some(note) = note {
2277 let mut ids = cx.id_map.borrow_mut();
2278 let html = MarkdownHtml(
2283 &cx.shared.playground,
2285 message.push_str(&format!(": {}", html.into_string()));
2287 extra_info.push(format!(
2288 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2293 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2294 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2295 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2298 .filter(|stab| stab.feature != sym::rustc_private)
2299 .map(|stab| (stab.level, stab.feature))
2302 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2304 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2305 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2306 feature.push_str(&format!(
2307 " <a href=\"{url}{issue}\">#{issue}</a>",
2313 message.push_str(&format!(" ({})", feature));
2315 if let Some(unstable_reason) = reason {
2316 let mut ids = cx.id_map.borrow_mut();
2318 "<details><summary>{}</summary>{}</details>",
2321 &unstable_reason.as_str(),
2325 &cx.shared.playground,
2331 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2334 if let Some(portability) = portability(item, parent) {
2335 extra_info.push(portability);
2341 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2342 write!(w, "<pre class=\"rust const\">");
2343 render_attributes(w, it, false);
2347 "{vis}const {name}: {typ}",
2348 vis = it.visibility.print_with_space(),
2349 name = it.name.as_ref().unwrap(),
2350 typ = c.type_.print(),
2353 if c.value.is_some() || c.is_literal {
2354 write!(w, " = {expr};", expr = Escape(&c.expr));
2359 if let Some(value) = &c.value {
2361 let value_lowercase = value.to_lowercase();
2362 let expr_lowercase = c.expr.to_lowercase();
2364 if value_lowercase != expr_lowercase
2365 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2367 write!(w, " // {value}", value = Escape(value));
2372 write!(w, "</pre>");
2373 document(w, cx, it, None)
2376 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2377 write!(w, "<pre class=\"rust static\">");
2378 render_attributes(w, it, false);
2381 "{vis}static {mutability}{name}: {typ}</pre>",
2382 vis = it.visibility.print_with_space(),
2383 mutability = s.mutability.print_with_space(),
2384 name = it.name.as_ref().unwrap(),
2385 typ = s.type_.print()
2387 document(w, cx, it, None)
2390 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2391 let header_len = format!(
2392 "{}{}{}{}{:#}fn {}{:#}",
2393 it.visibility.print_with_space(),
2394 f.header.constness.print_with_space(),
2395 f.header.asyncness.print_with_space(),
2396 f.header.unsafety.print_with_space(),
2397 print_abi_with_space(f.header.abi),
2398 it.name.as_ref().unwrap(),
2402 write!(w, "<pre class=\"rust fn\">");
2403 render_attributes(w, it, false);
2406 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2407 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2408 vis = it.visibility.print_with_space(),
2409 constness = f.header.constness.print_with_space(),
2410 asyncness = f.header.asyncness.print_with_space(),
2411 unsafety = f.header.unsafety.print_with_space(),
2412 abi = print_abi_with_space(f.header.abi),
2413 name = it.name.as_ref().unwrap(),
2414 generics = f.generics.print(),
2415 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2416 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2418 spotlight = spotlight_decl(&f.decl),
2420 document(w, cx, it, None)
2423 fn render_implementor(
2426 parent: &clean::Item,
2428 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2432 // If there's already another implementor that has the same abbridged name, use the
2433 // full path, for example in `std::iter::ExactSizeIterator`
2434 let use_absolute = match implementor.inner_impl().for_ {
2435 clean::ResolvedPath { ref path, is_generic: false, .. }
2436 | clean::BorrowedRef {
2437 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2439 } => implementor_dups[path.last_name()].1,
2447 AssocItemLink::Anchor(None),
2449 implementor.impl_item.stable_since().as_deref(),
2450 implementor.impl_item.const_stable_since().as_deref(),
2464 containing_item: &clean::Item,
2467 let mut impls = traits
2470 let did = i.trait_did().unwrap();
2471 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2472 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2480 containing_item.stable_since().as_deref(),
2481 containing_item.const_stable_since().as_deref(),
2491 .collect::<Vec<_>>();
2493 w.write_str(&impls.join(""));
2496 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2497 let mut bounds = String::new();
2498 if !t_bounds.is_empty() {
2500 bounds.push_str(": ");
2502 for (i, p) in t_bounds.iter().enumerate() {
2504 bounds.push_str(" + ");
2506 bounds.push_str(&p.print().to_string());
2512 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2513 let lhs = format!("{}", lhs.inner_impl().print());
2514 let rhs = format!("{}", rhs.inner_impl().print());
2516 // lhs and rhs are formatted as HTML, which may be unnecessary
2517 compare_names(&lhs, &rhs)
2520 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2521 let bounds = bounds(&t.bounds, false);
2522 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2523 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2524 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2525 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2527 // Output the trait definition
2528 wrap_into_docblock(w, |w| {
2529 write!(w, "<pre class=\"rust trait\">");
2530 render_attributes(w, it, true);
2533 "{}{}{}trait {}{}{}",
2534 it.visibility.print_with_space(),
2535 t.unsafety.print_with_space(),
2536 if t.is_auto { "auto " } else { "" },
2537 it.name.as_ref().unwrap(),
2542 if !t.generics.where_predicates.is_empty() {
2543 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2548 if t.items.is_empty() {
2551 // FIXME: we should be using a derived_id for the Anchors here
2554 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2557 if !types.is_empty() && !consts.is_empty() {
2561 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2564 if !consts.is_empty() && !required.is_empty() {
2567 for (pos, m) in required.iter().enumerate() {
2568 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2571 if pos < required.len() - 1 {
2572 write!(w, "<div class=\"item-spacer\"></div>");
2575 if !required.is_empty() && !provided.is_empty() {
2578 for (pos, m) in provided.iter().enumerate() {
2579 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2581 clean::MethodItem(ref inner, _)
2582 if !inner.generics.where_predicates.is_empty() =>
2584 write!(w, ",\n {{ ... }}\n");
2587 write!(w, " {{ ... }}\n");
2590 if pos < provided.len() - 1 {
2591 write!(w, "<div class=\"item-spacer\"></div>");
2599 // Trait documentation
2600 document(w, cx, it, None);
2602 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2605 "<h2 id=\"{0}\" class=\"small-section-header\">\
2606 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2608 id, title, extra_content
2612 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2613 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2616 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item, cache: &Cache) {
2617 let name = m.name.as_ref().unwrap();
2618 info!("Documenting {} on {}", name, t.name.as_deref().unwrap_or_default());
2619 let item_type = m.type_();
2620 let id = cx.derive_id(format!("{}.{}", item_type, name));
2621 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2622 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2623 write!(w, "</code>");
2624 render_stability_since(w, m, t);
2625 write_srclink(cx, m, w, cache);
2627 document(w, cx, m, Some(t));
2630 if !types.is_empty() {
2631 write_small_section_header(
2635 "<div class=\"methods\">",
2638 trait_item(w, cx, t, it, cache);
2640 write_loading_content(w, "</div>");
2643 if !consts.is_empty() {
2644 write_small_section_header(
2647 "Associated Constants",
2648 "<div class=\"methods\">",
2651 trait_item(w, cx, t, it, cache);
2653 write_loading_content(w, "</div>");
2656 // Output the documentation for each function individually
2657 if !required.is_empty() {
2658 write_small_section_header(
2662 "<div class=\"methods\">",
2665 trait_item(w, cx, m, it, cache);
2667 write_loading_content(w, "</div>");
2669 if !provided.is_empty() {
2670 write_small_section_header(
2674 "<div class=\"methods\">",
2677 trait_item(w, cx, m, it, cache);
2679 write_loading_content(w, "</div>");
2682 // If there are methods directly on this trait object, render them here.
2683 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2685 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2686 // The DefId is for the first Type found with that name. The bool is
2687 // if any Types with the same name but different DefId have been found.
2688 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2689 for implementor in implementors {
2690 match implementor.inner_impl().for_ {
2691 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2692 | clean::BorrowedRef {
2693 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2696 let &mut (prev_did, ref mut has_duplicates) =
2697 implementor_dups.entry(path.last_name()).or_insert((did, false));
2698 if prev_did != did {
2699 *has_duplicates = true;
2706 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2707 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2710 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2711 local.iter().partition(|i| i.inner_impl().synthetic);
2713 synthetic.sort_by(compare_impl);
2714 concrete.sort_by(compare_impl);
2716 if !foreign.is_empty() {
2717 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2719 for implementor in foreign {
2720 let assoc_link = AssocItemLink::GotoSource(
2721 implementor.impl_item.def_id,
2722 &implementor.inner_impl().provided_trait_methods,
2731 implementor.impl_item.stable_since().as_deref(),
2732 implementor.impl_item.const_stable_since().as_deref(),
2741 write_loading_content(w, "");
2744 write_small_section_header(
2748 "<div class=\"item-list\" id=\"implementors-list\">",
2750 for implementor in concrete {
2751 render_implementor(cx, implementor, it, w, &implementor_dups, &[], cache);
2753 write_loading_content(w, "</div>");
2756 write_small_section_header(
2758 "synthetic-implementors",
2759 "Auto implementors",
2760 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2762 for implementor in synthetic {
2769 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2773 write_loading_content(w, "</div>");
2776 // even without any implementations to write in, we still want the heading and list, so the
2777 // implementors javascript file pulled in below has somewhere to write the impls into
2778 write_small_section_header(
2782 "<div class=\"item-list\" id=\"implementors-list\">",
2784 write_loading_content(w, "</div>");
2787 write_small_section_header(
2789 "synthetic-implementors",
2790 "Auto implementors",
2791 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2793 write_loading_content(w, "</div>");
2799 "<script type=\"text/javascript\" \
2800 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2802 root_path = vec![".."; cx.current.len()].join("/"),
2803 path = if it.def_id.is_local() {
2804 cx.current.join("/")
2806 let (ref path, _) = cache.external_paths[&it.def_id];
2807 path[..path.len() - 1].join("/")
2810 name = *it.name.as_ref().unwrap()
2814 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2815 use crate::formats::item_type::ItemType::*;
2817 let name = it.name.as_ref().unwrap();
2818 let ty = match it.type_() {
2819 Typedef | AssocType => AssocType,
2823 let anchor = format!("#{}.{}", ty, name);
2825 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2826 AssocItemLink::Anchor(None) => anchor,
2827 AssocItemLink::GotoSource(did, _) => {
2828 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2837 _default: Option<&String>,
2838 link: AssocItemLink<'_>,
2843 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2845 it.visibility.print_with_space(),
2846 naive_assoc_href(it, link),
2847 it.name.as_ref().unwrap(),
2855 bounds: &[clean::GenericBound],
2856 default: Option<&clean::Type>,
2857 link: AssocItemLink<'_>,
2862 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2864 naive_assoc_href(it, link),
2865 it.name.as_ref().unwrap()
2867 if !bounds.is_empty() {
2868 write!(w, ": {}", print_generic_bounds(bounds))
2870 if let Some(default) = default {
2871 write!(w, " = {}", default.print())
2875 fn render_stability_since_raw(
2878 const_ver: Option<&str>,
2879 containing_ver: Option<&str>,
2880 containing_const_ver: Option<&str>,
2882 let ver = ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2884 let const_ver = const_ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2886 if let Some(v) = ver {
2887 if let Some(cv) = const_ver {
2888 if const_ver != containing_const_ver {
2891 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2894 } else if ver != containing_ver {
2897 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2902 if ver != containing_ver {
2905 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2913 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2914 render_stability_since_raw(
2916 item.stable_since().as_deref(),
2917 item.const_stable_since().as_deref(),
2918 containing_item.stable_since().as_deref(),
2919 containing_item.const_stable_since().as_deref(),
2923 fn render_assoc_item(
2926 link: AssocItemLink<'_>,
2932 header: hir::FnHeader,
2933 g: &clean::Generics,
2935 link: AssocItemLink<'_>,
2938 let name = meth.name.as_ref().unwrap();
2939 let anchor = format!("#{}.{}", meth.type_(), name);
2940 let href = match link {
2941 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2942 AssocItemLink::Anchor(None) => anchor,
2943 AssocItemLink::GotoSource(did, provided_methods) => {
2944 // We're creating a link from an impl-item to the corresponding
2945 // trait-item and need to map the anchored type accordingly.
2946 let ty = if provided_methods.contains(name) {
2952 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2955 let mut header_len = format!(
2956 "{}{}{}{}{}{:#}fn {}{:#}",
2957 meth.visibility.print_with_space(),
2958 header.constness.print_with_space(),
2959 header.asyncness.print_with_space(),
2960 header.unsafety.print_with_space(),
2961 print_default_space(meth.is_default()),
2962 print_abi_with_space(header.abi),
2967 let (indent, end_newline) = if parent == ItemType::Trait {
2973 render_attributes(w, meth, false);
2976 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
2977 {generics}{decl}{spotlight}{where_clause}",
2978 if parent == ItemType::Trait { " " } else { "" },
2979 meth.visibility.print_with_space(),
2980 header.constness.print_with_space(),
2981 header.asyncness.print_with_space(),
2982 header.unsafety.print_with_space(),
2983 print_default_space(meth.is_default()),
2984 print_abi_with_space(header.abi),
2987 generics = g.print(),
2988 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
2989 spotlight = spotlight_decl(&d),
2990 where_clause = WhereClause { gens: g, indent, end_newline }
2994 clean::StrippedItem(..) => {}
2995 clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2996 clean::MethodItem(ref m, _) => {
2997 method(w, item, m.header, &m.generics, &m.decl, link, parent)
2999 clean::AssocConstItem(ref ty, ref default) => assoc_const(
3005 if parent == ItemType::Trait { " " } else { "" },
3007 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3013 if parent == ItemType::Trait { " " } else { "" },
3015 _ => panic!("render_assoc_item called on non-associated-item"),
3019 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
3020 wrap_into_docblock(w, |w| {
3021 write!(w, "<pre class=\"rust struct\">");
3022 render_attributes(w, it, true);
3023 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
3027 document(w, cx, it, None);
3031 .filter_map(|f| match f.kind {
3032 clean::StructFieldItem(ref ty) => Some((f, ty)),
3036 if let doctree::Plain = s.struct_type {
3037 if fields.peek().is_some() {
3040 "<h2 id=\"fields\" class=\"fields small-section-header\">
3041 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3042 document_non_exhaustive_header(it)
3044 document_non_exhaustive(w, it);
3045 for (field, ty) in fields {
3046 let id = cx.derive_id(format!(
3048 ItemType::StructField,
3049 field.name.as_ref().unwrap()
3053 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3054 <a href=\"#{id}\" class=\"anchor field\"></a>\
3055 <code>{name}: {ty}</code>\
3057 item_type = ItemType::StructField,
3059 name = field.name.as_ref().unwrap(),
3062 document(w, cx, field, Some(it));
3066 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3069 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
3070 wrap_into_docblock(w, |w| {
3071 write!(w, "<pre class=\"rust union\">");
3072 render_attributes(w, it, true);
3073 render_union(w, it, Some(&s.generics), &s.fields, "", true);
3077 document(w, cx, it, None);
3081 .filter_map(|f| match f.kind {
3082 clean::StructFieldItem(ref ty) => Some((f, ty)),
3086 if fields.peek().is_some() {
3089 "<h2 id=\"fields\" class=\"fields small-section-header\">
3090 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3092 for (field, ty) in fields {
3093 let name = field.name.as_ref().expect("union field name");
3094 let id = format!("{}.{}", ItemType::StructField, name);
3097 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3098 <a href=\"#{id}\" class=\"anchor field\"></a>\
3099 <code>{name}: {ty}</code>\
3103 shortty = ItemType::StructField,
3106 if let Some(stability_class) = field.stability_class() {
3107 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3109 document(w, cx, field, Some(it));
3112 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3115 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
3116 wrap_into_docblock(w, |w| {
3117 write!(w, "<pre class=\"rust enum\">");
3118 render_attributes(w, it, true);
3122 it.visibility.print_with_space(),
3123 it.name.as_ref().unwrap(),
3125 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
3127 if e.variants.is_empty() && !e.variants_stripped {
3131 for v in &e.variants {
3133 let name = v.name.as_ref().unwrap();
3135 clean::VariantItem(ref var) => match var.kind {
3136 clean::VariantKind::CLike => write!(w, "{}", name),
3137 clean::VariantKind::Tuple(ref tys) => {
3138 write!(w, "{}(", name);
3139 for (i, ty) in tys.iter().enumerate() {
3141 write!(w, ", ")
3143 write!(w, "{}", ty.print());
3147 clean::VariantKind::Struct(ref s) => {
3148 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
3151 _ => unreachable!(),
3156 if e.variants_stripped {
3157 write!(w, " // some variants omitted\n");
3164 document(w, cx, it, None);
3165 if !e.variants.is_empty() {
3168 "<h2 id=\"variants\" class=\"variants small-section-header\">
3169 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3170 document_non_exhaustive_header(it)
3172 document_non_exhaustive(w, it);
3173 for variant in &e.variants {
3175 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3178 "<div id=\"{id}\" class=\"variant small-section-header\">\
3179 <a href=\"#{id}\" class=\"anchor field\"></a>\
3182 name = variant.name.as_ref().unwrap()
3184 if let clean::VariantItem(ref var) = variant.kind {
3185 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3187 for (i, ty) in tys.iter().enumerate() {
3189 write!(w, ", ");
3191 write!(w, "{}", ty.print());
3196 write!(w, "</code></div>");
3197 document(w, cx, variant, Some(it));
3198 document_non_exhaustive(w, variant);
3200 use crate::clean::{Variant, VariantKind};
3201 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.kind {
3202 let variant_id = cx.derive_id(format!(
3205 variant.name.as_ref().unwrap()
3207 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3210 "<h3>Fields of <b>{name}</b></h3><div>",
3211 name = variant.name.as_ref().unwrap()
3213 for field in &s.fields {
3214 use crate::clean::StructFieldItem;
3215 if let StructFieldItem(ref ty) = field.kind {
3216 let id = cx.derive_id(format!(
3217 "variant.{}.field.{}",
3218 variant.name.as_ref().unwrap(),
3219 field.name.as_ref().unwrap()
3223 "<span id=\"{id}\" class=\"variant small-section-header\">\
3224 <a href=\"#{id}\" class=\"anchor field\"></a>\
3225 <code>{f}: {t}</code>\
3228 f = field.name.as_ref().unwrap(),
3231 document(w, cx, field, Some(variant));
3234 write!(w, "</div></div>");
3236 render_stability_since(w, variant, it);
3239 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3242 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3249 sym::non_exhaustive,
3252 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3253 // left padding. For example:
3255 // #[foo] <----- "top" attribute
3257 // #[bar] <---- not "top" attribute
3260 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3265 .filter_map(|attr| {
3266 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3267 Some(pprust::attribute_to_string(&attr))
3274 if !attrs.is_empty() {
3277 "<span class=\"docblock attributes{}\">{}</span>",
3278 if top { " top-attr" } else { "" },
3287 g: Option<&clean::Generics>,
3288 ty: doctree::StructType,
3289 fields: &[clean::Item],
3296 it.visibility.print_with_space(),
3297 if structhead { "struct " } else { "" },
3298 it.name.as_ref().unwrap()
3300 if let Some(g) = g {
3301 write!(w, "{}", g.print())
3305 if let Some(g) = g {
3306 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3308 let mut has_visible_fields = false;
3310 for field in fields {
3311 if let clean::StructFieldItem(ref ty) = field.kind {
3316 field.visibility.print_with_space(),
3317 field.name.as_ref().unwrap(),
3320 has_visible_fields = true;
3324 if has_visible_fields {
3325 if it.has_stripped_fields().unwrap() {
3326 write!(w, "\n{} // some fields omitted", tab);
3328 write!(w, "\n{}", tab);
3329 } else if it.has_stripped_fields().unwrap() {
3330 // If there are no visible fields we can just display
3331 // `{ /* fields omitted */ }` to save space.
3332 write!(w, " /* fields omitted */ ");
3338 for (i, field) in fields.iter().enumerate() {
3343 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3344 clean::StructFieldItem(ref ty) => {
3345 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3347 _ => unreachable!(),
3351 if let Some(g) = g {
3352 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3357 // Needed for PhantomData.
3358 if let Some(g) = g {
3359 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3369 g: Option<&clean::Generics>,
3370 fields: &[clean::Item],
3377 it.visibility.print_with_space(),
3378 if structhead { "union " } else { "" },
3379 it.name.as_ref().unwrap()
3381 if let Some(g) = g {
3382 write!(w, "{}", g.print());
3383 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3386 write!(w, " {{\n{}", tab);
3387 for field in fields {
3388 if let clean::StructFieldItem(ref ty) = field.kind {
3392 field.visibility.print_with_space(),
3393 field.name.as_ref().unwrap(),
3400 if it.has_stripped_fields().unwrap() {
3401 write!(w, " // some fields omitted\n{}", tab);
3406 #[derive(Copy, Clone)]
3407 enum AssocItemLink<'a> {
3408 Anchor(Option<&'a str>),
3409 GotoSource(DefId, &'a FxHashSet<String>),
3412 impl<'a> AssocItemLink<'a> {
3413 fn anchor(&self, id: &'a String) -> Self {
3415 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3416 ref other => *other,
3421 fn render_assoc_items(
3424 containing_item: &clean::Item,
3426 what: AssocItemRender<'_>,
3430 "Documenting associated items of {}",
3431 containing_item.name.as_deref().unwrap_or_default()
3433 let v = match cache.impls.get(&it) {
3437 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3438 if !non_trait.is_empty() {
3439 let render_mode = match what {
3440 AssocItemRender::All => {
3443 "<h2 id=\"implementations\" class=\"small-section-header\">\
3444 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3449 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3452 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
3453 Methods from {}<Target = {}>\
3454 <a href=\"#deref-methods\" class=\"anchor\"></a>\
3459 RenderMode::ForDeref { mut_: deref_mut_ }
3462 for i in &non_trait {
3468 AssocItemLink::Anchor(None),
3470 containing_item.stable_since().as_deref(),
3471 containing_item.const_stable_since().as_deref(),
3481 if let AssocItemRender::DerefFor { .. } = what {
3484 if !traits.is_empty() {
3486 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3487 if let Some(impl_) = deref_impl {
3489 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3490 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3493 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3494 traits.iter().partition(|t| t.inner_impl().synthetic);
3495 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3496 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3498 let mut impls = Buffer::empty_from(&w);
3499 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3500 let impls = impls.into_inner();
3501 if !impls.is_empty() {
3504 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3505 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3507 <div id=\"trait-implementations-list\">{}</div>",
3512 if !synthetic.is_empty() {
3515 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3516 Auto Trait Implementations\
3517 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3519 <div id=\"synthetic-implementations-list\">"
3521 render_impls(cx, w, &synthetic, containing_item, cache);
3522 write!(w, "</div>");
3525 if !blanket_impl.is_empty() {
3528 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3529 Blanket Implementations\
3530 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3532 <div id=\"blanket-implementations-list\">"
3534 render_impls(cx, w, &blanket_impl, containing_item, cache);
3535 write!(w, "</div>");
3540 fn render_deref_methods(
3544 container_item: &clean::Item,
3548 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3549 let (target, real_target) = impl_
3553 .find_map(|item| match item.kind {
3554 clean::TypedefItem(ref t, true) => Some(match *t {
3555 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3556 _ => (&t.type_, &t.type_),
3560 .expect("Expected associated type binding");
3562 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3563 if let Some(did) = target.def_id() {
3564 render_assoc_items(w, cx, container_item, did, what, cache);
3566 if let Some(prim) = target.primitive_type() {
3567 if let Some(&did) = cache.primitive_locations.get(&prim) {
3568 render_assoc_items(w, cx, container_item, did, what, cache);
3574 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3575 let self_type_opt = match item.kind {
3576 clean::MethodItem(ref method, _) => method.decl.self_type(),
3577 clean::TyMethodItem(ref method) => method.decl.self_type(),
3581 if let Some(self_ty) = self_type_opt {
3582 let (by_mut_ref, by_box, by_value) = match self_ty {
3583 SelfTy::SelfBorrowed(_, mutability)
3584 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3585 (mutability == Mutability::Mut, false, false)
3587 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3588 (false, Some(did) == cache().owned_box_did, false)
3590 SelfTy::SelfValue => (false, false, true),
3591 _ => (false, false, false),
3594 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3600 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3601 let mut out = Buffer::html();
3602 let mut trait_ = String::new();
3604 if let Some(did) = decl.output.def_id() {
3606 if let Some(impls) = c.impls.get(&did) {
3608 let impl_ = i.inner_impl();
3609 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3611 out.push_str(&format!(
3612 "<h3 class=\"notable\">Notable traits for {}</h3>\
3613 <code class=\"content\">",
3616 trait_.push_str(&impl_.for_.print().to_string());
3619 //use the "where" class here to make it small
3620 out.push_str(&format!(
3621 "<span class=\"where fmt-newline\">{}</span>",
3624 let t_did = impl_.trait_.def_id().unwrap();
3625 for it in &impl_.items {
3626 if let clean::TypedefItem(ref tydef, _) = it.kind {
3627 out.push_str("<span class=\"where fmt-newline\"> ");
3633 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3636 out.push_str(";</span>");
3644 if !out.is_empty() {
3647 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3648 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3650 out.push_str("</code></span></div></span></span>");
3660 parent: &clean::Item,
3661 link: AssocItemLink<'_>,
3662 render_mode: RenderMode,
3663 outer_version: Option<&str>,
3664 outer_const_version: Option<&str>,
3665 show_def_docs: bool,
3666 use_absolute: Option<bool>,
3667 is_on_foreign_type: bool,
3668 show_default_items: bool,
3669 // This argument is used to reference same type with different paths to avoid duplication
3670 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3674 let traits = &cache.traits;
3675 let trait_ = i.trait_did().map(|did| &traits[&did]);
3677 if render_mode == RenderMode::Normal {
3678 let id = cx.derive_id(match i.inner_impl().trait_ {
3680 if is_on_foreign_type {
3681 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3683 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3686 None => "impl".to_string(),
3688 let aliases = if aliases.is_empty() {
3691 format!(" aliases=\"{}\"", aliases.join(","))
3693 if let Some(use_absolute) = use_absolute {
3694 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3695 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3697 for it in &i.inner_impl().items {
3698 if let clean::TypedefItem(ref tydef, _) = it.kind {
3699 write!(w, "<span class=\"where fmt-newline\"> ");
3700 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3701 write!(w, ";</span>");
3705 write!(w, "</code>");
3709 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3712 i.inner_impl().print()
3715 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3716 render_stability_since_raw(
3718 i.impl_item.stable_since().as_deref(),
3719 i.impl_item.const_stable_since().as_deref(),
3721 outer_const_version,
3723 write_srclink(cx, &i.impl_item, w, cache);
3726 if trait_.is_some() {
3727 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3728 write!(w, "<div class=\"item-info\">{}</div>", portability);
3732 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3733 let mut ids = cx.id_map.borrow_mut();
3736 "<div class=\"docblock\">{}</div>",
3739 &i.impl_item.links(),
3743 &cx.shared.playground
3754 parent: &clean::Item,
3755 link: AssocItemLink<'_>,
3756 render_mode: RenderMode,
3757 is_default_item: bool,
3758 outer_version: Option<&str>,
3759 outer_const_version: Option<&str>,
3760 trait_: Option<&clean::Trait>,
3761 show_def_docs: bool,
3764 let item_type = item.type_();
3765 let name = item.name.as_ref().unwrap();
3767 let render_method_item = match render_mode {
3768 RenderMode::Normal => true,
3769 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3772 let (is_hidden, extra_class) =
3773 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3781 clean::MethodItem(..) | clean::TyMethodItem(_) => {
3782 // Only render when the method is not static or we allow static methods
3783 if render_method_item {
3784 let id = cx.derive_id(format!("{}.{}", item_type, name));
3785 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3786 write!(w, "<code>");
3787 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3788 write!(w, "</code>");
3789 render_stability_since_raw(
3791 item.stable_since().as_deref(),
3792 item.const_stable_since().as_deref(),
3794 outer_const_version,
3796 write_srclink(cx, item, w, cache);
3800 clean::TypedefItem(ref tydef, _) => {
3801 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3802 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3803 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3804 write!(w, "</code></h4>");
3806 clean::AssocConstItem(ref ty, ref default) => {
3807 let id = cx.derive_id(format!("{}.{}", item_type, name));
3808 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3809 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3810 write!(w, "</code>");
3811 render_stability_since_raw(
3813 item.stable_since().as_deref(),
3814 item.const_stable_since().as_deref(),
3816 outer_const_version,
3818 write_srclink(cx, item, w, cache);
3821 clean::AssocTypeItem(ref bounds, ref default) => {
3822 let id = cx.derive_id(format!("{}.{}", item_type, name));
3823 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3824 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3825 write!(w, "</code></h4>");
3827 clean::StrippedItem(..) => return,
3828 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3831 if render_method_item {
3832 if !is_default_item {
3833 if let Some(t) = trait_ {
3834 // The trait item may have been stripped so we might not
3835 // find any documentation or stability for it.
3836 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3837 // We need the stability of the item from the trait
3838 // because impls can't have a stability.
3839 if item.doc_value().is_some() {
3840 document_item_info(w, cx, it, is_hidden, Some(parent));
3841 document_full(w, item, cx, "", is_hidden);
3843 // In case the item isn't documented,
3844 // provide short documentation from the trait.
3858 document_item_info(w, cx, item, is_hidden, Some(parent));
3860 document_full(w, item, cx, "", is_hidden);
3864 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3869 write!(w, "<div class=\"impl-items\">");
3870 for trait_item in &i.inner_impl().items {
3875 if trait_.is_some() { &i.impl_item } else { parent },
3880 outer_const_version,
3887 fn render_default_items(
3892 parent: &clean::Item,
3893 render_mode: RenderMode,
3894 outer_version: Option<&str>,
3895 outer_const_version: Option<&str>,
3896 show_def_docs: bool,
3899 for trait_item in &t.items {
3900 let n = trait_item.name.clone();
3901 if i.items.iter().any(|m| m.name == n) {
3904 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3905 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3916 outer_const_version,
3924 // If we've implemented a trait, then also emit documentation for all
3925 // default items which weren't overridden in the implementation block.
3926 // We don't emit documentation for default items if they appear in the
3927 // Implementations on Foreign Types or Implementors sections.
3928 if show_default_items {
3929 if let Some(t) = trait_ {
3930 render_default_items(
3938 outer_const_version,
3944 write!(w, "</div>");
3951 t: &clean::OpaqueTy,
3954 write!(w, "<pre class=\"rust opaque\">");
3955 render_attributes(w, it, false);
3958 "type {}{}{where_clause} = impl {bounds};</pre>",
3959 it.name.as_ref().unwrap(),
3961 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3962 bounds = bounds(&t.bounds, false)
3965 document(w, cx, it, None);
3967 // Render any items associated directly to this alias, as otherwise they
3968 // won't be visible anywhere in the docs. It would be nice to also show
3969 // associated items from the aliased type (see discussion in #32077), but
3970 // we need #14072 to make sense of the generics.
3971 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3974 fn item_trait_alias(
3978 t: &clean::TraitAlias,
3981 write!(w, "<pre class=\"rust trait-alias\">");
3982 render_attributes(w, it, false);
3985 "trait {}{}{} = {};</pre>",
3986 it.name.as_ref().unwrap(),
3988 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3989 bounds(&t.bounds, true)
3992 document(w, cx, it, None);
3994 // Render any items associated directly to this alias, as otherwise they
3995 // won't be visible anywhere in the docs. It would be nice to also show
3996 // associated items from the aliased type (see discussion in #32077), but
3997 // we need #14072 to make sense of the generics.
3998 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4001 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
4002 write!(w, "<pre class=\"rust typedef\">");
4003 render_attributes(w, it, false);
4006 "type {}{}{where_clause} = {type_};</pre>",
4007 it.name.as_ref().unwrap(),
4009 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4010 type_ = t.type_.print()
4013 document(w, cx, it, None);
4015 // Render any items associated directly to this alias, as otherwise they
4016 // won't be visible anywhere in the docs. It would be nice to also show
4017 // associated items from the aliased type (see discussion in #32077), but
4018 // we need #14072 to make sense of the generics.
4019 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4022 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4023 writeln!(w, "<pre class=\"rust foreigntype\">extern {{");
4024 render_attributes(w, it, false);
4027 " {}type {};\n}}</pre>",
4028 it.visibility.print_with_space(),
4029 it.name.as_ref().unwrap(),
4032 document(w, cx, it, None);
4034 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4037 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
4038 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4042 || it.is_primitive()
4050 "<p class=\"location\">{}{}</p>",
4052 clean::StructItem(..) => "Struct ",
4053 clean::TraitItem(..) => "Trait ",
4054 clean::PrimitiveItem(..) => "Primitive Type ",
4055 clean::UnionItem(..) => "Union ",
4056 clean::EnumItem(..) => "Enum ",
4057 clean::TypedefItem(..) => "Type Definition ",
4058 clean::ForeignTypeItem => "Foreign Type ",
4059 clean::ModuleItem(..) =>
4067 it.name.as_ref().unwrap()
4072 if let Some(ref version) = cache.crate_version {
4075 "<div class=\"block version\">\
4083 write!(buffer, "<div class=\"sidebar-elems\">");
4087 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4088 it.name.as_ref().expect("crates always have a name")
4092 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
4093 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
4094 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
4095 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
4096 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
4097 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
4098 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4099 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
4103 // The sidebar is designed to display sibling functions, modules and
4104 // other miscellaneous information. since there are lots of sibling
4105 // items (and that causes quadratic growth in large modules),
4106 // we refactor common parts into a shared JavaScript file per module.
4107 // still, we don't move everything into JS because we want to preserve
4108 // as much HTML as possible in order to allow non-JS-enabled browsers
4109 // to navigate the documentation (though slightly inefficiently).
4111 write!(buffer, "<p class=\"location\">");
4112 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4114 write!(buffer, "::<wbr>");
4118 "<a href=\"{}index.html\">{}</a>",
4119 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4123 write!(buffer, "</p>");
4125 // Sidebar refers to the enclosing module, not this module.
4126 let relpath = if it.is_mod() { "../" } else { "" };
4129 "<script>window.sidebarCurrent = {{\
4132 relpath: \"{path}\"\
4134 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4139 // There is no sidebar-items.js beyond the crate root path
4140 // FIXME maybe dynamic crate loading can be merged here
4142 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4144 // Closes sidebar-elems div.
4145 write!(buffer, "</div>");
4148 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4149 if used_links.insert(url.clone()) {
4153 while !used_links.insert(format!("{}-{}", url, add)) {
4156 format!("{}-{}", url, add)
4162 used_links: &mut FxHashSet<String>,
4167 .filter_map(|item| match item.name {
4168 Some(ref name) if !name.is_empty() && item.is_method() => {
4169 if !for_deref || should_render_item(item, deref_mut) {
4171 "<a href=\"#{}\">{}</a>",
4172 get_next_url(used_links, format!("method.{}", name)),
4181 .collect::<Vec<_>>()
4184 // The point is to url encode any potential character from a type with genericity.
4185 fn small_url_encode(s: &str) -> String {
4186 s.replace("<", "%3C")
4187 .replace(">", "%3E")
4188 .replace(" ", "%20")
4189 .replace("?", "%3F")
4190 .replace("'", "%27")
4191 .replace("&", "%26")
4192 .replace(",", "%2C")
4193 .replace(":", "%3A")
4194 .replace(";", "%3B")
4195 .replace("[", "%5B")
4196 .replace("]", "%5D")
4197 .replace("\"", "%22")
4200 fn sidebar_assoc_items(it: &clean::Item) -> String {
4201 let mut out = String::new();
4203 if let Some(v) = c.impls.get(&it.def_id) {
4204 let mut used_links = FxHashSet::default();
4207 let used_links_bor = &mut used_links;
4210 .filter(|i| i.inner_impl().trait_.is_none())
4211 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4212 .collect::<Vec<_>>();
4213 if !ret.is_empty() {
4214 // We want links' order to be reproducible so we don't use unstable sort.
4216 out.push_str(&format!(
4217 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4218 <div class=\"sidebar-links\">{}</div>",
4224 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4225 if let Some(impl_) = v
4227 .filter(|i| i.inner_impl().trait_.is_some())
4228 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4230 if let Some((target, real_target)) =
4231 impl_.inner_impl().items.iter().find_map(|item| match item.kind {
4232 clean::TypedefItem(ref t, true) => Some(match *t {
4233 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4234 _ => (&t.type_, &t.type_),
4241 .filter(|i| i.inner_impl().trait_.is_some())
4242 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4243 let inner_impl = target
4247 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4248 .and_then(|did| c.impls.get(&did));
4249 if let Some(impls) = inner_impl {
4250 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4251 out.push_str(&format!(
4252 "Methods from {}<Target={}>",
4255 impl_.inner_impl().trait_.as_ref().unwrap().print()
4257 Escape(&format!("{:#}", real_target.print()))
4259 out.push_str("</a>");
4262 .filter(|i| i.inner_impl().trait_.is_none())
4264 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4266 .collect::<Vec<_>>();
4267 // We want links' order to be reproducible so we don't use unstable sort.
4269 if !ret.is_empty() {
4270 out.push_str(&format!(
4271 "<div class=\"sidebar-links\">{}</div>",
4278 let format_impls = |impls: Vec<&Impl>| {
4279 let mut links = FxHashSet::default();
4284 let is_negative_impl = is_negative_impl(i.inner_impl());
4285 if let Some(ref i) = i.inner_impl().trait_ {
4286 let i_display = format!("{:#}", i.print());
4287 let out = Escape(&i_display);
4288 let encoded = small_url_encode(&format!("{:#}", i.print()));
4289 let generated = format!(
4290 "<a href=\"#impl-{}\">{}{}</a>",
4292 if is_negative_impl { "!" } else { "" },
4295 if links.insert(generated.clone()) { Some(generated) } else { None }
4300 .collect::<Vec<String>>();
4305 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4306 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4307 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4309 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4311 let concrete_format = format_impls(concrete);
4312 let synthetic_format = format_impls(synthetic);
4313 let blanket_format = format_impls(blanket_impl);
4315 if !concrete_format.is_empty() {
4317 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4318 Trait Implementations</a>",
4320 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4323 if !synthetic_format.is_empty() {
4325 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4326 Auto Trait Implementations</a>",
4328 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4331 if !blanket_format.is_empty() {
4333 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4334 Blanket Implementations</a>",
4336 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4344 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4345 let mut sidebar = String::new();
4346 let fields = get_struct_fields_name(&s.fields);
4348 if !fields.is_empty() {
4349 if let doctree::Plain = s.struct_type {
4350 sidebar.push_str(&format!(
4351 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4352 <div class=\"sidebar-links\">{}</div>",
4358 sidebar.push_str(&sidebar_assoc_items(it));
4360 if !sidebar.is_empty() {
4361 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4365 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4366 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4369 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4371 clean::ItemKind::ImplItem(ref i) => {
4372 if let Some(ref trait_) = i.trait_ {
4374 format!("{:#}", i.for_.print()),
4375 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4385 fn is_negative_impl(i: &clean::Impl) -> bool {
4386 i.polarity == Some(clean::ImplPolarity::Negative)
4389 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4390 let mut sidebar = String::new();
4395 .filter_map(|m| match m.name {
4396 Some(ref name) if m.is_associated_type() => {
4397 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4401 .collect::<Vec<_>>();
4405 .filter_map(|m| match m.name {
4406 Some(ref name) if m.is_associated_const() => {
4407 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4411 .collect::<Vec<_>>();
4412 let mut required = t
4415 .filter_map(|m| match m.name {
4416 Some(ref name) if m.is_ty_method() => {
4417 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4421 .collect::<Vec<String>>();
4422 let mut provided = t
4425 .filter_map(|m| match m.name {
4426 Some(ref name) if m.is_method() => {
4427 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4431 .collect::<Vec<String>>();
4433 if !types.is_empty() {
4435 sidebar.push_str(&format!(
4436 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4437 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4441 if !consts.is_empty() {
4443 sidebar.push_str(&format!(
4444 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4445 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4449 if !required.is_empty() {
4451 sidebar.push_str(&format!(
4452 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4453 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4457 if !provided.is_empty() {
4459 sidebar.push_str(&format!(
4460 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4461 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4468 if let Some(implementors) = c.implementors.get(&it.def_id) {
4469 let mut res = implementors
4471 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4472 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4473 .collect::<Vec<_>>();
4475 if !res.is_empty() {
4477 sidebar.push_str(&format!(
4478 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4479 Implementations on Foreign Types</a>\
4480 <div class=\"sidebar-links\">{}</div>",
4482 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4483 .collect::<Vec<_>>()
4489 sidebar.push_str(&sidebar_assoc_items(it));
4491 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4494 "<a class=\"sidebar-title\" \
4495 href=\"#synthetic-implementors\">Auto Implementors</a>",
4499 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4502 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4503 let sidebar = sidebar_assoc_items(it);
4505 if !sidebar.is_empty() {
4506 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4510 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4511 let sidebar = sidebar_assoc_items(it);
4513 if !sidebar.is_empty() {
4514 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4518 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4519 let mut fields = fields
4521 .filter(|f| if let clean::StructFieldItem(..) = f.kind { true } else { false })
4522 .filter_map(|f| match f.name {
4524 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4528 .collect::<Vec<_>>();
4533 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4534 let mut sidebar = String::new();
4535 let fields = get_struct_fields_name(&u.fields);
4537 if !fields.is_empty() {
4538 sidebar.push_str(&format!(
4539 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4540 <div class=\"sidebar-links\">{}</div>",
4545 sidebar.push_str(&sidebar_assoc_items(it));
4547 if !sidebar.is_empty() {
4548 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4552 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4553 let mut sidebar = String::new();
4555 let mut variants = e
4558 .filter_map(|v| match v.name {
4559 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4562 .collect::<Vec<_>>();
4563 if !variants.is_empty() {
4564 variants.sort_unstable();
4565 sidebar.push_str(&format!(
4566 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4567 <div class=\"sidebar-links\">{}</div>",
4572 sidebar.push_str(&sidebar_assoc_items(it));
4574 if !sidebar.is_empty() {
4575 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4579 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4581 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4582 ItemType::Module => ("modules", "Modules"),
4583 ItemType::Struct => ("structs", "Structs"),
4584 ItemType::Union => ("unions", "Unions"),
4585 ItemType::Enum => ("enums", "Enums"),
4586 ItemType::Function => ("functions", "Functions"),
4587 ItemType::Typedef => ("types", "Type Definitions"),
4588 ItemType::Static => ("statics", "Statics"),
4589 ItemType::Constant => ("constants", "Constants"),
4590 ItemType::Trait => ("traits", "Traits"),
4591 ItemType::Impl => ("impls", "Implementations"),
4592 ItemType::TyMethod => ("tymethods", "Type Methods"),
4593 ItemType::Method => ("methods", "Methods"),
4594 ItemType::StructField => ("fields", "Struct Fields"),
4595 ItemType::Variant => ("variants", "Variants"),
4596 ItemType::Macro => ("macros", "Macros"),
4597 ItemType::Primitive => ("primitives", "Primitive Types"),
4598 ItemType::AssocType => ("associated-types", "Associated Types"),
4599 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4600 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4601 ItemType::Keyword => ("keywords", "Keywords"),
4602 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4603 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4604 ItemType::ProcDerive => ("derives", "Derive Macros"),
4605 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4609 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4610 let mut sidebar = String::new();
4612 if items.iter().any(|it| {
4613 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4615 sidebar.push_str(&format!(
4616 "<li><a href=\"#{id}\">{name}</a></li>",
4622 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4623 // to print its headings
4625 ItemType::Primitive,
4639 ItemType::StructField,
4641 ItemType::AssocType,
4642 ItemType::AssocConst,
4643 ItemType::ForeignType,
4646 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4647 let (short, name) = item_ty_to_strs(&myty);
4648 sidebar.push_str(&format!(
4649 "<li><a href=\"#{id}\">{name}</a></li>",
4656 if !sidebar.is_empty() {
4657 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4661 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4662 let sidebar = sidebar_assoc_items(it);
4663 if !sidebar.is_empty() {
4664 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4668 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4669 wrap_into_docblock(w, |w| {
4670 w.write_str(&highlight::render_with_highlighting(
4677 document(w, cx, it, None)
4680 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4681 let name = it.name.as_ref().expect("proc-macros always have names");
4683 MacroKind::Bang => {
4684 write!(w, "<pre class=\"rust macro\">");
4685 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4686 write!(w, "</pre>");
4688 MacroKind::Attr => {
4689 write!(w, "<pre class=\"rust attr\">");
4690 write!(w, "#[{}]", name);
4691 write!(w, "</pre>");
4693 MacroKind::Derive => {
4694 write!(w, "<pre class=\"rust derive\">");
4695 write!(w, "#[derive({})]", name);
4696 if !m.helpers.is_empty() {
4697 writeln!(w, "\n{{");
4698 writeln!(w, " // Attributes available to this derive:");
4699 for attr in &m.helpers {
4700 writeln!(w, " #[{}]", attr);
4704 write!(w, "</pre>");
4707 document(w, cx, it, None)
4710 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4711 document(w, cx, it, None);
4712 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4715 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4716 document(w, cx, it, None)
4719 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4721 fn make_item_keywords(it: &clean::Item) -> String {
4722 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4725 /// Returns a list of all paths used in the type.
4726 /// This is used to help deduplicate imported impls
4727 /// for reexported types. If any of the contained
4728 /// types are re-exported, we don't use the corresponding
4729 /// entry from the js file, as inlining will have already
4730 /// picked up the impl
4731 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4732 let mut out = Vec::new();
4733 let mut visited = FxHashSet::default();
4734 let mut work = VecDeque::new();
4735 let cache = cache();
4737 work.push_back(first_ty);
4739 while let Some(ty) = work.pop_front() {
4740 if !visited.insert(ty.clone()) {
4745 clean::Type::ResolvedPath { did, .. } => {
4746 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4747 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4749 if let Some(path) = fqp {
4750 out.push(path.join("::"));
4753 clean::Type::Tuple(tys) => {
4754 work.extend(tys.into_iter());
4756 clean::Type::Slice(ty) => {
4757 work.push_back(*ty);
4759 clean::Type::Array(ty, _) => {
4760 work.push_back(*ty);
4762 clean::Type::RawPointer(_, ty) => {
4763 work.push_back(*ty);
4765 clean::Type::BorrowedRef { type_, .. } => {
4766 work.push_back(*type_);
4768 clean::Type::QPath { self_type, trait_, .. } => {
4769 work.push_back(*self_type);
4770 work.push_back(*trait_);