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 mut iter = filename.splitn(2, '.');
171 let base = iter.next().unwrap();
172 let ext = iter.next().unwrap();
173 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext,);
174 self.dst.join(&filename)
179 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
180 let mut dirs = self.created_dirs.borrow_mut();
181 if !dirs.contains(dst) {
182 try_err!(self.fs.create_dir_all(dst), dst);
183 dirs.insert(dst.to_path_buf());
189 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
190 /// `collapsed_doc_value` of the given item.
191 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
193 item.collapsed_doc_value().map(|s| s.into())
195 item.doc_value().map(|s| s.into())
200 // Helper structs for rendering items/sidebars and carrying along contextual
203 /// Struct representing one entry in the JS search index. These are all emitted
204 /// by hand to a large JS file at the end of cache-creation.
206 crate struct IndexItem {
211 crate parent: Option<DefId>,
212 crate parent_idx: Option<usize>,
213 crate search_type: Option<IndexItemFunctionType>,
216 impl Serialize for IndexItem {
217 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
222 self.parent.is_some(),
223 self.parent_idx.is_some(),
224 "`{}` is missing idx",
228 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
229 .serialize(serializer)
233 /// A type used for the search index.
235 crate struct RenderType {
238 name: Option<String>,
239 generics: Option<Vec<Generic>>,
242 impl Serialize for RenderType {
243 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
247 if let Some(name) = &self.name {
248 let mut seq = serializer.serialize_seq(None)?;
249 if let Some(id) = self.idx {
250 seq.serialize_element(&id)?;
252 seq.serialize_element(&name)?;
254 if let Some(generics) = &self.generics {
255 seq.serialize_element(&generics)?;
259 serializer.serialize_none()
264 /// A type used for the search index.
266 crate struct Generic {
268 defid: Option<DefId>,
272 impl Serialize for Generic {
273 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
277 if let Some(id) = self.idx {
278 serializer.serialize_some(&id)
280 serializer.serialize_some(&self.name)
285 /// Full type of functions/methods in the search index.
287 crate struct IndexItemFunctionType {
288 inputs: Vec<TypeWithKind>,
289 output: Option<Vec<TypeWithKind>>,
292 impl Serialize for IndexItemFunctionType {
293 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
297 // If we couldn't figure out a type, just write `null`.
298 let mut iter = self.inputs.iter();
299 if match self.output {
300 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
301 None => iter.any(|ref i| i.ty.name.is_none()),
303 serializer.serialize_none()
305 let mut seq = serializer.serialize_seq(None)?;
306 seq.serialize_element(&self.inputs)?;
307 if let Some(output) = &self.output {
308 if output.len() > 1 {
309 seq.serialize_element(&output)?;
311 seq.serialize_element(&output[0])?;
320 crate struct TypeWithKind {
325 impl From<(RenderType, TypeKind)> for TypeWithKind {
326 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
327 TypeWithKind { ty: x.0, kind: x.1 }
331 impl Serialize for TypeWithKind {
332 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
336 let mut seq = serializer.serialize_seq(None)?;
337 seq.serialize_element(&self.ty.name)?;
338 let x: ItemType = self.kind.into();
339 seq.serialize_element(&x)?;
344 #[derive(Debug, Clone)]
345 crate struct StylePath {
346 /// The path to the theme
348 /// What the `disabled` attribute should be set to in the HTML tag
349 crate disabled: bool,
352 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
354 crate fn initial_ids() -> Vec<String> {
366 "synthetic-implementors",
368 "synthetic-implementors-list",
374 .map(|id| (String::from(*id)))
378 /// Generates the documentation for `crate` into the directory `dst`
379 impl FormatRenderer for Context {
381 mut krate: clean::Crate,
382 options: RenderOptions,
383 _render_info: RenderInfo,
386 ) -> Result<(Context, clean::Crate), Error> {
387 // need to save a copy of the options for rendering the index page
388 let md_opts = options.clone();
394 sort_modules_alphabetically,
400 generate_search_filter,
405 let src_root = match krate.src {
406 FileName::Real(ref p) => match p.local_path().parent() {
407 Some(p) => p.to_path_buf(),
408 None => PathBuf::new(),
412 // If user passed in `--playground-url` arg, we fill in crate name here
413 let mut playground = None;
414 if let Some(url) = playground_url {
415 playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url });
417 let mut layout = layout::Layout {
419 favicon: String::new(),
422 krate: krate.name.clone(),
423 css_file_extension: extension_css,
424 generate_search_filter,
426 let mut issue_tracker_base_url = None;
427 let mut include_sources = true;
429 // Crawl the crate attributes looking for attributes which control how we're
430 // going to emit HTML
431 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
432 for attr in attrs.lists(sym::doc) {
433 match (attr.name_or_empty(), attr.value_str()) {
434 (sym::html_favicon_url, Some(s)) => {
435 layout.favicon = s.to_string();
437 (sym::html_logo_url, Some(s)) => {
438 layout.logo = s.to_string();
440 (sym::html_playground_url, Some(s)) => {
441 playground = Some(markdown::Playground {
442 crate_name: Some(krate.name.clone()),
446 (sym::issue_tracker_base_url, Some(s)) => {
447 issue_tracker_base_url = Some(s.to_string());
449 (sym::html_no_source, None) if attr.is_word() => {
450 include_sources = false;
456 let (sender, receiver) = channel();
457 let mut scx = SharedContext {
458 collapsed: krate.collapsed,
461 local_sources: Default::default(),
462 issue_tracker_base_url,
464 created_dirs: Default::default(),
465 sort_modules_alphabetically,
469 fs: DocFS::new(sender),
471 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
475 // Add the default themes to the `Vec` of stylepaths
477 // Note that these must be added before `sources::render` is called
478 // so that the resulting source pages are styled
480 // `light.css` is not disabled because it is the stylesheet that stays loaded
481 // by the browser as the theme stylesheet. The theme system (hackily) works by
482 // changing the href to this stylesheet. All other themes are disabled to
483 // prevent rule conflicts
484 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
485 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
486 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
489 scx.ensure_dir(&dst)?;
490 krate = sources::render(&dst, &mut scx, krate)?;
492 // Build our search index
493 let index = build_index(&krate, cache);
495 let cache = Arc::new(cache);
496 let mut cx = Context {
499 render_redirect_pages: false,
500 id_map: Rc::new(RefCell::new(id_map)),
501 shared: Arc::new(scx),
502 all: Rc::new(RefCell::new(AllTypes::new())),
503 errors: Rc::new(receiver),
506 CURRENT_DEPTH.with(|s| s.set(0));
508 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
509 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
510 write_shared(&cx, &krate, index, &md_opts, &cache)?;
511 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
515 fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
516 Arc::get_mut(&mut self.shared).unwrap().fs.close();
517 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
519 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
525 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
526 let final_file = self.dst.join(&krate.name).join("all.html");
527 let settings_file = self.dst.join("settings.html");
528 let crate_name = krate.name.clone();
530 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
531 if !root_path.ends_with('/') {
534 let mut page = layout::Page {
535 title: "List of all items in this crate",
538 static_root_path: self.shared.static_root_path.as_deref(),
539 description: "List of all items in this crate",
540 keywords: BASIC_KEYWORDS,
541 resource_suffix: &self.shared.resource_suffix,
543 static_extra_scripts: &[],
545 let sidebar = if let Some(ref version) = cache.crate_version {
547 "<p class=\"location\">Crate {}</p>\
548 <div class=\"block version\">\
551 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
558 let all = self.all.replace(AllTypes::new());
559 let v = layout::render(
563 |buf: &mut Buffer| all.print(buf),
564 &self.shared.style_files,
566 self.shared.fs.write(&final_file, v.as_bytes())?;
568 // Generating settings page.
569 page.title = "Rustdoc settings";
570 page.description = "Settings of Rustdoc";
571 page.root_path = "./";
573 let mut style_files = self.shared.style_files.clone();
574 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
575 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
576 let v = layout::render(
581 self.shared.static_root_path.as_deref().unwrap_or("./"),
582 &self.shared.resource_suffix,
583 &self.shared.style_files,
587 self.shared.fs.write(&settings_file, v.as_bytes())?;
596 ) -> Result<(), Error> {
597 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
598 // if they contain impls for public types. These modules can also
599 // contain items such as publicly re-exported structures.
601 // External crates will provide links to these structures, so
602 // these modules are recursed into, but not rendered normally
603 // (a flag on the context).
604 if !self.render_redirect_pages {
605 self.render_redirect_pages = item.is_stripped();
607 let scx = &self.shared;
608 self.dst.push(item_name);
609 self.current.push(item_name.to_owned());
611 info!("Recursing into {}", self.dst.display());
613 let buf = self.render_item(item, false, cache);
614 // buf will be empty if the module is stripped and there is no redirect for it
616 self.shared.ensure_dir(&self.dst)?;
617 let joint_dst = self.dst.join("index.html");
618 scx.fs.write(&joint_dst, buf.as_bytes())?;
621 // Render sidebar-items.js used throughout this module.
622 if !self.render_redirect_pages {
623 let module = match item.kind {
624 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
627 let items = self.build_sidebar_items(module);
628 let js_dst = self.dst.join("sidebar-items.js");
629 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
630 scx.fs.write(&js_dst, &v)?;
635 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
636 info!("Recursed; leaving {}", self.dst.display());
638 // Go back to where we were at
644 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
645 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
646 // if they contain impls for public types. These modules can also
647 // contain items such as publicly re-exported structures.
649 // External crates will provide links to these structures, so
650 // these modules are recursed into, but not rendered normally
651 // (a flag on the context).
652 if !self.render_redirect_pages {
653 self.render_redirect_pages = item.is_stripped();
656 let buf = self.render_item(&item, true, cache);
657 // buf will be empty if the item is stripped and there is no redirect for it
659 let name = item.name.as_ref().unwrap();
660 let item_type = item.type_();
661 let file_name = &item_path(item_type, name);
662 self.shared.ensure_dir(&self.dst)?;
663 let joint_dst = self.dst.join(file_name);
664 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
666 if !self.render_redirect_pages {
667 self.all.borrow_mut().append(full_path(self, &item), &item_type);
669 // If the item is a macro, redirect from the old macro URL (with !)
670 // to the new one (without).
671 if item_type == ItemType::Macro {
672 let redir_name = format!("{}.{}!.html", item_type, name);
673 let redir_dst = self.dst.join(redir_name);
674 let v = layout::redirect(file_name);
675 self.shared.fs.write(&redir_dst, v.as_bytes())?;
684 krate: &clean::Crate,
685 search_index: String,
686 options: &RenderOptions,
688 ) -> Result<(), Error> {
689 // Write out the shared files. Note that these are shared among all rustdoc
690 // docs placed in the output directory, so this needs to be a synchronized
691 // operation with respect to all other rustdocs running around.
692 let lock_file = cx.dst.join(".lock");
693 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
695 // Add all the static files. These may already exist, but we just
696 // overwrite them anyway to make sure that they're fresh and up-to-date.
700 cx.path("rustdoc.css"),
701 static_files::RUSTDOC_CSS,
702 options.enable_minification,
706 cx.path("settings.css"),
707 static_files::SETTINGS_CSS,
708 options.enable_minification,
712 cx.path("noscript.css"),
713 static_files::NOSCRIPT_CSS,
714 options.enable_minification,
717 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
718 // then we'll run over the "official" styles.
719 let mut themes: FxHashSet<String> = FxHashSet::default();
721 for entry in &cx.shared.style_files {
722 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
724 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
726 // Handle the official themes
728 "light" => write_minify(
730 cx.path("light.css"),
731 static_files::themes::LIGHT,
732 options.enable_minification,
734 "dark" => write_minify(
737 static_files::themes::DARK,
738 options.enable_minification,
740 "ayu" => write_minify(
743 static_files::themes::AYU,
744 options.enable_minification,
747 // Handle added third-party themes
748 let content = try_err!(fs::read(&entry.path), &entry.path);
751 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
755 themes.insert(theme.to_owned());
758 let write = |p, c| cx.shared.fs.write(p, c);
759 if (*cx.shared).layout.logo.is_empty() {
760 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
762 if (*cx.shared).layout.favicon.is_empty() {
763 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
764 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
765 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
767 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
768 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
769 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
771 let mut themes: Vec<&String> = themes.iter().collect();
773 // To avoid theme switch latencies as much as possible, we put everything theme related
774 // at the beginning of the html files into another js file.
775 let theme_js = format!(
776 r#"var themes = document.getElementById("theme-choices");
777 var themePicker = document.getElementById("theme-picker");
779 function showThemeButtonState() {{
780 themes.style.display = "block";
781 themePicker.style.borderBottomRightRadius = "0";
782 themePicker.style.borderBottomLeftRadius = "0";
785 function hideThemeButtonState() {{
786 themes.style.display = "none";
787 themePicker.style.borderBottomRightRadius = "3px";
788 themePicker.style.borderBottomLeftRadius = "3px";
791 function switchThemeButtonState() {{
792 if (themes.style.display === "block") {{
793 hideThemeButtonState();
795 showThemeButtonState();
799 function handleThemeButtonsBlur(e) {{
800 var active = document.activeElement;
801 var related = e.relatedTarget;
803 if (active.id !== "theme-picker" &&
804 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
806 (related.id !== "theme-picker" &&
807 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
808 hideThemeButtonState();
812 themePicker.onclick = switchThemeButtonState;
813 themePicker.onblur = handleThemeButtonsBlur;
814 {}.forEach(function(item) {{
815 var but = document.createElement("button");
816 but.textContent = item;
817 but.onclick = function(el) {{
818 switchTheme(currentTheme, mainTheme, item, true);
819 useSystemTheme(false);
821 but.onblur = handleThemeButtonsBlur;
822 themes.appendChild(but);
824 serde_json::to_string(&themes).unwrap()
827 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
831 static_files::MAIN_JS,
832 options.enable_minification,
836 cx.path("settings.js"),
837 static_files::SETTINGS_JS,
838 options.enable_minification,
840 if cx.shared.include_sources {
843 cx.path("source-script.js"),
844 static_files::sidebar::SOURCE_SCRIPT,
845 options.enable_minification,
852 cx.path("storage.js"),
854 "var resourcesSuffix = \"{}\";{}",
855 cx.shared.resource_suffix,
856 static_files::STORAGE_JS
858 options.enable_minification,
862 if let Some(ref css) = cx.shared.layout.css_file_extension {
863 let out = cx.path("theme.css");
864 let buffer = try_err!(fs::read_to_string(css), css);
865 if !options.enable_minification {
866 cx.shared.fs.write(&out, &buffer)?;
868 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
873 cx.path("normalize.css"),
874 static_files::NORMALIZE_CSS,
875 options.enable_minification,
877 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
878 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
879 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
880 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
881 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
882 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
883 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
884 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
885 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
886 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
887 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
888 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
889 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
891 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
892 let mut ret = Vec::new();
893 let mut krates = Vec::new();
896 for line in BufReader::new(File::open(path)?).lines() {
898 if !line.starts_with(key) {
901 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
904 ret.push(line.to_string());
906 line[key.len() + 2..]
909 .map(|s| s.to_owned())
910 .unwrap_or_else(String::new),
917 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
918 let mut ret = Vec::new();
919 let mut krates = Vec::new();
922 for line in BufReader::new(File::open(path)?).lines() {
924 if !line.starts_with('"') {
927 if line.starts_with(&format!("\"{}\"", krate)) {
930 if line.ends_with(",\\") {
931 ret.push(line[..line.len() - 2].to_string());
933 // Ends with "\\" (it's the case for the last added crate line)
934 ret.push(line[..line.len() - 1].to_string());
938 .find(|s| !s.is_empty())
939 .map(|s| s.to_owned())
940 .unwrap_or_else(String::new),
947 use std::ffi::OsString;
952 children: FxHashMap<OsString, Hierarchy>,
953 elems: FxHashSet<OsString>,
957 fn new(elem: OsString) -> Hierarchy {
958 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
961 fn to_json_string(&self) -> String {
962 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
963 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
967 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
968 .collect::<Vec<_>>();
969 files.sort_unstable_by(|a, b| a.cmp(b));
970 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
972 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
973 let files = files.join(",");
975 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
977 "{{\"name\":\"{name}\"{dirs}{files}}}",
978 name = self.elem.to_str().expect("invalid osstring conversion"),
985 if cx.shared.include_sources {
986 let mut hierarchy = Hierarchy::new(OsString::new());
991 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
993 let mut h = &mut hierarchy;
994 let mut elems = source
996 .filter_map(|s| match s {
997 Component::Normal(s) => Some(s.to_owned()),
1002 let cur_elem = elems.next().expect("empty file path");
1003 if elems.peek().is_none() {
1004 h.elems.insert(cur_elem);
1007 let e = cur_elem.clone();
1008 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1009 h = h.children.get_mut(&cur_elem).expect("not found child");
1014 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1015 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1016 all_sources.push(format!(
1017 "sourcesIndex[\"{}\"] = {};",
1019 hierarchy.to_json_string()
1023 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1024 all_sources.join("\n")
1026 cx.shared.fs.write(&dst, v.as_bytes())?;
1029 // Update the search index
1030 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1031 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name), &dst);
1032 all_indexes.push(search_index);
1034 // Sort the indexes by crate so the file will be generated identically even
1035 // with rustdoc running in parallel.
1038 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1039 v.push_str(&all_indexes.join(",\\\n"));
1040 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1041 // search might start (if it's set into the URL for example).
1042 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1043 cx.shared.fs.write(&dst, &v)?;
1045 if options.enable_index_page {
1046 if let Some(index_page) = options.index_page.clone() {
1047 let mut md_opts = options.clone();
1048 md_opts.output = cx.dst.clone();
1049 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1051 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1052 .map_err(|e| Error::new(e, &index_page))?;
1054 let dst = cx.dst.join("index.html");
1055 let page = layout::Page {
1056 title: "Index of crates",
1059 static_root_path: cx.shared.static_root_path.as_deref(),
1060 description: "List of crates",
1061 keywords: BASIC_KEYWORDS,
1062 resource_suffix: &cx.shared.resource_suffix,
1064 static_extra_scripts: &[],
1066 krates.push(krate.name.clone());
1070 let content = format!(
1071 "<h1 class=\"fqn\">\
1072 <span class=\"in-band\">List of all crates</span>\
1073 </h1><ul class=\"crate mod\">{}</ul>",
1078 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1079 ensure_trailing_slash(s),
1083 .collect::<String>()
1085 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1086 cx.shared.fs.write(&dst, v.as_bytes())?;
1090 // Update the list of all implementors for traits
1091 let dst = cx.dst.join("implementors");
1092 for (&did, imps) in &cache.implementors {
1093 // Private modules can leak through to this phase of rustdoc, which
1094 // could contain implementations for otherwise private types. In some
1095 // rare cases we could find an implementation for an item which wasn't
1096 // indexed, so we just skip this step in that case.
1098 // FIXME: this is a vague explanation for why this can't be a `get`, in
1099 // theory it should be...
1100 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1102 None => match cache.external_paths.get(&did) {
1108 #[derive(Serialize)]
1109 struct Implementor {
1115 let implementors = imps
1118 // If the trait and implementation are in the same crate, then
1119 // there's no need to emit information about it (there's inlining
1120 // going on). If they're in different crates then the crate defining
1121 // the trait will be interested in our implementation.
1123 // If the implementation is from another crate then that crate
1125 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1129 text: imp.inner_impl().print().to_string(),
1130 synthetic: imp.inner_impl().synthetic,
1131 types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1135 .collect::<Vec<_>>();
1137 // Only create a js file if we have impls to add to it. If the trait is
1138 // documented locally though we always create the file to avoid dead
1140 if implementors.is_empty() && !cache.paths.contains_key(&did) {
1144 let implementors = format!(
1145 r#"implementors["{}"] = {};"#,
1147 serde_json::to_string(&implementors).unwrap()
1150 let mut mydst = dst.clone();
1151 for part in &remote_path[..remote_path.len() - 1] {
1154 cx.shared.ensure_dir(&mydst)?;
1155 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1157 let (mut all_implementors, _) =
1158 try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1159 all_implementors.push(implementors);
1160 // Sort the implementors by crate so the file will be generated
1161 // identically even with rustdoc running in parallel.
1162 all_implementors.sort();
1164 let mut v = String::from("(function() {var implementors = {};\n");
1165 for implementor in &all_implementors {
1166 writeln!(v, "{}", *implementor).unwrap();
1169 "if (window.register_implementors) {\
1170 window.register_implementors(implementors);\
1172 window.pending_implementors = implementors;\
1176 cx.shared.fs.write(&mydst, &v)?;
1185 enable_minification: bool,
1186 ) -> Result<(), Error> {
1187 if enable_minification {
1188 if dst.extension() == Some(&OsStr::new("css")) {
1189 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1190 fs.write(dst, res.as_bytes())
1192 fs.write(dst, minifier::js::minify(contents).as_bytes())
1195 fs.write(dst, contents.as_bytes())
1199 fn write_srclink(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1200 if let Some(l) = cx.src_href(item, cache) {
1203 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
1204 l, "goto source code"
1209 #[derive(Debug, Eq, PartialEq, Hash)]
1216 fn new(mut url: String, name: String) -> ItemEntry {
1217 while url.starts_with('/') {
1220 ItemEntry { url, name }
1225 crate fn print(&self) -> impl fmt::Display + '_ {
1226 crate::html::format::display_fn(move |f| {
1227 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1232 impl PartialOrd for ItemEntry {
1233 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1234 Some(self.cmp(other))
1238 impl Ord for ItemEntry {
1239 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1240 self.name.cmp(&other.name)
1246 structs: FxHashSet<ItemEntry>,
1247 enums: FxHashSet<ItemEntry>,
1248 unions: FxHashSet<ItemEntry>,
1249 primitives: FxHashSet<ItemEntry>,
1250 traits: FxHashSet<ItemEntry>,
1251 macros: FxHashSet<ItemEntry>,
1252 functions: FxHashSet<ItemEntry>,
1253 typedefs: FxHashSet<ItemEntry>,
1254 opaque_tys: FxHashSet<ItemEntry>,
1255 statics: FxHashSet<ItemEntry>,
1256 constants: FxHashSet<ItemEntry>,
1257 keywords: FxHashSet<ItemEntry>,
1258 attributes: FxHashSet<ItemEntry>,
1259 derives: FxHashSet<ItemEntry>,
1260 trait_aliases: FxHashSet<ItemEntry>,
1264 fn new() -> AllTypes {
1265 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1267 structs: new_set(100),
1268 enums: new_set(100),
1269 unions: new_set(100),
1270 primitives: new_set(26),
1271 traits: new_set(100),
1272 macros: new_set(100),
1273 functions: new_set(100),
1274 typedefs: new_set(100),
1275 opaque_tys: new_set(100),
1276 statics: new_set(100),
1277 constants: new_set(100),
1278 keywords: new_set(100),
1279 attributes: new_set(100),
1280 derives: new_set(100),
1281 trait_aliases: new_set(100),
1285 fn append(&mut self, item_name: String, item_type: &ItemType) {
1286 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1287 if let Some(name) = url.pop() {
1288 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1290 let name = url.join("::");
1292 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1293 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1294 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1295 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1296 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1297 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1298 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1299 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1300 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1301 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1302 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1303 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1304 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1305 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1312 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1314 let mut e: Vec<&ItemEntry> = e.iter().collect();
1318 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">{}</ul>",
1322 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1328 fn print(self, f: &mut Buffer) {
1331 "<h1 class=\"fqn\">\
1332 <span class=\"out-of-band\">\
1333 <span id=\"render-detail\">\
1334 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1335 title=\"collapse all docs\">\
1336 [<span class=\"inner\">−</span>]\
1340 <span class=\"in-band\">List of all items</span>\
1343 print_entries(f, &self.structs, "Structs", "structs");
1344 print_entries(f, &self.enums, "Enums", "enums");
1345 print_entries(f, &self.unions, "Unions", "unions");
1346 print_entries(f, &self.primitives, "Primitives", "primitives");
1347 print_entries(f, &self.traits, "Traits", "traits");
1348 print_entries(f, &self.macros, "Macros", "macros");
1349 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1350 print_entries(f, &self.derives, "Derive Macros", "derives");
1351 print_entries(f, &self.functions, "Functions", "functions");
1352 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1353 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1354 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1355 print_entries(f, &self.statics, "Statics", "statics");
1356 print_entries(f, &self.constants, "Constants", "constants")
1363 description: &'static str,
1364 sub_settings: Vec<Setting>,
1367 js_data_name: &'static str,
1368 description: &'static str,
1369 default_value: bool,
1372 js_data_name: &'static str,
1373 description: &'static str,
1374 default_value: &'static str,
1375 options: Vec<(String, String)>,
1380 fn display(&self, root_path: &str, suffix: &str) -> String {
1382 Setting::Section { description, ref sub_settings } => format!(
1383 "<div class=\"setting-line\">\
1384 <div class=\"title\">{}</div>\
1385 <div class=\"sub-settings\">{}</div>
1388 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1390 Setting::Toggle { js_data_name, description, default_value } => format!(
1391 "<div class=\"setting-line\">\
1392 <label class=\"toggle\">\
1393 <input type=\"checkbox\" id=\"{}\" {}>\
1394 <span class=\"slider\"></span>\
1399 if default_value { " checked" } else { "" },
1402 Setting::Select { js_data_name, description, default_value, ref options } => format!(
1403 "<div class=\"setting-line\">\
1405 <label class=\"select-wrapper\">\
1406 <select id=\"{}\" autocomplete=\"off\">{}</select>\
1407 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1415 "<option value=\"{}\" {}>{}</option>",
1417 if &opt.0 == default_value { "selected" } else { "" },
1420 .collect::<String>(),
1428 impl From<(&'static str, &'static str, bool)> for Setting {
1429 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1430 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1434 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1435 fn from(values: (&'static str, Vec<T>)) -> Setting {
1437 description: values.0,
1438 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1443 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1444 let theme_names: Vec<(String, String)> = themes
1448 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1451 Ok((theme.clone(), theme))
1453 .collect::<Result<_, Error>>()?;
1455 // (id, explanation, default value)
1456 let settings: &[Setting] = &[
1458 "Theme preferences",
1460 Setting::from(("use-system-theme", "Use system theme", true)),
1462 js_data_name: "preferred-dark-theme",
1463 description: "Preferred dark theme",
1464 default_value: "dark",
1465 options: theme_names.clone(),
1468 js_data_name: "preferred-light-theme",
1469 description: "Preferred light theme",
1470 default_value: "light",
1471 options: theme_names,
1477 "Auto-hide item declarations",
1479 ("auto-hide-struct", "Auto-hide structs declaration", true),
1480 ("auto-hide-enum", "Auto-hide enums declaration", false),
1481 ("auto-hide-union", "Auto-hide unions declaration", true),
1482 ("auto-hide-trait", "Auto-hide traits declaration", true),
1483 ("auto-hide-macro", "Auto-hide macros declaration", false),
1487 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1488 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1489 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1491 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1492 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1494 ("line-numbers", "Show line numbers on code examples", false).into(),
1495 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1499 "<h1 class=\"fqn\">\
1500 <span class=\"in-band\">Rustdoc settings</span>\
1502 <div class=\"settings\">{}</div>\
1503 <script src=\"{}settings{}.js\"></script>",
1504 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1511 fn derive_id(&self, id: String) -> String {
1512 let mut map = self.id_map.borrow_mut();
1516 /// String representation of how to get back to the root path of the 'doc/'
1517 /// folder in terms of a relative URL.
1518 fn root_path(&self) -> String {
1519 "../".repeat(self.current.len())
1522 fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1523 // A little unfortunate that this is done like this, but it sure
1524 // does make formatting *a lot* nicer.
1525 CURRENT_DEPTH.with(|slot| {
1526 slot.set(self.current.len());
1529 let mut title = if it.is_primitive() || it.is_keyword() {
1530 // No need to include the namespace for primitive types and keywords
1533 self.current.join("::")
1536 if !title.is_empty() {
1537 title.push_str("::");
1539 title.push_str(it.name.as_ref().unwrap());
1541 title.push_str(" - Rust");
1542 let tyname = it.type_();
1543 let desc = if it.is_crate() {
1544 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1547 "API documentation for the Rust `{}` {} in crate `{}`.",
1548 it.name.as_ref().unwrap(),
1550 self.shared.layout.krate
1553 let keywords = make_item_keywords(it);
1554 let page = layout::Page {
1555 css_class: tyname.as_str(),
1556 root_path: &self.root_path(),
1557 static_root_path: self.shared.static_root_path.as_deref(),
1560 keywords: &keywords,
1561 resource_suffix: &self.shared.resource_suffix,
1563 static_extra_scripts: &[],
1567 self.id_map.borrow_mut().reset();
1568 self.id_map.borrow_mut().populate(initial_ids());
1571 if !self.render_redirect_pages {
1573 &self.shared.layout,
1575 |buf: &mut _| print_sidebar(self, it, buf, cache),
1576 |buf: &mut _| print_item(self, it, buf, cache),
1577 &self.shared.style_files,
1580 let mut url = self.root_path();
1581 if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1582 for name in &names[..names.len() - 1] {
1586 url.push_str(&item_path(ty, names.last().unwrap()));
1587 layout::redirect(&url)
1594 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1595 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1596 // BTreeMap instead of HashMap to get a sorted output
1597 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1598 for item in &m.items {
1599 if item.is_stripped() {
1603 let short = item.type_();
1604 let myname = match item.name {
1606 Some(ref s) => s.to_string(),
1608 let short = short.to_string();
1609 map.entry(short).or_default().push((
1611 Some(item.doc_value().map_or_else(|| String::new(), plain_text_summary)),
1615 if self.shared.sort_modules_alphabetically {
1616 for items in map.values_mut() {
1623 /// Generates a url appropriate for an `href` attribute back to the source of
1626 /// The url generated, when clicked, will redirect the browser back to the
1627 /// original source code.
1629 /// If `None` is returned, then a source link couldn't be generated. This
1630 /// may happen, for example, with externally inlined items where the source
1631 /// of their crate documentation isn't known.
1632 fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1633 let mut root = self.root_path();
1635 let mut path = String::new();
1637 // We can safely ignore synthetic `SourceFile`s.
1638 let file = match item.source.filename {
1639 FileName::Real(ref path) => path.local_path().to_path_buf(),
1644 let (krate, path) = if item.source.cnum == LOCAL_CRATE {
1645 if let Some(path) = self.shared.local_sources.get(file) {
1646 (&self.shared.layout.krate, path)
1651 let (krate, src_root) = match *cache.extern_locations.get(&item.source.cnum)? {
1652 (ref name, ref src, ExternalLocation::Local) => (name, src),
1653 (ref name, ref src, ExternalLocation::Remote(ref s)) => {
1654 root = s.to_string();
1657 (_, _, ExternalLocation::Unknown) => return None,
1660 sources::clean_path(&src_root, file, false, |component| {
1661 path.push_str(&component.to_string_lossy());
1664 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1665 fname.push(".html");
1666 path.push_str(&fname.to_string_lossy());
1670 let lines = if item.source.loline == item.source.hiline {
1671 item.source.loline.to_string()
1673 format!("{}-{}", item.source.loline, item.source.hiline)
1676 "{root}src/{krate}/{path}#{lines}",
1677 root = Escape(&root),
1685 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1687 F: FnOnce(&mut Buffer),
1689 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1694 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1695 debug_assert!(!item.is_stripped());
1696 // Write the breadcrumb trail header for the top
1697 write!(buf, "<h1 class=\"fqn\"><span class=\"out-of-band\">");
1698 render_stability_since_raw(
1700 item.stable_since().as_deref(),
1701 item.const_stable_since().as_deref(),
1707 "<span id=\"render-detail\">\
1708 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1709 title=\"collapse all docs\">\
1710 [<span class=\"inner\">−</span>]\
1717 // When this item is part of a `crate use` in a downstream crate, the
1718 // [src] link in the downstream documentation will actually come back to
1719 // this page, and this link will be auto-clicked. The `id` attribute is
1720 // used to find the link to auto-click.
1721 if cx.shared.include_sources && !item.is_primitive() {
1722 write_srclink(cx, item, buf, cache);
1725 write!(buf, "</span>"); // out-of-band
1726 write!(buf, "<span class=\"in-band\">");
1727 let name = match item.kind {
1728 clean::ModuleItem(ref m) => {
1735 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1736 clean::TraitItem(..) => "Trait ",
1737 clean::StructItem(..) => "Struct ",
1738 clean::UnionItem(..) => "Union ",
1739 clean::EnumItem(..) => "Enum ",
1740 clean::TypedefItem(..) => "Type Definition ",
1741 clean::MacroItem(..) => "Macro ",
1742 clean::ProcMacroItem(ref mac) => match mac.kind {
1743 MacroKind::Bang => "Macro ",
1744 MacroKind::Attr => "Attribute Macro ",
1745 MacroKind::Derive => "Derive Macro ",
1747 clean::PrimitiveItem(..) => "Primitive Type ",
1748 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1749 clean::ConstantItem(..) => "Constant ",
1750 clean::ForeignTypeItem => "Foreign Type ",
1751 clean::KeywordItem(..) => "Keyword ",
1752 clean::OpaqueTyItem(..) => "Opaque Type ",
1753 clean::TraitAliasItem(..) => "Trait Alias ",
1755 // We don't generate pages for any other type.
1759 buf.write_str(name);
1760 if !item.is_primitive() && !item.is_keyword() {
1761 let cur = &cx.current;
1762 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1763 for (i, component) in cur.iter().enumerate().take(amt) {
1766 "<a href=\"{}index.html\">{}</a>::<wbr>",
1767 "../".repeat(cur.len() - i - 1),
1772 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1774 write!(buf, "</span></h1>"); // in-band
1777 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1778 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1779 item_function(buf, cx, item, f)
1781 clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1782 clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1783 clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1784 clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1785 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1786 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1787 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1788 clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1789 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1790 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1791 clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1792 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1793 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e, cache),
1794 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1796 // We don't generate pages for any other type.
1802 fn item_path(ty: ItemType, name: &str) -> String {
1804 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1805 _ => format!("{}.{}.html", ty, name),
1809 fn full_path(cx: &Context, item: &clean::Item) -> String {
1810 let mut s = cx.current.join("::");
1812 s.push_str(item.name.as_ref().unwrap());
1816 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item, parent: Option<&clean::Item>) {
1817 if let Some(ref name) = item.name {
1818 info!("Documenting {}", name);
1820 document_item_info(w, cx, item, false, parent);
1821 document_full(w, item, cx, "", false);
1824 /// Render md_text as markdown.
1829 links: Vec<RenderedLink>,
1833 let mut ids = cx.id_map.borrow_mut();
1836 "<div class=\"docblock{}\">{}{}</div>",
1837 if is_hidden { " hidden" } else { "" },
1845 &cx.shared.playground
1851 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1852 /// docs are longer, a "Read more" link is appended to the end.
1857 link: AssocItemLink<'_>,
1860 parent: Option<&clean::Item>,
1861 show_def_docs: bool,
1863 document_item_info(w, cx, item, is_hidden, parent);
1867 if let Some(s) = item.doc_value() {
1868 let mut summary_html = MarkdownSummaryLine(s, &item.links()).into_string();
1870 if s.contains('\n') {
1871 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link));
1873 if let Some(idx) = summary_html.rfind("</p>") {
1874 summary_html.insert_str(idx, &link);
1876 summary_html.push_str(&link);
1882 "<div class='docblock{}'>{}{}</div>",
1883 if is_hidden { " hidden" } else { "" },
1887 } else if !prefix.is_empty() {
1890 "<div class=\"docblock{}\">{}</div>",
1891 if is_hidden { " hidden" } else { "" },
1897 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1898 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1899 debug!("Doc block: =====\n{}\n=====", s);
1900 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1901 } else if !prefix.is_empty() {
1904 "<div class=\"docblock{}\">{}</div>",
1905 if is_hidden { " hidden" } else { "" },
1911 /// Add extra information about an item such as:
1915 /// * Required features (through the `doc_cfg` feature)
1916 fn document_item_info(
1921 parent: Option<&clean::Item>,
1923 let item_infos = short_item_info(item, cx, parent);
1924 if !item_infos.is_empty() {
1925 write!(w, "<div class=\"item-info{}\">", if is_hidden { " hidden" } else { "" });
1926 for info in item_infos {
1927 write!(w, "{}", info);
1929 write!(w, "</div>");
1933 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1934 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1937 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1938 if item.is_non_exhaustive() {
1939 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1940 if item.is_struct() {
1942 } else if item.is_enum() {
1944 } else if item.is_variant() {
1951 if item.is_struct() {
1954 "Non-exhaustive structs could have additional fields added in future. \
1955 Therefore, non-exhaustive structs cannot be constructed in external crates \
1956 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1957 matched against without a wildcard <code>..</code>; and \
1958 struct update syntax will not work."
1960 } else if item.is_enum() {
1963 "Non-exhaustive enums could have additional variants added in future. \
1964 Therefore, when matching against variants of non-exhaustive enums, an \
1965 extra wildcard arm must be added to account for any future variants."
1967 } else if item.is_variant() {
1970 "Non-exhaustive enum variants could have additional fields added in future. \
1971 Therefore, non-exhaustive enum variants cannot be constructed in external \
1972 crates and cannot be matched against."
1977 "This type will require a wildcard arm in any match statements or constructors."
1981 write!(w, "</div>");
1985 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1986 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1987 /// Takes a non-numeric and a numeric part from the given &str.
1988 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1989 let i = s.find(|c: char| c.is_ascii_digit());
1990 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1991 let i = b.find(|c: char| !c.is_ascii_digit());
1992 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1997 while !lhs.is_empty() || !rhs.is_empty() {
1998 let (la, lb) = take_parts(&mut lhs);
1999 let (ra, rb) = take_parts(&mut rhs);
2000 // First process the non-numeric part.
2002 Ordering::Equal => (),
2005 // Then process the numeric part, if both sides have one (and they fit in a u64).
2006 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2008 Ordering::Equal => (),
2012 // Then process the numeric part again, but this time as strings.
2014 Ordering::Equal => (),
2022 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
2023 document(w, cx, item, None);
2025 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2027 // the order of item types in the listing
2028 fn reorder(ty: ItemType) -> u8 {
2030 ItemType::ExternCrate => 0,
2031 ItemType::Import => 1,
2032 ItemType::Primitive => 2,
2033 ItemType::Module => 3,
2034 ItemType::Macro => 4,
2035 ItemType::Struct => 5,
2036 ItemType::Enum => 6,
2037 ItemType::Constant => 7,
2038 ItemType::Static => 8,
2039 ItemType::Trait => 9,
2040 ItemType::Function => 10,
2041 ItemType::Typedef => 12,
2042 ItemType::Union => 13,
2047 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2048 let ty1 = i1.type_();
2049 let ty2 = i2.type_();
2051 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2053 let s1 = i1.stability.as_ref().map(|s| s.level);
2054 let s2 = i2.stability.as_ref().map(|s| s.level);
2055 if let (Some(a), Some(b)) = (s1, s2) {
2056 match (a.is_stable(), b.is_stable()) {
2057 (true, true) | (false, false) => {}
2058 (false, true) => return Ordering::Less,
2059 (true, false) => return Ordering::Greater,
2062 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2063 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2064 compare_names(lhs, rhs)
2067 if cx.shared.sort_modules_alphabetically {
2068 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2070 // This call is to remove re-export duplicates in cases such as:
2075 // crate trait Double { fn foo(); }
2079 // crate use foo::bar::*;
2080 // crate use foo::*;
2083 // `Double` will appear twice in the generated docs.
2085 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2086 // can be identical even if the elements are different (mostly in imports).
2087 // So in case this is an import, we keep everything by adding a "unique id"
2088 // (which is the position in the vector).
2089 indices.dedup_by_key(|i| {
2092 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2094 if items[*i].is_import() { *i } else { 0 },
2098 debug!("{:?}", indices);
2099 let mut curty = None;
2100 for &idx in &indices {
2101 let myitem = &items[idx];
2102 if myitem.is_stripped() {
2106 let myty = Some(myitem.type_());
2107 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2108 // Put `extern crate` and `use` re-exports in the same section.
2110 } else if myty != curty {
2111 if curty.is_some() {
2112 write!(w, "</table>");
2115 let (short, name) = item_ty_to_strs(&myty.unwrap());
2118 "<h2 id=\"{id}\" class=\"section-header\">\
2119 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2120 id = cx.derive_id(short.to_owned()),
2126 clean::ExternCrateItem(ref name, ref src) => {
2127 use crate::html::format::anchor;
2130 Some(ref src) => write!(
2132 "<tr><td><code>{}extern crate {} as {};",
2133 myitem.visibility.print_with_space(),
2134 anchor(myitem.def_id, src),
2139 "<tr><td><code>{}extern crate {};",
2140 myitem.visibility.print_with_space(),
2141 anchor(myitem.def_id, name)
2144 write!(w, "</code></td></tr>");
2147 clean::ImportItem(ref import) => {
2150 "<tr><td><code>{}{}</code></td></tr>",
2151 myitem.visibility.print_with_space(),
2157 if myitem.name.is_none() {
2161 let unsafety_flag = match myitem.kind {
2162 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2163 if func.header.unsafety == hir::Unsafety::Unsafe =>
2165 "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2170 let stab = myitem.stability_class();
2171 let add = if stab.is_some() { " " } else { "" };
2173 let doc_value = myitem.doc_value().unwrap_or("");
2176 "<tr class=\"{stab}{add}module-item\">\
2177 <td><a class=\"{class}\" href=\"{href}\" \
2178 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2179 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2181 name = *myitem.name.as_ref().unwrap(),
2182 stab_tags = extra_info_tags(myitem, item),
2183 docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2184 class = myitem.type_(),
2186 stab = stab.unwrap_or_else(String::new),
2187 unsafety_flag = unsafety_flag,
2188 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2189 title = [full_path(cx, myitem), myitem.type_().to_string()]
2191 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2192 .collect::<Vec<_>>()
2199 if curty.is_some() {
2200 write!(w, "</table>");
2204 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
2205 /// at the module level.
2206 fn extra_info_tags(item: &clean::Item, parent: &clean::Item) -> String {
2207 let mut tags = String::new();
2209 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2210 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2213 // The trailing space after each tag is to space it properly against the rest of the docs.
2214 if let Some(depr) = &item.deprecation {
2215 let mut message = "Deprecated";
2216 if !stability::deprecation_in_effect(depr.is_since_rustc_version, depr.since.as_deref()) {
2217 message = "Deprecation planned";
2219 tags += &tag_html("deprecated", "", message);
2222 // The "rustc_private" crates are permanently unstable so it makes no sense
2223 // to render "unstable" everywhere.
2224 if item.stability.as_ref().map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2227 tags += &tag_html("unstable", "", "Experimental");
2230 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2231 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2232 (cfg, _) => cfg.as_deref().cloned(),
2235 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2236 if let Some(ref cfg) = cfg {
2237 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2243 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2244 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2245 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2246 (cfg, _) => cfg.as_deref().cloned(),
2250 "Portability {:?} - {:?} = {:?}",
2252 parent.and_then(|p| p.attrs.cfg.as_ref()),
2256 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2259 /// Render the stability, deprecation and portability information that is displayed at the top of
2260 /// the item's documentation.
2261 fn short_item_info(item: &clean::Item, cx: &Context, parent: Option<&clean::Item>) -> Vec<String> {
2262 let mut extra_info = vec![];
2263 let error_codes = cx.shared.codes;
2265 if let Some(Deprecation { ref note, ref since, is_since_rustc_version }) = item.deprecation {
2266 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2267 // but only display the future-deprecation messages for #[rustc_deprecated].
2268 let mut message = if let Some(since) = since {
2269 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2270 format!("Deprecating in {}", Escape(&since))
2272 format!("Deprecated since {}", Escape(&since))
2275 String::from("Deprecated")
2278 if let Some(note) = note {
2279 let mut ids = cx.id_map.borrow_mut();
2280 let html = MarkdownHtml(
2285 &cx.shared.playground,
2287 message.push_str(&format!(": {}", html.into_string()));
2289 extra_info.push(format!(
2290 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2295 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2296 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2297 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2300 .filter(|stab| stab.feature != sym::rustc_private)
2301 .map(|stab| (stab.level, stab.feature))
2304 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2306 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2307 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2308 feature.push_str(&format!(
2309 " <a href=\"{url}{issue}\">#{issue}</a>",
2315 message.push_str(&format!(" ({})", feature));
2317 if let Some(unstable_reason) = reason {
2318 let mut ids = cx.id_map.borrow_mut();
2320 "<details><summary>{}</summary>{}</details>",
2323 &unstable_reason.as_str(),
2327 &cx.shared.playground,
2333 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2336 if let Some(portability) = portability(item, parent) {
2337 extra_info.push(portability);
2343 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2344 write!(w, "<pre class=\"rust const\">");
2345 render_attributes(w, it, false);
2349 "{vis}const {name}: {typ}",
2350 vis = it.visibility.print_with_space(),
2351 name = it.name.as_ref().unwrap(),
2352 typ = c.type_.print(),
2355 if c.value.is_some() || c.is_literal {
2356 write!(w, " = {expr};", expr = Escape(&c.expr));
2361 if let Some(value) = &c.value {
2363 let value_lowercase = value.to_lowercase();
2364 let expr_lowercase = c.expr.to_lowercase();
2366 if value_lowercase != expr_lowercase
2367 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2369 write!(w, " // {value}", value = Escape(value));
2374 write!(w, "</pre>");
2375 document(w, cx, it, None)
2378 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2379 write!(w, "<pre class=\"rust static\">");
2380 render_attributes(w, it, false);
2383 "{vis}static {mutability}{name}: {typ}</pre>",
2384 vis = it.visibility.print_with_space(),
2385 mutability = s.mutability.print_with_space(),
2386 name = it.name.as_ref().unwrap(),
2387 typ = s.type_.print()
2389 document(w, cx, it, None)
2392 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2393 let header_len = format!(
2394 "{}{}{}{}{:#}fn {}{:#}",
2395 it.visibility.print_with_space(),
2396 f.header.constness.print_with_space(),
2397 f.header.asyncness.print_with_space(),
2398 f.header.unsafety.print_with_space(),
2399 print_abi_with_space(f.header.abi),
2400 it.name.as_ref().unwrap(),
2404 write!(w, "<pre class=\"rust fn\">");
2405 render_attributes(w, it, false);
2408 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2409 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2410 vis = it.visibility.print_with_space(),
2411 constness = f.header.constness.print_with_space(),
2412 asyncness = f.header.asyncness.print_with_space(),
2413 unsafety = f.header.unsafety.print_with_space(),
2414 abi = print_abi_with_space(f.header.abi),
2415 name = it.name.as_ref().unwrap(),
2416 generics = f.generics.print(),
2417 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2418 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2420 spotlight = spotlight_decl(&f.decl),
2422 document(w, cx, it, None)
2425 fn render_implementor(
2428 parent: &clean::Item,
2430 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2434 // If there's already another implementor that has the same abbridged name, use the
2435 // full path, for example in `std::iter::ExactSizeIterator`
2436 let use_absolute = match implementor.inner_impl().for_ {
2437 clean::ResolvedPath { ref path, is_generic: false, .. }
2438 | clean::BorrowedRef {
2439 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2441 } => implementor_dups[path.last_name()].1,
2449 AssocItemLink::Anchor(None),
2451 implementor.impl_item.stable_since().as_deref(),
2452 implementor.impl_item.const_stable_since().as_deref(),
2466 containing_item: &clean::Item,
2469 let mut impls = traits
2472 let did = i.trait_did().unwrap();
2473 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2474 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2482 containing_item.stable_since().as_deref(),
2483 containing_item.const_stable_since().as_deref(),
2493 .collect::<Vec<_>>();
2495 w.write_str(&impls.join(""));
2498 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2499 let mut bounds = String::new();
2500 if !t_bounds.is_empty() {
2502 bounds.push_str(": ");
2504 for (i, p) in t_bounds.iter().enumerate() {
2506 bounds.push_str(" + ");
2508 bounds.push_str(&p.print().to_string());
2514 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2515 let lhs = format!("{}", lhs.inner_impl().print());
2516 let rhs = format!("{}", rhs.inner_impl().print());
2518 // lhs and rhs are formatted as HTML, which may be unnecessary
2519 compare_names(&lhs, &rhs)
2522 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2523 let bounds = bounds(&t.bounds, false);
2524 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2525 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2526 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2527 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2529 // Output the trait definition
2530 wrap_into_docblock(w, |w| {
2531 write!(w, "<pre class=\"rust trait\">");
2532 render_attributes(w, it, true);
2535 "{}{}{}trait {}{}{}",
2536 it.visibility.print_with_space(),
2537 t.unsafety.print_with_space(),
2538 if t.is_auto { "auto " } else { "" },
2539 it.name.as_ref().unwrap(),
2544 if !t.generics.where_predicates.is_empty() {
2545 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2550 if t.items.is_empty() {
2553 // FIXME: we should be using a derived_id for the Anchors here
2556 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2559 if !types.is_empty() && !consts.is_empty() {
2563 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2566 if !consts.is_empty() && !required.is_empty() {
2569 for (pos, m) in required.iter().enumerate() {
2570 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2573 if pos < required.len() - 1 {
2574 write!(w, "<div class=\"item-spacer\"></div>");
2577 if !required.is_empty() && !provided.is_empty() {
2580 for (pos, m) in provided.iter().enumerate() {
2581 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2583 clean::MethodItem(ref inner, _)
2584 if !inner.generics.where_predicates.is_empty() =>
2586 write!(w, ",\n {{ ... }}\n");
2589 write!(w, " {{ ... }}\n");
2592 if pos < provided.len() - 1 {
2593 write!(w, "<div class=\"item-spacer\"></div>");
2601 // Trait documentation
2602 document(w, cx, it, None);
2604 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2607 "<h2 id=\"{0}\" class=\"small-section-header\">\
2608 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2610 id, title, extra_content
2614 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2615 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2618 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item, cache: &Cache) {
2619 let name = m.name.as_ref().unwrap();
2620 info!("Documenting {} on {}", name, t.name.as_deref().unwrap_or_default());
2621 let item_type = m.type_();
2622 let id = cx.derive_id(format!("{}.{}", item_type, name));
2623 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2624 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2625 write!(w, "</code>");
2626 render_stability_since(w, m, t);
2627 write_srclink(cx, m, w, cache);
2629 document(w, cx, m, Some(t));
2632 if !types.is_empty() {
2633 write_small_section_header(
2637 "<div class=\"methods\">",
2640 trait_item(w, cx, t, it, cache);
2642 write_loading_content(w, "</div>");
2645 if !consts.is_empty() {
2646 write_small_section_header(
2649 "Associated Constants",
2650 "<div class=\"methods\">",
2653 trait_item(w, cx, t, it, cache);
2655 write_loading_content(w, "</div>");
2658 // Output the documentation for each function individually
2659 if !required.is_empty() {
2660 write_small_section_header(
2664 "<div class=\"methods\">",
2667 trait_item(w, cx, m, it, cache);
2669 write_loading_content(w, "</div>");
2671 if !provided.is_empty() {
2672 write_small_section_header(
2676 "<div class=\"methods\">",
2679 trait_item(w, cx, m, it, cache);
2681 write_loading_content(w, "</div>");
2684 // If there are methods directly on this trait object, render them here.
2685 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2687 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2688 // The DefId is for the first Type found with that name. The bool is
2689 // if any Types with the same name but different DefId have been found.
2690 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2691 for implementor in implementors {
2692 match implementor.inner_impl().for_ {
2693 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2694 | clean::BorrowedRef {
2695 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2698 let &mut (prev_did, ref mut has_duplicates) =
2699 implementor_dups.entry(path.last_name()).or_insert((did, false));
2700 if prev_did != did {
2701 *has_duplicates = true;
2708 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2709 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2712 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2713 local.iter().partition(|i| i.inner_impl().synthetic);
2715 synthetic.sort_by(compare_impl);
2716 concrete.sort_by(compare_impl);
2718 if !foreign.is_empty() {
2719 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2721 for implementor in foreign {
2722 let assoc_link = AssocItemLink::GotoSource(
2723 implementor.impl_item.def_id,
2724 &implementor.inner_impl().provided_trait_methods,
2733 implementor.impl_item.stable_since().as_deref(),
2734 implementor.impl_item.const_stable_since().as_deref(),
2743 write_loading_content(w, "");
2746 write_small_section_header(
2750 "<div class=\"item-list\" id=\"implementors-list\">",
2752 for implementor in concrete {
2753 render_implementor(cx, implementor, it, w, &implementor_dups, &[], cache);
2755 write_loading_content(w, "</div>");
2758 write_small_section_header(
2760 "synthetic-implementors",
2761 "Auto implementors",
2762 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2764 for implementor in synthetic {
2771 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2775 write_loading_content(w, "</div>");
2778 // even without any implementations to write in, we still want the heading and list, so the
2779 // implementors javascript file pulled in below has somewhere to write the impls into
2780 write_small_section_header(
2784 "<div class=\"item-list\" id=\"implementors-list\">",
2786 write_loading_content(w, "</div>");
2789 write_small_section_header(
2791 "synthetic-implementors",
2792 "Auto implementors",
2793 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2795 write_loading_content(w, "</div>");
2801 "<script type=\"text/javascript\" \
2802 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2804 root_path = vec![".."; cx.current.len()].join("/"),
2805 path = if it.def_id.is_local() {
2806 cx.current.join("/")
2808 let (ref path, _) = cache.external_paths[&it.def_id];
2809 path[..path.len() - 1].join("/")
2812 name = *it.name.as_ref().unwrap()
2816 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2817 use crate::formats::item_type::ItemType::*;
2819 let name = it.name.as_ref().unwrap();
2820 let ty = match it.type_() {
2821 Typedef | AssocType => AssocType,
2825 let anchor = format!("#{}.{}", ty, name);
2827 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2828 AssocItemLink::Anchor(None) => anchor,
2829 AssocItemLink::GotoSource(did, _) => {
2830 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2839 _default: Option<&String>,
2840 link: AssocItemLink<'_>,
2845 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2847 it.visibility.print_with_space(),
2848 naive_assoc_href(it, link),
2849 it.name.as_ref().unwrap(),
2857 bounds: &[clean::GenericBound],
2858 default: Option<&clean::Type>,
2859 link: AssocItemLink<'_>,
2864 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2866 naive_assoc_href(it, link),
2867 it.name.as_ref().unwrap()
2869 if !bounds.is_empty() {
2870 write!(w, ": {}", print_generic_bounds(bounds))
2872 if let Some(default) = default {
2873 write!(w, " = {}", default.print())
2877 fn render_stability_since_raw(
2880 const_ver: Option<&str>,
2881 containing_ver: Option<&str>,
2882 containing_const_ver: Option<&str>,
2884 let ver = ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2886 let const_ver = const_ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2888 if let Some(v) = ver {
2889 if let Some(cv) = const_ver {
2890 if const_ver != containing_const_ver {
2893 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2896 } else if ver != containing_ver {
2899 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2904 if ver != containing_ver {
2907 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2915 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2916 render_stability_since_raw(
2918 item.stable_since().as_deref(),
2919 item.const_stable_since().as_deref(),
2920 containing_item.stable_since().as_deref(),
2921 containing_item.const_stable_since().as_deref(),
2925 fn render_assoc_item(
2928 link: AssocItemLink<'_>,
2934 header: hir::FnHeader,
2935 g: &clean::Generics,
2937 link: AssocItemLink<'_>,
2940 let name = meth.name.as_ref().unwrap();
2941 let anchor = format!("#{}.{}", meth.type_(), name);
2942 let href = match link {
2943 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2944 AssocItemLink::Anchor(None) => anchor,
2945 AssocItemLink::GotoSource(did, provided_methods) => {
2946 // We're creating a link from an impl-item to the corresponding
2947 // trait-item and need to map the anchored type accordingly.
2948 let ty = if provided_methods.contains(name) {
2954 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2957 let mut header_len = format!(
2958 "{}{}{}{}{}{:#}fn {}{:#}",
2959 meth.visibility.print_with_space(),
2960 header.constness.print_with_space(),
2961 header.asyncness.print_with_space(),
2962 header.unsafety.print_with_space(),
2963 print_default_space(meth.is_default()),
2964 print_abi_with_space(header.abi),
2969 let (indent, end_newline) = if parent == ItemType::Trait {
2975 render_attributes(w, meth, false);
2978 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
2979 {generics}{decl}{spotlight}{where_clause}",
2980 if parent == ItemType::Trait { " " } else { "" },
2981 meth.visibility.print_with_space(),
2982 header.constness.print_with_space(),
2983 header.asyncness.print_with_space(),
2984 header.unsafety.print_with_space(),
2985 print_default_space(meth.is_default()),
2986 print_abi_with_space(header.abi),
2989 generics = g.print(),
2990 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
2991 spotlight = spotlight_decl(&d),
2992 where_clause = WhereClause { gens: g, indent, end_newline }
2996 clean::StrippedItem(..) => {}
2997 clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2998 clean::MethodItem(ref m, _) => {
2999 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3001 clean::AssocConstItem(ref ty, ref default) => assoc_const(
3007 if parent == ItemType::Trait { " " } else { "" },
3009 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3015 if parent == ItemType::Trait { " " } else { "" },
3017 _ => panic!("render_assoc_item called on non-associated-item"),
3021 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
3022 wrap_into_docblock(w, |w| {
3023 write!(w, "<pre class=\"rust struct\">");
3024 render_attributes(w, it, true);
3025 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
3029 document(w, cx, it, None);
3033 .filter_map(|f| match f.kind {
3034 clean::StructFieldItem(ref ty) => Some((f, ty)),
3038 if let doctree::Plain = s.struct_type {
3039 if fields.peek().is_some() {
3042 "<h2 id=\"fields\" class=\"fields small-section-header\">
3043 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3044 document_non_exhaustive_header(it)
3046 document_non_exhaustive(w, it);
3047 for (field, ty) in fields {
3048 let id = cx.derive_id(format!(
3050 ItemType::StructField,
3051 field.name.as_ref().unwrap()
3055 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3056 <a href=\"#{id}\" class=\"anchor field\"></a>\
3057 <code>{name}: {ty}</code>\
3059 item_type = ItemType::StructField,
3061 name = field.name.as_ref().unwrap(),
3064 document(w, cx, field, Some(it));
3068 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3071 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
3072 wrap_into_docblock(w, |w| {
3073 write!(w, "<pre class=\"rust union\">");
3074 render_attributes(w, it, true);
3075 render_union(w, it, Some(&s.generics), &s.fields, "", true);
3079 document(w, cx, it, None);
3083 .filter_map(|f| match f.kind {
3084 clean::StructFieldItem(ref ty) => Some((f, ty)),
3088 if fields.peek().is_some() {
3091 "<h2 id=\"fields\" class=\"fields small-section-header\">
3092 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3094 for (field, ty) in fields {
3095 let name = field.name.as_ref().expect("union field name");
3096 let id = format!("{}.{}", ItemType::StructField, name);
3099 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3100 <a href=\"#{id}\" class=\"anchor field\"></a>\
3101 <code>{name}: {ty}</code>\
3105 shortty = ItemType::StructField,
3108 if let Some(stability_class) = field.stability_class() {
3109 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3111 document(w, cx, field, Some(it));
3114 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3117 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
3118 wrap_into_docblock(w, |w| {
3119 write!(w, "<pre class=\"rust enum\">");
3120 render_attributes(w, it, true);
3124 it.visibility.print_with_space(),
3125 it.name.as_ref().unwrap(),
3127 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
3129 if e.variants.is_empty() && !e.variants_stripped {
3133 for v in &e.variants {
3135 let name = v.name.as_ref().unwrap();
3137 clean::VariantItem(ref var) => match var.kind {
3138 clean::VariantKind::CLike => write!(w, "{}", name),
3139 clean::VariantKind::Tuple(ref tys) => {
3140 write!(w, "{}(", name);
3141 for (i, ty) in tys.iter().enumerate() {
3143 write!(w, ", ")
3145 write!(w, "{}", ty.print());
3149 clean::VariantKind::Struct(ref s) => {
3150 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
3153 _ => unreachable!(),
3158 if e.variants_stripped {
3159 write!(w, " // some variants omitted\n");
3166 document(w, cx, it, None);
3167 if !e.variants.is_empty() {
3170 "<h2 id=\"variants\" class=\"variants small-section-header\">
3171 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3172 document_non_exhaustive_header(it)
3174 document_non_exhaustive(w, it);
3175 for variant in &e.variants {
3177 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3180 "<div id=\"{id}\" class=\"variant small-section-header\">\
3181 <a href=\"#{id}\" class=\"anchor field\"></a>\
3184 name = variant.name.as_ref().unwrap()
3186 if let clean::VariantItem(ref var) = variant.kind {
3187 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3189 for (i, ty) in tys.iter().enumerate() {
3191 write!(w, ", ");
3193 write!(w, "{}", ty.print());
3198 write!(w, "</code></div>");
3199 document(w, cx, variant, Some(it));
3200 document_non_exhaustive(w, variant);
3202 use crate::clean::{Variant, VariantKind};
3203 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.kind {
3204 let variant_id = cx.derive_id(format!(
3207 variant.name.as_ref().unwrap()
3209 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3212 "<h3>Fields of <b>{name}</b></h3><div>",
3213 name = variant.name.as_ref().unwrap()
3215 for field in &s.fields {
3216 use crate::clean::StructFieldItem;
3217 if let StructFieldItem(ref ty) = field.kind {
3218 let id = cx.derive_id(format!(
3219 "variant.{}.field.{}",
3220 variant.name.as_ref().unwrap(),
3221 field.name.as_ref().unwrap()
3225 "<span id=\"{id}\" class=\"variant small-section-header\">\
3226 <a href=\"#{id}\" class=\"anchor field\"></a>\
3227 <code>{f}: {t}</code>\
3230 f = field.name.as_ref().unwrap(),
3233 document(w, cx, field, Some(variant));
3236 write!(w, "</div></div>");
3238 render_stability_since(w, variant, it);
3241 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3244 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3251 sym::non_exhaustive,
3254 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3255 // left padding. For example:
3257 // #[foo] <----- "top" attribute
3259 // #[bar] <---- not "top" attribute
3262 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3267 .filter_map(|attr| {
3268 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3269 Some(pprust::attribute_to_string(&attr))
3276 if !attrs.is_empty() {
3279 "<span class=\"docblock attributes{}\">{}</span>",
3280 if top { " top-attr" } else { "" },
3289 g: Option<&clean::Generics>,
3290 ty: doctree::StructType,
3291 fields: &[clean::Item],
3298 it.visibility.print_with_space(),
3299 if structhead { "struct " } else { "" },
3300 it.name.as_ref().unwrap()
3302 if let Some(g) = g {
3303 write!(w, "{}", g.print())
3307 if let Some(g) = g {
3308 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3310 let mut has_visible_fields = false;
3312 for field in fields {
3313 if let clean::StructFieldItem(ref ty) = field.kind {
3318 field.visibility.print_with_space(),
3319 field.name.as_ref().unwrap(),
3322 has_visible_fields = true;
3326 if has_visible_fields {
3327 if it.has_stripped_fields().unwrap() {
3328 write!(w, "\n{} // some fields omitted", tab);
3330 write!(w, "\n{}", tab);
3331 } else if it.has_stripped_fields().unwrap() {
3332 // If there are no visible fields we can just display
3333 // `{ /* fields omitted */ }` to save space.
3334 write!(w, " /* fields omitted */ ");
3340 for (i, field) in fields.iter().enumerate() {
3345 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3346 clean::StructFieldItem(ref ty) => {
3347 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3349 _ => unreachable!(),
3353 if let Some(g) = g {
3354 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3359 // Needed for PhantomData.
3360 if let Some(g) = g {
3361 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3371 g: Option<&clean::Generics>,
3372 fields: &[clean::Item],
3379 it.visibility.print_with_space(),
3380 if structhead { "union " } else { "" },
3381 it.name.as_ref().unwrap()
3383 if let Some(g) = g {
3384 write!(w, "{}", g.print());
3385 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3388 write!(w, " {{\n{}", tab);
3389 for field in fields {
3390 if let clean::StructFieldItem(ref ty) = field.kind {
3394 field.visibility.print_with_space(),
3395 field.name.as_ref().unwrap(),
3402 if it.has_stripped_fields().unwrap() {
3403 write!(w, " // some fields omitted\n{}", tab);
3408 #[derive(Copy, Clone)]
3409 enum AssocItemLink<'a> {
3410 Anchor(Option<&'a str>),
3411 GotoSource(DefId, &'a FxHashSet<String>),
3414 impl<'a> AssocItemLink<'a> {
3415 fn anchor(&self, id: &'a String) -> Self {
3417 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3418 ref other => *other,
3423 fn render_assoc_items(
3426 containing_item: &clean::Item,
3428 what: AssocItemRender<'_>,
3432 "Documenting associated items of {}",
3433 containing_item.name.as_deref().unwrap_or_default()
3435 let v = match cache.impls.get(&it) {
3439 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3440 if !non_trait.is_empty() {
3441 let render_mode = match what {
3442 AssocItemRender::All => {
3445 "<h2 id=\"implementations\" class=\"small-section-header\">\
3446 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3451 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3454 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
3455 Methods from {}<Target = {}>\
3456 <a href=\"#deref-methods\" class=\"anchor\"></a>\
3461 RenderMode::ForDeref { mut_: deref_mut_ }
3464 for i in &non_trait {
3470 AssocItemLink::Anchor(None),
3472 containing_item.stable_since().as_deref(),
3473 containing_item.const_stable_since().as_deref(),
3483 if let AssocItemRender::DerefFor { .. } = what {
3486 if !traits.is_empty() {
3488 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3489 if let Some(impl_) = deref_impl {
3491 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3492 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3495 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3496 traits.iter().partition(|t| t.inner_impl().synthetic);
3497 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3498 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3500 let mut impls = Buffer::empty_from(&w);
3501 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3502 let impls = impls.into_inner();
3503 if !impls.is_empty() {
3506 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3507 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3509 <div id=\"trait-implementations-list\">{}</div>",
3514 if !synthetic.is_empty() {
3517 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3518 Auto Trait Implementations\
3519 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3521 <div id=\"synthetic-implementations-list\">"
3523 render_impls(cx, w, &synthetic, containing_item, cache);
3524 write!(w, "</div>");
3527 if !blanket_impl.is_empty() {
3530 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3531 Blanket Implementations\
3532 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3534 <div id=\"blanket-implementations-list\">"
3536 render_impls(cx, w, &blanket_impl, containing_item, cache);
3537 write!(w, "</div>");
3542 fn render_deref_methods(
3546 container_item: &clean::Item,
3550 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3551 let (target, real_target) = impl_
3555 .find_map(|item| match item.kind {
3556 clean::TypedefItem(ref t, true) => Some(match *t {
3557 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3558 _ => (&t.type_, &t.type_),
3562 .expect("Expected associated type binding");
3564 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3565 if let Some(did) = target.def_id() {
3566 render_assoc_items(w, cx, container_item, did, what, cache);
3568 if let Some(prim) = target.primitive_type() {
3569 if let Some(&did) = cache.primitive_locations.get(&prim) {
3570 render_assoc_items(w, cx, container_item, did, what, cache);
3576 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3577 let self_type_opt = match item.kind {
3578 clean::MethodItem(ref method, _) => method.decl.self_type(),
3579 clean::TyMethodItem(ref method) => method.decl.self_type(),
3583 if let Some(self_ty) = self_type_opt {
3584 let (by_mut_ref, by_box, by_value) = match self_ty {
3585 SelfTy::SelfBorrowed(_, mutability)
3586 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3587 (mutability == Mutability::Mut, false, false)
3589 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3590 (false, Some(did) == cache().owned_box_did, false)
3592 SelfTy::SelfValue => (false, false, true),
3593 _ => (false, false, false),
3596 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3602 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3603 let mut out = Buffer::html();
3604 let mut trait_ = String::new();
3606 if let Some(did) = decl.output.def_id() {
3608 if let Some(impls) = c.impls.get(&did) {
3610 let impl_ = i.inner_impl();
3611 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3613 out.push_str(&format!(
3614 "<h3 class=\"notable\">Notable traits for {}</h3>\
3615 <code class=\"content\">",
3618 trait_.push_str(&impl_.for_.print().to_string());
3621 //use the "where" class here to make it small
3622 out.push_str(&format!(
3623 "<span class=\"where fmt-newline\">{}</span>",
3626 let t_did = impl_.trait_.def_id().unwrap();
3627 for it in &impl_.items {
3628 if let clean::TypedefItem(ref tydef, _) = it.kind {
3629 out.push_str("<span class=\"where fmt-newline\"> ");
3635 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3638 out.push_str(";</span>");
3646 if !out.is_empty() {
3649 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3650 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3652 out.push_str("</code></span></div></span></span>");
3662 parent: &clean::Item,
3663 link: AssocItemLink<'_>,
3664 render_mode: RenderMode,
3665 outer_version: Option<&str>,
3666 outer_const_version: Option<&str>,
3667 show_def_docs: bool,
3668 use_absolute: Option<bool>,
3669 is_on_foreign_type: bool,
3670 show_default_items: bool,
3671 // This argument is used to reference same type with different paths to avoid duplication
3672 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3676 let traits = &cache.traits;
3677 let trait_ = i.trait_did().map(|did| &traits[&did]);
3679 if render_mode == RenderMode::Normal {
3680 let id = cx.derive_id(match i.inner_impl().trait_ {
3682 if is_on_foreign_type {
3683 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3685 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3688 None => "impl".to_string(),
3690 let aliases = if aliases.is_empty() {
3693 format!(" aliases=\"{}\"", aliases.join(","))
3695 if let Some(use_absolute) = use_absolute {
3696 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3697 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3699 for it in &i.inner_impl().items {
3700 if let clean::TypedefItem(ref tydef, _) = it.kind {
3701 write!(w, "<span class=\"where fmt-newline\"> ");
3702 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3703 write!(w, ";</span>");
3707 write!(w, "</code>");
3711 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3714 i.inner_impl().print()
3717 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3718 render_stability_since_raw(
3720 i.impl_item.stable_since().as_deref(),
3721 i.impl_item.const_stable_since().as_deref(),
3723 outer_const_version,
3725 write_srclink(cx, &i.impl_item, w, cache);
3728 if trait_.is_some() {
3729 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3730 write!(w, "<div class=\"item-info\">{}</div>", portability);
3734 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3735 let mut ids = cx.id_map.borrow_mut();
3738 "<div class=\"docblock\">{}</div>",
3741 &i.impl_item.links(),
3745 &cx.shared.playground
3756 parent: &clean::Item,
3757 link: AssocItemLink<'_>,
3758 render_mode: RenderMode,
3759 is_default_item: bool,
3760 outer_version: Option<&str>,
3761 outer_const_version: Option<&str>,
3762 trait_: Option<&clean::Trait>,
3763 show_def_docs: bool,
3766 let item_type = item.type_();
3767 let name = item.name.as_ref().unwrap();
3769 let render_method_item = match render_mode {
3770 RenderMode::Normal => true,
3771 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3774 let (is_hidden, extra_class) =
3775 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3783 clean::MethodItem(..) | clean::TyMethodItem(_) => {
3784 // Only render when the method is not static or we allow static methods
3785 if render_method_item {
3786 let id = cx.derive_id(format!("{}.{}", item_type, name));
3787 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3788 write!(w, "<code>");
3789 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3790 write!(w, "</code>");
3791 render_stability_since_raw(
3793 item.stable_since().as_deref(),
3794 item.const_stable_since().as_deref(),
3796 outer_const_version,
3798 write_srclink(cx, item, w, cache);
3802 clean::TypedefItem(ref tydef, _) => {
3803 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3804 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3805 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3806 write!(w, "</code></h4>");
3808 clean::AssocConstItem(ref ty, ref default) => {
3809 let id = cx.derive_id(format!("{}.{}", item_type, name));
3810 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3811 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3812 write!(w, "</code>");
3813 render_stability_since_raw(
3815 item.stable_since().as_deref(),
3816 item.const_stable_since().as_deref(),
3818 outer_const_version,
3820 write_srclink(cx, item, w, cache);
3823 clean::AssocTypeItem(ref bounds, ref default) => {
3824 let id = cx.derive_id(format!("{}.{}", item_type, name));
3825 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3826 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3827 write!(w, "</code></h4>");
3829 clean::StrippedItem(..) => return,
3830 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3833 if render_method_item {
3834 if !is_default_item {
3835 if let Some(t) = trait_ {
3836 // The trait item may have been stripped so we might not
3837 // find any documentation or stability for it.
3838 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3839 // We need the stability of the item from the trait
3840 // because impls can't have a stability.
3841 if item.doc_value().is_some() {
3842 document_item_info(w, cx, it, is_hidden, Some(parent));
3843 document_full(w, item, cx, "", is_hidden);
3845 // In case the item isn't documented,
3846 // provide short documentation from the trait.
3860 document_item_info(w, cx, item, is_hidden, Some(parent));
3862 document_full(w, item, cx, "", is_hidden);
3866 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3871 write!(w, "<div class=\"impl-items\">");
3872 for trait_item in &i.inner_impl().items {
3877 if trait_.is_some() { &i.impl_item } else { parent },
3882 outer_const_version,
3889 fn render_default_items(
3894 parent: &clean::Item,
3895 render_mode: RenderMode,
3896 outer_version: Option<&str>,
3897 outer_const_version: Option<&str>,
3898 show_def_docs: bool,
3901 for trait_item in &t.items {
3902 let n = trait_item.name.clone();
3903 if i.items.iter().any(|m| m.name == n) {
3906 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3907 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3918 outer_const_version,
3926 // If we've implemented a trait, then also emit documentation for all
3927 // default items which weren't overridden in the implementation block.
3928 // We don't emit documentation for default items if they appear in the
3929 // Implementations on Foreign Types or Implementors sections.
3930 if show_default_items {
3931 if let Some(t) = trait_ {
3932 render_default_items(
3940 outer_const_version,
3946 write!(w, "</div>");
3953 t: &clean::OpaqueTy,
3956 write!(w, "<pre class=\"rust opaque\">");
3957 render_attributes(w, it, false);
3960 "type {}{}{where_clause} = impl {bounds};</pre>",
3961 it.name.as_ref().unwrap(),
3963 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3964 bounds = bounds(&t.bounds, false)
3967 document(w, cx, it, None);
3969 // Render any items associated directly to this alias, as otherwise they
3970 // won't be visible anywhere in the docs. It would be nice to also show
3971 // associated items from the aliased type (see discussion in #32077), but
3972 // we need #14072 to make sense of the generics.
3973 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3976 fn item_trait_alias(
3980 t: &clean::TraitAlias,
3983 write!(w, "<pre class=\"rust trait-alias\">");
3984 render_attributes(w, it, false);
3987 "trait {}{}{} = {};</pre>",
3988 it.name.as_ref().unwrap(),
3990 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3991 bounds(&t.bounds, true)
3994 document(w, cx, it, None);
3996 // Render any items associated directly to this alias, as otherwise they
3997 // won't be visible anywhere in the docs. It would be nice to also show
3998 // associated items from the aliased type (see discussion in #32077), but
3999 // we need #14072 to make sense of the generics.
4000 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4003 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
4004 write!(w, "<pre class=\"rust typedef\">");
4005 render_attributes(w, it, false);
4008 "type {}{}{where_clause} = {type_};</pre>",
4009 it.name.as_ref().unwrap(),
4011 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4012 type_ = t.type_.print()
4015 document(w, cx, it, None);
4017 // Render any items associated directly to this alias, as otherwise they
4018 // won't be visible anywhere in the docs. It would be nice to also show
4019 // associated items from the aliased type (see discussion in #32077), but
4020 // we need #14072 to make sense of the generics.
4021 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4024 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4025 writeln!(w, "<pre class=\"rust foreigntype\">extern {{");
4026 render_attributes(w, it, false);
4029 " {}type {};\n}}</pre>",
4030 it.visibility.print_with_space(),
4031 it.name.as_ref().unwrap(),
4034 document(w, cx, it, None);
4036 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4039 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
4040 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4044 || it.is_primitive()
4052 "<p class=\"location\">{}{}</p>",
4054 clean::StructItem(..) => "Struct ",
4055 clean::TraitItem(..) => "Trait ",
4056 clean::PrimitiveItem(..) => "Primitive Type ",
4057 clean::UnionItem(..) => "Union ",
4058 clean::EnumItem(..) => "Enum ",
4059 clean::TypedefItem(..) => "Type Definition ",
4060 clean::ForeignTypeItem => "Foreign Type ",
4061 clean::ModuleItem(..) =>
4069 it.name.as_ref().unwrap()
4074 if let Some(ref version) = cache.crate_version {
4077 "<div class=\"block version\">\
4085 write!(buffer, "<div class=\"sidebar-elems\">");
4089 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4090 it.name.as_ref().expect("crates always have a name")
4094 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
4095 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
4096 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
4097 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
4098 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
4099 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
4100 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4101 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
4105 // The sidebar is designed to display sibling functions, modules and
4106 // other miscellaneous information. since there are lots of sibling
4107 // items (and that causes quadratic growth in large modules),
4108 // we refactor common parts into a shared JavaScript file per module.
4109 // still, we don't move everything into JS because we want to preserve
4110 // as much HTML as possible in order to allow non-JS-enabled browsers
4111 // to navigate the documentation (though slightly inefficiently).
4113 write!(buffer, "<p class=\"location\">");
4114 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4116 write!(buffer, "::<wbr>");
4120 "<a href=\"{}index.html\">{}</a>",
4121 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4125 write!(buffer, "</p>");
4127 // Sidebar refers to the enclosing module, not this module.
4128 let relpath = if it.is_mod() { "../" } else { "" };
4131 "<script>window.sidebarCurrent = {{\
4134 relpath: \"{path}\"\
4136 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4141 // There is no sidebar-items.js beyond the crate root path
4142 // FIXME maybe dynamic crate loading can be merged here
4144 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4146 // Closes sidebar-elems div.
4147 write!(buffer, "</div>");
4150 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4151 if used_links.insert(url.clone()) {
4155 while !used_links.insert(format!("{}-{}", url, add)) {
4158 format!("{}-{}", url, add)
4164 used_links: &mut FxHashSet<String>,
4169 .filter_map(|item| match item.name {
4170 Some(ref name) if !name.is_empty() && item.is_method() => {
4171 if !for_deref || should_render_item(item, deref_mut) {
4173 "<a href=\"#{}\">{}</a>",
4174 get_next_url(used_links, format!("method.{}", name)),
4183 .collect::<Vec<_>>()
4186 // The point is to url encode any potential character from a type with genericity.
4187 fn small_url_encode(s: &str) -> String {
4188 s.replace("<", "%3C")
4189 .replace(">", "%3E")
4190 .replace(" ", "%20")
4191 .replace("?", "%3F")
4192 .replace("'", "%27")
4193 .replace("&", "%26")
4194 .replace(",", "%2C")
4195 .replace(":", "%3A")
4196 .replace(";", "%3B")
4197 .replace("[", "%5B")
4198 .replace("]", "%5D")
4199 .replace("\"", "%22")
4202 fn sidebar_assoc_items(it: &clean::Item) -> String {
4203 let mut out = String::new();
4205 if let Some(v) = c.impls.get(&it.def_id) {
4206 let mut used_links = FxHashSet::default();
4209 let used_links_bor = &mut used_links;
4212 .filter(|i| i.inner_impl().trait_.is_none())
4213 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4214 .collect::<Vec<_>>();
4215 if !ret.is_empty() {
4216 // We want links' order to be reproducible so we don't use unstable sort.
4218 out.push_str(&format!(
4219 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4220 <div class=\"sidebar-links\">{}</div>",
4226 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4227 if let Some(impl_) = v
4229 .filter(|i| i.inner_impl().trait_.is_some())
4230 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4232 if let Some((target, real_target)) =
4233 impl_.inner_impl().items.iter().find_map(|item| match item.kind {
4234 clean::TypedefItem(ref t, true) => Some(match *t {
4235 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4236 _ => (&t.type_, &t.type_),
4243 .filter(|i| i.inner_impl().trait_.is_some())
4244 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4245 let inner_impl = target
4249 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4250 .and_then(|did| c.impls.get(&did));
4251 if let Some(impls) = inner_impl {
4252 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4253 out.push_str(&format!(
4254 "Methods from {}<Target={}>",
4257 impl_.inner_impl().trait_.as_ref().unwrap().print()
4259 Escape(&format!("{:#}", real_target.print()))
4261 out.push_str("</a>");
4264 .filter(|i| i.inner_impl().trait_.is_none())
4266 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4268 .collect::<Vec<_>>();
4269 // We want links' order to be reproducible so we don't use unstable sort.
4271 if !ret.is_empty() {
4272 out.push_str(&format!(
4273 "<div class=\"sidebar-links\">{}</div>",
4280 let format_impls = |impls: Vec<&Impl>| {
4281 let mut links = FxHashSet::default();
4286 let is_negative_impl = is_negative_impl(i.inner_impl());
4287 if let Some(ref i) = i.inner_impl().trait_ {
4288 let i_display = format!("{:#}", i.print());
4289 let out = Escape(&i_display);
4290 let encoded = small_url_encode(&format!("{:#}", i.print()));
4291 let generated = format!(
4292 "<a href=\"#impl-{}\">{}{}</a>",
4294 if is_negative_impl { "!" } else { "" },
4297 if links.insert(generated.clone()) { Some(generated) } else { None }
4302 .collect::<Vec<String>>();
4307 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4308 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4309 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4311 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4313 let concrete_format = format_impls(concrete);
4314 let synthetic_format = format_impls(synthetic);
4315 let blanket_format = format_impls(blanket_impl);
4317 if !concrete_format.is_empty() {
4319 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4320 Trait Implementations</a>",
4322 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4325 if !synthetic_format.is_empty() {
4327 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4328 Auto Trait Implementations</a>",
4330 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4333 if !blanket_format.is_empty() {
4335 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4336 Blanket Implementations</a>",
4338 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4346 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4347 let mut sidebar = String::new();
4348 let fields = get_struct_fields_name(&s.fields);
4350 if !fields.is_empty() {
4351 if let doctree::Plain = s.struct_type {
4352 sidebar.push_str(&format!(
4353 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4354 <div class=\"sidebar-links\">{}</div>",
4360 sidebar.push_str(&sidebar_assoc_items(it));
4362 if !sidebar.is_empty() {
4363 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4367 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4368 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4371 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4373 clean::ItemKind::ImplItem(ref i) => {
4374 if let Some(ref trait_) = i.trait_ {
4376 format!("{:#}", i.for_.print()),
4377 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4387 fn is_negative_impl(i: &clean::Impl) -> bool {
4388 i.polarity == Some(clean::ImplPolarity::Negative)
4391 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4392 let mut sidebar = String::new();
4397 .filter_map(|m| match m.name {
4398 Some(ref name) if m.is_associated_type() => {
4399 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4403 .collect::<Vec<_>>();
4407 .filter_map(|m| match m.name {
4408 Some(ref name) if m.is_associated_const() => {
4409 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4413 .collect::<Vec<_>>();
4414 let mut required = t
4417 .filter_map(|m| match m.name {
4418 Some(ref name) if m.is_ty_method() => {
4419 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4423 .collect::<Vec<String>>();
4424 let mut provided = t
4427 .filter_map(|m| match m.name {
4428 Some(ref name) if m.is_method() => {
4429 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4433 .collect::<Vec<String>>();
4435 if !types.is_empty() {
4437 sidebar.push_str(&format!(
4438 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4439 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4443 if !consts.is_empty() {
4445 sidebar.push_str(&format!(
4446 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4447 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4451 if !required.is_empty() {
4453 sidebar.push_str(&format!(
4454 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4455 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4459 if !provided.is_empty() {
4461 sidebar.push_str(&format!(
4462 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4463 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4470 if let Some(implementors) = c.implementors.get(&it.def_id) {
4471 let mut res = implementors
4473 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4474 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4475 .collect::<Vec<_>>();
4477 if !res.is_empty() {
4479 sidebar.push_str(&format!(
4480 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4481 Implementations on Foreign Types</a>\
4482 <div class=\"sidebar-links\">{}</div>",
4484 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4485 .collect::<Vec<_>>()
4491 sidebar.push_str(&sidebar_assoc_items(it));
4493 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4496 "<a class=\"sidebar-title\" \
4497 href=\"#synthetic-implementors\">Auto Implementors</a>",
4501 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4504 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4505 let sidebar = sidebar_assoc_items(it);
4507 if !sidebar.is_empty() {
4508 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4512 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4513 let sidebar = sidebar_assoc_items(it);
4515 if !sidebar.is_empty() {
4516 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4520 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4521 let mut fields = fields
4523 .filter(|f| if let clean::StructFieldItem(..) = f.kind { true } else { false })
4524 .filter_map(|f| match f.name {
4526 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4530 .collect::<Vec<_>>();
4535 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4536 let mut sidebar = String::new();
4537 let fields = get_struct_fields_name(&u.fields);
4539 if !fields.is_empty() {
4540 sidebar.push_str(&format!(
4541 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4542 <div class=\"sidebar-links\">{}</div>",
4547 sidebar.push_str(&sidebar_assoc_items(it));
4549 if !sidebar.is_empty() {
4550 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4554 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4555 let mut sidebar = String::new();
4557 let mut variants = e
4560 .filter_map(|v| match v.name {
4561 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4564 .collect::<Vec<_>>();
4565 if !variants.is_empty() {
4566 variants.sort_unstable();
4567 sidebar.push_str(&format!(
4568 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4569 <div class=\"sidebar-links\">{}</div>",
4574 sidebar.push_str(&sidebar_assoc_items(it));
4576 if !sidebar.is_empty() {
4577 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4581 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4583 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4584 ItemType::Module => ("modules", "Modules"),
4585 ItemType::Struct => ("structs", "Structs"),
4586 ItemType::Union => ("unions", "Unions"),
4587 ItemType::Enum => ("enums", "Enums"),
4588 ItemType::Function => ("functions", "Functions"),
4589 ItemType::Typedef => ("types", "Type Definitions"),
4590 ItemType::Static => ("statics", "Statics"),
4591 ItemType::Constant => ("constants", "Constants"),
4592 ItemType::Trait => ("traits", "Traits"),
4593 ItemType::Impl => ("impls", "Implementations"),
4594 ItemType::TyMethod => ("tymethods", "Type Methods"),
4595 ItemType::Method => ("methods", "Methods"),
4596 ItemType::StructField => ("fields", "Struct Fields"),
4597 ItemType::Variant => ("variants", "Variants"),
4598 ItemType::Macro => ("macros", "Macros"),
4599 ItemType::Primitive => ("primitives", "Primitive Types"),
4600 ItemType::AssocType => ("associated-types", "Associated Types"),
4601 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4602 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4603 ItemType::Keyword => ("keywords", "Keywords"),
4604 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4605 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4606 ItemType::ProcDerive => ("derives", "Derive Macros"),
4607 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4611 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4612 let mut sidebar = String::new();
4614 if items.iter().any(|it| {
4615 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4617 sidebar.push_str(&format!(
4618 "<li><a href=\"#{id}\">{name}</a></li>",
4624 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4625 // to print its headings
4627 ItemType::Primitive,
4641 ItemType::StructField,
4643 ItemType::AssocType,
4644 ItemType::AssocConst,
4645 ItemType::ForeignType,
4648 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4649 let (short, name) = item_ty_to_strs(&myty);
4650 sidebar.push_str(&format!(
4651 "<li><a href=\"#{id}\">{name}</a></li>",
4658 if !sidebar.is_empty() {
4659 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4663 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4664 let sidebar = sidebar_assoc_items(it);
4665 if !sidebar.is_empty() {
4666 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4670 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4671 wrap_into_docblock(w, |w| {
4672 w.write_str(&highlight::render_with_highlighting(
4679 document(w, cx, it, None)
4682 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4683 let name = it.name.as_ref().expect("proc-macros always have names");
4685 MacroKind::Bang => {
4686 write!(w, "<pre class=\"rust macro\">");
4687 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4688 write!(w, "</pre>");
4690 MacroKind::Attr => {
4691 write!(w, "<pre class=\"rust attr\">");
4692 write!(w, "#[{}]", name);
4693 write!(w, "</pre>");
4695 MacroKind::Derive => {
4696 write!(w, "<pre class=\"rust derive\">");
4697 write!(w, "#[derive({})]", name);
4698 if !m.helpers.is_empty() {
4699 writeln!(w, "\n{{");
4700 writeln!(w, " // Attributes available to this derive:");
4701 for attr in &m.helpers {
4702 writeln!(w, " #[{}]", attr);
4706 write!(w, "</pre>");
4709 document(w, cx, it, None)
4712 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4713 document(w, cx, it, None);
4714 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4717 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4718 document(w, cx, it, None)
4721 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4723 fn make_item_keywords(it: &clean::Item) -> String {
4724 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4727 /// Returns a list of all paths used in the type.
4728 /// This is used to help deduplicate imported impls
4729 /// for reexported types. If any of the contained
4730 /// types are re-exported, we don't use the corresponding
4731 /// entry from the js file, as inlining will have already
4732 /// picked up the impl
4733 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4734 let mut out = Vec::new();
4735 let mut visited = FxHashSet::default();
4736 let mut work = VecDeque::new();
4737 let cache = cache();
4739 work.push_back(first_ty);
4741 while let Some(ty) = work.pop_front() {
4742 if !visited.insert(ty.clone()) {
4747 clean::Type::ResolvedPath { did, .. } => {
4748 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4749 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4751 if let Some(path) = fqp {
4752 out.push(path.join("::"));
4755 clean::Type::Tuple(tys) => {
4756 work.extend(tys.into_iter());
4758 clean::Type::Slice(ty) => {
4759 work.push_back(*ty);
4761 clean::Type::Array(ty, _) => {
4762 work.push_back(*ty);
4764 clean::Type::RawPointer(_, ty) => {
4765 work.push_back(*ty);
4767 clean::Type::BorrowedRef { type_, .. } => {
4768 work.push_back(*type_);
4770 clean::Type::QPath { self_type, trait_, .. } => {
4771 work.push_back(*self_type);
4772 work.push_back(*trait_);