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::{Deprecation, 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::{kw, sym, Symbol};
65 use serde::ser::SerializeSeq;
66 use serde::{Serialize, Serializer};
68 use crate::clean::{self, AttributesExt, GetDefId, RenderedLink, SelfTy, TypeKind};
69 use crate::config::{RenderInfo, RenderOptions};
70 use crate::docfs::{DocFS, PathError};
72 use crate::error::Error;
73 use crate::formats::cache::{cache, Cache};
74 use crate::formats::item_type::ItemType;
75 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
76 use crate::html::escape::Escape;
77 use crate::html::format::fmt_impl_for_trait_page;
78 use crate::html::format::Function;
79 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
80 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
81 use crate::html::markdown::{
82 self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine,
84 use crate::html::sources;
85 use crate::html::{highlight, layout, static_files};
86 use cache::{build_index, ExternalLocation};
88 /// A pair of name and its optional document.
89 crate type NameDoc = (String, Option<String>);
91 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
92 crate::html::format::display_fn(move |f| {
93 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
97 /// Major driving force in all rustdoc rendering. This contains information
98 /// about where in the tree-like hierarchy rendering is occurring and controls
99 /// how the current page is being rendered.
101 /// It is intended that this context is a lightweight object which can be fairly
102 /// easily cloned because it is cloned per work-job (about once per item in the
105 crate struct Context {
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.as_str());
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.unwrap().as_str());
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.unwrap().as_str());
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.unwrap_or(kw::Invalid).as_str();
2069 let rhs = i2.name.unwrap_or(kw::Invalid).as_str();
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.unwrap().as_str()),
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(
2223 depr.is_since_rustc_version,
2224 depr.since.map(|s| s.as_str()).as_deref(),
2226 message = "Deprecation planned";
2228 tags += &tag_html("deprecated", "", message);
2231 // The "rustc_private" crates are permanently unstable so it makes no sense
2232 // to render "unstable" everywhere.
2233 if item.stability.as_ref().map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2236 tags += &tag_html("unstable", "", "Experimental");
2239 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2240 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2241 (cfg, _) => cfg.as_deref().cloned(),
2244 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2245 if let Some(ref cfg) = cfg {
2246 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2252 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2253 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2254 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2255 (cfg, _) => cfg.as_deref().cloned(),
2259 "Portability {:?} - {:?} = {:?}",
2261 parent.and_then(|p| p.attrs.cfg.as_ref()),
2265 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2268 /// Render the stability, deprecation and portability information that is displayed at the top of
2269 /// the item's documentation.
2270 fn short_item_info(item: &clean::Item, cx: &Context, parent: Option<&clean::Item>) -> Vec<String> {
2271 let mut extra_info = vec![];
2272 let error_codes = cx.shared.codes;
2274 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
2277 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2278 // but only display the future-deprecation messages for #[rustc_deprecated].
2279 let mut message = if let Some(since) = since {
2280 let since = &since.as_str();
2281 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2282 if *since == "TBD" {
2283 format!("Deprecating in a future Rust version")
2285 format!("Deprecating in {}", Escape(since))
2288 format!("Deprecated since {}", Escape(since))
2291 String::from("Deprecated")
2294 if let Some(note) = note {
2295 let note = note.as_str();
2296 let mut ids = cx.id_map.borrow_mut();
2297 let html = MarkdownHtml(
2302 &cx.shared.playground,
2304 message.push_str(&format!(": {}", html.into_string()));
2306 extra_info.push(format!(
2307 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2312 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2313 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2314 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2317 .filter(|stab| stab.feature != sym::rustc_private)
2318 .map(|stab| (stab.level, stab.feature))
2321 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2323 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2324 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2325 feature.push_str(&format!(
2326 " <a href=\"{url}{issue}\">#{issue}</a>",
2332 message.push_str(&format!(" ({})", feature));
2334 if let Some(unstable_reason) = reason {
2335 let mut ids = cx.id_map.borrow_mut();
2337 "<details><summary>{}</summary>{}</details>",
2340 &unstable_reason.as_str(),
2344 &cx.shared.playground,
2350 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2353 if let Some(portability) = portability(item, parent) {
2354 extra_info.push(portability);
2360 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2361 write!(w, "<pre class=\"rust const\">");
2362 render_attributes(w, it, false);
2366 "{vis}const {name}: {typ}",
2367 vis = it.visibility.print_with_space(),
2368 name = it.name.as_ref().unwrap(),
2369 typ = c.type_.print(),
2372 if c.value.is_some() || c.is_literal {
2373 write!(w, " = {expr};", expr = Escape(&c.expr));
2378 if let Some(value) = &c.value {
2380 let value_lowercase = value.to_lowercase();
2381 let expr_lowercase = c.expr.to_lowercase();
2383 if value_lowercase != expr_lowercase
2384 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2386 write!(w, " // {value}", value = Escape(value));
2391 write!(w, "</pre>");
2392 document(w, cx, it, None)
2395 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2396 write!(w, "<pre class=\"rust static\">");
2397 render_attributes(w, it, false);
2400 "{vis}static {mutability}{name}: {typ}</pre>",
2401 vis = it.visibility.print_with_space(),
2402 mutability = s.mutability.print_with_space(),
2403 name = it.name.as_ref().unwrap(),
2404 typ = s.type_.print()
2406 document(w, cx, it, None)
2409 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2410 let header_len = format!(
2411 "{}{}{}{}{:#}fn {}{:#}",
2412 it.visibility.print_with_space(),
2413 f.header.constness.print_with_space(),
2414 f.header.asyncness.print_with_space(),
2415 f.header.unsafety.print_with_space(),
2416 print_abi_with_space(f.header.abi),
2417 it.name.as_ref().unwrap(),
2421 write!(w, "<pre class=\"rust fn\">");
2422 render_attributes(w, it, false);
2425 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2426 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2427 vis = it.visibility.print_with_space(),
2428 constness = f.header.constness.print_with_space(),
2429 asyncness = f.header.asyncness.print_with_space(),
2430 unsafety = f.header.unsafety.print_with_space(),
2431 abi = print_abi_with_space(f.header.abi),
2432 name = it.name.as_ref().unwrap(),
2433 generics = f.generics.print(),
2434 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2435 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2437 spotlight = spotlight_decl(&f.decl),
2439 document(w, cx, it, None)
2442 fn render_implementor(
2445 parent: &clean::Item,
2447 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2451 // If there's already another implementor that has the same abbridged name, use the
2452 // full path, for example in `std::iter::ExactSizeIterator`
2453 let use_absolute = match implementor.inner_impl().for_ {
2454 clean::ResolvedPath { ref path, is_generic: false, .. }
2455 | clean::BorrowedRef {
2456 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2458 } => implementor_dups[path.last_name()].1,
2466 AssocItemLink::Anchor(None),
2468 implementor.impl_item.stable_since().as_deref(),
2469 implementor.impl_item.const_stable_since().as_deref(),
2483 containing_item: &clean::Item,
2486 let mut impls = traits
2489 let did = i.trait_did().unwrap();
2490 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2491 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2499 containing_item.stable_since().as_deref(),
2500 containing_item.const_stable_since().as_deref(),
2510 .collect::<Vec<_>>();
2512 w.write_str(&impls.join(""));
2515 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2516 let mut bounds = String::new();
2517 if !t_bounds.is_empty() {
2519 bounds.push_str(": ");
2521 for (i, p) in t_bounds.iter().enumerate() {
2523 bounds.push_str(" + ");
2525 bounds.push_str(&p.print().to_string());
2531 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2532 let lhs = format!("{}", lhs.inner_impl().print());
2533 let rhs = format!("{}", rhs.inner_impl().print());
2535 // lhs and rhs are formatted as HTML, which may be unnecessary
2536 compare_names(&lhs, &rhs)
2539 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2540 let bounds = bounds(&t.bounds, false);
2541 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2542 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2543 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2544 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2546 // Output the trait definition
2547 wrap_into_docblock(w, |w| {
2548 write!(w, "<pre class=\"rust trait\">");
2549 render_attributes(w, it, true);
2552 "{}{}{}trait {}{}{}",
2553 it.visibility.print_with_space(),
2554 t.unsafety.print_with_space(),
2555 if t.is_auto { "auto " } else { "" },
2556 it.name.as_ref().unwrap(),
2561 if !t.generics.where_predicates.is_empty() {
2562 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2567 if t.items.is_empty() {
2570 // FIXME: we should be using a derived_id for the Anchors here
2573 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2576 if !types.is_empty() && !consts.is_empty() {
2580 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2583 if !consts.is_empty() && !required.is_empty() {
2586 for (pos, m) in required.iter().enumerate() {
2587 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2590 if pos < required.len() - 1 {
2591 write!(w, "<div class=\"item-spacer\"></div>");
2594 if !required.is_empty() && !provided.is_empty() {
2597 for (pos, m) in provided.iter().enumerate() {
2598 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2600 clean::MethodItem(ref inner, _)
2601 if !inner.generics.where_predicates.is_empty() =>
2603 write!(w, ",\n {{ ... }}\n");
2606 write!(w, " {{ ... }}\n");
2609 if pos < provided.len() - 1 {
2610 write!(w, "<div class=\"item-spacer\"></div>");
2618 // Trait documentation
2619 document(w, cx, it, None);
2621 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2624 "<h2 id=\"{0}\" class=\"small-section-header\">\
2625 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2627 id, title, extra_content
2631 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2632 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2635 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item, cache: &Cache) {
2636 let name = m.name.as_ref().unwrap();
2637 info!("Documenting {} on {:?}", name, t.name);
2638 let item_type = m.type_();
2639 let id = cx.derive_id(format!("{}.{}", item_type, name));
2640 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2641 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2642 write!(w, "</code>");
2643 render_stability_since(w, m, t);
2644 write_srclink(cx, m, w, cache);
2646 document(w, cx, m, Some(t));
2649 if !types.is_empty() {
2650 write_small_section_header(
2654 "<div class=\"methods\">",
2657 trait_item(w, cx, t, it, cache);
2659 write_loading_content(w, "</div>");
2662 if !consts.is_empty() {
2663 write_small_section_header(
2666 "Associated Constants",
2667 "<div class=\"methods\">",
2670 trait_item(w, cx, t, it, cache);
2672 write_loading_content(w, "</div>");
2675 // Output the documentation for each function individually
2676 if !required.is_empty() {
2677 write_small_section_header(
2681 "<div class=\"methods\">",
2684 trait_item(w, cx, m, it, cache);
2686 write_loading_content(w, "</div>");
2688 if !provided.is_empty() {
2689 write_small_section_header(
2693 "<div class=\"methods\">",
2696 trait_item(w, cx, m, it, cache);
2698 write_loading_content(w, "</div>");
2701 // If there are methods directly on this trait object, render them here.
2702 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2704 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2705 // The DefId is for the first Type found with that name. The bool is
2706 // if any Types with the same name but different DefId have been found.
2707 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2708 for implementor in implementors {
2709 match implementor.inner_impl().for_ {
2710 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2711 | clean::BorrowedRef {
2712 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2715 let &mut (prev_did, ref mut has_duplicates) =
2716 implementor_dups.entry(path.last_name()).or_insert((did, false));
2717 if prev_did != did {
2718 *has_duplicates = true;
2725 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2726 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2729 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2730 local.iter().partition(|i| i.inner_impl().synthetic);
2732 synthetic.sort_by(compare_impl);
2733 concrete.sort_by(compare_impl);
2735 if !foreign.is_empty() {
2736 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2738 for implementor in foreign {
2739 let assoc_link = AssocItemLink::GotoSource(
2740 implementor.impl_item.def_id,
2741 &implementor.inner_impl().provided_trait_methods,
2750 implementor.impl_item.stable_since().as_deref(),
2751 implementor.impl_item.const_stable_since().as_deref(),
2760 write_loading_content(w, "");
2763 write_small_section_header(
2767 "<div class=\"item-list\" id=\"implementors-list\">",
2769 for implementor in concrete {
2770 render_implementor(cx, implementor, it, w, &implementor_dups, &[], cache);
2772 write_loading_content(w, "</div>");
2775 write_small_section_header(
2777 "synthetic-implementors",
2778 "Auto implementors",
2779 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2781 for implementor in synthetic {
2788 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2792 write_loading_content(w, "</div>");
2795 // even without any implementations to write in, we still want the heading and list, so the
2796 // implementors javascript file pulled in below has somewhere to write the impls into
2797 write_small_section_header(
2801 "<div class=\"item-list\" id=\"implementors-list\">",
2803 write_loading_content(w, "</div>");
2806 write_small_section_header(
2808 "synthetic-implementors",
2809 "Auto implementors",
2810 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2812 write_loading_content(w, "</div>");
2818 "<script type=\"text/javascript\" \
2819 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2821 root_path = vec![".."; cx.current.len()].join("/"),
2822 path = if it.def_id.is_local() {
2823 cx.current.join("/")
2825 let (ref path, _) = cache.external_paths[&it.def_id];
2826 path[..path.len() - 1].join("/")
2829 name = *it.name.as_ref().unwrap()
2833 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2834 use crate::formats::item_type::ItemType::*;
2836 let name = it.name.as_ref().unwrap();
2837 let ty = match it.type_() {
2838 Typedef | AssocType => AssocType,
2842 let anchor = format!("#{}.{}", ty, name);
2844 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2845 AssocItemLink::Anchor(None) => anchor,
2846 AssocItemLink::GotoSource(did, _) => {
2847 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2856 _default: Option<&String>,
2857 link: AssocItemLink<'_>,
2862 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2864 it.visibility.print_with_space(),
2865 naive_assoc_href(it, link),
2866 it.name.as_ref().unwrap(),
2874 bounds: &[clean::GenericBound],
2875 default: Option<&clean::Type>,
2876 link: AssocItemLink<'_>,
2881 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2883 naive_assoc_href(it, link),
2884 it.name.as_ref().unwrap()
2886 if !bounds.is_empty() {
2887 write!(w, ": {}", print_generic_bounds(bounds))
2889 if let Some(default) = default {
2890 write!(w, " = {}", default.print())
2894 fn render_stability_since_raw(
2897 const_ver: Option<&str>,
2898 containing_ver: Option<&str>,
2899 containing_const_ver: Option<&str>,
2901 let ver = ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2903 let const_ver = const_ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2905 if let Some(v) = ver {
2906 if let Some(cv) = const_ver {
2907 if const_ver != containing_const_ver {
2910 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2913 } else if ver != containing_ver {
2916 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2921 if ver != containing_ver {
2924 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2932 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2933 render_stability_since_raw(
2935 item.stable_since().as_deref(),
2936 item.const_stable_since().as_deref(),
2937 containing_item.stable_since().as_deref(),
2938 containing_item.const_stable_since().as_deref(),
2942 fn render_assoc_item(
2945 link: AssocItemLink<'_>,
2951 header: hir::FnHeader,
2952 g: &clean::Generics,
2954 link: AssocItemLink<'_>,
2957 let name = meth.name.as_ref().unwrap();
2958 let anchor = format!("#{}.{}", meth.type_(), name);
2959 let href = match link {
2960 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2961 AssocItemLink::Anchor(None) => anchor,
2962 AssocItemLink::GotoSource(did, provided_methods) => {
2963 // We're creating a link from an impl-item to the corresponding
2964 // trait-item and need to map the anchored type accordingly.
2965 let ty = if provided_methods.contains(&*name.as_str()) {
2971 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2974 let mut header_len = format!(
2975 "{}{}{}{}{}{:#}fn {}{:#}",
2976 meth.visibility.print_with_space(),
2977 header.constness.print_with_space(),
2978 header.asyncness.print_with_space(),
2979 header.unsafety.print_with_space(),
2980 print_default_space(meth.is_default()),
2981 print_abi_with_space(header.abi),
2986 let (indent, end_newline) = if parent == ItemType::Trait {
2992 render_attributes(w, meth, false);
2995 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
2996 {generics}{decl}{spotlight}{where_clause}",
2997 if parent == ItemType::Trait { " " } else { "" },
2998 meth.visibility.print_with_space(),
2999 header.constness.print_with_space(),
3000 header.asyncness.print_with_space(),
3001 header.unsafety.print_with_space(),
3002 print_default_space(meth.is_default()),
3003 print_abi_with_space(header.abi),
3006 generics = g.print(),
3007 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
3008 spotlight = spotlight_decl(&d),
3009 where_clause = WhereClause { gens: g, indent, end_newline }
3013 clean::StrippedItem(..) => {}
3014 clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
3015 clean::MethodItem(ref m, _) => {
3016 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3018 clean::AssocConstItem(ref ty, ref default) => assoc_const(
3024 if parent == ItemType::Trait { " " } else { "" },
3026 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3032 if parent == ItemType::Trait { " " } else { "" },
3034 _ => panic!("render_assoc_item called on non-associated-item"),
3038 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
3039 wrap_into_docblock(w, |w| {
3040 write!(w, "<pre class=\"rust struct\">");
3041 render_attributes(w, it, true);
3042 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
3046 document(w, cx, it, None);
3050 .filter_map(|f| match f.kind {
3051 clean::StructFieldItem(ref ty) => Some((f, ty)),
3055 if let doctree::Plain = s.struct_type {
3056 if fields.peek().is_some() {
3059 "<h2 id=\"fields\" class=\"fields small-section-header\">
3060 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3061 document_non_exhaustive_header(it)
3063 document_non_exhaustive(w, it);
3064 for (field, ty) in fields {
3065 let id = cx.derive_id(format!(
3067 ItemType::StructField,
3068 field.name.as_ref().unwrap()
3072 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3073 <a href=\"#{id}\" class=\"anchor field\"></a>\
3074 <code>{name}: {ty}</code>\
3076 item_type = ItemType::StructField,
3078 name = field.name.as_ref().unwrap(),
3081 document(w, cx, field, Some(it));
3085 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3088 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
3089 wrap_into_docblock(w, |w| {
3090 write!(w, "<pre class=\"rust union\">");
3091 render_attributes(w, it, true);
3092 render_union(w, it, Some(&s.generics), &s.fields, "", true);
3096 document(w, cx, it, None);
3100 .filter_map(|f| match f.kind {
3101 clean::StructFieldItem(ref ty) => Some((f, ty)),
3105 if fields.peek().is_some() {
3108 "<h2 id=\"fields\" class=\"fields small-section-header\">
3109 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3111 for (field, ty) in fields {
3112 let name = field.name.as_ref().expect("union field name");
3113 let id = format!("{}.{}", ItemType::StructField, name);
3116 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3117 <a href=\"#{id}\" class=\"anchor field\"></a>\
3118 <code>{name}: {ty}</code>\
3122 shortty = ItemType::StructField,
3125 if let Some(stability_class) = field.stability_class() {
3126 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3128 document(w, cx, field, Some(it));
3131 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3134 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
3135 wrap_into_docblock(w, |w| {
3136 write!(w, "<pre class=\"rust enum\">");
3137 render_attributes(w, it, true);
3141 it.visibility.print_with_space(),
3142 it.name.as_ref().unwrap(),
3144 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
3146 if e.variants.is_empty() && !e.variants_stripped {
3150 for v in &e.variants {
3152 let name = v.name.as_ref().unwrap();
3154 clean::VariantItem(ref var) => match var.kind {
3155 clean::VariantKind::CLike => write!(w, "{}", name),
3156 clean::VariantKind::Tuple(ref tys) => {
3157 write!(w, "{}(", name);
3158 for (i, ty) in tys.iter().enumerate() {
3160 write!(w, ", ")
3162 write!(w, "{}", ty.print());
3166 clean::VariantKind::Struct(ref s) => {
3167 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
3170 _ => unreachable!(),
3175 if e.variants_stripped {
3176 write!(w, " // some variants omitted\n");
3183 document(w, cx, it, None);
3184 if !e.variants.is_empty() {
3187 "<h2 id=\"variants\" class=\"variants small-section-header\">
3188 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3189 document_non_exhaustive_header(it)
3191 document_non_exhaustive(w, it);
3192 for variant in &e.variants {
3194 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3197 "<div id=\"{id}\" class=\"variant small-section-header\">\
3198 <a href=\"#{id}\" class=\"anchor field\"></a>\
3201 name = variant.name.as_ref().unwrap()
3203 if let clean::VariantItem(ref var) = variant.kind {
3204 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3206 for (i, ty) in tys.iter().enumerate() {
3208 write!(w, ", ");
3210 write!(w, "{}", ty.print());
3215 write!(w, "</code></div>");
3216 document(w, cx, variant, Some(it));
3217 document_non_exhaustive(w, variant);
3219 use crate::clean::{Variant, VariantKind};
3220 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.kind {
3221 let variant_id = cx.derive_id(format!(
3224 variant.name.as_ref().unwrap()
3226 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3229 "<h3>Fields of <b>{name}</b></h3><div>",
3230 name = variant.name.as_ref().unwrap()
3232 for field in &s.fields {
3233 use crate::clean::StructFieldItem;
3234 if let StructFieldItem(ref ty) = field.kind {
3235 let id = cx.derive_id(format!(
3236 "variant.{}.field.{}",
3237 variant.name.as_ref().unwrap(),
3238 field.name.as_ref().unwrap()
3242 "<span id=\"{id}\" class=\"variant small-section-header\">\
3243 <a href=\"#{id}\" class=\"anchor field\"></a>\
3244 <code>{f}: {t}</code>\
3247 f = field.name.as_ref().unwrap(),
3250 document(w, cx, field, Some(variant));
3253 write!(w, "</div></div>");
3255 render_stability_since(w, variant, it);
3258 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3261 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3268 sym::non_exhaustive,
3271 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3272 // left padding. For example:
3274 // #[foo] <----- "top" attribute
3276 // #[bar] <---- not "top" attribute
3279 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3284 .filter_map(|attr| {
3285 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3286 Some(pprust::attribute_to_string(&attr))
3293 if !attrs.is_empty() {
3296 "<span class=\"docblock attributes{}\">{}</span>",
3297 if top { " top-attr" } else { "" },
3306 g: Option<&clean::Generics>,
3307 ty: doctree::StructType,
3308 fields: &[clean::Item],
3315 it.visibility.print_with_space(),
3316 if structhead { "struct " } else { "" },
3317 it.name.as_ref().unwrap()
3319 if let Some(g) = g {
3320 write!(w, "{}", g.print())
3324 if let Some(g) = g {
3325 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3327 let mut has_visible_fields = false;
3329 for field in fields {
3330 if let clean::StructFieldItem(ref ty) = field.kind {
3335 field.visibility.print_with_space(),
3336 field.name.as_ref().unwrap(),
3339 has_visible_fields = true;
3343 if has_visible_fields {
3344 if it.has_stripped_fields().unwrap() {
3345 write!(w, "\n{} // some fields omitted", tab);
3347 write!(w, "\n{}", tab);
3348 } else if it.has_stripped_fields().unwrap() {
3349 // If there are no visible fields we can just display
3350 // `{ /* fields omitted */ }` to save space.
3351 write!(w, " /* fields omitted */ ");
3357 for (i, field) in fields.iter().enumerate() {
3362 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3363 clean::StructFieldItem(ref ty) => {
3364 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3366 _ => unreachable!(),
3370 if let Some(g) = g {
3371 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3376 // Needed for PhantomData.
3377 if let Some(g) = g {
3378 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3388 g: Option<&clean::Generics>,
3389 fields: &[clean::Item],
3396 it.visibility.print_with_space(),
3397 if structhead { "union " } else { "" },
3398 it.name.as_ref().unwrap()
3400 if let Some(g) = g {
3401 write!(w, "{}", g.print());
3402 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3405 write!(w, " {{\n{}", tab);
3406 for field in fields {
3407 if let clean::StructFieldItem(ref ty) = field.kind {
3411 field.visibility.print_with_space(),
3412 field.name.as_ref().unwrap(),
3419 if it.has_stripped_fields().unwrap() {
3420 write!(w, " // some fields omitted\n{}", tab);
3425 #[derive(Copy, Clone)]
3426 enum AssocItemLink<'a> {
3427 Anchor(Option<&'a str>),
3428 GotoSource(DefId, &'a FxHashSet<String>),
3431 impl<'a> AssocItemLink<'a> {
3432 fn anchor(&self, id: &'a String) -> Self {
3434 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3435 ref other => *other,
3440 fn render_assoc_items(
3443 containing_item: &clean::Item,
3445 what: AssocItemRender<'_>,
3448 info!("Documenting associated items of {:?}", containing_item.name);
3449 let v = match cache.impls.get(&it) {
3453 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3454 if !non_trait.is_empty() {
3455 let render_mode = match what {
3456 AssocItemRender::All => {
3459 "<h2 id=\"implementations\" class=\"small-section-header\">\
3460 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3465 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3468 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
3469 Methods from {}<Target = {}>\
3470 <a href=\"#deref-methods\" class=\"anchor\"></a>\
3475 RenderMode::ForDeref { mut_: deref_mut_ }
3478 for i in &non_trait {
3484 AssocItemLink::Anchor(None),
3486 containing_item.stable_since().as_deref(),
3487 containing_item.const_stable_since().as_deref(),
3497 if let AssocItemRender::DerefFor { .. } = what {
3500 if !traits.is_empty() {
3502 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3503 if let Some(impl_) = deref_impl {
3505 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3506 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3509 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3510 traits.iter().partition(|t| t.inner_impl().synthetic);
3511 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3512 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3514 let mut impls = Buffer::empty_from(&w);
3515 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3516 let impls = impls.into_inner();
3517 if !impls.is_empty() {
3520 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3521 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3523 <div id=\"trait-implementations-list\">{}</div>",
3528 if !synthetic.is_empty() {
3531 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3532 Auto Trait Implementations\
3533 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3535 <div id=\"synthetic-implementations-list\">"
3537 render_impls(cx, w, &synthetic, containing_item, cache);
3538 write!(w, "</div>");
3541 if !blanket_impl.is_empty() {
3544 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3545 Blanket Implementations\
3546 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3548 <div id=\"blanket-implementations-list\">"
3550 render_impls(cx, w, &blanket_impl, containing_item, cache);
3551 write!(w, "</div>");
3556 fn render_deref_methods(
3560 container_item: &clean::Item,
3564 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3565 let (target, real_target) = impl_
3569 .find_map(|item| match item.kind {
3570 clean::TypedefItem(ref t, true) => Some(match *t {
3571 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3572 _ => (&t.type_, &t.type_),
3576 .expect("Expected associated type binding");
3578 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3579 if let Some(did) = target.def_id() {
3580 render_assoc_items(w, cx, container_item, did, what, cache);
3582 if let Some(prim) = target.primitive_type() {
3583 if let Some(&did) = cache.primitive_locations.get(&prim) {
3584 render_assoc_items(w, cx, container_item, did, what, cache);
3590 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3591 let self_type_opt = match item.kind {
3592 clean::MethodItem(ref method, _) => method.decl.self_type(),
3593 clean::TyMethodItem(ref method) => method.decl.self_type(),
3597 if let Some(self_ty) = self_type_opt {
3598 let (by_mut_ref, by_box, by_value) = match self_ty {
3599 SelfTy::SelfBorrowed(_, mutability)
3600 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3601 (mutability == Mutability::Mut, false, false)
3603 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3604 (false, Some(did) == cache().owned_box_did, false)
3606 SelfTy::SelfValue => (false, false, true),
3607 _ => (false, false, false),
3610 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3616 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3617 let mut out = Buffer::html();
3618 let mut trait_ = String::new();
3620 if let Some(did) = decl.output.def_id() {
3622 if let Some(impls) = c.impls.get(&did) {
3624 let impl_ = i.inner_impl();
3625 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3627 out.push_str(&format!(
3628 "<h3 class=\"notable\">Notable traits for {}</h3>\
3629 <code class=\"content\">",
3632 trait_.push_str(&impl_.for_.print().to_string());
3635 //use the "where" class here to make it small
3636 out.push_str(&format!(
3637 "<span class=\"where fmt-newline\">{}</span>",
3640 let t_did = impl_.trait_.def_id().unwrap();
3641 for it in &impl_.items {
3642 if let clean::TypedefItem(ref tydef, _) = it.kind {
3643 out.push_str("<span class=\"where fmt-newline\"> ");
3649 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3652 out.push_str(";</span>");
3660 if !out.is_empty() {
3663 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3664 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3666 out.push_str("</code></span></div></span></span>");
3676 parent: &clean::Item,
3677 link: AssocItemLink<'_>,
3678 render_mode: RenderMode,
3679 outer_version: Option<&str>,
3680 outer_const_version: Option<&str>,
3681 show_def_docs: bool,
3682 use_absolute: Option<bool>,
3683 is_on_foreign_type: bool,
3684 show_default_items: bool,
3685 // This argument is used to reference same type with different paths to avoid duplication
3686 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3690 let traits = &cache.traits;
3691 let trait_ = i.trait_did().map(|did| &traits[&did]);
3693 if render_mode == RenderMode::Normal {
3694 let id = cx.derive_id(match i.inner_impl().trait_ {
3696 if is_on_foreign_type {
3697 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3699 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3702 None => "impl".to_string(),
3704 let aliases = if aliases.is_empty() {
3707 format!(" aliases=\"{}\"", aliases.join(","))
3709 if let Some(use_absolute) = use_absolute {
3710 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3711 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3713 for it in &i.inner_impl().items {
3714 if let clean::TypedefItem(ref tydef, _) = it.kind {
3715 write!(w, "<span class=\"where fmt-newline\"> ");
3716 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3717 write!(w, ";</span>");
3721 write!(w, "</code>");
3725 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3728 i.inner_impl().print()
3731 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3732 render_stability_since_raw(
3734 i.impl_item.stable_since().as_deref(),
3735 i.impl_item.const_stable_since().as_deref(),
3737 outer_const_version,
3739 write_srclink(cx, &i.impl_item, w, cache);
3742 if trait_.is_some() {
3743 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3744 write!(w, "<div class=\"item-info\">{}</div>", portability);
3748 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3749 let mut ids = cx.id_map.borrow_mut();
3752 "<div class=\"docblock\">{}</div>",
3755 &i.impl_item.links(),
3759 &cx.shared.playground
3770 parent: &clean::Item,
3771 link: AssocItemLink<'_>,
3772 render_mode: RenderMode,
3773 is_default_item: bool,
3774 outer_version: Option<&str>,
3775 outer_const_version: Option<&str>,
3776 trait_: Option<&clean::Trait>,
3777 show_def_docs: bool,
3780 let item_type = item.type_();
3781 let name = item.name.as_ref().unwrap();
3783 let render_method_item = match render_mode {
3784 RenderMode::Normal => true,
3785 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3788 let (is_hidden, extra_class) =
3789 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3797 clean::MethodItem(..) | clean::TyMethodItem(_) => {
3798 // Only render when the method is not static or we allow static methods
3799 if render_method_item {
3800 let id = cx.derive_id(format!("{}.{}", item_type, name));
3801 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3802 write!(w, "<code>");
3803 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3804 write!(w, "</code>");
3805 render_stability_since_raw(
3807 item.stable_since().as_deref(),
3808 item.const_stable_since().as_deref(),
3810 outer_const_version,
3812 write_srclink(cx, item, w, cache);
3816 clean::TypedefItem(ref tydef, _) => {
3817 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3818 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3819 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3820 write!(w, "</code></h4>");
3822 clean::AssocConstItem(ref ty, ref default) => {
3823 let id = cx.derive_id(format!("{}.{}", item_type, name));
3824 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3825 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3826 write!(w, "</code>");
3827 render_stability_since_raw(
3829 item.stable_since().as_deref(),
3830 item.const_stable_since().as_deref(),
3832 outer_const_version,
3834 write_srclink(cx, item, w, cache);
3837 clean::AssocTypeItem(ref bounds, ref default) => {
3838 let id = cx.derive_id(format!("{}.{}", item_type, name));
3839 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3840 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3841 write!(w, "</code></h4>");
3843 clean::StrippedItem(..) => return,
3844 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3847 if render_method_item {
3848 if !is_default_item {
3849 if let Some(t) = trait_ {
3850 // The trait item may have been stripped so we might not
3851 // find any documentation or stability for it.
3852 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3853 // We need the stability of the item from the trait
3854 // because impls can't have a stability.
3855 if item.doc_value().is_some() {
3856 document_item_info(w, cx, it, is_hidden, Some(parent));
3857 document_full(w, item, cx, "", is_hidden);
3859 // In case the item isn't documented,
3860 // provide short documentation from the trait.
3874 document_item_info(w, cx, item, is_hidden, Some(parent));
3876 document_full(w, item, cx, "", is_hidden);
3880 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3885 write!(w, "<div class=\"impl-items\">");
3886 for trait_item in &i.inner_impl().items {
3891 if trait_.is_some() { &i.impl_item } else { parent },
3896 outer_const_version,
3903 fn render_default_items(
3908 parent: &clean::Item,
3909 render_mode: RenderMode,
3910 outer_version: Option<&str>,
3911 outer_const_version: Option<&str>,
3912 show_def_docs: bool,
3915 for trait_item in &t.items {
3916 let n = trait_item.name.clone();
3917 if i.items.iter().any(|m| m.name == n) {
3920 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3921 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3932 outer_const_version,
3940 // If we've implemented a trait, then also emit documentation for all
3941 // default items which weren't overridden in the implementation block.
3942 // We don't emit documentation for default items if they appear in the
3943 // Implementations on Foreign Types or Implementors sections.
3944 if show_default_items {
3945 if let Some(t) = trait_ {
3946 render_default_items(
3954 outer_const_version,
3960 write!(w, "</div>");
3967 t: &clean::OpaqueTy,
3970 write!(w, "<pre class=\"rust opaque\">");
3971 render_attributes(w, it, false);
3974 "type {}{}{where_clause} = impl {bounds};</pre>",
3975 it.name.as_ref().unwrap(),
3977 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3978 bounds = bounds(&t.bounds, false)
3981 document(w, cx, it, None);
3983 // Render any items associated directly to this alias, as otherwise they
3984 // won't be visible anywhere in the docs. It would be nice to also show
3985 // associated items from the aliased type (see discussion in #32077), but
3986 // we need #14072 to make sense of the generics.
3987 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3990 fn item_trait_alias(
3994 t: &clean::TraitAlias,
3997 write!(w, "<pre class=\"rust trait-alias\">");
3998 render_attributes(w, it, false);
4001 "trait {}{}{} = {};</pre>",
4002 it.name.as_ref().unwrap(),
4004 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4005 bounds(&t.bounds, true)
4008 document(w, cx, it, None);
4010 // Render any items associated directly to this alias, as otherwise they
4011 // won't be visible anywhere in the docs. It would be nice to also show
4012 // associated items from the aliased type (see discussion in #32077), but
4013 // we need #14072 to make sense of the generics.
4014 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4017 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
4018 write!(w, "<pre class=\"rust typedef\">");
4019 render_attributes(w, it, false);
4022 "type {}{}{where_clause} = {type_};</pre>",
4023 it.name.as_ref().unwrap(),
4025 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4026 type_ = t.type_.print()
4029 document(w, cx, it, None);
4031 // Render any items associated directly to this alias, as otherwise they
4032 // won't be visible anywhere in the docs. It would be nice to also show
4033 // associated items from the aliased type (see discussion in #32077), but
4034 // we need #14072 to make sense of the generics.
4035 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4038 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4039 writeln!(w, "<pre class=\"rust foreigntype\">extern {{");
4040 render_attributes(w, it, false);
4043 " {}type {};\n}}</pre>",
4044 it.visibility.print_with_space(),
4045 it.name.as_ref().unwrap(),
4048 document(w, cx, it, None);
4050 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4053 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
4054 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4058 || it.is_primitive()
4066 "<p class=\"location\">{}{}</p>",
4068 clean::StructItem(..) => "Struct ",
4069 clean::TraitItem(..) => "Trait ",
4070 clean::PrimitiveItem(..) => "Primitive Type ",
4071 clean::UnionItem(..) => "Union ",
4072 clean::EnumItem(..) => "Enum ",
4073 clean::TypedefItem(..) => "Type Definition ",
4074 clean::ForeignTypeItem => "Foreign Type ",
4075 clean::ModuleItem(..) =>
4083 it.name.as_ref().unwrap()
4088 if let Some(ref version) = cache.crate_version {
4091 "<div class=\"block version\">\
4099 write!(buffer, "<div class=\"sidebar-elems\">");
4103 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4104 it.name.as_ref().expect("crates always have a name")
4108 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
4109 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
4110 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
4111 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
4112 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
4113 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
4114 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4115 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
4119 // The sidebar is designed to display sibling functions, modules and
4120 // other miscellaneous information. since there are lots of sibling
4121 // items (and that causes quadratic growth in large modules),
4122 // we refactor common parts into a shared JavaScript file per module.
4123 // still, we don't move everything into JS because we want to preserve
4124 // as much HTML as possible in order to allow non-JS-enabled browsers
4125 // to navigate the documentation (though slightly inefficiently).
4127 write!(buffer, "<p class=\"location\">");
4128 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4130 write!(buffer, "::<wbr>");
4134 "<a href=\"{}index.html\">{}</a>",
4135 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4139 write!(buffer, "</p>");
4141 // Sidebar refers to the enclosing module, not this module.
4142 let relpath = if it.is_mod() { "../" } else { "" };
4145 "<script>window.sidebarCurrent = {{\
4148 relpath: \"{path}\"\
4150 name = it.name.unwrap_or(kw::Invalid),
4155 // There is no sidebar-items.js beyond the crate root path
4156 // FIXME maybe dynamic crate loading can be merged here
4158 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4160 // Closes sidebar-elems div.
4161 write!(buffer, "</div>");
4164 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4165 if used_links.insert(url.clone()) {
4169 while !used_links.insert(format!("{}-{}", url, add)) {
4172 format!("{}-{}", url, add)
4178 used_links: &mut FxHashSet<String>,
4183 .filter_map(|item| match item.name {
4184 Some(ref name) if !name.is_empty() && item.is_method() => {
4185 if !for_deref || should_render_item(item, deref_mut) {
4187 "<a href=\"#{}\">{}</a>",
4188 get_next_url(used_links, format!("method.{}", name)),
4197 .collect::<Vec<_>>()
4200 // The point is to url encode any potential character from a type with genericity.
4201 fn small_url_encode(s: &str) -> String {
4202 s.replace("<", "%3C")
4203 .replace(">", "%3E")
4204 .replace(" ", "%20")
4205 .replace("?", "%3F")
4206 .replace("'", "%27")
4207 .replace("&", "%26")
4208 .replace(",", "%2C")
4209 .replace(":", "%3A")
4210 .replace(";", "%3B")
4211 .replace("[", "%5B")
4212 .replace("]", "%5D")
4213 .replace("\"", "%22")
4216 fn sidebar_assoc_items(it: &clean::Item) -> String {
4217 let mut out = String::new();
4219 if let Some(v) = c.impls.get(&it.def_id) {
4220 let mut used_links = FxHashSet::default();
4223 let used_links_bor = &mut used_links;
4226 .filter(|i| i.inner_impl().trait_.is_none())
4227 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4228 .collect::<Vec<_>>();
4229 if !ret.is_empty() {
4230 // We want links' order to be reproducible so we don't use unstable sort.
4232 out.push_str(&format!(
4233 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4234 <div class=\"sidebar-links\">{}</div>",
4240 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4241 if let Some(impl_) = v
4243 .filter(|i| i.inner_impl().trait_.is_some())
4244 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4246 if let Some((target, real_target)) =
4247 impl_.inner_impl().items.iter().find_map(|item| match item.kind {
4248 clean::TypedefItem(ref t, true) => Some(match *t {
4249 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4250 _ => (&t.type_, &t.type_),
4257 .filter(|i| i.inner_impl().trait_.is_some())
4258 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4259 let inner_impl = target
4263 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4264 .and_then(|did| c.impls.get(&did));
4265 if let Some(impls) = inner_impl {
4266 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4267 out.push_str(&format!(
4268 "Methods from {}<Target={}>",
4271 impl_.inner_impl().trait_.as_ref().unwrap().print()
4273 Escape(&format!("{:#}", real_target.print()))
4275 out.push_str("</a>");
4278 .filter(|i| i.inner_impl().trait_.is_none())
4280 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4282 .collect::<Vec<_>>();
4283 // We want links' order to be reproducible so we don't use unstable sort.
4285 if !ret.is_empty() {
4286 out.push_str(&format!(
4287 "<div class=\"sidebar-links\">{}</div>",
4294 let format_impls = |impls: Vec<&Impl>| {
4295 let mut links = FxHashSet::default();
4300 let is_negative_impl = is_negative_impl(i.inner_impl());
4301 if let Some(ref i) = i.inner_impl().trait_ {
4302 let i_display = format!("{:#}", i.print());
4303 let out = Escape(&i_display);
4304 let encoded = small_url_encode(&format!("{:#}", i.print()));
4305 let generated = format!(
4306 "<a href=\"#impl-{}\">{}{}</a>",
4308 if is_negative_impl { "!" } else { "" },
4311 if links.insert(generated.clone()) { Some(generated) } else { None }
4316 .collect::<Vec<String>>();
4321 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4322 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4323 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4325 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4327 let concrete_format = format_impls(concrete);
4328 let synthetic_format = format_impls(synthetic);
4329 let blanket_format = format_impls(blanket_impl);
4331 if !concrete_format.is_empty() {
4333 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4334 Trait Implementations</a>",
4336 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4339 if !synthetic_format.is_empty() {
4341 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4342 Auto Trait Implementations</a>",
4344 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4347 if !blanket_format.is_empty() {
4349 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4350 Blanket Implementations</a>",
4352 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4360 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4361 let mut sidebar = String::new();
4362 let fields = get_struct_fields_name(&s.fields);
4364 if !fields.is_empty() {
4365 if let doctree::Plain = s.struct_type {
4366 sidebar.push_str(&format!(
4367 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4368 <div class=\"sidebar-links\">{}</div>",
4374 sidebar.push_str(&sidebar_assoc_items(it));
4376 if !sidebar.is_empty() {
4377 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4381 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4382 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4385 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4387 clean::ItemKind::ImplItem(ref i) => {
4388 if let Some(ref trait_) = i.trait_ {
4390 format!("{:#}", i.for_.print()),
4391 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4401 fn is_negative_impl(i: &clean::Impl) -> bool {
4402 i.polarity == Some(clean::ImplPolarity::Negative)
4405 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4406 let mut sidebar = String::new();
4411 .filter_map(|m| match m.name {
4412 Some(ref name) if m.is_associated_type() => {
4413 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4417 .collect::<Vec<_>>();
4421 .filter_map(|m| match m.name {
4422 Some(ref name) if m.is_associated_const() => {
4423 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4427 .collect::<Vec<_>>();
4428 let mut required = t
4431 .filter_map(|m| match m.name {
4432 Some(ref name) if m.is_ty_method() => {
4433 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4437 .collect::<Vec<String>>();
4438 let mut provided = t
4441 .filter_map(|m| match m.name {
4442 Some(ref name) if m.is_method() => {
4443 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4447 .collect::<Vec<String>>();
4449 if !types.is_empty() {
4451 sidebar.push_str(&format!(
4452 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4453 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4457 if !consts.is_empty() {
4459 sidebar.push_str(&format!(
4460 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4461 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4465 if !required.is_empty() {
4467 sidebar.push_str(&format!(
4468 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4469 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4473 if !provided.is_empty() {
4475 sidebar.push_str(&format!(
4476 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4477 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4484 if let Some(implementors) = c.implementors.get(&it.def_id) {
4485 let mut res = implementors
4487 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4488 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4489 .collect::<Vec<_>>();
4491 if !res.is_empty() {
4493 sidebar.push_str(&format!(
4494 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4495 Implementations on Foreign Types</a>\
4496 <div class=\"sidebar-links\">{}</div>",
4498 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4499 .collect::<Vec<_>>()
4505 sidebar.push_str(&sidebar_assoc_items(it));
4507 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4510 "<a class=\"sidebar-title\" \
4511 href=\"#synthetic-implementors\">Auto Implementors</a>",
4515 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4518 fn sidebar_primitive(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 sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4527 let sidebar = sidebar_assoc_items(it);
4529 if !sidebar.is_empty() {
4530 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4534 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4535 let mut fields = fields
4537 .filter(|f| if let clean::StructFieldItem(..) = f.kind { true } else { false })
4538 .filter_map(|f| match f.name {
4540 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4544 .collect::<Vec<_>>();
4549 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4550 let mut sidebar = String::new();
4551 let fields = get_struct_fields_name(&u.fields);
4553 if !fields.is_empty() {
4554 sidebar.push_str(&format!(
4555 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4556 <div class=\"sidebar-links\">{}</div>",
4561 sidebar.push_str(&sidebar_assoc_items(it));
4563 if !sidebar.is_empty() {
4564 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4568 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4569 let mut sidebar = String::new();
4571 let mut variants = e
4574 .filter_map(|v| match v.name {
4575 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4578 .collect::<Vec<_>>();
4579 if !variants.is_empty() {
4580 variants.sort_unstable();
4581 sidebar.push_str(&format!(
4582 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4583 <div class=\"sidebar-links\">{}</div>",
4588 sidebar.push_str(&sidebar_assoc_items(it));
4590 if !sidebar.is_empty() {
4591 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4595 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4597 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4598 ItemType::Module => ("modules", "Modules"),
4599 ItemType::Struct => ("structs", "Structs"),
4600 ItemType::Union => ("unions", "Unions"),
4601 ItemType::Enum => ("enums", "Enums"),
4602 ItemType::Function => ("functions", "Functions"),
4603 ItemType::Typedef => ("types", "Type Definitions"),
4604 ItemType::Static => ("statics", "Statics"),
4605 ItemType::Constant => ("constants", "Constants"),
4606 ItemType::Trait => ("traits", "Traits"),
4607 ItemType::Impl => ("impls", "Implementations"),
4608 ItemType::TyMethod => ("tymethods", "Type Methods"),
4609 ItemType::Method => ("methods", "Methods"),
4610 ItemType::StructField => ("fields", "Struct Fields"),
4611 ItemType::Variant => ("variants", "Variants"),
4612 ItemType::Macro => ("macros", "Macros"),
4613 ItemType::Primitive => ("primitives", "Primitive Types"),
4614 ItemType::AssocType => ("associated-types", "Associated Types"),
4615 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4616 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4617 ItemType::Keyword => ("keywords", "Keywords"),
4618 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4619 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4620 ItemType::ProcDerive => ("derives", "Derive Macros"),
4621 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4625 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4626 let mut sidebar = String::new();
4628 if items.iter().any(|it| {
4629 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4631 sidebar.push_str(&format!(
4632 "<li><a href=\"#{id}\">{name}</a></li>",
4638 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4639 // to print its headings
4641 ItemType::Primitive,
4655 ItemType::StructField,
4657 ItemType::AssocType,
4658 ItemType::AssocConst,
4659 ItemType::ForeignType,
4662 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4663 let (short, name) = item_ty_to_strs(&myty);
4664 sidebar.push_str(&format!(
4665 "<li><a href=\"#{id}\">{name}</a></li>",
4672 if !sidebar.is_empty() {
4673 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4677 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4678 let sidebar = sidebar_assoc_items(it);
4679 if !sidebar.is_empty() {
4680 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4684 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4685 wrap_into_docblock(w, |w| {
4686 w.write_str(&highlight::render_with_highlighting(
4693 document(w, cx, it, None)
4696 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4697 let name = it.name.as_ref().expect("proc-macros always have names");
4699 MacroKind::Bang => {
4700 write!(w, "<pre class=\"rust macro\">");
4701 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4702 write!(w, "</pre>");
4704 MacroKind::Attr => {
4705 write!(w, "<pre class=\"rust attr\">");
4706 write!(w, "#[{}]", name);
4707 write!(w, "</pre>");
4709 MacroKind::Derive => {
4710 write!(w, "<pre class=\"rust derive\">");
4711 write!(w, "#[derive({})]", name);
4712 if !m.helpers.is_empty() {
4713 writeln!(w, "\n{{");
4714 writeln!(w, " // Attributes available to this derive:");
4715 for attr in &m.helpers {
4716 writeln!(w, " #[{}]", attr);
4720 write!(w, "</pre>");
4723 document(w, cx, it, None)
4726 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4727 document(w, cx, it, None);
4728 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4731 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4732 document(w, cx, it, None)
4735 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4737 fn make_item_keywords(it: &clean::Item) -> String {
4738 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4741 /// Returns a list of all paths used in the type.
4742 /// This is used to help deduplicate imported impls
4743 /// for reexported types. If any of the contained
4744 /// types are re-exported, we don't use the corresponding
4745 /// entry from the js file, as inlining will have already
4746 /// picked up the impl
4747 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4748 let mut out = Vec::new();
4749 let mut visited = FxHashSet::default();
4750 let mut work = VecDeque::new();
4751 let cache = cache();
4753 work.push_back(first_ty);
4755 while let Some(ty) = work.pop_front() {
4756 if !visited.insert(ty.clone()) {
4761 clean::Type::ResolvedPath { did, .. } => {
4762 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4763 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4765 if let Some(path) = fqp {
4766 out.push(path.join("::"));
4769 clean::Type::Tuple(tys) => {
4770 work.extend(tys.into_iter());
4772 clean::Type::Slice(ty) => {
4773 work.push_back(*ty);
4775 clean::Type::Array(ty, _) => {
4776 work.push_back(*ty);
4778 clean::Type::RawPointer(_, ty) => {
4779 work.push_back(*ty);
4781 clean::Type::BorrowedRef { type_, .. } => {
4782 work.push_back(*type_);
4784 clean::Type::QPath { self_type, trait_, .. } => {
4785 work.push_back(*self_type);
4786 work.push_back(*trait_);