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};
55 use rustc_data_structures::sync::Lrc;
57 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
58 use rustc_hir::Mutability;
59 use rustc_middle::middle::stability;
60 use rustc_session::Session;
61 use rustc_span::edition::Edition;
62 use rustc_span::hygiene::MacroKind;
63 use rustc_span::source_map::FileName;
64 use rustc_span::symbol::{sym, Symbol};
65 use serde::ser::SerializeSeq;
66 use serde::{Serialize, Serializer};
68 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, RenderedLink, SelfTy, TypeKind};
69 use crate::config::{RenderInfo, RenderOptions};
70 use crate::docfs::{DocFS, PathError};
72 use crate::error::Error;
73 use crate::formats::cache::{cache, Cache};
74 use crate::formats::item_type::ItemType;
75 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
76 use crate::html::escape::Escape;
77 use crate::html::format::fmt_impl_for_trait_page;
78 use crate::html::format::Function;
79 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
80 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
81 use crate::html::markdown::{
82 self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine,
84 use crate::html::sources;
85 use crate::html::{highlight, layout, static_files};
86 use cache::{build_index, ExternalLocation};
88 /// A pair of name and its optional document.
89 crate type NameDoc = (String, Option<String>);
91 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
92 crate::html::format::display_fn(move |f| {
93 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
97 /// Major driving force in all rustdoc rendering. This contains information
98 /// about where in the tree-like hierarchy rendering is occurring and controls
99 /// how the current page is being rendered.
101 /// It is intended that this context is a lightweight object which can be fairly
102 /// easily cloned because it is cloned per work-job (about once per item in the
105 crate struct Context {
106 /// Current hierarchy of components leading down to what's currently being
108 crate current: Vec<String>,
109 /// The current destination folder of where HTML artifacts should be placed.
110 /// This changes as the context descends into the module hierarchy.
112 /// A flag, which when `true`, will render pages which redirect to the
113 /// real location of an item. This is used to allow external links to
114 /// publicly reused items to redirect to the right location.
115 crate render_redirect_pages: bool,
116 /// The map used to ensure all generated 'id=' attributes are unique.
117 id_map: Rc<RefCell<IdMap>>,
118 crate shared: Arc<SharedContext>,
119 all: Rc<RefCell<AllTypes>>,
120 /// Storage for the errors produced while generating documentation so they
121 /// can be printed together at the end.
122 crate errors: Rc<Receiver<String>>,
125 crate struct SharedContext {
126 crate sess: Lrc<Session>,
127 /// The path to the crate root source minus the file name.
128 /// Used for simplifying paths to the highlighted source code files.
129 crate src_root: PathBuf,
130 /// This describes the layout of each page, and is not modified after
131 /// creation of the context (contains info like the favicon and added html).
132 crate layout: layout::Layout,
133 /// This flag indicates whether `[src]` links should be generated or not. If
134 /// the source files are present in the html rendering, then this will be
136 crate include_sources: bool,
137 /// The local file sources we've emitted and their respective url-paths.
138 crate local_sources: FxHashMap<PathBuf, String>,
139 /// Whether the collapsed pass ran
140 crate collapsed: bool,
141 /// The base-URL of the issue tracker for when an item has been tagged with
143 crate issue_tracker_base_url: Option<String>,
144 /// The directories that have already been created in this doc run. Used to reduce the number
145 /// of spurious `create_dir_all` calls.
146 crate created_dirs: RefCell<FxHashSet<PathBuf>>,
147 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
148 /// should be ordered alphabetically or in order of appearance (in the source code).
149 crate sort_modules_alphabetically: bool,
150 /// Additional CSS files to be added to the generated docs.
151 crate style_files: Vec<StylePath>,
152 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
154 crate resource_suffix: String,
155 /// Optional path string to be used to load static files on output pages. If not set, uses
156 /// combinations of `../` to reach the documentation root.
157 crate static_root_path: Option<String>,
158 /// The fs handle we are working with.
160 /// The default edition used to parse doctests.
161 crate edition: Edition,
162 crate codes: ErrorCodes,
163 playground: Option<markdown::Playground>,
167 fn path(&self, filename: &str) -> PathBuf {
168 // We use splitn vs Path::extension here because we might get a filename
169 // like `style.min.css` and we want to process that into
170 // `style-suffix.min.css`. Path::extension would just return `css`
171 // which would result in `style.min-suffix.css` which isn't what we
173 let (base, ext) = filename.split_once('.').unwrap();
174 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext);
175 self.dst.join(&filename)
178 fn sess(&self) -> &Session {
184 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
185 let mut dirs = self.created_dirs.borrow_mut();
186 if !dirs.contains(dst) {
187 try_err!(self.fs.create_dir_all(dst), dst);
188 dirs.insert(dst.to_path_buf());
194 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
195 /// `collapsed_doc_value` of the given item.
196 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
198 item.collapsed_doc_value().map(|s| s.into())
200 item.doc_value().map(|s| s.into())
205 // Helper structs for rendering items/sidebars and carrying along contextual
208 /// Struct representing one entry in the JS search index. These are all emitted
209 /// by hand to a large JS file at the end of cache-creation.
211 crate struct IndexItem {
216 crate parent: Option<DefId>,
217 crate parent_idx: Option<usize>,
218 crate search_type: Option<IndexItemFunctionType>,
221 impl Serialize for IndexItem {
222 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
227 self.parent.is_some(),
228 self.parent_idx.is_some(),
229 "`{}` is missing idx",
233 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
234 .serialize(serializer)
238 /// A type used for the search index.
240 crate struct RenderType {
243 name: Option<String>,
244 generics: Option<Vec<Generic>>,
247 impl Serialize for RenderType {
248 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
252 if let Some(name) = &self.name {
253 let mut seq = serializer.serialize_seq(None)?;
254 if let Some(id) = self.idx {
255 seq.serialize_element(&id)?;
257 seq.serialize_element(&name)?;
259 if let Some(generics) = &self.generics {
260 seq.serialize_element(&generics)?;
264 serializer.serialize_none()
269 /// A type used for the search index.
271 crate struct Generic {
273 defid: Option<DefId>,
277 impl Serialize for Generic {
278 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
282 if let Some(id) = self.idx {
283 serializer.serialize_some(&id)
285 serializer.serialize_some(&self.name)
290 /// Full type of functions/methods in the search index.
292 crate struct IndexItemFunctionType {
293 inputs: Vec<TypeWithKind>,
294 output: Option<Vec<TypeWithKind>>,
297 impl Serialize for IndexItemFunctionType {
298 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
302 // If we couldn't figure out a type, just write `null`.
303 let mut iter = self.inputs.iter();
304 if match self.output {
305 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
306 None => iter.any(|ref i| i.ty.name.is_none()),
308 serializer.serialize_none()
310 let mut seq = serializer.serialize_seq(None)?;
311 seq.serialize_element(&self.inputs)?;
312 if let Some(output) = &self.output {
313 if output.len() > 1 {
314 seq.serialize_element(&output)?;
316 seq.serialize_element(&output[0])?;
325 crate struct TypeWithKind {
330 impl From<(RenderType, TypeKind)> for TypeWithKind {
331 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
332 TypeWithKind { ty: x.0, kind: x.1 }
336 impl Serialize for TypeWithKind {
337 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
341 let mut seq = serializer.serialize_seq(None)?;
342 seq.serialize_element(&self.ty.name)?;
343 let x: ItemType = self.kind.into();
344 seq.serialize_element(&x)?;
349 #[derive(Debug, Clone)]
350 crate struct StylePath {
351 /// The path to the theme
353 /// What the `disabled` attribute should be set to in the HTML tag
354 crate disabled: bool,
357 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
359 crate fn initial_ids() -> Vec<String> {
371 "synthetic-implementors",
373 "synthetic-implementors-list",
379 .map(|id| (String::from(*id)))
383 /// Generates the documentation for `crate` into the directory `dst`
384 impl FormatRenderer for Context {
386 mut krate: clean::Crate,
387 options: RenderOptions,
388 _render_info: RenderInfo,
392 ) -> Result<(Context, clean::Crate), Error> {
393 // need to save a copy of the options for rendering the index page
394 let md_opts = options.clone();
400 sort_modules_alphabetically,
406 generate_search_filter,
411 let src_root = match krate.src {
412 FileName::Real(ref p) => match p.local_path().parent() {
413 Some(p) => p.to_path_buf(),
414 None => PathBuf::new(),
418 // If user passed in `--playground-url` arg, we fill in crate name here
419 let mut playground = None;
420 if let Some(url) = playground_url {
421 playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url });
423 let mut layout = layout::Layout {
425 favicon: String::new(),
428 krate: krate.name.clone(),
429 css_file_extension: extension_css,
430 generate_search_filter,
432 let mut issue_tracker_base_url = None;
433 let mut include_sources = true;
435 // Crawl the crate attributes looking for attributes which control how we're
436 // going to emit HTML
437 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
438 for attr in attrs.lists(sym::doc) {
439 match (attr.name_or_empty(), attr.value_str()) {
440 (sym::html_favicon_url, Some(s)) => {
441 layout.favicon = s.to_string();
443 (sym::html_logo_url, Some(s)) => {
444 layout.logo = s.to_string();
446 (sym::html_playground_url, Some(s)) => {
447 playground = Some(markdown::Playground {
448 crate_name: Some(krate.name.clone()),
452 (sym::issue_tracker_base_url, Some(s)) => {
453 issue_tracker_base_url = Some(s.to_string());
455 (sym::html_no_source, None) if attr.is_word() => {
456 include_sources = false;
462 let (sender, receiver) = channel();
463 let mut scx = SharedContext {
465 collapsed: krate.collapsed,
468 local_sources: Default::default(),
469 issue_tracker_base_url,
471 created_dirs: Default::default(),
472 sort_modules_alphabetically,
476 fs: DocFS::new(sender),
478 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
482 // Add the default themes to the `Vec` of stylepaths
484 // Note that these must be added before `sources::render` is called
485 // so that the resulting source pages are styled
487 // `light.css` is not disabled because it is the stylesheet that stays loaded
488 // by the browser as the theme stylesheet. The theme system (hackily) works by
489 // changing the href to this stylesheet. All other themes are disabled to
490 // prevent rule conflicts
491 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
492 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
493 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
496 scx.ensure_dir(&dst)?;
497 krate = sources::render(&dst, &mut scx, krate)?;
499 // Build our search index
500 let index = build_index(&krate, cache);
502 let cache = Arc::new(cache);
503 let mut cx = Context {
506 render_redirect_pages: false,
507 id_map: Rc::new(RefCell::new(id_map)),
508 shared: Arc::new(scx),
509 all: Rc::new(RefCell::new(AllTypes::new())),
510 errors: Rc::new(receiver),
513 CURRENT_DEPTH.with(|s| s.set(0));
515 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
516 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
517 write_shared(&cx, &krate, index, &md_opts, &cache)?;
518 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
522 fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
523 Arc::get_mut(&mut self.shared).unwrap().fs.close();
524 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
526 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
532 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
533 let final_file = self.dst.join(&krate.name).join("all.html");
534 let settings_file = self.dst.join("settings.html");
535 let crate_name = krate.name.clone();
537 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
538 if !root_path.ends_with('/') {
541 let mut page = layout::Page {
542 title: "List of all items in this crate",
545 static_root_path: self.shared.static_root_path.as_deref(),
546 description: "List of all items in this crate",
547 keywords: BASIC_KEYWORDS,
548 resource_suffix: &self.shared.resource_suffix,
550 static_extra_scripts: &[],
552 let sidebar = if let Some(ref version) = cache.crate_version {
554 "<p class=\"location\">Crate {}</p>\
555 <div class=\"block version\">\
558 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
565 let all = self.all.replace(AllTypes::new());
566 let v = layout::render(
570 |buf: &mut Buffer| all.print(buf),
571 &self.shared.style_files,
573 self.shared.fs.write(&final_file, v.as_bytes())?;
575 // Generating settings page.
576 page.title = "Rustdoc settings";
577 page.description = "Settings of Rustdoc";
578 page.root_path = "./";
580 let mut style_files = self.shared.style_files.clone();
581 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
582 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
583 let v = layout::render(
588 self.shared.static_root_path.as_deref().unwrap_or("./"),
589 &self.shared.resource_suffix,
590 &self.shared.style_files,
594 self.shared.fs.write(&settings_file, v.as_bytes())?;
603 ) -> Result<(), Error> {
604 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
605 // if they contain impls for public types. These modules can also
606 // contain items such as publicly re-exported structures.
608 // External crates will provide links to these structures, so
609 // these modules are recursed into, but not rendered normally
610 // (a flag on the context).
611 if !self.render_redirect_pages {
612 self.render_redirect_pages = item.is_stripped();
614 let scx = &self.shared;
615 self.dst.push(item_name);
616 self.current.push(item_name.to_owned());
618 info!("Recursing into {}", self.dst.display());
620 let buf = self.render_item(item, false, cache);
621 // buf will be empty if the module is stripped and there is no redirect for it
623 self.shared.ensure_dir(&self.dst)?;
624 let joint_dst = self.dst.join("index.html");
625 scx.fs.write(&joint_dst, buf.as_bytes())?;
628 // Render sidebar-items.js used throughout this module.
629 if !self.render_redirect_pages {
630 let module = match item.kind {
631 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
634 let items = self.build_sidebar_items(module);
635 let js_dst = self.dst.join("sidebar-items.js");
636 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
637 scx.fs.write(&js_dst, &v)?;
642 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
643 info!("Recursed; leaving {}", self.dst.display());
645 // Go back to where we were at
651 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
652 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
653 // if they contain impls for public types. These modules can also
654 // contain items such as publicly re-exported structures.
656 // External crates will provide links to these structures, so
657 // these modules are recursed into, but not rendered normally
658 // (a flag on the context).
659 if !self.render_redirect_pages {
660 self.render_redirect_pages = item.is_stripped();
663 let buf = self.render_item(&item, true, cache);
664 // buf will be empty if the item is stripped and there is no redirect for it
666 let name = item.name.as_ref().unwrap();
667 let item_type = item.type_();
668 let file_name = &item_path(item_type, name);
669 self.shared.ensure_dir(&self.dst)?;
670 let joint_dst = self.dst.join(file_name);
671 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
673 if !self.render_redirect_pages {
674 self.all.borrow_mut().append(full_path(self, &item), &item_type);
676 // If the item is a macro, redirect from the old macro URL (with !)
677 // to the new one (without).
678 if item_type == ItemType::Macro {
679 let redir_name = format!("{}.{}!.html", item_type, name);
680 let redir_dst = self.dst.join(redir_name);
681 let v = layout::redirect(file_name);
682 self.shared.fs.write(&redir_dst, v.as_bytes())?;
691 krate: &clean::Crate,
692 search_index: String,
693 options: &RenderOptions,
695 ) -> Result<(), Error> {
696 // Write out the shared files. Note that these are shared among all rustdoc
697 // docs placed in the output directory, so this needs to be a synchronized
698 // operation with respect to all other rustdocs running around.
699 let lock_file = cx.dst.join(".lock");
700 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
702 // Add all the static files. These may already exist, but we just
703 // overwrite them anyway to make sure that they're fresh and up-to-date.
707 cx.path("rustdoc.css"),
708 static_files::RUSTDOC_CSS,
709 options.enable_minification,
713 cx.path("settings.css"),
714 static_files::SETTINGS_CSS,
715 options.enable_minification,
719 cx.path("noscript.css"),
720 static_files::NOSCRIPT_CSS,
721 options.enable_minification,
724 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
725 // then we'll run over the "official" styles.
726 let mut themes: FxHashSet<String> = FxHashSet::default();
728 for entry in &cx.shared.style_files {
729 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
731 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
733 // Handle the official themes
735 "light" => write_minify(
737 cx.path("light.css"),
738 static_files::themes::LIGHT,
739 options.enable_minification,
741 "dark" => write_minify(
744 static_files::themes::DARK,
745 options.enable_minification,
747 "ayu" => write_minify(
750 static_files::themes::AYU,
751 options.enable_minification,
754 // Handle added third-party themes
755 let content = try_err!(fs::read(&entry.path), &entry.path);
758 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
762 themes.insert(theme.to_owned());
765 let write = |p, c| cx.shared.fs.write(p, c);
766 if (*cx.shared).layout.logo.is_empty() {
767 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
769 if (*cx.shared).layout.favicon.is_empty() {
770 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
771 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
772 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
774 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
775 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
776 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
778 let mut themes: Vec<&String> = themes.iter().collect();
780 // To avoid theme switch latencies as much as possible, we put everything theme related
781 // at the beginning of the html files into another js file.
782 let theme_js = format!(
783 r#"var themes = document.getElementById("theme-choices");
784 var themePicker = document.getElementById("theme-picker");
786 function showThemeButtonState() {{
787 themes.style.display = "block";
788 themePicker.style.borderBottomRightRadius = "0";
789 themePicker.style.borderBottomLeftRadius = "0";
792 function hideThemeButtonState() {{
793 themes.style.display = "none";
794 themePicker.style.borderBottomRightRadius = "3px";
795 themePicker.style.borderBottomLeftRadius = "3px";
798 function switchThemeButtonState() {{
799 if (themes.style.display === "block") {{
800 hideThemeButtonState();
802 showThemeButtonState();
806 function handleThemeButtonsBlur(e) {{
807 var active = document.activeElement;
808 var related = e.relatedTarget;
810 if (active.id !== "theme-picker" &&
811 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
813 (related.id !== "theme-picker" &&
814 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
815 hideThemeButtonState();
819 themePicker.onclick = switchThemeButtonState;
820 themePicker.onblur = handleThemeButtonsBlur;
821 {}.forEach(function(item) {{
822 var but = document.createElement("button");
823 but.textContent = item;
824 but.onclick = function(el) {{
825 switchTheme(currentTheme, mainTheme, item, true);
826 useSystemTheme(false);
828 but.onblur = handleThemeButtonsBlur;
829 themes.appendChild(but);
831 serde_json::to_string(&themes).unwrap()
834 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
838 static_files::MAIN_JS,
839 options.enable_minification,
843 cx.path("settings.js"),
844 static_files::SETTINGS_JS,
845 options.enable_minification,
847 if cx.shared.include_sources {
850 cx.path("source-script.js"),
851 static_files::sidebar::SOURCE_SCRIPT,
852 options.enable_minification,
859 cx.path("storage.js"),
861 "var resourcesSuffix = \"{}\";{}",
862 cx.shared.resource_suffix,
863 static_files::STORAGE_JS
865 options.enable_minification,
869 if let Some(ref css) = cx.shared.layout.css_file_extension {
870 let out = cx.path("theme.css");
871 let buffer = try_err!(fs::read_to_string(css), css);
872 if !options.enable_minification {
873 cx.shared.fs.write(&out, &buffer)?;
875 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
880 cx.path("normalize.css"),
881 static_files::NORMALIZE_CSS,
882 options.enable_minification,
884 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
885 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
886 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
887 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
888 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
889 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
890 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
891 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
892 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
893 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
894 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
895 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
896 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
898 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
899 let mut ret = Vec::new();
900 let mut krates = Vec::new();
903 for line in BufReader::new(File::open(path)?).lines() {
905 if !line.starts_with(key) {
908 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
911 ret.push(line.to_string());
913 line[key.len() + 2..]
916 .map(|s| s.to_owned())
917 .unwrap_or_else(String::new),
924 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
925 let mut ret = Vec::new();
926 let mut krates = Vec::new();
929 for line in BufReader::new(File::open(path)?).lines() {
931 if !line.starts_with('"') {
934 if line.starts_with(&format!("\"{}\"", krate)) {
937 if line.ends_with(",\\") {
938 ret.push(line[..line.len() - 2].to_string());
940 // Ends with "\\" (it's the case for the last added crate line)
941 ret.push(line[..line.len() - 1].to_string());
945 .find(|s| !s.is_empty())
946 .map(|s| s.to_owned())
947 .unwrap_or_else(String::new),
954 use std::ffi::OsString;
959 children: FxHashMap<OsString, Hierarchy>,
960 elems: FxHashSet<OsString>,
964 fn new(elem: OsString) -> Hierarchy {
965 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
968 fn to_json_string(&self) -> String {
969 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
970 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
974 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
975 .collect::<Vec<_>>();
976 files.sort_unstable_by(|a, b| a.cmp(b));
977 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
979 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
980 let files = files.join(",");
982 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
984 "{{\"name\":\"{name}\"{dirs}{files}}}",
985 name = self.elem.to_str().expect("invalid osstring conversion"),
992 if cx.shared.include_sources {
993 let mut hierarchy = Hierarchy::new(OsString::new());
998 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
1000 let mut h = &mut hierarchy;
1001 let mut elems = source
1003 .filter_map(|s| match s {
1004 Component::Normal(s) => Some(s.to_owned()),
1009 let cur_elem = elems.next().expect("empty file path");
1010 if elems.peek().is_none() {
1011 h.elems.insert(cur_elem);
1014 let e = cur_elem.clone();
1015 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1016 h = h.children.get_mut(&cur_elem).expect("not found child");
1021 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1022 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1023 all_sources.push(format!(
1024 "sourcesIndex[\"{}\"] = {};",
1026 hierarchy.to_json_string()
1030 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1031 all_sources.join("\n")
1033 cx.shared.fs.write(&dst, v.as_bytes())?;
1036 // Update the search index
1037 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1038 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name), &dst);
1039 all_indexes.push(search_index);
1041 // Sort the indexes by crate so the file will be generated identically even
1042 // with rustdoc running in parallel.
1045 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1046 v.push_str(&all_indexes.join(",\\\n"));
1047 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1048 // search might start (if it's set into the URL for example).
1049 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1050 cx.shared.fs.write(&dst, &v)?;
1052 if options.enable_index_page {
1053 if let Some(index_page) = options.index_page.clone() {
1054 let mut md_opts = options.clone();
1055 md_opts.output = cx.dst.clone();
1056 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1058 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1059 .map_err(|e| Error::new(e, &index_page))?;
1061 let dst = cx.dst.join("index.html");
1062 let page = layout::Page {
1063 title: "Index of crates",
1066 static_root_path: cx.shared.static_root_path.as_deref(),
1067 description: "List of crates",
1068 keywords: BASIC_KEYWORDS,
1069 resource_suffix: &cx.shared.resource_suffix,
1071 static_extra_scripts: &[],
1073 krates.push(krate.name.clone());
1077 let content = format!(
1078 "<h1 class=\"fqn\">\
1079 <span class=\"in-band\">List of all crates</span>\
1080 </h1><ul class=\"crate mod\">{}</ul>",
1085 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1086 ensure_trailing_slash(s),
1090 .collect::<String>()
1092 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1093 cx.shared.fs.write(&dst, v.as_bytes())?;
1097 // Update the list of all implementors for traits
1098 let dst = cx.dst.join("implementors");
1099 for (&did, imps) in &cache.implementors {
1100 // Private modules can leak through to this phase of rustdoc, which
1101 // could contain implementations for otherwise private types. In some
1102 // rare cases we could find an implementation for an item which wasn't
1103 // indexed, so we just skip this step in that case.
1105 // FIXME: this is a vague explanation for why this can't be a `get`, in
1106 // theory it should be...
1107 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1109 None => match cache.external_paths.get(&did) {
1115 #[derive(Serialize)]
1116 struct Implementor {
1122 let implementors = imps
1125 // If the trait and implementation are in the same crate, then
1126 // there's no need to emit information about it (there's inlining
1127 // going on). If they're in different crates then the crate defining
1128 // the trait will be interested in our implementation.
1130 // If the implementation is from another crate then that crate
1132 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1136 text: imp.inner_impl().print().to_string(),
1137 synthetic: imp.inner_impl().synthetic,
1138 types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1142 .collect::<Vec<_>>();
1144 // Only create a js file if we have impls to add to it. If the trait is
1145 // documented locally though we always create the file to avoid dead
1147 if implementors.is_empty() && !cache.paths.contains_key(&did) {
1151 let implementors = format!(
1152 r#"implementors["{}"] = {};"#,
1154 serde_json::to_string(&implementors).unwrap()
1157 let mut mydst = dst.clone();
1158 for part in &remote_path[..remote_path.len() - 1] {
1161 cx.shared.ensure_dir(&mydst)?;
1162 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1164 let (mut all_implementors, _) =
1165 try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1166 all_implementors.push(implementors);
1167 // Sort the implementors by crate so the file will be generated
1168 // identically even with rustdoc running in parallel.
1169 all_implementors.sort();
1171 let mut v = String::from("(function() {var implementors = {};\n");
1172 for implementor in &all_implementors {
1173 writeln!(v, "{}", *implementor).unwrap();
1176 "if (window.register_implementors) {\
1177 window.register_implementors(implementors);\
1179 window.pending_implementors = implementors;\
1183 cx.shared.fs.write(&mydst, &v)?;
1192 enable_minification: bool,
1193 ) -> Result<(), Error> {
1194 if enable_minification {
1195 if dst.extension() == Some(&OsStr::new("css")) {
1196 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1197 fs.write(dst, res.as_bytes())
1199 fs.write(dst, minifier::js::minify(contents).as_bytes())
1202 fs.write(dst, contents.as_bytes())
1206 fn write_srclink(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1207 if let Some(l) = cx.src_href(item, cache) {
1210 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
1211 l, "goto source code"
1216 #[derive(Debug, Eq, PartialEq, Hash)]
1223 fn new(mut url: String, name: String) -> ItemEntry {
1224 while url.starts_with('/') {
1227 ItemEntry { url, name }
1232 crate fn print(&self) -> impl fmt::Display + '_ {
1233 crate::html::format::display_fn(move |f| {
1234 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1239 impl PartialOrd for ItemEntry {
1240 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1241 Some(self.cmp(other))
1245 impl Ord for ItemEntry {
1246 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1247 self.name.cmp(&other.name)
1253 structs: FxHashSet<ItemEntry>,
1254 enums: FxHashSet<ItemEntry>,
1255 unions: FxHashSet<ItemEntry>,
1256 primitives: FxHashSet<ItemEntry>,
1257 traits: FxHashSet<ItemEntry>,
1258 macros: FxHashSet<ItemEntry>,
1259 functions: FxHashSet<ItemEntry>,
1260 typedefs: FxHashSet<ItemEntry>,
1261 opaque_tys: FxHashSet<ItemEntry>,
1262 statics: FxHashSet<ItemEntry>,
1263 constants: FxHashSet<ItemEntry>,
1264 keywords: FxHashSet<ItemEntry>,
1265 attributes: FxHashSet<ItemEntry>,
1266 derives: FxHashSet<ItemEntry>,
1267 trait_aliases: FxHashSet<ItemEntry>,
1271 fn new() -> AllTypes {
1272 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1274 structs: new_set(100),
1275 enums: new_set(100),
1276 unions: new_set(100),
1277 primitives: new_set(26),
1278 traits: new_set(100),
1279 macros: new_set(100),
1280 functions: new_set(100),
1281 typedefs: new_set(100),
1282 opaque_tys: new_set(100),
1283 statics: new_set(100),
1284 constants: new_set(100),
1285 keywords: new_set(100),
1286 attributes: new_set(100),
1287 derives: new_set(100),
1288 trait_aliases: new_set(100),
1292 fn append(&mut self, item_name: String, item_type: &ItemType) {
1293 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1294 if let Some(name) = url.pop() {
1295 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1297 let name = url.join("::");
1299 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1300 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1301 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1302 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1303 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1304 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1305 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1306 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1307 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1308 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1309 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1310 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1311 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1312 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1319 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1321 let mut e: Vec<&ItemEntry> = e.iter().collect();
1325 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">{}</ul>",
1329 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1335 fn print(self, f: &mut Buffer) {
1338 "<h1 class=\"fqn\">\
1339 <span class=\"out-of-band\">\
1340 <span id=\"render-detail\">\
1341 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1342 title=\"collapse all docs\">\
1343 [<span class=\"inner\">−</span>]\
1347 <span class=\"in-band\">List of all items</span>\
1350 print_entries(f, &self.structs, "Structs", "structs");
1351 print_entries(f, &self.enums, "Enums", "enums");
1352 print_entries(f, &self.unions, "Unions", "unions");
1353 print_entries(f, &self.primitives, "Primitives", "primitives");
1354 print_entries(f, &self.traits, "Traits", "traits");
1355 print_entries(f, &self.macros, "Macros", "macros");
1356 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1357 print_entries(f, &self.derives, "Derive Macros", "derives");
1358 print_entries(f, &self.functions, "Functions", "functions");
1359 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1360 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1361 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1362 print_entries(f, &self.statics, "Statics", "statics");
1363 print_entries(f, &self.constants, "Constants", "constants")
1370 description: &'static str,
1371 sub_settings: Vec<Setting>,
1374 js_data_name: &'static str,
1375 description: &'static str,
1376 default_value: bool,
1379 js_data_name: &'static str,
1380 description: &'static str,
1381 default_value: &'static str,
1382 options: Vec<(String, String)>,
1387 fn display(&self, root_path: &str, suffix: &str) -> String {
1389 Setting::Section { description, ref sub_settings } => format!(
1390 "<div class=\"setting-line\">\
1391 <div class=\"title\">{}</div>\
1392 <div class=\"sub-settings\">{}</div>
1395 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1397 Setting::Toggle { js_data_name, description, default_value } => format!(
1398 "<div class=\"setting-line\">\
1399 <label class=\"toggle\">\
1400 <input type=\"checkbox\" id=\"{}\" {}>\
1401 <span class=\"slider\"></span>\
1406 if default_value { " checked" } else { "" },
1409 Setting::Select { js_data_name, description, default_value, ref options } => format!(
1410 "<div class=\"setting-line\">\
1412 <label class=\"select-wrapper\">\
1413 <select id=\"{}\" autocomplete=\"off\">{}</select>\
1414 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1422 "<option value=\"{}\" {}>{}</option>",
1424 if &opt.0 == default_value { "selected" } else { "" },
1427 .collect::<String>(),
1435 impl From<(&'static str, &'static str, bool)> for Setting {
1436 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1437 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1441 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1442 fn from(values: (&'static str, Vec<T>)) -> Setting {
1444 description: values.0,
1445 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1450 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1451 let theme_names: Vec<(String, String)> = themes
1455 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1458 Ok((theme.clone(), theme))
1460 .collect::<Result<_, Error>>()?;
1462 // (id, explanation, default value)
1463 let settings: &[Setting] = &[
1465 "Theme preferences",
1467 Setting::from(("use-system-theme", "Use system theme", true)),
1469 js_data_name: "preferred-dark-theme",
1470 description: "Preferred dark theme",
1471 default_value: "dark",
1472 options: theme_names.clone(),
1475 js_data_name: "preferred-light-theme",
1476 description: "Preferred light theme",
1477 default_value: "light",
1478 options: theme_names,
1484 "Auto-hide item declarations",
1486 ("auto-hide-struct", "Auto-hide structs declaration", true),
1487 ("auto-hide-enum", "Auto-hide enums declaration", false),
1488 ("auto-hide-union", "Auto-hide unions declaration", true),
1489 ("auto-hide-trait", "Auto-hide traits declaration", true),
1490 ("auto-hide-macro", "Auto-hide macros declaration", false),
1494 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1495 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1496 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1498 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1499 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1501 ("line-numbers", "Show line numbers on code examples", false).into(),
1502 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1506 "<h1 class=\"fqn\">\
1507 <span class=\"in-band\">Rustdoc settings</span>\
1509 <div class=\"settings\">{}</div>\
1510 <script src=\"{}settings{}.js\"></script>",
1511 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1518 fn derive_id(&self, id: String) -> String {
1519 let mut map = self.id_map.borrow_mut();
1523 /// String representation of how to get back to the root path of the 'doc/'
1524 /// folder in terms of a relative URL.
1525 fn root_path(&self) -> String {
1526 "../".repeat(self.current.len())
1529 fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1530 // A little unfortunate that this is done like this, but it sure
1531 // does make formatting *a lot* nicer.
1532 CURRENT_DEPTH.with(|slot| {
1533 slot.set(self.current.len());
1536 let mut title = if it.is_primitive() || it.is_keyword() {
1537 // No need to include the namespace for primitive types and keywords
1540 self.current.join("::")
1543 if !title.is_empty() {
1544 title.push_str("::");
1546 title.push_str(it.name.as_ref().unwrap());
1548 title.push_str(" - Rust");
1549 let tyname = it.type_();
1550 let desc = if it.is_crate() {
1551 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1554 "API documentation for the Rust `{}` {} in crate `{}`.",
1555 it.name.as_ref().unwrap(),
1557 self.shared.layout.krate
1560 let keywords = make_item_keywords(it);
1561 let page = layout::Page {
1562 css_class: tyname.as_str(),
1563 root_path: &self.root_path(),
1564 static_root_path: self.shared.static_root_path.as_deref(),
1567 keywords: &keywords,
1568 resource_suffix: &self.shared.resource_suffix,
1570 static_extra_scripts: &[],
1574 self.id_map.borrow_mut().reset();
1575 self.id_map.borrow_mut().populate(initial_ids());
1578 if !self.render_redirect_pages {
1580 &self.shared.layout,
1582 |buf: &mut _| print_sidebar(self, it, buf, cache),
1583 |buf: &mut _| print_item(self, it, buf, cache),
1584 &self.shared.style_files,
1587 let mut url = self.root_path();
1588 if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1589 for name in &names[..names.len() - 1] {
1593 url.push_str(&item_path(ty, names.last().unwrap()));
1594 layout::redirect(&url)
1601 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1602 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1603 // BTreeMap instead of HashMap to get a sorted output
1604 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1605 for item in &m.items {
1606 if item.is_stripped() {
1610 let short = item.type_();
1611 let myname = match item.name {
1613 Some(ref s) => s.to_string(),
1615 let short = short.to_string();
1616 map.entry(short).or_default().push((
1618 Some(item.doc_value().map_or_else(|| String::new(), plain_text_summary)),
1622 if self.shared.sort_modules_alphabetically {
1623 for items in map.values_mut() {
1630 /// Generates a url appropriate for an `href` attribute back to the source of
1633 /// The url generated, when clicked, will redirect the browser back to the
1634 /// original source code.
1636 /// If `None` is returned, then a source link couldn't be generated. This
1637 /// may happen, for example, with externally inlined items where the source
1638 /// of their crate documentation isn't known.
1639 fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1640 let mut root = self.root_path();
1641 let mut path = String::new();
1642 let cnum = item.source.cnum(self.sess());
1644 // We can safely ignore synthetic `SourceFile`s.
1645 let file = match item.source.filename(self.sess()) {
1646 FileName::Real(ref path) => path.local_path().to_path_buf(),
1651 let (krate, path) = if cnum == LOCAL_CRATE {
1652 if let Some(path) = self.shared.local_sources.get(file) {
1653 (&self.shared.layout.krate, path)
1658 let (krate, src_root) = match *cache.extern_locations.get(&cnum)? {
1659 (ref name, ref src, ExternalLocation::Local) => (name, src),
1660 (ref name, ref src, ExternalLocation::Remote(ref s)) => {
1661 root = s.to_string();
1664 (_, _, ExternalLocation::Unknown) => return None,
1667 sources::clean_path(&src_root, file, false, |component| {
1668 path.push_str(&component.to_string_lossy());
1671 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1672 fname.push(".html");
1673 path.push_str(&fname.to_string_lossy());
1677 let loline = item.source.lo(self.sess()).line;
1678 let hiline = item.source.hi(self.sess()).line;
1680 if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) };
1682 "{root}src/{krate}/{path}#{lines}",
1683 root = Escape(&root),
1691 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1693 F: FnOnce(&mut Buffer),
1695 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1700 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1701 debug_assert!(!item.is_stripped());
1702 // Write the breadcrumb trail header for the top
1703 write!(buf, "<h1 class=\"fqn\"><span class=\"out-of-band\">");
1704 render_stability_since_raw(
1706 item.stable_since().as_deref(),
1707 item.const_stable_since().as_deref(),
1713 "<span id=\"render-detail\">\
1714 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1715 title=\"collapse all docs\">\
1716 [<span class=\"inner\">−</span>]\
1723 // When this item is part of a `crate use` in a downstream crate, the
1724 // [src] link in the downstream documentation will actually come back to
1725 // this page, and this link will be auto-clicked. The `id` attribute is
1726 // used to find the link to auto-click.
1727 if cx.shared.include_sources && !item.is_primitive() {
1728 write_srclink(cx, item, buf, cache);
1731 write!(buf, "</span>"); // out-of-band
1732 write!(buf, "<span class=\"in-band\">");
1733 let name = match item.kind {
1734 clean::ModuleItem(ref m) => {
1741 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1742 clean::TraitItem(..) => "Trait ",
1743 clean::StructItem(..) => "Struct ",
1744 clean::UnionItem(..) => "Union ",
1745 clean::EnumItem(..) => "Enum ",
1746 clean::TypedefItem(..) => "Type Definition ",
1747 clean::MacroItem(..) => "Macro ",
1748 clean::ProcMacroItem(ref mac) => match mac.kind {
1749 MacroKind::Bang => "Macro ",
1750 MacroKind::Attr => "Attribute Macro ",
1751 MacroKind::Derive => "Derive Macro ",
1753 clean::PrimitiveItem(..) => "Primitive Type ",
1754 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1755 clean::ConstantItem(..) => "Constant ",
1756 clean::ForeignTypeItem => "Foreign Type ",
1757 clean::KeywordItem(..) => "Keyword ",
1758 clean::OpaqueTyItem(..) => "Opaque Type ",
1759 clean::TraitAliasItem(..) => "Trait Alias ",
1761 // We don't generate pages for any other type.
1765 buf.write_str(name);
1766 if !item.is_primitive() && !item.is_keyword() {
1767 let cur = &cx.current;
1768 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1769 for (i, component) in cur.iter().enumerate().take(amt) {
1772 "<a href=\"{}index.html\">{}</a>::<wbr>",
1773 "../".repeat(cur.len() - i - 1),
1778 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1780 write!(buf, "</span></h1>"); // in-band
1783 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1784 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1785 item_function(buf, cx, item, f)
1787 clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1788 clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1789 clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1790 clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1791 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1792 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1793 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1794 clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1795 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1796 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1797 clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1798 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1799 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e, cache),
1800 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1802 // We don't generate pages for any other type.
1808 fn item_path(ty: ItemType, name: &str) -> String {
1810 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1811 _ => format!("{}.{}.html", ty, name),
1815 fn full_path(cx: &Context, item: &clean::Item) -> String {
1816 let mut s = cx.current.join("::");
1818 s.push_str(item.name.as_ref().unwrap());
1822 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item, parent: Option<&clean::Item>) {
1823 if let Some(ref name) = item.name {
1824 info!("Documenting {}", name);
1826 document_item_info(w, cx, item, false, parent);
1827 document_full(w, item, cx, "", false);
1830 /// Render md_text as markdown.
1835 links: Vec<RenderedLink>,
1839 let mut ids = cx.id_map.borrow_mut();
1842 "<div class=\"docblock{}\">{}{}</div>",
1843 if is_hidden { " hidden" } else { "" },
1851 &cx.shared.playground
1857 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1858 /// docs are longer, a "Read more" link is appended to the end.
1863 link: AssocItemLink<'_>,
1866 parent: Option<&clean::Item>,
1867 show_def_docs: bool,
1869 document_item_info(w, cx, item, is_hidden, parent);
1873 if let Some(s) = item.doc_value() {
1874 let mut summary_html = MarkdownSummaryLine(s, &item.links()).into_string();
1876 if s.contains('\n') {
1877 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link));
1879 if let Some(idx) = summary_html.rfind("</p>") {
1880 summary_html.insert_str(idx, &link);
1882 summary_html.push_str(&link);
1888 "<div class='docblock{}'>{}{}</div>",
1889 if is_hidden { " hidden" } else { "" },
1893 } else if !prefix.is_empty() {
1896 "<div class=\"docblock{}\">{}</div>",
1897 if is_hidden { " hidden" } else { "" },
1903 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1904 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1905 debug!("Doc block: =====\n{}\n=====", s);
1906 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1907 } else if !prefix.is_empty() {
1910 "<div class=\"docblock{}\">{}</div>",
1911 if is_hidden { " hidden" } else { "" },
1917 /// Add extra information about an item such as:
1921 /// * Required features (through the `doc_cfg` feature)
1922 fn document_item_info(
1927 parent: Option<&clean::Item>,
1929 let item_infos = short_item_info(item, cx, parent);
1930 if !item_infos.is_empty() {
1931 write!(w, "<div class=\"item-info{}\">", if is_hidden { " hidden" } else { "" });
1932 for info in item_infos {
1933 write!(w, "{}", info);
1935 write!(w, "</div>");
1939 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1940 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1943 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1944 if item.is_non_exhaustive() {
1945 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1946 if item.is_struct() {
1948 } else if item.is_enum() {
1950 } else if item.is_variant() {
1957 if item.is_struct() {
1960 "Non-exhaustive structs could have additional fields added in future. \
1961 Therefore, non-exhaustive structs cannot be constructed in external crates \
1962 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1963 matched against without a wildcard <code>..</code>; and \
1964 struct update syntax will not work."
1966 } else if item.is_enum() {
1969 "Non-exhaustive enums could have additional variants added in future. \
1970 Therefore, when matching against variants of non-exhaustive enums, an \
1971 extra wildcard arm must be added to account for any future variants."
1973 } else if item.is_variant() {
1976 "Non-exhaustive enum variants could have additional fields added in future. \
1977 Therefore, non-exhaustive enum variants cannot be constructed in external \
1978 crates and cannot be matched against."
1983 "This type will require a wildcard arm in any match statements or constructors."
1987 write!(w, "</div>");
1991 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1992 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1993 /// Takes a non-numeric and a numeric part from the given &str.
1994 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1995 let i = s.find(|c: char| c.is_ascii_digit());
1996 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1997 let i = b.find(|c: char| !c.is_ascii_digit());
1998 let (b, c) = b.split_at(i.unwrap_or(b.len()));
2003 while !lhs.is_empty() || !rhs.is_empty() {
2004 let (la, lb) = take_parts(&mut lhs);
2005 let (ra, rb) = take_parts(&mut rhs);
2006 // First process the non-numeric part.
2008 Ordering::Equal => (),
2011 // Then process the numeric part, if both sides have one (and they fit in a u64).
2012 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2014 Ordering::Equal => (),
2018 // Then process the numeric part again, but this time as strings.
2020 Ordering::Equal => (),
2028 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
2029 document(w, cx, item, None);
2031 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2033 // the order of item types in the listing
2034 fn reorder(ty: ItemType) -> u8 {
2036 ItemType::ExternCrate => 0,
2037 ItemType::Import => 1,
2038 ItemType::Primitive => 2,
2039 ItemType::Module => 3,
2040 ItemType::Macro => 4,
2041 ItemType::Struct => 5,
2042 ItemType::Enum => 6,
2043 ItemType::Constant => 7,
2044 ItemType::Static => 8,
2045 ItemType::Trait => 9,
2046 ItemType::Function => 10,
2047 ItemType::Typedef => 12,
2048 ItemType::Union => 13,
2053 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2054 let ty1 = i1.type_();
2055 let ty2 = i2.type_();
2057 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2059 let s1 = i1.stability.as_ref().map(|s| s.level);
2060 let s2 = i2.stability.as_ref().map(|s| s.level);
2061 if let (Some(a), Some(b)) = (s1, s2) {
2062 match (a.is_stable(), b.is_stable()) {
2063 (true, true) | (false, false) => {}
2064 (false, true) => return Ordering::Less,
2065 (true, false) => return Ordering::Greater,
2068 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2069 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2070 compare_names(lhs, rhs)
2073 if cx.shared.sort_modules_alphabetically {
2074 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2076 // This call is to remove re-export duplicates in cases such as:
2081 // crate trait Double { fn foo(); }
2085 // crate use foo::bar::*;
2086 // crate use foo::*;
2089 // `Double` will appear twice in the generated docs.
2091 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2092 // can be identical even if the elements are different (mostly in imports).
2093 // So in case this is an import, we keep everything by adding a "unique id"
2094 // (which is the position in the vector).
2095 indices.dedup_by_key(|i| {
2098 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2100 if items[*i].is_import() { *i } else { 0 },
2104 debug!("{:?}", indices);
2105 let mut curty = None;
2106 for &idx in &indices {
2107 let myitem = &items[idx];
2108 if myitem.is_stripped() {
2112 let myty = Some(myitem.type_());
2113 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2114 // Put `extern crate` and `use` re-exports in the same section.
2116 } else if myty != curty {
2117 if curty.is_some() {
2118 write!(w, "</table>");
2121 let (short, name) = item_ty_to_strs(&myty.unwrap());
2124 "<h2 id=\"{id}\" class=\"section-header\">\
2125 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2126 id = cx.derive_id(short.to_owned()),
2132 clean::ExternCrateItem(ref name, ref src) => {
2133 use crate::html::format::anchor;
2136 Some(ref src) => write!(
2138 "<tr><td><code>{}extern crate {} as {};",
2139 myitem.visibility.print_with_space(),
2140 anchor(myitem.def_id, src),
2145 "<tr><td><code>{}extern crate {};",
2146 myitem.visibility.print_with_space(),
2147 anchor(myitem.def_id, name)
2150 write!(w, "</code></td></tr>");
2153 clean::ImportItem(ref import) => {
2156 "<tr><td><code>{}{}</code></td></tr>",
2157 myitem.visibility.print_with_space(),
2163 if myitem.name.is_none() {
2167 let unsafety_flag = match myitem.kind {
2168 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2169 if func.header.unsafety == hir::Unsafety::Unsafe =>
2171 "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2176 let stab = myitem.stability_class();
2177 let add = if stab.is_some() { " " } else { "" };
2179 let doc_value = myitem.doc_value().unwrap_or("");
2182 "<tr class=\"{stab}{add}module-item\">\
2183 <td><a class=\"{class}\" href=\"{href}\" \
2184 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2185 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2187 name = *myitem.name.as_ref().unwrap(),
2188 stab_tags = extra_info_tags(myitem, item),
2189 docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2190 class = myitem.type_(),
2192 stab = stab.unwrap_or_else(String::new),
2193 unsafety_flag = unsafety_flag,
2194 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2195 title = [full_path(cx, myitem), myitem.type_().to_string()]
2197 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2198 .collect::<Vec<_>>()
2205 if curty.is_some() {
2206 write!(w, "</table>");
2210 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
2211 /// at the module level.
2212 fn extra_info_tags(item: &clean::Item, parent: &clean::Item) -> String {
2213 let mut tags = String::new();
2215 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2216 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2219 // The trailing space after each tag is to space it properly against the rest of the docs.
2220 if let Some(depr) = &item.deprecation {
2221 let mut message = "Deprecated";
2222 if !stability::deprecation_in_effect(depr.is_since_rustc_version, depr.since.as_deref()) {
2223 message = "Deprecation planned";
2225 tags += &tag_html("deprecated", "", message);
2228 // The "rustc_private" crates are permanently unstable so it makes no sense
2229 // to render "unstable" everywhere.
2230 if item.stability.as_ref().map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2233 tags += &tag_html("unstable", "", "Experimental");
2236 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2237 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2238 (cfg, _) => cfg.as_deref().cloned(),
2241 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2242 if let Some(ref cfg) = cfg {
2243 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2249 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2250 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2251 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2252 (cfg, _) => cfg.as_deref().cloned(),
2256 "Portability {:?} - {:?} = {:?}",
2258 parent.and_then(|p| p.attrs.cfg.as_ref()),
2262 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2265 /// Render the stability, deprecation and portability information that is displayed at the top of
2266 /// the item's documentation.
2267 fn short_item_info(item: &clean::Item, cx: &Context, parent: Option<&clean::Item>) -> Vec<String> {
2268 let mut extra_info = vec![];
2269 let error_codes = cx.shared.codes;
2271 if let Some(Deprecation { ref note, ref since, is_since_rustc_version }) = item.deprecation {
2272 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2273 // but only display the future-deprecation messages for #[rustc_deprecated].
2274 let mut message = if let Some(since) = since {
2275 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2276 format!("Deprecating in {}", Escape(&since))
2278 format!("Deprecated since {}", Escape(&since))
2281 String::from("Deprecated")
2284 if let Some(note) = note {
2285 let mut ids = cx.id_map.borrow_mut();
2286 let html = MarkdownHtml(
2291 &cx.shared.playground,
2293 message.push_str(&format!(": {}", html.into_string()));
2295 extra_info.push(format!(
2296 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2301 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2302 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2303 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2306 .filter(|stab| stab.feature != sym::rustc_private)
2307 .map(|stab| (stab.level, stab.feature))
2310 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2312 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2313 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2314 feature.push_str(&format!(
2315 " <a href=\"{url}{issue}\">#{issue}</a>",
2321 message.push_str(&format!(" ({})", feature));
2323 if let Some(unstable_reason) = reason {
2324 let mut ids = cx.id_map.borrow_mut();
2326 "<details><summary>{}</summary>{}</details>",
2329 &unstable_reason.as_str(),
2333 &cx.shared.playground,
2339 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2342 if let Some(portability) = portability(item, parent) {
2343 extra_info.push(portability);
2349 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2350 write!(w, "<pre class=\"rust const\">");
2351 render_attributes(w, it, false);
2355 "{vis}const {name}: {typ}",
2356 vis = it.visibility.print_with_space(),
2357 name = it.name.as_ref().unwrap(),
2358 typ = c.type_.print(),
2361 if c.value.is_some() || c.is_literal {
2362 write!(w, " = {expr};", expr = Escape(&c.expr));
2367 if let Some(value) = &c.value {
2369 let value_lowercase = value.to_lowercase();
2370 let expr_lowercase = c.expr.to_lowercase();
2372 if value_lowercase != expr_lowercase
2373 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2375 write!(w, " // {value}", value = Escape(value));
2380 write!(w, "</pre>");
2381 document(w, cx, it, None)
2384 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2385 write!(w, "<pre class=\"rust static\">");
2386 render_attributes(w, it, false);
2389 "{vis}static {mutability}{name}: {typ}</pre>",
2390 vis = it.visibility.print_with_space(),
2391 mutability = s.mutability.print_with_space(),
2392 name = it.name.as_ref().unwrap(),
2393 typ = s.type_.print()
2395 document(w, cx, it, None)
2398 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2399 let header_len = format!(
2400 "{}{}{}{}{:#}fn {}{:#}",
2401 it.visibility.print_with_space(),
2402 f.header.constness.print_with_space(),
2403 f.header.asyncness.print_with_space(),
2404 f.header.unsafety.print_with_space(),
2405 print_abi_with_space(f.header.abi),
2406 it.name.as_ref().unwrap(),
2410 write!(w, "<pre class=\"rust fn\">");
2411 render_attributes(w, it, false);
2414 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2415 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2416 vis = it.visibility.print_with_space(),
2417 constness = f.header.constness.print_with_space(),
2418 asyncness = f.header.asyncness.print_with_space(),
2419 unsafety = f.header.unsafety.print_with_space(),
2420 abi = print_abi_with_space(f.header.abi),
2421 name = it.name.as_ref().unwrap(),
2422 generics = f.generics.print(),
2423 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2424 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2426 spotlight = spotlight_decl(&f.decl),
2428 document(w, cx, it, None)
2431 fn render_implementor(
2434 parent: &clean::Item,
2436 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2440 // If there's already another implementor that has the same abbridged name, use the
2441 // full path, for example in `std::iter::ExactSizeIterator`
2442 let use_absolute = match implementor.inner_impl().for_ {
2443 clean::ResolvedPath { ref path, is_generic: false, .. }
2444 | clean::BorrowedRef {
2445 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2447 } => implementor_dups[path.last_name()].1,
2455 AssocItemLink::Anchor(None),
2457 implementor.impl_item.stable_since().as_deref(),
2458 implementor.impl_item.const_stable_since().as_deref(),
2472 containing_item: &clean::Item,
2475 let mut impls = traits
2478 let did = i.trait_did().unwrap();
2479 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2480 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2488 containing_item.stable_since().as_deref(),
2489 containing_item.const_stable_since().as_deref(),
2499 .collect::<Vec<_>>();
2501 w.write_str(&impls.join(""));
2504 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2505 let mut bounds = String::new();
2506 if !t_bounds.is_empty() {
2508 bounds.push_str(": ");
2510 for (i, p) in t_bounds.iter().enumerate() {
2512 bounds.push_str(" + ");
2514 bounds.push_str(&p.print().to_string());
2520 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2521 let lhs = format!("{}", lhs.inner_impl().print());
2522 let rhs = format!("{}", rhs.inner_impl().print());
2524 // lhs and rhs are formatted as HTML, which may be unnecessary
2525 compare_names(&lhs, &rhs)
2528 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2529 let bounds = bounds(&t.bounds, false);
2530 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2531 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2532 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2533 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2535 // Output the trait definition
2536 wrap_into_docblock(w, |w| {
2537 write!(w, "<pre class=\"rust trait\">");
2538 render_attributes(w, it, true);
2541 "{}{}{}trait {}{}{}",
2542 it.visibility.print_with_space(),
2543 t.unsafety.print_with_space(),
2544 if t.is_auto { "auto " } else { "" },
2545 it.name.as_ref().unwrap(),
2550 if !t.generics.where_predicates.is_empty() {
2551 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2556 if t.items.is_empty() {
2559 // FIXME: we should be using a derived_id for the Anchors here
2562 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2565 if !types.is_empty() && !consts.is_empty() {
2569 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2572 if !consts.is_empty() && !required.is_empty() {
2575 for (pos, m) in required.iter().enumerate() {
2576 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2579 if pos < required.len() - 1 {
2580 write!(w, "<div class=\"item-spacer\"></div>");
2583 if !required.is_empty() && !provided.is_empty() {
2586 for (pos, m) in provided.iter().enumerate() {
2587 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2589 clean::MethodItem(ref inner, _)
2590 if !inner.generics.where_predicates.is_empty() =>
2592 write!(w, ",\n {{ ... }}\n");
2595 write!(w, " {{ ... }}\n");
2598 if pos < provided.len() - 1 {
2599 write!(w, "<div class=\"item-spacer\"></div>");
2607 // Trait documentation
2608 document(w, cx, it, None);
2610 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2613 "<h2 id=\"{0}\" class=\"small-section-header\">\
2614 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2616 id, title, extra_content
2620 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2621 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2624 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item, cache: &Cache) {
2625 let name = m.name.as_ref().unwrap();
2626 info!("Documenting {} on {}", name, t.name.as_deref().unwrap_or_default());
2627 let item_type = m.type_();
2628 let id = cx.derive_id(format!("{}.{}", item_type, name));
2629 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2630 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2631 write!(w, "</code>");
2632 render_stability_since(w, m, t);
2633 write_srclink(cx, m, w, cache);
2635 document(w, cx, m, Some(t));
2638 if !types.is_empty() {
2639 write_small_section_header(
2643 "<div class=\"methods\">",
2646 trait_item(w, cx, t, it, cache);
2648 write_loading_content(w, "</div>");
2651 if !consts.is_empty() {
2652 write_small_section_header(
2655 "Associated Constants",
2656 "<div class=\"methods\">",
2659 trait_item(w, cx, t, it, cache);
2661 write_loading_content(w, "</div>");
2664 // Output the documentation for each function individually
2665 if !required.is_empty() {
2666 write_small_section_header(
2670 "<div class=\"methods\">",
2673 trait_item(w, cx, m, it, cache);
2675 write_loading_content(w, "</div>");
2677 if !provided.is_empty() {
2678 write_small_section_header(
2682 "<div class=\"methods\">",
2685 trait_item(w, cx, m, it, cache);
2687 write_loading_content(w, "</div>");
2690 // If there are methods directly on this trait object, render them here.
2691 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2693 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2694 // The DefId is for the first Type found with that name. The bool is
2695 // if any Types with the same name but different DefId have been found.
2696 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2697 for implementor in implementors {
2698 match implementor.inner_impl().for_ {
2699 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2700 | clean::BorrowedRef {
2701 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2704 let &mut (prev_did, ref mut has_duplicates) =
2705 implementor_dups.entry(path.last_name()).or_insert((did, false));
2706 if prev_did != did {
2707 *has_duplicates = true;
2714 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2715 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2718 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2719 local.iter().partition(|i| i.inner_impl().synthetic);
2721 synthetic.sort_by(compare_impl);
2722 concrete.sort_by(compare_impl);
2724 if !foreign.is_empty() {
2725 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2727 for implementor in foreign {
2728 let assoc_link = AssocItemLink::GotoSource(
2729 implementor.impl_item.def_id,
2730 &implementor.inner_impl().provided_trait_methods,
2739 implementor.impl_item.stable_since().as_deref(),
2740 implementor.impl_item.const_stable_since().as_deref(),
2749 write_loading_content(w, "");
2752 write_small_section_header(
2756 "<div class=\"item-list\" id=\"implementors-list\">",
2758 for implementor in concrete {
2759 render_implementor(cx, implementor, it, w, &implementor_dups, &[], cache);
2761 write_loading_content(w, "</div>");
2764 write_small_section_header(
2766 "synthetic-implementors",
2767 "Auto implementors",
2768 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2770 for implementor in synthetic {
2777 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2781 write_loading_content(w, "</div>");
2784 // even without any implementations to write in, we still want the heading and list, so the
2785 // implementors javascript file pulled in below has somewhere to write the impls into
2786 write_small_section_header(
2790 "<div class=\"item-list\" id=\"implementors-list\">",
2792 write_loading_content(w, "</div>");
2795 write_small_section_header(
2797 "synthetic-implementors",
2798 "Auto implementors",
2799 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2801 write_loading_content(w, "</div>");
2807 "<script type=\"text/javascript\" \
2808 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2810 root_path = vec![".."; cx.current.len()].join("/"),
2811 path = if it.def_id.is_local() {
2812 cx.current.join("/")
2814 let (ref path, _) = cache.external_paths[&it.def_id];
2815 path[..path.len() - 1].join("/")
2818 name = *it.name.as_ref().unwrap()
2822 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2823 use crate::formats::item_type::ItemType::*;
2825 let name = it.name.as_ref().unwrap();
2826 let ty = match it.type_() {
2827 Typedef | AssocType => AssocType,
2831 let anchor = format!("#{}.{}", ty, name);
2833 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2834 AssocItemLink::Anchor(None) => anchor,
2835 AssocItemLink::GotoSource(did, _) => {
2836 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2845 _default: Option<&String>,
2846 link: AssocItemLink<'_>,
2851 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2853 it.visibility.print_with_space(),
2854 naive_assoc_href(it, link),
2855 it.name.as_ref().unwrap(),
2863 bounds: &[clean::GenericBound],
2864 default: Option<&clean::Type>,
2865 link: AssocItemLink<'_>,
2870 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2872 naive_assoc_href(it, link),
2873 it.name.as_ref().unwrap()
2875 if !bounds.is_empty() {
2876 write!(w, ": {}", print_generic_bounds(bounds))
2878 if let Some(default) = default {
2879 write!(w, " = {}", default.print())
2883 fn render_stability_since_raw(
2886 const_ver: Option<&str>,
2887 containing_ver: Option<&str>,
2888 containing_const_ver: Option<&str>,
2890 let ver = ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2892 let const_ver = const_ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2894 if let Some(v) = ver {
2895 if let Some(cv) = const_ver {
2896 if const_ver != containing_const_ver {
2899 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2902 } else if ver != containing_ver {
2905 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2910 if ver != containing_ver {
2913 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2921 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2922 render_stability_since_raw(
2924 item.stable_since().as_deref(),
2925 item.const_stable_since().as_deref(),
2926 containing_item.stable_since().as_deref(),
2927 containing_item.const_stable_since().as_deref(),
2931 fn render_assoc_item(
2934 link: AssocItemLink<'_>,
2940 header: hir::FnHeader,
2941 g: &clean::Generics,
2943 link: AssocItemLink<'_>,
2946 let name = meth.name.as_ref().unwrap();
2947 let anchor = format!("#{}.{}", meth.type_(), name);
2948 let href = match link {
2949 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2950 AssocItemLink::Anchor(None) => anchor,
2951 AssocItemLink::GotoSource(did, provided_methods) => {
2952 // We're creating a link from an impl-item to the corresponding
2953 // trait-item and need to map the anchored type accordingly.
2954 let ty = if provided_methods.contains(name) {
2960 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2963 let mut header_len = format!(
2964 "{}{}{}{}{}{:#}fn {}{:#}",
2965 meth.visibility.print_with_space(),
2966 header.constness.print_with_space(),
2967 header.asyncness.print_with_space(),
2968 header.unsafety.print_with_space(),
2969 print_default_space(meth.is_default()),
2970 print_abi_with_space(header.abi),
2975 let (indent, end_newline) = if parent == ItemType::Trait {
2981 render_attributes(w, meth, false);
2984 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
2985 {generics}{decl}{spotlight}{where_clause}",
2986 if parent == ItemType::Trait { " " } else { "" },
2987 meth.visibility.print_with_space(),
2988 header.constness.print_with_space(),
2989 header.asyncness.print_with_space(),
2990 header.unsafety.print_with_space(),
2991 print_default_space(meth.is_default()),
2992 print_abi_with_space(header.abi),
2995 generics = g.print(),
2996 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
2997 spotlight = spotlight_decl(&d),
2998 where_clause = WhereClause { gens: g, indent, end_newline }
3002 clean::StrippedItem(..) => {}
3003 clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
3004 clean::MethodItem(ref m, _) => {
3005 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3007 clean::AssocConstItem(ref ty, ref default) => assoc_const(
3013 if parent == ItemType::Trait { " " } else { "" },
3015 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3021 if parent == ItemType::Trait { " " } else { "" },
3023 _ => panic!("render_assoc_item called on non-associated-item"),
3027 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
3028 wrap_into_docblock(w, |w| {
3029 write!(w, "<pre class=\"rust struct\">");
3030 render_attributes(w, it, true);
3031 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
3035 document(w, cx, it, None);
3039 .filter_map(|f| match f.kind {
3040 clean::StructFieldItem(ref ty) => Some((f, ty)),
3044 if let doctree::Plain = s.struct_type {
3045 if fields.peek().is_some() {
3048 "<h2 id=\"fields\" class=\"fields small-section-header\">
3049 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3050 document_non_exhaustive_header(it)
3052 document_non_exhaustive(w, it);
3053 for (field, ty) in fields {
3054 let id = cx.derive_id(format!(
3056 ItemType::StructField,
3057 field.name.as_ref().unwrap()
3061 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3062 <a href=\"#{id}\" class=\"anchor field\"></a>\
3063 <code>{name}: {ty}</code>\
3065 item_type = ItemType::StructField,
3067 name = field.name.as_ref().unwrap(),
3070 document(w, cx, field, Some(it));
3074 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3077 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
3078 wrap_into_docblock(w, |w| {
3079 write!(w, "<pre class=\"rust union\">");
3080 render_attributes(w, it, true);
3081 render_union(w, it, Some(&s.generics), &s.fields, "", true);
3085 document(w, cx, it, None);
3089 .filter_map(|f| match f.kind {
3090 clean::StructFieldItem(ref ty) => Some((f, ty)),
3094 if fields.peek().is_some() {
3097 "<h2 id=\"fields\" class=\"fields small-section-header\">
3098 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3100 for (field, ty) in fields {
3101 let name = field.name.as_ref().expect("union field name");
3102 let id = format!("{}.{}", ItemType::StructField, name);
3105 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3106 <a href=\"#{id}\" class=\"anchor field\"></a>\
3107 <code>{name}: {ty}</code>\
3111 shortty = ItemType::StructField,
3114 if let Some(stability_class) = field.stability_class() {
3115 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3117 document(w, cx, field, Some(it));
3120 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3123 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
3124 wrap_into_docblock(w, |w| {
3125 write!(w, "<pre class=\"rust enum\">");
3126 render_attributes(w, it, true);
3130 it.visibility.print_with_space(),
3131 it.name.as_ref().unwrap(),
3133 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
3135 if e.variants.is_empty() && !e.variants_stripped {
3139 for v in &e.variants {
3141 let name = v.name.as_ref().unwrap();
3143 clean::VariantItem(ref var) => match var.kind {
3144 clean::VariantKind::CLike => write!(w, "{}", name),
3145 clean::VariantKind::Tuple(ref tys) => {
3146 write!(w, "{}(", name);
3147 for (i, ty) in tys.iter().enumerate() {
3149 write!(w, ", ")
3151 write!(w, "{}", ty.print());
3155 clean::VariantKind::Struct(ref s) => {
3156 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
3159 _ => unreachable!(),
3164 if e.variants_stripped {
3165 write!(w, " // some variants omitted\n");
3172 document(w, cx, it, None);
3173 if !e.variants.is_empty() {
3176 "<h2 id=\"variants\" class=\"variants small-section-header\">
3177 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3178 document_non_exhaustive_header(it)
3180 document_non_exhaustive(w, it);
3181 for variant in &e.variants {
3183 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3186 "<div id=\"{id}\" class=\"variant small-section-header\">\
3187 <a href=\"#{id}\" class=\"anchor field\"></a>\
3190 name = variant.name.as_ref().unwrap()
3192 if let clean::VariantItem(ref var) = variant.kind {
3193 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3195 for (i, ty) in tys.iter().enumerate() {
3197 write!(w, ", ");
3199 write!(w, "{}", ty.print());
3204 write!(w, "</code></div>");
3205 document(w, cx, variant, Some(it));
3206 document_non_exhaustive(w, variant);
3208 use crate::clean::{Variant, VariantKind};
3209 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.kind {
3210 let variant_id = cx.derive_id(format!(
3213 variant.name.as_ref().unwrap()
3215 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3218 "<h3>Fields of <b>{name}</b></h3><div>",
3219 name = variant.name.as_ref().unwrap()
3221 for field in &s.fields {
3222 use crate::clean::StructFieldItem;
3223 if let StructFieldItem(ref ty) = field.kind {
3224 let id = cx.derive_id(format!(
3225 "variant.{}.field.{}",
3226 variant.name.as_ref().unwrap(),
3227 field.name.as_ref().unwrap()
3231 "<span id=\"{id}\" class=\"variant small-section-header\">\
3232 <a href=\"#{id}\" class=\"anchor field\"></a>\
3233 <code>{f}: {t}</code>\
3236 f = field.name.as_ref().unwrap(),
3239 document(w, cx, field, Some(variant));
3242 write!(w, "</div></div>");
3244 render_stability_since(w, variant, it);
3247 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3250 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3257 sym::non_exhaustive,
3260 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3261 // left padding. For example:
3263 // #[foo] <----- "top" attribute
3265 // #[bar] <---- not "top" attribute
3268 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3273 .filter_map(|attr| {
3274 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3275 Some(pprust::attribute_to_string(&attr))
3282 if !attrs.is_empty() {
3285 "<span class=\"docblock attributes{}\">{}</span>",
3286 if top { " top-attr" } else { "" },
3295 g: Option<&clean::Generics>,
3296 ty: doctree::StructType,
3297 fields: &[clean::Item],
3304 it.visibility.print_with_space(),
3305 if structhead { "struct " } else { "" },
3306 it.name.as_ref().unwrap()
3308 if let Some(g) = g {
3309 write!(w, "{}", g.print())
3313 if let Some(g) = g {
3314 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3316 let mut has_visible_fields = false;
3318 for field in fields {
3319 if let clean::StructFieldItem(ref ty) = field.kind {
3324 field.visibility.print_with_space(),
3325 field.name.as_ref().unwrap(),
3328 has_visible_fields = true;
3332 if has_visible_fields {
3333 if it.has_stripped_fields().unwrap() {
3334 write!(w, "\n{} // some fields omitted", tab);
3336 write!(w, "\n{}", tab);
3337 } else if it.has_stripped_fields().unwrap() {
3338 // If there are no visible fields we can just display
3339 // `{ /* fields omitted */ }` to save space.
3340 write!(w, " /* fields omitted */ ");
3346 for (i, field) in fields.iter().enumerate() {
3351 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3352 clean::StructFieldItem(ref ty) => {
3353 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3355 _ => unreachable!(),
3359 if let Some(g) = g {
3360 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3365 // Needed for PhantomData.
3366 if let Some(g) = g {
3367 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3377 g: Option<&clean::Generics>,
3378 fields: &[clean::Item],
3385 it.visibility.print_with_space(),
3386 if structhead { "union " } else { "" },
3387 it.name.as_ref().unwrap()
3389 if let Some(g) = g {
3390 write!(w, "{}", g.print());
3391 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3394 write!(w, " {{\n{}", tab);
3395 for field in fields {
3396 if let clean::StructFieldItem(ref ty) = field.kind {
3400 field.visibility.print_with_space(),
3401 field.name.as_ref().unwrap(),
3408 if it.has_stripped_fields().unwrap() {
3409 write!(w, " // some fields omitted\n{}", tab);
3414 #[derive(Copy, Clone)]
3415 enum AssocItemLink<'a> {
3416 Anchor(Option<&'a str>),
3417 GotoSource(DefId, &'a FxHashSet<String>),
3420 impl<'a> AssocItemLink<'a> {
3421 fn anchor(&self, id: &'a String) -> Self {
3423 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3424 ref other => *other,
3429 fn render_assoc_items(
3432 containing_item: &clean::Item,
3434 what: AssocItemRender<'_>,
3438 "Documenting associated items of {}",
3439 containing_item.name.as_deref().unwrap_or_default()
3441 let v = match cache.impls.get(&it) {
3445 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3446 if !non_trait.is_empty() {
3447 let render_mode = match what {
3448 AssocItemRender::All => {
3451 "<h2 id=\"implementations\" class=\"small-section-header\">\
3452 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3457 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3460 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
3461 Methods from {}<Target = {}>\
3462 <a href=\"#deref-methods\" class=\"anchor\"></a>\
3467 RenderMode::ForDeref { mut_: deref_mut_ }
3470 for i in &non_trait {
3476 AssocItemLink::Anchor(None),
3478 containing_item.stable_since().as_deref(),
3479 containing_item.const_stable_since().as_deref(),
3489 if let AssocItemRender::DerefFor { .. } = what {
3492 if !traits.is_empty() {
3494 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3495 if let Some(impl_) = deref_impl {
3497 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3498 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3501 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3502 traits.iter().partition(|t| t.inner_impl().synthetic);
3503 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3504 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3506 let mut impls = Buffer::empty_from(&w);
3507 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3508 let impls = impls.into_inner();
3509 if !impls.is_empty() {
3512 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3513 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3515 <div id=\"trait-implementations-list\">{}</div>",
3520 if !synthetic.is_empty() {
3523 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3524 Auto Trait Implementations\
3525 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3527 <div id=\"synthetic-implementations-list\">"
3529 render_impls(cx, w, &synthetic, containing_item, cache);
3530 write!(w, "</div>");
3533 if !blanket_impl.is_empty() {
3536 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3537 Blanket Implementations\
3538 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3540 <div id=\"blanket-implementations-list\">"
3542 render_impls(cx, w, &blanket_impl, containing_item, cache);
3543 write!(w, "</div>");
3548 fn render_deref_methods(
3552 container_item: &clean::Item,
3556 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3557 let (target, real_target) = impl_
3561 .find_map(|item| match item.kind {
3562 clean::TypedefItem(ref t, true) => Some(match *t {
3563 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3564 _ => (&t.type_, &t.type_),
3568 .expect("Expected associated type binding");
3570 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3571 if let Some(did) = target.def_id() {
3572 render_assoc_items(w, cx, container_item, did, what, cache);
3574 if let Some(prim) = target.primitive_type() {
3575 if let Some(&did) = cache.primitive_locations.get(&prim) {
3576 render_assoc_items(w, cx, container_item, did, what, cache);
3582 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3583 let self_type_opt = match item.kind {
3584 clean::MethodItem(ref method, _) => method.decl.self_type(),
3585 clean::TyMethodItem(ref method) => method.decl.self_type(),
3589 if let Some(self_ty) = self_type_opt {
3590 let (by_mut_ref, by_box, by_value) = match self_ty {
3591 SelfTy::SelfBorrowed(_, mutability)
3592 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3593 (mutability == Mutability::Mut, false, false)
3595 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3596 (false, Some(did) == cache().owned_box_did, false)
3598 SelfTy::SelfValue => (false, false, true),
3599 _ => (false, false, false),
3602 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3608 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3609 let mut out = Buffer::html();
3610 let mut trait_ = String::new();
3612 if let Some(did) = decl.output.def_id() {
3614 if let Some(impls) = c.impls.get(&did) {
3616 let impl_ = i.inner_impl();
3617 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3619 out.push_str(&format!(
3620 "<h3 class=\"notable\">Notable traits for {}</h3>\
3621 <code class=\"content\">",
3624 trait_.push_str(&impl_.for_.print().to_string());
3627 //use the "where" class here to make it small
3628 out.push_str(&format!(
3629 "<span class=\"where fmt-newline\">{}</span>",
3632 let t_did = impl_.trait_.def_id().unwrap();
3633 for it in &impl_.items {
3634 if let clean::TypedefItem(ref tydef, _) = it.kind {
3635 out.push_str("<span class=\"where fmt-newline\"> ");
3641 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3644 out.push_str(";</span>");
3652 if !out.is_empty() {
3655 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3656 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3658 out.push_str("</code></span></div></span></span>");
3668 parent: &clean::Item,
3669 link: AssocItemLink<'_>,
3670 render_mode: RenderMode,
3671 outer_version: Option<&str>,
3672 outer_const_version: Option<&str>,
3673 show_def_docs: bool,
3674 use_absolute: Option<bool>,
3675 is_on_foreign_type: bool,
3676 show_default_items: bool,
3677 // This argument is used to reference same type with different paths to avoid duplication
3678 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3682 let traits = &cache.traits;
3683 let trait_ = i.trait_did().map(|did| &traits[&did]);
3685 if render_mode == RenderMode::Normal {
3686 let id = cx.derive_id(match i.inner_impl().trait_ {
3688 if is_on_foreign_type {
3689 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3691 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3694 None => "impl".to_string(),
3696 let aliases = if aliases.is_empty() {
3699 format!(" aliases=\"{}\"", aliases.join(","))
3701 if let Some(use_absolute) = use_absolute {
3702 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3703 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3705 for it in &i.inner_impl().items {
3706 if let clean::TypedefItem(ref tydef, _) = it.kind {
3707 write!(w, "<span class=\"where fmt-newline\"> ");
3708 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3709 write!(w, ";</span>");
3713 write!(w, "</code>");
3717 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3720 i.inner_impl().print()
3723 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3724 render_stability_since_raw(
3726 i.impl_item.stable_since().as_deref(),
3727 i.impl_item.const_stable_since().as_deref(),
3729 outer_const_version,
3731 write_srclink(cx, &i.impl_item, w, cache);
3734 if trait_.is_some() {
3735 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3736 write!(w, "<div class=\"item-info\">{}</div>", portability);
3740 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3741 let mut ids = cx.id_map.borrow_mut();
3744 "<div class=\"docblock\">{}</div>",
3747 &i.impl_item.links(),
3751 &cx.shared.playground
3762 parent: &clean::Item,
3763 link: AssocItemLink<'_>,
3764 render_mode: RenderMode,
3765 is_default_item: bool,
3766 outer_version: Option<&str>,
3767 outer_const_version: Option<&str>,
3768 trait_: Option<&clean::Trait>,
3769 show_def_docs: bool,
3772 let item_type = item.type_();
3773 let name = item.name.as_ref().unwrap();
3775 let render_method_item = match render_mode {
3776 RenderMode::Normal => true,
3777 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3780 let (is_hidden, extra_class) =
3781 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3789 clean::MethodItem(..) | clean::TyMethodItem(_) => {
3790 // Only render when the method is not static or we allow static methods
3791 if render_method_item {
3792 let id = cx.derive_id(format!("{}.{}", item_type, name));
3793 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3794 write!(w, "<code>");
3795 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3796 write!(w, "</code>");
3797 render_stability_since_raw(
3799 item.stable_since().as_deref(),
3800 item.const_stable_since().as_deref(),
3802 outer_const_version,
3804 write_srclink(cx, item, w, cache);
3808 clean::TypedefItem(ref tydef, _) => {
3809 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3810 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3811 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3812 write!(w, "</code></h4>");
3814 clean::AssocConstItem(ref ty, ref default) => {
3815 let id = cx.derive_id(format!("{}.{}", item_type, name));
3816 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3817 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3818 write!(w, "</code>");
3819 render_stability_since_raw(
3821 item.stable_since().as_deref(),
3822 item.const_stable_since().as_deref(),
3824 outer_const_version,
3826 write_srclink(cx, item, w, cache);
3829 clean::AssocTypeItem(ref bounds, ref default) => {
3830 let id = cx.derive_id(format!("{}.{}", item_type, name));
3831 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3832 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3833 write!(w, "</code></h4>");
3835 clean::StrippedItem(..) => return,
3836 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3839 if render_method_item {
3840 if !is_default_item {
3841 if let Some(t) = trait_ {
3842 // The trait item may have been stripped so we might not
3843 // find any documentation or stability for it.
3844 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3845 // We need the stability of the item from the trait
3846 // because impls can't have a stability.
3847 if item.doc_value().is_some() {
3848 document_item_info(w, cx, it, is_hidden, Some(parent));
3849 document_full(w, item, cx, "", is_hidden);
3851 // In case the item isn't documented,
3852 // provide short documentation from the trait.
3866 document_item_info(w, cx, item, is_hidden, Some(parent));
3868 document_full(w, item, cx, "", is_hidden);
3872 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3877 write!(w, "<div class=\"impl-items\">");
3878 for trait_item in &i.inner_impl().items {
3883 if trait_.is_some() { &i.impl_item } else { parent },
3888 outer_const_version,
3895 fn render_default_items(
3900 parent: &clean::Item,
3901 render_mode: RenderMode,
3902 outer_version: Option<&str>,
3903 outer_const_version: Option<&str>,
3904 show_def_docs: bool,
3907 for trait_item in &t.items {
3908 let n = trait_item.name.clone();
3909 if i.items.iter().any(|m| m.name == n) {
3912 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3913 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3924 outer_const_version,
3932 // If we've implemented a trait, then also emit documentation for all
3933 // default items which weren't overridden in the implementation block.
3934 // We don't emit documentation for default items if they appear in the
3935 // Implementations on Foreign Types or Implementors sections.
3936 if show_default_items {
3937 if let Some(t) = trait_ {
3938 render_default_items(
3946 outer_const_version,
3952 write!(w, "</div>");
3959 t: &clean::OpaqueTy,
3962 write!(w, "<pre class=\"rust opaque\">");
3963 render_attributes(w, it, false);
3966 "type {}{}{where_clause} = impl {bounds};</pre>",
3967 it.name.as_ref().unwrap(),
3969 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3970 bounds = bounds(&t.bounds, false)
3973 document(w, cx, it, None);
3975 // Render any items associated directly to this alias, as otherwise they
3976 // won't be visible anywhere in the docs. It would be nice to also show
3977 // associated items from the aliased type (see discussion in #32077), but
3978 // we need #14072 to make sense of the generics.
3979 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3982 fn item_trait_alias(
3986 t: &clean::TraitAlias,
3989 write!(w, "<pre class=\"rust trait-alias\">");
3990 render_attributes(w, it, false);
3993 "trait {}{}{} = {};</pre>",
3994 it.name.as_ref().unwrap(),
3996 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3997 bounds(&t.bounds, true)
4000 document(w, cx, it, None);
4002 // Render any items associated directly to this alias, as otherwise they
4003 // won't be visible anywhere in the docs. It would be nice to also show
4004 // associated items from the aliased type (see discussion in #32077), but
4005 // we need #14072 to make sense of the generics.
4006 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4009 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
4010 write!(w, "<pre class=\"rust typedef\">");
4011 render_attributes(w, it, false);
4014 "type {}{}{where_clause} = {type_};</pre>",
4015 it.name.as_ref().unwrap(),
4017 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4018 type_ = t.type_.print()
4021 document(w, cx, it, None);
4023 // Render any items associated directly to this alias, as otherwise they
4024 // won't be visible anywhere in the docs. It would be nice to also show
4025 // associated items from the aliased type (see discussion in #32077), but
4026 // we need #14072 to make sense of the generics.
4027 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4030 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4031 writeln!(w, "<pre class=\"rust foreigntype\">extern {{");
4032 render_attributes(w, it, false);
4035 " {}type {};\n}}</pre>",
4036 it.visibility.print_with_space(),
4037 it.name.as_ref().unwrap(),
4040 document(w, cx, it, None);
4042 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4045 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
4046 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4050 || it.is_primitive()
4058 "<p class=\"location\">{}{}</p>",
4060 clean::StructItem(..) => "Struct ",
4061 clean::TraitItem(..) => "Trait ",
4062 clean::PrimitiveItem(..) => "Primitive Type ",
4063 clean::UnionItem(..) => "Union ",
4064 clean::EnumItem(..) => "Enum ",
4065 clean::TypedefItem(..) => "Type Definition ",
4066 clean::ForeignTypeItem => "Foreign Type ",
4067 clean::ModuleItem(..) =>
4075 it.name.as_ref().unwrap()
4080 if let Some(ref version) = cache.crate_version {
4083 "<div class=\"block version\">\
4091 write!(buffer, "<div class=\"sidebar-elems\">");
4095 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4096 it.name.as_ref().expect("crates always have a name")
4100 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
4101 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
4102 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
4103 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
4104 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
4105 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
4106 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4107 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
4111 // The sidebar is designed to display sibling functions, modules and
4112 // other miscellaneous information. since there are lots of sibling
4113 // items (and that causes quadratic growth in large modules),
4114 // we refactor common parts into a shared JavaScript file per module.
4115 // still, we don't move everything into JS because we want to preserve
4116 // as much HTML as possible in order to allow non-JS-enabled browsers
4117 // to navigate the documentation (though slightly inefficiently).
4119 write!(buffer, "<p class=\"location\">");
4120 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4122 write!(buffer, "::<wbr>");
4126 "<a href=\"{}index.html\">{}</a>",
4127 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4131 write!(buffer, "</p>");
4133 // Sidebar refers to the enclosing module, not this module.
4134 let relpath = if it.is_mod() { "../" } else { "" };
4137 "<script>window.sidebarCurrent = {{\
4140 relpath: \"{path}\"\
4142 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4147 // There is no sidebar-items.js beyond the crate root path
4148 // FIXME maybe dynamic crate loading can be merged here
4150 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4152 // Closes sidebar-elems div.
4153 write!(buffer, "</div>");
4156 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4157 if used_links.insert(url.clone()) {
4161 while !used_links.insert(format!("{}-{}", url, add)) {
4164 format!("{}-{}", url, add)
4170 used_links: &mut FxHashSet<String>,
4175 .filter_map(|item| match item.name {
4176 Some(ref name) if !name.is_empty() && item.is_method() => {
4177 if !for_deref || should_render_item(item, deref_mut) {
4179 "<a href=\"#{}\">{}</a>",
4180 get_next_url(used_links, format!("method.{}", name)),
4189 .collect::<Vec<_>>()
4192 // The point is to url encode any potential character from a type with genericity.
4193 fn small_url_encode(s: &str) -> String {
4194 s.replace("<", "%3C")
4195 .replace(">", "%3E")
4196 .replace(" ", "%20")
4197 .replace("?", "%3F")
4198 .replace("'", "%27")
4199 .replace("&", "%26")
4200 .replace(",", "%2C")
4201 .replace(":", "%3A")
4202 .replace(";", "%3B")
4203 .replace("[", "%5B")
4204 .replace("]", "%5D")
4205 .replace("\"", "%22")
4208 fn sidebar_assoc_items(it: &clean::Item) -> String {
4209 let mut out = String::new();
4211 if let Some(v) = c.impls.get(&it.def_id) {
4212 let mut used_links = FxHashSet::default();
4215 let used_links_bor = &mut used_links;
4218 .filter(|i| i.inner_impl().trait_.is_none())
4219 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4220 .collect::<Vec<_>>();
4221 if !ret.is_empty() {
4222 // We want links' order to be reproducible so we don't use unstable sort.
4224 out.push_str(&format!(
4225 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4226 <div class=\"sidebar-links\">{}</div>",
4232 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4233 if let Some(impl_) = v
4235 .filter(|i| i.inner_impl().trait_.is_some())
4236 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4238 if let Some((target, real_target)) =
4239 impl_.inner_impl().items.iter().find_map(|item| match item.kind {
4240 clean::TypedefItem(ref t, true) => Some(match *t {
4241 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4242 _ => (&t.type_, &t.type_),
4249 .filter(|i| i.inner_impl().trait_.is_some())
4250 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4251 let inner_impl = target
4255 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4256 .and_then(|did| c.impls.get(&did));
4257 if let Some(impls) = inner_impl {
4258 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4259 out.push_str(&format!(
4260 "Methods from {}<Target={}>",
4263 impl_.inner_impl().trait_.as_ref().unwrap().print()
4265 Escape(&format!("{:#}", real_target.print()))
4267 out.push_str("</a>");
4270 .filter(|i| i.inner_impl().trait_.is_none())
4272 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4274 .collect::<Vec<_>>();
4275 // We want links' order to be reproducible so we don't use unstable sort.
4277 if !ret.is_empty() {
4278 out.push_str(&format!(
4279 "<div class=\"sidebar-links\">{}</div>",
4286 let format_impls = |impls: Vec<&Impl>| {
4287 let mut links = FxHashSet::default();
4292 let is_negative_impl = is_negative_impl(i.inner_impl());
4293 if let Some(ref i) = i.inner_impl().trait_ {
4294 let i_display = format!("{:#}", i.print());
4295 let out = Escape(&i_display);
4296 let encoded = small_url_encode(&format!("{:#}", i.print()));
4297 let generated = format!(
4298 "<a href=\"#impl-{}\">{}{}</a>",
4300 if is_negative_impl { "!" } else { "" },
4303 if links.insert(generated.clone()) { Some(generated) } else { None }
4308 .collect::<Vec<String>>();
4313 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4314 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4315 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4317 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4319 let concrete_format = format_impls(concrete);
4320 let synthetic_format = format_impls(synthetic);
4321 let blanket_format = format_impls(blanket_impl);
4323 if !concrete_format.is_empty() {
4325 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4326 Trait Implementations</a>",
4328 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4331 if !synthetic_format.is_empty() {
4333 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4334 Auto Trait Implementations</a>",
4336 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4339 if !blanket_format.is_empty() {
4341 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4342 Blanket Implementations</a>",
4344 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4352 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4353 let mut sidebar = String::new();
4354 let fields = get_struct_fields_name(&s.fields);
4356 if !fields.is_empty() {
4357 if let doctree::Plain = s.struct_type {
4358 sidebar.push_str(&format!(
4359 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4360 <div class=\"sidebar-links\">{}</div>",
4366 sidebar.push_str(&sidebar_assoc_items(it));
4368 if !sidebar.is_empty() {
4369 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4373 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4374 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4377 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4379 clean::ItemKind::ImplItem(ref i) => {
4380 if let Some(ref trait_) = i.trait_ {
4382 format!("{:#}", i.for_.print()),
4383 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4393 fn is_negative_impl(i: &clean::Impl) -> bool {
4394 i.polarity == Some(clean::ImplPolarity::Negative)
4397 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4398 let mut sidebar = String::new();
4403 .filter_map(|m| match m.name {
4404 Some(ref name) if m.is_associated_type() => {
4405 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4409 .collect::<Vec<_>>();
4413 .filter_map(|m| match m.name {
4414 Some(ref name) if m.is_associated_const() => {
4415 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4419 .collect::<Vec<_>>();
4420 let mut required = t
4423 .filter_map(|m| match m.name {
4424 Some(ref name) if m.is_ty_method() => {
4425 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4429 .collect::<Vec<String>>();
4430 let mut provided = t
4433 .filter_map(|m| match m.name {
4434 Some(ref name) if m.is_method() => {
4435 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4439 .collect::<Vec<String>>();
4441 if !types.is_empty() {
4443 sidebar.push_str(&format!(
4444 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4445 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4449 if !consts.is_empty() {
4451 sidebar.push_str(&format!(
4452 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4453 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4457 if !required.is_empty() {
4459 sidebar.push_str(&format!(
4460 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4461 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4465 if !provided.is_empty() {
4467 sidebar.push_str(&format!(
4468 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4469 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4476 if let Some(implementors) = c.implementors.get(&it.def_id) {
4477 let mut res = implementors
4479 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4480 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4481 .collect::<Vec<_>>();
4483 if !res.is_empty() {
4485 sidebar.push_str(&format!(
4486 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4487 Implementations on Foreign Types</a>\
4488 <div class=\"sidebar-links\">{}</div>",
4490 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4491 .collect::<Vec<_>>()
4497 sidebar.push_str(&sidebar_assoc_items(it));
4499 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4502 "<a class=\"sidebar-title\" \
4503 href=\"#synthetic-implementors\">Auto Implementors</a>",
4507 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4510 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4511 let sidebar = sidebar_assoc_items(it);
4513 if !sidebar.is_empty() {
4514 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4518 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4519 let sidebar = sidebar_assoc_items(it);
4521 if !sidebar.is_empty() {
4522 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4526 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4527 let mut fields = fields
4529 .filter(|f| if let clean::StructFieldItem(..) = f.kind { true } else { false })
4530 .filter_map(|f| match f.name {
4532 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4536 .collect::<Vec<_>>();
4541 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4542 let mut sidebar = String::new();
4543 let fields = get_struct_fields_name(&u.fields);
4545 if !fields.is_empty() {
4546 sidebar.push_str(&format!(
4547 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4548 <div class=\"sidebar-links\">{}</div>",
4553 sidebar.push_str(&sidebar_assoc_items(it));
4555 if !sidebar.is_empty() {
4556 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4560 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4561 let mut sidebar = String::new();
4563 let mut variants = e
4566 .filter_map(|v| match v.name {
4567 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4570 .collect::<Vec<_>>();
4571 if !variants.is_empty() {
4572 variants.sort_unstable();
4573 sidebar.push_str(&format!(
4574 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4575 <div class=\"sidebar-links\">{}</div>",
4580 sidebar.push_str(&sidebar_assoc_items(it));
4582 if !sidebar.is_empty() {
4583 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4587 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4589 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4590 ItemType::Module => ("modules", "Modules"),
4591 ItemType::Struct => ("structs", "Structs"),
4592 ItemType::Union => ("unions", "Unions"),
4593 ItemType::Enum => ("enums", "Enums"),
4594 ItemType::Function => ("functions", "Functions"),
4595 ItemType::Typedef => ("types", "Type Definitions"),
4596 ItemType::Static => ("statics", "Statics"),
4597 ItemType::Constant => ("constants", "Constants"),
4598 ItemType::Trait => ("traits", "Traits"),
4599 ItemType::Impl => ("impls", "Implementations"),
4600 ItemType::TyMethod => ("tymethods", "Type Methods"),
4601 ItemType::Method => ("methods", "Methods"),
4602 ItemType::StructField => ("fields", "Struct Fields"),
4603 ItemType::Variant => ("variants", "Variants"),
4604 ItemType::Macro => ("macros", "Macros"),
4605 ItemType::Primitive => ("primitives", "Primitive Types"),
4606 ItemType::AssocType => ("associated-types", "Associated Types"),
4607 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4608 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4609 ItemType::Keyword => ("keywords", "Keywords"),
4610 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4611 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4612 ItemType::ProcDerive => ("derives", "Derive Macros"),
4613 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4617 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4618 let mut sidebar = String::new();
4620 if items.iter().any(|it| {
4621 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4623 sidebar.push_str(&format!(
4624 "<li><a href=\"#{id}\">{name}</a></li>",
4630 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4631 // to print its headings
4633 ItemType::Primitive,
4647 ItemType::StructField,
4649 ItemType::AssocType,
4650 ItemType::AssocConst,
4651 ItemType::ForeignType,
4654 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4655 let (short, name) = item_ty_to_strs(&myty);
4656 sidebar.push_str(&format!(
4657 "<li><a href=\"#{id}\">{name}</a></li>",
4664 if !sidebar.is_empty() {
4665 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4669 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4670 let sidebar = sidebar_assoc_items(it);
4671 if !sidebar.is_empty() {
4672 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4676 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4677 wrap_into_docblock(w, |w| {
4678 w.write_str(&highlight::render_with_highlighting(
4685 document(w, cx, it, None)
4688 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4689 let name = it.name.as_ref().expect("proc-macros always have names");
4691 MacroKind::Bang => {
4692 write!(w, "<pre class=\"rust macro\">");
4693 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4694 write!(w, "</pre>");
4696 MacroKind::Attr => {
4697 write!(w, "<pre class=\"rust attr\">");
4698 write!(w, "#[{}]", name);
4699 write!(w, "</pre>");
4701 MacroKind::Derive => {
4702 write!(w, "<pre class=\"rust derive\">");
4703 write!(w, "#[derive({})]", name);
4704 if !m.helpers.is_empty() {
4705 writeln!(w, "\n{{");
4706 writeln!(w, " // Attributes available to this derive:");
4707 for attr in &m.helpers {
4708 writeln!(w, " #[{}]", attr);
4712 write!(w, "</pre>");
4715 document(w, cx, it, None)
4718 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4719 document(w, cx, it, None);
4720 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4723 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4724 document(w, cx, it, None)
4727 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4729 fn make_item_keywords(it: &clean::Item) -> String {
4730 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4733 /// Returns a list of all paths used in the type.
4734 /// This is used to help deduplicate imported impls
4735 /// for reexported types. If any of the contained
4736 /// types are re-exported, we don't use the corresponding
4737 /// entry from the js file, as inlining will have already
4738 /// picked up the impl
4739 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4740 let mut out = Vec::new();
4741 let mut visited = FxHashSet::default();
4742 let mut work = VecDeque::new();
4743 let cache = cache();
4745 work.push_back(first_ty);
4747 while let Some(ty) = work.pop_front() {
4748 if !visited.insert(ty.clone()) {
4753 clean::Type::ResolvedPath { did, .. } => {
4754 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4755 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4757 if let Some(path) = fqp {
4758 out.push(path.join("::"));
4761 clean::Type::Tuple(tys) => {
4762 work.extend(tys.into_iter());
4764 clean::Type::Slice(ty) => {
4765 work.push_back(*ty);
4767 clean::Type::Array(ty, _) => {
4768 work.push_back(*ty);
4770 clean::Type::RawPointer(_, ty) => {
4771 work.push_back(*ty);
4773 clean::Type::BorrowedRef { type_, .. } => {
4774 work.push_back(*type_);
4776 clean::Type::QPath { self_type, trait_, .. } => {
4777 work.push_back(*self_type);
4778 work.push_back(*trait_);