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_data_structures::flock;
53 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
54 use rustc_feature::UnstableFeatures;
56 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
57 use rustc_hir::Mutability;
58 use rustc_middle::middle::stability;
59 use rustc_span::edition::Edition;
60 use rustc_span::hygiene::MacroKind;
61 use rustc_span::source_map::FileName;
62 use rustc_span::symbol::{sym, Symbol};
63 use serde::ser::SerializeSeq;
64 use serde::{Serialize, Serializer};
66 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, TypeKind};
67 use crate::config::RenderInfo;
68 use crate::config::RenderOptions;
69 use crate::docfs::{DocFS, PathError};
71 use crate::error::Error;
72 use crate::formats::cache::{cache, Cache};
73 use crate::formats::item_type::ItemType;
74 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
75 use crate::html::escape::Escape;
76 use crate::html::format::fmt_impl_for_trait_page;
77 use crate::html::format::Function;
78 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
79 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
80 use crate::html::markdown::{self, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine};
81 use crate::html::sources;
82 use crate::html::{highlight, layout, static_files};
83 use cache::{build_index, ExternalLocation};
85 /// A pair of name and its optional document.
86 pub type NameDoc = (String, Option<String>);
88 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
89 crate::html::format::display_fn(move |f| {
90 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
94 /// Major driving force in all rustdoc rendering. This contains information
95 /// about where in the tree-like hierarchy rendering is occurring and controls
96 /// how the current page is being rendered.
98 /// It is intended that this context is a lightweight object which can be fairly
99 /// easily cloned because it is cloned per work-job (about once per item in the
102 crate struct Context {
103 /// Current hierarchy of components leading down to what's currently being
105 pub current: Vec<String>,
106 /// The current destination folder of where HTML artifacts should be placed.
107 /// This changes as the context descends into the module hierarchy.
109 /// A flag, which when `true`, will render pages which redirect to the
110 /// real location of an item. This is used to allow external links to
111 /// publicly reused items to redirect to the right location.
112 pub render_redirect_pages: bool,
113 /// The map used to ensure all generated 'id=' attributes are unique.
114 id_map: Rc<RefCell<IdMap>>,
115 pub shared: Arc<SharedContext>,
116 all: Rc<RefCell<AllTypes>>,
117 /// Storage for the errors produced while generating documentation so they
118 /// can be printed together at the end.
119 pub errors: Rc<Receiver<String>>,
122 crate struct SharedContext {
123 /// The path to the crate root source minus the file name.
124 /// Used for simplifying paths to the highlighted source code files.
125 pub src_root: PathBuf,
126 /// This describes the layout of each page, and is not modified after
127 /// creation of the context (contains info like the favicon and added html).
128 pub layout: layout::Layout,
129 /// This flag indicates whether `[src]` links should be generated or not. If
130 /// the source files are present in the html rendering, then this will be
132 pub include_sources: bool,
133 /// The local file sources we've emitted and their respective url-paths.
134 pub local_sources: FxHashMap<PathBuf, String>,
135 /// Whether the collapsed pass ran
137 /// The base-URL of the issue tracker for when an item has been tagged with
139 pub issue_tracker_base_url: Option<String>,
140 /// The directories that have already been created in this doc run. Used to reduce the number
141 /// of spurious `create_dir_all` calls.
142 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
143 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
144 /// should be ordered alphabetically or in order of appearance (in the source code).
145 pub sort_modules_alphabetically: bool,
146 /// Additional CSS files to be added to the generated docs.
147 pub style_files: Vec<StylePath>,
148 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
150 pub resource_suffix: String,
151 /// Optional path string to be used to load static files on output pages. If not set, uses
152 /// combinations of `../` to reach the documentation root.
153 pub static_root_path: Option<String>,
154 /// The fs handle we are working with.
156 /// The default edition used to parse doctests.
157 pub edition: Edition,
158 pub codes: ErrorCodes,
159 playground: Option<markdown::Playground>,
163 fn path(&self, filename: &str) -> PathBuf {
164 // We use splitn vs Path::extension here because we might get a filename
165 // like `style.min.css` and we want to process that into
166 // `style-suffix.min.css`. Path::extension would just return `css`
167 // which would result in `style.min-suffix.css` which isn't what we
169 let mut iter = filename.splitn(2, '.');
170 let base = iter.next().unwrap();
171 let ext = iter.next().unwrap();
172 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext,);
173 self.dst.join(&filename)
178 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
179 let mut dirs = self.created_dirs.borrow_mut();
180 if !dirs.contains(dst) {
181 try_err!(self.fs.create_dir_all(dst), dst);
182 dirs.insert(dst.to_path_buf());
188 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
189 /// `collapsed_doc_value` of the given item.
190 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
192 item.collapsed_doc_value().map(|s| s.into())
194 item.doc_value().map(|s| s.into())
199 // Helper structs for rendering items/sidebars and carrying along contextual
202 /// Struct representing one entry in the JS search index. These are all emitted
203 /// by hand to a large JS file at the end of cache-creation.
205 pub struct IndexItem {
210 pub parent: Option<DefId>,
211 pub parent_idx: Option<usize>,
212 pub search_type: Option<IndexItemFunctionType>,
215 impl Serialize for IndexItem {
216 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
221 self.parent.is_some(),
222 self.parent_idx.is_some(),
223 "`{}` is missing idx",
227 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
228 .serialize(serializer)
232 /// A type used for the search index.
234 crate struct RenderType {
237 name: Option<String>,
238 generics: Option<Vec<Generic>>,
241 impl Serialize for RenderType {
242 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
246 if let Some(name) = &self.name {
247 let mut seq = serializer.serialize_seq(None)?;
248 if let Some(id) = self.idx {
249 seq.serialize_element(&id)?;
251 seq.serialize_element(&name)?;
253 if let Some(generics) = &self.generics {
254 seq.serialize_element(&generics)?;
258 serializer.serialize_none()
263 /// A type used for the search index.
265 crate struct Generic {
267 defid: Option<DefId>,
271 impl Serialize for Generic {
272 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
276 if let Some(id) = self.idx {
277 serializer.serialize_some(&id)
279 serializer.serialize_some(&self.name)
284 /// Full type of functions/methods in the search index.
286 pub struct IndexItemFunctionType {
287 inputs: Vec<TypeWithKind>,
288 output: Option<Vec<TypeWithKind>>,
291 impl Serialize for IndexItemFunctionType {
292 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
296 // If we couldn't figure out a type, just write `null`.
297 let mut iter = self.inputs.iter();
298 if match self.output {
299 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
300 None => iter.any(|ref i| i.ty.name.is_none()),
302 serializer.serialize_none()
304 let mut seq = serializer.serialize_seq(None)?;
305 seq.serialize_element(&self.inputs)?;
306 if let Some(output) = &self.output {
307 if output.len() > 1 {
308 seq.serialize_element(&output)?;
310 seq.serialize_element(&output[0])?;
319 crate struct TypeWithKind {
324 impl From<(RenderType, TypeKind)> for TypeWithKind {
325 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
326 TypeWithKind { ty: x.0, kind: x.1 }
330 impl Serialize for TypeWithKind {
331 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
335 let mut seq = serializer.serialize_seq(None)?;
336 seq.serialize_element(&self.ty.name)?;
337 let x: ItemType = self.kind.into();
338 seq.serialize_element(&x)?;
343 #[derive(Debug, Clone)]
344 pub struct StylePath {
345 /// The path to the theme
347 /// What the `disabled` attribute should be set to in the HTML tag
351 thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
353 pub fn initial_ids() -> Vec<String> {
365 "synthetic-implementors",
367 "synthetic-implementors-list",
373 .map(|id| (String::from(*id)))
377 /// Generates the documentation for `crate` into the directory `dst`
378 impl FormatRenderer for Context {
380 mut krate: clean::Crate,
381 options: RenderOptions,
382 _render_info: RenderInfo,
385 ) -> Result<(Context, clean::Crate), Error> {
386 // need to save a copy of the options for rendering the index page
387 let md_opts = options.clone();
393 sort_modules_alphabetically,
398 generate_search_filter,
402 let src_root = match krate.src {
403 FileName::Real(ref p) => match p.local_path().parent() {
404 Some(p) => p.to_path_buf(),
405 None => PathBuf::new(),
409 // If user passed in `--playground-url` arg, we fill in crate name here
410 let mut playground = None;
411 if let Some(url) = playground_url {
412 playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url });
414 let mut layout = layout::Layout {
416 favicon: String::new(),
418 krate: krate.name.clone(),
419 css_file_extension: extension_css,
420 generate_search_filter,
422 let mut issue_tracker_base_url = None;
423 let mut include_sources = true;
425 // Crawl the crate attributes looking for attributes which control how we're
426 // going to emit HTML
427 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
428 for attr in attrs.lists(sym::doc) {
429 match (attr.name_or_empty(), attr.value_str()) {
430 (sym::html_favicon_url, Some(s)) => {
431 layout.favicon = s.to_string();
433 (sym::html_logo_url, Some(s)) => {
434 layout.logo = s.to_string();
436 (sym::html_playground_url, Some(s)) => {
437 playground = Some(markdown::Playground {
438 crate_name: Some(krate.name.clone()),
442 (sym::issue_tracker_base_url, Some(s)) => {
443 issue_tracker_base_url = Some(s.to_string());
445 (sym::html_no_source, None) if attr.is_word() => {
446 include_sources = false;
452 let (sender, receiver) = channel();
453 let mut scx = SharedContext {
454 collapsed: krate.collapsed,
457 local_sources: Default::default(),
458 issue_tracker_base_url,
460 created_dirs: Default::default(),
461 sort_modules_alphabetically,
465 fs: DocFS::new(sender),
467 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
471 // Add the default themes to the `Vec` of stylepaths
473 // Note that these must be added before `sources::render` is called
474 // so that the resulting source pages are styled
476 // `light.css` is not disabled because it is the stylesheet that stays loaded
477 // by the browser as the theme stylesheet. The theme system (hackily) works by
478 // changing the href to this stylesheet. All other themes are disabled to
479 // prevent rule conflicts
480 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
481 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
482 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
485 scx.ensure_dir(&dst)?;
486 krate = sources::render(&dst, &mut scx, krate)?;
488 // Build our search index
489 let index = build_index(&krate, cache);
491 let cache = Arc::new(cache);
492 let mut cx = Context {
495 render_redirect_pages: false,
496 id_map: Rc::new(RefCell::new(id_map)),
497 shared: Arc::new(scx),
498 all: Rc::new(RefCell::new(AllTypes::new())),
499 errors: Rc::new(receiver),
502 CURRENT_DEPTH.with(|s| s.set(0));
504 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
505 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
506 write_shared(&cx, &krate, index, &md_opts, &cache)?;
507 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
511 fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
512 Arc::get_mut(&mut self.shared).unwrap().fs.close();
513 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
515 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
521 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
522 let final_file = self.dst.join(&krate.name).join("all.html");
523 let settings_file = self.dst.join("settings.html");
524 let crate_name = krate.name.clone();
526 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
527 if !root_path.ends_with('/') {
530 let mut page = layout::Page {
531 title: "List of all items in this crate",
534 static_root_path: self.shared.static_root_path.as_deref(),
535 description: "List of all items in this crate",
536 keywords: BASIC_KEYWORDS,
537 resource_suffix: &self.shared.resource_suffix,
539 static_extra_scripts: &[],
541 let sidebar = if let Some(ref version) = cache.crate_version {
543 "<p class='location'>Crate {}</p>\
544 <div class='block version'>\
547 <a id='all-types' href='index.html'><p>Back to index</p></a>",
554 let all = self.all.replace(AllTypes::new());
555 let v = layout::render(
559 |buf: &mut Buffer| all.print(buf),
560 &self.shared.style_files,
562 self.shared.fs.write(&final_file, v.as_bytes())?;
564 // Generating settings page.
565 page.title = "Rustdoc settings";
566 page.description = "Settings of Rustdoc";
567 page.root_path = "./";
569 let mut style_files = self.shared.style_files.clone();
570 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
571 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
572 let v = layout::render(
577 self.shared.static_root_path.as_deref().unwrap_or("./"),
578 &self.shared.resource_suffix,
582 self.shared.fs.write(&settings_file, v.as_bytes())?;
591 ) -> Result<(), Error> {
592 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
593 // if they contain impls for public types. These modules can also
594 // contain items such as publicly re-exported structures.
596 // External crates will provide links to these structures, so
597 // these modules are recursed into, but not rendered normally
598 // (a flag on the context).
599 if !self.render_redirect_pages {
600 self.render_redirect_pages = item.is_stripped();
602 let scx = &self.shared;
603 self.dst.push(item_name);
604 self.current.push(item_name.to_owned());
606 info!("Recursing into {}", self.dst.display());
608 let buf = self.render_item(item, false, cache);
609 // buf will be empty if the module is stripped and there is no redirect for it
611 self.shared.ensure_dir(&self.dst)?;
612 let joint_dst = self.dst.join("index.html");
613 scx.fs.write(&joint_dst, buf.as_bytes())?;
616 // Render sidebar-items.js used throughout this module.
617 if !self.render_redirect_pages {
618 let module = match item.inner {
619 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
622 let items = self.build_sidebar_items(module);
623 let js_dst = self.dst.join("sidebar-items.js");
624 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
625 scx.fs.write(&js_dst, &v)?;
630 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
631 info!("Recursed; leaving {}", self.dst.display());
633 // Go back to where we were at
639 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
640 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
641 // if they contain impls for public types. These modules can also
642 // contain items such as publicly re-exported structures.
644 // External crates will provide links to these structures, so
645 // these modules are recursed into, but not rendered normally
646 // (a flag on the context).
647 if !self.render_redirect_pages {
648 self.render_redirect_pages = item.is_stripped();
651 let buf = self.render_item(&item, true, cache);
652 // buf will be empty if the item is stripped and there is no redirect for it
654 let name = item.name.as_ref().unwrap();
655 let item_type = item.type_();
656 let file_name = &item_path(item_type, name);
657 self.shared.ensure_dir(&self.dst)?;
658 let joint_dst = self.dst.join(file_name);
659 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
661 if !self.render_redirect_pages {
662 self.all.borrow_mut().append(full_path(self, &item), &item_type);
664 // If the item is a macro, redirect from the old macro URL (with !)
665 // to the new one (without).
666 if item_type == ItemType::Macro {
667 let redir_name = format!("{}.{}!.html", item_type, name);
668 let redir_dst = self.dst.join(redir_name);
669 let v = layout::redirect(file_name);
670 self.shared.fs.write(&redir_dst, v.as_bytes())?;
679 krate: &clean::Crate,
680 search_index: String,
681 options: &RenderOptions,
683 ) -> Result<(), Error> {
684 // Write out the shared files. Note that these are shared among all rustdoc
685 // docs placed in the output directory, so this needs to be a synchronized
686 // operation with respect to all other rustdocs running around.
687 let lock_file = cx.dst.join(".lock");
688 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
690 // Add all the static files. These may already exist, but we just
691 // overwrite them anyway to make sure that they're fresh and up-to-date.
695 cx.path("rustdoc.css"),
696 static_files::RUSTDOC_CSS,
697 options.enable_minification,
701 cx.path("settings.css"),
702 static_files::SETTINGS_CSS,
703 options.enable_minification,
707 cx.path("noscript.css"),
708 static_files::NOSCRIPT_CSS,
709 options.enable_minification,
712 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
713 // then we'll run over the "official" styles.
714 let mut themes: FxHashSet<String> = FxHashSet::default();
716 for entry in &cx.shared.style_files {
717 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
719 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
721 // Handle the official themes
723 "light" => write_minify(
725 cx.path("light.css"),
726 static_files::themes::LIGHT,
727 options.enable_minification,
729 "dark" => write_minify(
732 static_files::themes::DARK,
733 options.enable_minification,
735 "ayu" => write_minify(
738 static_files::themes::AYU,
739 options.enable_minification,
742 // Handle added third-party themes
743 let content = try_err!(fs::read(&entry.path), &entry.path);
746 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
750 themes.insert(theme.to_owned());
753 let write = |p, c| cx.shared.fs.write(p, c);
754 if (*cx.shared).layout.logo.is_empty() {
755 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
757 if (*cx.shared).layout.favicon.is_empty() {
758 write(cx.path("favicon.ico"), static_files::RUST_FAVICON)?;
760 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
761 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
762 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
764 let mut themes: Vec<&String> = themes.iter().collect();
766 // To avoid theme switch latencies as much as possible, we put everything theme related
767 // at the beginning of the html files into another js file.
768 let theme_js = format!(
769 r#"var themes = document.getElementById("theme-choices");
770 var themePicker = document.getElementById("theme-picker");
772 function showThemeButtonState() {{
773 themes.style.display = "block";
774 themePicker.style.borderBottomRightRadius = "0";
775 themePicker.style.borderBottomLeftRadius = "0";
778 function hideThemeButtonState() {{
779 themes.style.display = "none";
780 themePicker.style.borderBottomRightRadius = "3px";
781 themePicker.style.borderBottomLeftRadius = "3px";
784 function switchThemeButtonState() {{
785 if (themes.style.display === "block") {{
786 hideThemeButtonState();
788 showThemeButtonState();
792 function handleThemeButtonsBlur(e) {{
793 var active = document.activeElement;
794 var related = e.relatedTarget;
796 if (active.id !== "themePicker" &&
797 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
799 (related.id !== "themePicker" &&
800 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
801 hideThemeButtonState();
805 themePicker.onclick = switchThemeButtonState;
806 themePicker.onblur = handleThemeButtonsBlur;
807 {}.forEach(function(item) {{
808 var but = document.createElement('button');
809 but.textContent = item;
810 but.onclick = function(el) {{
811 switchTheme(currentTheme, mainTheme, item, true);
813 but.onblur = handleThemeButtonsBlur;
814 themes.appendChild(but);
816 serde_json::to_string(&themes).unwrap()
819 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
823 static_files::MAIN_JS,
824 options.enable_minification,
828 cx.path("settings.js"),
829 static_files::SETTINGS_JS,
830 options.enable_minification,
832 if cx.shared.include_sources {
835 cx.path("source-script.js"),
836 static_files::sidebar::SOURCE_SCRIPT,
837 options.enable_minification,
844 cx.path("storage.js"),
846 "var resourcesSuffix = \"{}\";{}",
847 cx.shared.resource_suffix,
848 static_files::STORAGE_JS
850 options.enable_minification,
854 if let Some(ref css) = cx.shared.layout.css_file_extension {
855 let out = cx.path("theme.css");
856 let buffer = try_err!(fs::read_to_string(css), css);
857 if !options.enable_minification {
858 cx.shared.fs.write(&out, &buffer)?;
860 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
865 cx.path("normalize.css"),
866 static_files::NORMALIZE_CSS,
867 options.enable_minification,
869 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
870 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
871 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
872 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
873 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
874 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
875 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
876 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
877 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
878 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
879 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
880 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
881 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
883 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
884 let mut ret = Vec::new();
885 let mut krates = Vec::new();
888 for line in BufReader::new(File::open(path)?).lines() {
890 if !line.starts_with(key) {
893 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
896 ret.push(line.to_string());
898 line[key.len() + 2..]
901 .map(|s| s.to_owned())
902 .unwrap_or_else(String::new),
909 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
910 let mut ret = Vec::new();
911 let mut krates = Vec::new();
914 for line in BufReader::new(File::open(path)?).lines() {
916 if !line.starts_with('"') {
919 if line.starts_with(&format!("\"{}\"", krate)) {
922 if line.ends_with(",\\") {
923 ret.push(line[..line.len() - 2].to_string());
925 // Ends with "\\" (it's the case for the last added crate line)
926 ret.push(line[..line.len() - 1].to_string());
930 .find(|s| !s.is_empty())
931 .map(|s| s.to_owned())
932 .unwrap_or_else(String::new),
939 use std::ffi::OsString;
944 children: FxHashMap<OsString, Hierarchy>,
945 elems: FxHashSet<OsString>,
949 fn new(elem: OsString) -> Hierarchy {
950 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
953 fn to_json_string(&self) -> String {
954 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
955 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
959 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
960 .collect::<Vec<_>>();
961 files.sort_unstable_by(|a, b| a.cmp(b));
962 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
964 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
965 let files = files.join(",");
967 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
969 "{{\"name\":\"{name}\"{dirs}{files}}}",
970 name = self.elem.to_str().expect("invalid osstring conversion"),
977 if cx.shared.include_sources {
978 let mut hierarchy = Hierarchy::new(OsString::new());
983 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
985 let mut h = &mut hierarchy;
986 let mut elems = source
988 .filter_map(|s| match s {
989 Component::Normal(s) => Some(s.to_owned()),
994 let cur_elem = elems.next().expect("empty file path");
995 if elems.peek().is_none() {
996 h.elems.insert(cur_elem);
999 let e = cur_elem.clone();
1000 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1001 h = h.children.get_mut(&cur_elem).expect("not found child");
1006 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1007 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1008 all_sources.push(format!(
1009 "sourcesIndex[\"{}\"] = {};",
1011 hierarchy.to_json_string()
1015 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1016 all_sources.join("\n")
1018 cx.shared.fs.write(&dst, v.as_bytes())?;
1021 // Update the search index
1022 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1023 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name), &dst);
1024 all_indexes.push(search_index);
1026 // Sort the indexes by crate so the file will be generated identically even
1027 // with rustdoc running in parallel.
1030 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1031 v.push_str(&all_indexes.join(",\\\n"));
1032 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1033 // search might start (if it's set into the URL for example).
1034 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1035 cx.shared.fs.write(&dst, &v)?;
1037 if options.enable_index_page {
1038 if let Some(index_page) = options.index_page.clone() {
1039 let mut md_opts = options.clone();
1040 md_opts.output = cx.dst.clone();
1041 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1043 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1044 .map_err(|e| Error::new(e, &index_page))?;
1046 let dst = cx.dst.join("index.html");
1047 let page = layout::Page {
1048 title: "Index of crates",
1051 static_root_path: cx.shared.static_root_path.as_deref(),
1052 description: "List of crates",
1053 keywords: BASIC_KEYWORDS,
1054 resource_suffix: &cx.shared.resource_suffix,
1056 static_extra_scripts: &[],
1058 krates.push(krate.name.clone());
1062 let content = format!(
1064 <span class='in-band'>List of all crates</span>\
1065 </h1><ul class='mod'>{}</ul>",
1070 "<li><a class=\"mod\" href=\"{}index.html\">{}</a></li>",
1071 ensure_trailing_slash(s),
1075 .collect::<String>()
1077 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1078 cx.shared.fs.write(&dst, v.as_bytes())?;
1082 // Update the list of all implementors for traits
1083 let dst = cx.dst.join("implementors");
1084 for (&did, imps) in &cache.implementors {
1085 // Private modules can leak through to this phase of rustdoc, which
1086 // could contain implementations for otherwise private types. In some
1087 // rare cases we could find an implementation for an item which wasn't
1088 // indexed, so we just skip this step in that case.
1090 // FIXME: this is a vague explanation for why this can't be a `get`, in
1091 // theory it should be...
1092 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1094 None => match cache.external_paths.get(&did) {
1100 #[derive(Serialize)]
1101 struct Implementor {
1107 let implementors = imps
1110 // If the trait and implementation are in the same crate, then
1111 // there's no need to emit information about it (there's inlining
1112 // going on). If they're in different crates then the crate defining
1113 // the trait will be interested in our implementation.
1115 // If the implementation is from another crate then that crate
1117 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1121 text: imp.inner_impl().print().to_string(),
1122 synthetic: imp.inner_impl().synthetic,
1123 types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1127 .collect::<Vec<_>>();
1129 // Only create a js file if we have impls to add to it. If the trait is
1130 // documented locally though we always create the file to avoid dead
1132 if implementors.is_empty() && !cache.paths.contains_key(&did) {
1136 let implementors = format!(
1137 r#"implementors["{}"] = {};"#,
1139 serde_json::to_string(&implementors).unwrap()
1142 let mut mydst = dst.clone();
1143 for part in &remote_path[..remote_path.len() - 1] {
1146 cx.shared.ensure_dir(&mydst)?;
1147 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1149 let (mut all_implementors, _) =
1150 try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1151 all_implementors.push(implementors);
1152 // Sort the implementors by crate so the file will be generated
1153 // identically even with rustdoc running in parallel.
1154 all_implementors.sort();
1156 let mut v = String::from("(function() {var implementors = {};\n");
1157 for implementor in &all_implementors {
1158 writeln!(v, "{}", *implementor).unwrap();
1161 "if (window.register_implementors) {\
1162 window.register_implementors(implementors);\
1164 window.pending_implementors = implementors;\
1168 cx.shared.fs.write(&mydst, &v)?;
1177 enable_minification: bool,
1178 ) -> Result<(), Error> {
1179 if enable_minification {
1180 if dst.extension() == Some(&OsStr::new("css")) {
1181 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1182 fs.write(dst, res.as_bytes())
1184 fs.write(dst, minifier::js::minify(contents).as_bytes())
1187 fs.write(dst, contents.as_bytes())
1191 #[derive(Debug, Eq, PartialEq, Hash)]
1198 fn new(mut url: String, name: String) -> ItemEntry {
1199 while url.starts_with('/') {
1202 ItemEntry { url, name }
1207 crate fn print(&self) -> impl fmt::Display + '_ {
1208 crate::html::format::display_fn(move |f| {
1209 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1214 impl PartialOrd for ItemEntry {
1215 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1216 Some(self.cmp(other))
1220 impl Ord for ItemEntry {
1221 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1222 self.name.cmp(&other.name)
1228 structs: FxHashSet<ItemEntry>,
1229 enums: FxHashSet<ItemEntry>,
1230 unions: FxHashSet<ItemEntry>,
1231 primitives: FxHashSet<ItemEntry>,
1232 traits: FxHashSet<ItemEntry>,
1233 macros: FxHashSet<ItemEntry>,
1234 functions: FxHashSet<ItemEntry>,
1235 typedefs: FxHashSet<ItemEntry>,
1236 opaque_tys: FxHashSet<ItemEntry>,
1237 statics: FxHashSet<ItemEntry>,
1238 constants: FxHashSet<ItemEntry>,
1239 keywords: FxHashSet<ItemEntry>,
1240 attributes: FxHashSet<ItemEntry>,
1241 derives: FxHashSet<ItemEntry>,
1242 trait_aliases: FxHashSet<ItemEntry>,
1246 fn new() -> AllTypes {
1247 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1249 structs: new_set(100),
1250 enums: new_set(100),
1251 unions: new_set(100),
1252 primitives: new_set(26),
1253 traits: new_set(100),
1254 macros: new_set(100),
1255 functions: new_set(100),
1256 typedefs: new_set(100),
1257 opaque_tys: new_set(100),
1258 statics: new_set(100),
1259 constants: new_set(100),
1260 keywords: new_set(100),
1261 attributes: new_set(100),
1262 derives: new_set(100),
1263 trait_aliases: new_set(100),
1267 fn append(&mut self, item_name: String, item_type: &ItemType) {
1268 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1269 if let Some(name) = url.pop() {
1270 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1272 let name = url.join("::");
1274 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1275 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1276 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1277 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1278 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1279 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1280 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1281 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1282 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1283 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1284 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1285 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1286 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1287 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1294 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1296 let mut e: Vec<&ItemEntry> = e.iter().collect();
1300 "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1304 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1310 fn print(self, f: &mut Buffer) {
1314 <span class='out-of-band'>\
1315 <span id='render-detail'>\
1316 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1317 [<span class='inner'>−</span>]\
1321 <span class='in-band'>List of all items</span>\
1324 print_entries(f, &self.structs, "Structs", "structs");
1325 print_entries(f, &self.enums, "Enums", "enums");
1326 print_entries(f, &self.unions, "Unions", "unions");
1327 print_entries(f, &self.primitives, "Primitives", "primitives");
1328 print_entries(f, &self.traits, "Traits", "traits");
1329 print_entries(f, &self.macros, "Macros", "macros");
1330 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1331 print_entries(f, &self.derives, "Derive Macros", "derives");
1332 print_entries(f, &self.functions, "Functions", "functions");
1333 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1334 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1335 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1336 print_entries(f, &self.statics, "Statics", "statics");
1337 print_entries(f, &self.constants, "Constants", "constants")
1343 Section { description: &'static str, sub_settings: Vec<Setting> },
1344 Entry { js_data_name: &'static str, description: &'static str, default_value: bool },
1348 fn display(&self) -> String {
1350 Setting::Section { ref description, ref sub_settings } => format!(
1351 "<div class='setting-line'>\
1352 <div class='title'>{}</div>\
1353 <div class='sub-settings'>{}</div>
1356 sub_settings.iter().map(|s| s.display()).collect::<String>()
1358 Setting::Entry { ref js_data_name, ref description, ref default_value } => format!(
1359 "<div class='setting-line'>\
1360 <label class='toggle'>\
1361 <input type='checkbox' id='{}' {}>\
1362 <span class='slider'></span>\
1367 if *default_value { " checked" } else { "" },
1374 impl From<(&'static str, &'static str, bool)> for Setting {
1375 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1376 Setting::Entry { js_data_name: values.0, description: values.1, default_value: values.2 }
1380 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1381 fn from(values: (&'static str, Vec<T>)) -> Setting {
1383 description: values.0,
1384 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1389 fn settings(root_path: &str, suffix: &str) -> String {
1390 // (id, explanation, default value)
1391 let settings: &[Setting] = &[
1393 "Auto-hide item declarations",
1395 ("auto-hide-struct", "Auto-hide structs declaration", true),
1396 ("auto-hide-enum", "Auto-hide enums declaration", false),
1397 ("auto-hide-union", "Auto-hide unions declaration", true),
1398 ("auto-hide-trait", "Auto-hide traits declaration", true),
1399 ("auto-hide-macro", "Auto-hide macros declaration", false),
1403 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1404 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1405 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1407 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1408 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1410 ("line-numbers", "Show line numbers on code examples", false).into(),
1411 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1415 <span class='in-band'>Rustdoc settings</span>\
1417 <div class='settings'>{}</div>\
1418 <script src='{}settings{}.js'></script>",
1419 settings.iter().map(|s| s.display()).collect::<String>(),
1426 fn derive_id(&self, id: String) -> String {
1427 let mut map = self.id_map.borrow_mut();
1431 /// String representation of how to get back to the root path of the 'doc/'
1432 /// folder in terms of a relative URL.
1433 fn root_path(&self) -> String {
1434 "../".repeat(self.current.len())
1437 fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1438 // A little unfortunate that this is done like this, but it sure
1439 // does make formatting *a lot* nicer.
1440 CURRENT_DEPTH.with(|slot| {
1441 slot.set(self.current.len());
1444 let mut title = if it.is_primitive() || it.is_keyword() {
1445 // No need to include the namespace for primitive types and keywords
1448 self.current.join("::")
1451 if !title.is_empty() {
1452 title.push_str("::");
1454 title.push_str(it.name.as_ref().unwrap());
1456 title.push_str(" - Rust");
1457 let tyname = it.type_();
1458 let desc = if it.is_crate() {
1459 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1462 "API documentation for the Rust `{}` {} in crate `{}`.",
1463 it.name.as_ref().unwrap(),
1465 self.shared.layout.krate
1468 let keywords = make_item_keywords(it);
1469 let page = layout::Page {
1470 css_class: tyname.as_str(),
1471 root_path: &self.root_path(),
1472 static_root_path: self.shared.static_root_path.as_deref(),
1475 keywords: &keywords,
1476 resource_suffix: &self.shared.resource_suffix,
1478 static_extra_scripts: &[],
1482 self.id_map.borrow_mut().reset();
1483 self.id_map.borrow_mut().populate(initial_ids());
1486 if !self.render_redirect_pages {
1488 &self.shared.layout,
1490 |buf: &mut _| print_sidebar(self, it, buf, cache),
1491 |buf: &mut _| print_item(self, it, buf, cache),
1492 &self.shared.style_files,
1495 let mut url = self.root_path();
1496 if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1497 for name in &names[..names.len() - 1] {
1501 url.push_str(&item_path(ty, names.last().unwrap()));
1502 layout::redirect(&url)
1509 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1510 // BTreeMap instead of HashMap to get a sorted output
1511 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1512 for item in &m.items {
1513 if item.is_stripped() {
1517 let short = item.type_();
1518 let myname = match item.name {
1520 Some(ref s) => s.to_string(),
1522 let short = short.to_string();
1525 .push((myname, Some(plain_summary_line(item.doc_value()))));
1528 if self.shared.sort_modules_alphabetically {
1529 for items in map.values_mut() {
1536 /// Generates a url appropriate for an `href` attribute back to the source of
1539 /// The url generated, when clicked, will redirect the browser back to the
1540 /// original source code.
1542 /// If `None` is returned, then a source link couldn't be generated. This
1543 /// may happen, for example, with externally inlined items where the source
1544 /// of their crate documentation isn't known.
1545 fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1546 let mut root = self.root_path();
1548 let mut path = String::new();
1550 // We can safely ignore synthetic `SourceFile`s.
1551 let file = match item.source.filename {
1552 FileName::Real(ref path) => path.local_path().to_path_buf(),
1557 let (krate, path) = if item.source.cnum == LOCAL_CRATE {
1558 if let Some(path) = self.shared.local_sources.get(file) {
1559 (&self.shared.layout.krate, path)
1564 let (krate, src_root) = match *cache.extern_locations.get(&item.source.cnum)? {
1565 (ref name, ref src, ExternalLocation::Local) => (name, src),
1566 (ref name, ref src, ExternalLocation::Remote(ref s)) => {
1567 root = s.to_string();
1570 (_, _, ExternalLocation::Unknown) => return None,
1573 sources::clean_path(&src_root, file, false, |component| {
1574 path.push_str(&component.to_string_lossy());
1577 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1578 fname.push(".html");
1579 path.push_str(&fname.to_string_lossy());
1583 let lines = if item.source.loline == item.source.hiline {
1584 item.source.loline.to_string()
1586 format!("{}-{}", item.source.loline, item.source.hiline)
1589 "{root}src/{krate}/{path}#{lines}",
1590 root = Escape(&root),
1598 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1600 F: FnOnce(&mut Buffer),
1602 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1607 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1608 debug_assert!(!item.is_stripped());
1609 // Write the breadcrumb trail header for the top
1610 write!(buf, "<h1 class='fqn'><span class='out-of-band'>");
1611 if let Some(version) = item.stable_since() {
1614 "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1620 "<span id='render-detail'>\
1621 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1622 title=\"collapse all docs\">\
1623 [<span class='inner'>−</span>]\
1630 // When this item is part of a `pub use` in a downstream crate, the
1631 // [src] link in the downstream documentation will actually come back to
1632 // this page, and this link will be auto-clicked. The `id` attribute is
1633 // used to find the link to auto-click.
1634 if cx.shared.include_sources && !item.is_primitive() {
1635 if let Some(l) = cx.src_href(item, cache) {
1636 write!(buf, "<a class='srclink' href='{}' title='{}'>[src]</a>", l, "goto source code");
1640 write!(buf, "</span>"); // out-of-band
1641 write!(buf, "<span class='in-band'>");
1642 let name = match item.inner {
1643 clean::ModuleItem(ref m) => {
1650 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1651 clean::TraitItem(..) => "Trait ",
1652 clean::StructItem(..) => "Struct ",
1653 clean::UnionItem(..) => "Union ",
1654 clean::EnumItem(..) => "Enum ",
1655 clean::TypedefItem(..) => "Type Definition ",
1656 clean::MacroItem(..) => "Macro ",
1657 clean::ProcMacroItem(ref mac) => match mac.kind {
1658 MacroKind::Bang => "Macro ",
1659 MacroKind::Attr => "Attribute Macro ",
1660 MacroKind::Derive => "Derive Macro ",
1662 clean::PrimitiveItem(..) => "Primitive Type ",
1663 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1664 clean::ConstantItem(..) => "Constant ",
1665 clean::ForeignTypeItem => "Foreign Type ",
1666 clean::KeywordItem(..) => "Keyword ",
1667 clean::OpaqueTyItem(..) => "Opaque Type ",
1668 clean::TraitAliasItem(..) => "Trait Alias ",
1670 // We don't generate pages for any other type.
1674 buf.write_str(name);
1675 if !item.is_primitive() && !item.is_keyword() {
1676 let cur = &cx.current;
1677 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1678 for (i, component) in cur.iter().enumerate().take(amt) {
1681 "<a href='{}index.html'>{}</a>::<wbr>",
1682 "../".repeat(cur.len() - i - 1),
1687 write!(buf, "<a class=\"{}\" href=''>{}</a>", item.type_(), item.name.as_ref().unwrap());
1689 write!(buf, "</span></h1>"); // in-band
1692 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1693 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1694 item_function(buf, cx, item, f)
1696 clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1697 clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1698 clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1699 clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1700 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1701 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1702 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1703 clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1704 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1705 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1706 clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1707 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1708 clean::OpaqueTyItem(ref e, _) => item_opaque_ty(buf, cx, item, e, cache),
1709 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1711 // We don't generate pages for any other type.
1717 fn item_path(ty: ItemType, name: &str) -> String {
1719 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1720 _ => format!("{}.{}.html", ty, name),
1724 fn full_path(cx: &Context, item: &clean::Item) -> String {
1725 let mut s = cx.current.join("::");
1727 s.push_str(item.name.as_ref().unwrap());
1732 crate fn plain_summary_line(s: Option<&str>) -> String {
1733 let s = s.unwrap_or("");
1734 // This essentially gets the first paragraph of text in one line.
1737 .skip_while(|line| line.chars().all(|c| c.is_whitespace()))
1738 .take_while(|line| line.chars().any(|c| !c.is_whitespace()))
1739 .fold(String::new(), |mut acc, line| {
1744 // remove final whitespace
1746 markdown::plain_summary_line(&line[..])
1749 crate fn shorten(s: String) -> String {
1750 if s.chars().count() > 60 {
1755 // + 1 for the added character after the word.
1756 len += p.chars().count() + 1;
1759 .collect::<Vec<_>>()
1768 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item) {
1769 if let Some(ref name) = item.name {
1770 info!("Documenting {}", name);
1772 document_stability(w, cx, item, false);
1773 document_full(w, item, cx, "", false);
1776 /// Render md_text as markdown.
1781 links: Vec<(String, String)>,
1785 let mut ids = cx.id_map.borrow_mut();
1788 "<div class='docblock{}'>{}{}</div>",
1789 if is_hidden { " hidden" } else { "" },
1797 &cx.shared.playground
1807 link: AssocItemLink<'_>,
1811 if let Some(s) = item.doc_value() {
1812 let markdown = if s.contains('\n') {
1814 "{} [Read more]({})",
1815 &plain_summary_line(Some(s)),
1816 naive_assoc_href(item, link)
1819 plain_summary_line(Some(s))
1821 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden);
1822 } else if !prefix.is_empty() {
1825 "<div class='docblock{}'>{}</div>",
1826 if is_hidden { " hidden" } else { "" },
1832 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1833 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1834 debug!("Doc block: =====\n{}\n=====", s);
1835 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1836 } else if !prefix.is_empty() {
1839 "<div class='docblock{}'>{}</div>",
1840 if is_hidden { " hidden" } else { "" },
1846 fn document_stability(w: &mut Buffer, cx: &Context, item: &clean::Item, is_hidden: bool) {
1847 let stabilities = short_stability(item, cx);
1848 if !stabilities.is_empty() {
1849 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" });
1850 for stability in stabilities {
1851 write!(w, "{}", stability);
1853 write!(w, "</div>");
1857 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1858 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1861 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1862 if item.is_non_exhaustive() {
1863 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
1864 if item.is_struct() {
1866 } else if item.is_enum() {
1868 } else if item.is_variant() {
1875 if item.is_struct() {
1878 "Non-exhaustive structs could have additional fields added in future. \
1879 Therefore, non-exhaustive structs cannot be constructed in external crates \
1880 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1881 matched against without a wildcard <code>..</code>; and \
1882 struct update syntax will not work."
1884 } else if item.is_enum() {
1887 "Non-exhaustive enums could have additional variants added in future. \
1888 Therefore, when matching against variants of non-exhaustive enums, an \
1889 extra wildcard arm must be added to account for any future variants."
1891 } else if item.is_variant() {
1894 "Non-exhaustive enum variants could have additional fields added in future. \
1895 Therefore, non-exhaustive enum variants cannot be constructed in external \
1896 crates and cannot be matched against."
1901 "This type will require a wildcard arm in any match statements or \
1906 write!(w, "</div>");
1910 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1911 pub fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1912 /// Takes a non-numeric and a numeric part from the given &str.
1913 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1914 let i = s.find(|c: char| c.is_ascii_digit());
1915 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1916 let i = b.find(|c: char| !c.is_ascii_digit());
1917 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1922 while !lhs.is_empty() || !rhs.is_empty() {
1923 let (la, lb) = take_parts(&mut lhs);
1924 let (ra, rb) = take_parts(&mut rhs);
1925 // First process the non-numeric part.
1927 Ordering::Equal => (),
1930 // Then process the numeric part, if both sides have one (and they fit in a u64).
1931 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1933 Ordering::Equal => (),
1937 // Then process the numeric part again, but this time as strings.
1939 Ordering::Equal => (),
1947 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
1948 document(w, cx, item);
1950 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1952 // the order of item types in the listing
1953 fn reorder(ty: ItemType) -> u8 {
1955 ItemType::ExternCrate => 0,
1956 ItemType::Import => 1,
1957 ItemType::Primitive => 2,
1958 ItemType::Module => 3,
1959 ItemType::Macro => 4,
1960 ItemType::Struct => 5,
1961 ItemType::Enum => 6,
1962 ItemType::Constant => 7,
1963 ItemType::Static => 8,
1964 ItemType::Trait => 9,
1965 ItemType::Function => 10,
1966 ItemType::Typedef => 12,
1967 ItemType::Union => 13,
1972 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1973 let ty1 = i1.type_();
1974 let ty2 = i2.type_();
1976 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
1978 let s1 = i1.stability.as_ref().map(|s| s.level);
1979 let s2 = i2.stability.as_ref().map(|s| s.level);
1981 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1982 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1985 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1986 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1987 compare_names(lhs, rhs)
1990 if cx.shared.sort_modules_alphabetically {
1991 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1993 // This call is to remove re-export duplicates in cases such as:
1998 // pub trait Double { fn foo(); }
2002 // pub use foo::bar::*;
2006 // `Double` will appear twice in the generated docs.
2008 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2009 // can be identical even if the elements are different (mostly in imports).
2010 // So in case this is an import, we keep everything by adding a "unique id"
2011 // (which is the position in the vector).
2012 indices.dedup_by_key(|i| {
2015 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2017 if items[*i].is_import() { *i } else { 0 },
2021 debug!("{:?}", indices);
2022 let mut curty = None;
2023 for &idx in &indices {
2024 let myitem = &items[idx];
2025 if myitem.is_stripped() {
2029 let myty = Some(myitem.type_());
2030 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2031 // Put `extern crate` and `use` re-exports in the same section.
2033 } else if myty != curty {
2034 if curty.is_some() {
2035 write!(w, "</table>");
2038 let (short, name) = item_ty_to_strs(&myty.unwrap());
2041 "<h2 id='{id}' class='section-header'>\
2042 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2043 id = cx.derive_id(short.to_owned()),
2048 match myitem.inner {
2049 clean::ExternCrateItem(ref name, ref src) => {
2050 use crate::html::format::anchor;
2053 Some(ref src) => write!(
2055 "<tr><td><code>{}extern crate {} as {};",
2056 myitem.visibility.print_with_space(),
2057 anchor(myitem.def_id, src),
2062 "<tr><td><code>{}extern crate {};",
2063 myitem.visibility.print_with_space(),
2064 anchor(myitem.def_id, name)
2067 write!(w, "</code></td></tr>");
2070 clean::ImportItem(ref import) => {
2073 "<tr><td><code>{}{}</code></td></tr>",
2074 myitem.visibility.print_with_space(),
2080 if myitem.name.is_none() {
2084 let unsafety_flag = match myitem.inner {
2085 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2086 if func.header.unsafety == hir::Unsafety::Unsafe =>
2088 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2093 let stab = myitem.stability_class();
2094 let add = if stab.is_some() { " " } else { "" };
2096 let doc_value = myitem.doc_value().unwrap_or("");
2100 <tr class='{stab}{add}module-item'>\
2101 <td><a class=\"{class}\" href=\"{href}\" \
2102 title='{title}'>{name}</a>{unsafety_flag}</td>\
2103 <td class='docblock-short'>{stab_tags}{docs}</td>\
2105 name = *myitem.name.as_ref().unwrap(),
2106 stab_tags = stability_tags(myitem),
2107 docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2108 class = myitem.type_(),
2110 stab = stab.unwrap_or_else(String::new),
2111 unsafety_flag = unsafety_flag,
2112 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2113 title = [full_path(cx, myitem), myitem.type_().to_string()]
2115 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2116 .collect::<Vec<_>>()
2123 if curty.is_some() {
2124 write!(w, "</table>");
2128 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2130 fn stability_tags(item: &clean::Item) -> String {
2131 let mut tags = String::new();
2133 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2134 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2137 // The trailing space after each tag is to space it properly against the rest of the docs.
2138 if let Some(depr) = &item.deprecation {
2139 let mut message = "Deprecated";
2140 if !stability::deprecation_in_effect(depr.is_since_rustc_version, depr.since.as_deref()) {
2141 message = "Deprecation planned";
2143 tags += &tag_html("deprecated", "", message);
2146 // The "rustc_private" crates are permanently unstable so it makes no sense
2147 // to render "unstable" everywhere.
2151 .map(|s| s.level == stability::Unstable && s.feature != "rustc_private")
2154 tags += &tag_html("unstable", "", "Experimental");
2157 if let Some(ref cfg) = item.attrs.cfg {
2158 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2164 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2166 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2167 let mut stability = vec![];
2168 let error_codes = cx.shared.codes;
2170 if let Some(Deprecation { ref note, ref since, is_since_rustc_version }) = item.deprecation {
2171 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2172 // but only display the future-deprecation messages for #[rustc_deprecated].
2173 let mut message = if let Some(since) = since {
2174 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2175 format!("Deprecating in {}", Escape(&since))
2177 format!("Deprecated since {}", Escape(&since))
2180 String::from("Deprecated")
2183 if let Some(note) = note {
2184 let mut ids = cx.id_map.borrow_mut();
2185 let html = MarkdownHtml(
2190 &cx.shared.playground,
2192 message.push_str(&format!(": {}", html.into_string()));
2194 stability.push(format!(
2195 "<div class='stab deprecated'><span class='emoji'>👎</span> {}</div>",
2200 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2201 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2202 if let Some(stab) = item
2205 .filter(|stab| stab.level == stability::Unstable && stab.feature != "rustc_private")
2208 "<span class='emoji'>🔬</span> This is a nightly-only experimental API.".to_owned();
2210 let mut feature = format!("<code>{}</code>", Escape(&stab.feature));
2211 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2212 feature.push_str(&format!(
2213 " <a href=\"{url}{issue}\">#{issue}</a>",
2219 message.push_str(&format!(" ({})", feature));
2221 if let Some(unstable_reason) = &stab.unstable_reason {
2222 let mut ids = cx.id_map.borrow_mut();
2224 "<details><summary>{}</summary>{}</details>",
2231 &cx.shared.playground,
2237 stability.push(format!("<div class='stab unstable'>{}</div>", message));
2240 if let Some(ref cfg) = item.attrs.cfg {
2241 stability.push(format!("<div class='stab portability'>{}</div>", cfg.render_long_html()));
2247 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2248 write!(w, "<pre class='rust const'>");
2249 render_attributes(w, it, false);
2255 vis = it.visibility.print_with_space(),
2256 name = it.name.as_ref().unwrap(),
2257 typ = c.type_.print(),
2260 if c.value.is_some() || c.is_literal {
2261 write!(w, " = {expr};", expr = Escape(&c.expr));
2266 if let Some(value) = &c.value {
2268 let value_lowercase = value.to_lowercase();
2269 let expr_lowercase = c.expr.to_lowercase();
2271 if value_lowercase != expr_lowercase
2272 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2274 write!(w, " // {value}", value = Escape(value));
2279 write!(w, "</pre>");
2283 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2284 write!(w, "<pre class='rust static'>");
2285 render_attributes(w, it, false);
2288 "{vis}static {mutability}\
2289 {name}: {typ}</pre>",
2290 vis = it.visibility.print_with_space(),
2291 mutability = s.mutability.print_with_space(),
2292 name = it.name.as_ref().unwrap(),
2293 typ = s.type_.print()
2298 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2299 let header_len = format!(
2300 "{}{}{}{}{:#}fn {}{:#}",
2301 it.visibility.print_with_space(),
2302 f.header.constness.print_with_space(),
2303 f.header.asyncness.print_with_space(),
2304 f.header.unsafety.print_with_space(),
2305 print_abi_with_space(f.header.abi),
2306 it.name.as_ref().unwrap(),
2310 write!(w, "<pre class='rust fn'>");
2311 render_attributes(w, it, false);
2314 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2315 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2316 vis = it.visibility.print_with_space(),
2317 constness = f.header.constness.print_with_space(),
2318 asyncness = f.header.asyncness.print_with_space(),
2319 unsafety = f.header.unsafety.print_with_space(),
2320 abi = print_abi_with_space(f.header.abi),
2321 name = it.name.as_ref().unwrap(),
2322 generics = f.generics.print(),
2323 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2324 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2326 spotlight = spotlight_decl(&f.decl),
2331 fn render_implementor(
2335 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2339 // If there's already another implementor that has the same abbridged name, use the
2340 // full path, for example in `std::iter::ExactSizeIterator`
2341 let use_absolute = match implementor.inner_impl().for_ {
2342 clean::ResolvedPath { ref path, is_generic: false, .. }
2343 | clean::BorrowedRef {
2344 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2346 } => implementor_dups[path.last_name()].1,
2353 AssocItemLink::Anchor(None),
2355 implementor.impl_item.stable_since(),
2369 containing_item: &clean::Item,
2372 let mut impls = traits
2375 let did = i.trait_did().unwrap();
2376 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2377 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2384 containing_item.stable_since(),
2394 .collect::<Vec<_>>();
2396 w.write_str(&impls.join(""));
2399 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2400 let mut bounds = String::new();
2401 if !t_bounds.is_empty() {
2403 bounds.push_str(": ");
2405 for (i, p) in t_bounds.iter().enumerate() {
2407 bounds.push_str(" + ");
2409 bounds.push_str(&p.print().to_string());
2415 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2416 let lhs = format!("{}", lhs.inner_impl().print());
2417 let rhs = format!("{}", rhs.inner_impl().print());
2419 // lhs and rhs are formatted as HTML, which may be unnecessary
2420 compare_names(&lhs, &rhs)
2423 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2424 let bounds = bounds(&t.bounds, false);
2425 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2426 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2427 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2428 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2430 // Output the trait definition
2431 wrap_into_docblock(w, |w| {
2432 write!(w, "<pre class='rust trait'>");
2433 render_attributes(w, it, true);
2436 "{}{}{}trait {}{}{}",
2437 it.visibility.print_with_space(),
2438 t.unsafety.print_with_space(),
2439 if t.is_auto { "auto " } else { "" },
2440 it.name.as_ref().unwrap(),
2445 if !t.generics.where_predicates.is_empty() {
2446 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2451 if t.items.is_empty() {
2454 // FIXME: we should be using a derived_id for the Anchors here
2457 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2460 if !types.is_empty() && !consts.is_empty() {
2464 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2467 if !consts.is_empty() && !required.is_empty() {
2470 for (pos, m) in required.iter().enumerate() {
2471 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2474 if pos < required.len() - 1 {
2475 write!(w, "<div class='item-spacer'></div>");
2478 if !required.is_empty() && !provided.is_empty() {
2481 for (pos, m) in provided.iter().enumerate() {
2482 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2484 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2485 write!(w, ",\n {{ ... }}\n");
2488 write!(w, " {{ ... }}\n");
2491 if pos < provided.len() - 1 {
2492 write!(w, "<div class='item-spacer'></div>");
2500 // Trait documentation
2501 document(w, cx, it);
2503 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2507 <h2 id='{0}' class='small-section-header'>\
2508 {1}<a href='#{0}' class='anchor'></a>\
2510 id, title, extra_content
2514 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2515 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
2518 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item) {
2519 let name = m.name.as_ref().unwrap();
2520 let item_type = m.type_();
2521 let id = cx.derive_id(format!("{}.{}", item_type, name));
2522 write!(w, "<h3 id='{id}' class='method'><code>", id = id,);
2523 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2524 write!(w, "</code>");
2525 render_stability_since(w, m, t);
2530 if !types.is_empty() {
2531 write_small_section_header(
2535 "<div class='methods'>",
2538 trait_item(w, cx, *t, it);
2540 write_loading_content(w, "</div>");
2543 if !consts.is_empty() {
2544 write_small_section_header(
2547 "Associated Constants",
2548 "<div class='methods'>",
2551 trait_item(w, cx, *t, it);
2553 write_loading_content(w, "</div>");
2556 // Output the documentation for each function individually
2557 if !required.is_empty() {
2558 write_small_section_header(
2562 "<div class='methods'>",
2564 for m in &required {
2565 trait_item(w, cx, *m, it);
2567 write_loading_content(w, "</div>");
2569 if !provided.is_empty() {
2570 write_small_section_header(
2574 "<div class='methods'>",
2576 for m in &provided {
2577 trait_item(w, cx, *m, it);
2579 write_loading_content(w, "</div>");
2582 // If there are methods directly on this trait object, render them here.
2583 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2585 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2586 // The DefId is for the first Type found with that name. The bool is
2587 // if any Types with the same name but different DefId have been found.
2588 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2589 for implementor in implementors {
2590 match implementor.inner_impl().for_ {
2591 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2592 | clean::BorrowedRef {
2593 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2596 let &mut (prev_did, ref mut has_duplicates) =
2597 implementor_dups.entry(path.last_name()).or_insert((did, false));
2598 if prev_did != did {
2599 *has_duplicates = true;
2606 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2607 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2610 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2611 local.iter().partition(|i| i.inner_impl().synthetic);
2613 synthetic.sort_by(compare_impl);
2614 concrete.sort_by(compare_impl);
2616 if !foreign.is_empty() {
2617 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2619 for implementor in foreign {
2620 let assoc_link = AssocItemLink::GotoSource(
2621 implementor.impl_item.def_id,
2622 &implementor.inner_impl().provided_trait_methods,
2630 implementor.impl_item.stable_since(),
2639 write_loading_content(w, "");
2642 write_small_section_header(
2646 "<div class='item-list' id='implementors-list'>",
2648 for implementor in concrete {
2649 render_implementor(cx, implementor, w, &implementor_dups, &[], cache);
2651 write_loading_content(w, "</div>");
2654 write_small_section_header(
2656 "synthetic-implementors",
2657 "Auto implementors",
2658 "<div class='item-list' id='synthetic-implementors-list'>",
2660 for implementor in synthetic {
2666 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2670 write_loading_content(w, "</div>");
2673 // even without any implementations to write in, we still want the heading and list, so the
2674 // implementors javascript file pulled in below has somewhere to write the impls into
2675 write_small_section_header(
2679 "<div class='item-list' id='implementors-list'>",
2681 write_loading_content(w, "</div>");
2684 write_small_section_header(
2686 "synthetic-implementors",
2687 "Auto implementors",
2688 "<div class='item-list' id='synthetic-implementors-list'>",
2690 write_loading_content(w, "</div>");
2696 "<script type=\"text/javascript\" \
2697 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2699 root_path = vec![".."; cx.current.len()].join("/"),
2700 path = if it.def_id.is_local() {
2701 cx.current.join("/")
2703 let (ref path, _) = cache.external_paths[&it.def_id];
2704 path[..path.len() - 1].join("/")
2707 name = *it.name.as_ref().unwrap()
2711 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2712 use crate::formats::item_type::ItemType::*;
2714 let name = it.name.as_ref().unwrap();
2715 let ty = match it.type_() {
2716 Typedef | AssocType => AssocType,
2720 let anchor = format!("#{}.{}", ty, name);
2722 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2723 AssocItemLink::Anchor(None) => anchor,
2724 AssocItemLink::GotoSource(did, _) => {
2725 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2734 _default: Option<&String>,
2735 link: AssocItemLink<'_>,
2740 "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2742 it.visibility.print_with_space(),
2743 naive_assoc_href(it, link),
2744 it.name.as_ref().unwrap(),
2752 bounds: &[clean::GenericBound],
2753 default: Option<&clean::Type>,
2754 link: AssocItemLink<'_>,
2759 "{}type <a href='{}' class=\"type\">{}</a>",
2761 naive_assoc_href(it, link),
2762 it.name.as_ref().unwrap()
2764 if !bounds.is_empty() {
2765 write!(w, ": {}", print_generic_bounds(bounds))
2767 if let Some(default) = default {
2768 write!(w, " = {}", default.print())
2772 fn render_stability_since_raw(w: &mut Buffer, ver: Option<&str>, containing_ver: Option<&str>) {
2773 if let Some(v) = ver {
2774 if containing_ver != ver && !v.is_empty() {
2775 write!(w, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", v)
2780 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2781 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2784 fn render_assoc_item(
2787 link: AssocItemLink<'_>,
2793 header: hir::FnHeader,
2794 g: &clean::Generics,
2796 link: AssocItemLink<'_>,
2799 let name = meth.name.as_ref().unwrap();
2800 let anchor = format!("#{}.{}", meth.type_(), name);
2801 let href = match link {
2802 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2803 AssocItemLink::Anchor(None) => anchor,
2804 AssocItemLink::GotoSource(did, provided_methods) => {
2805 // We're creating a link from an impl-item to the corresponding
2806 // trait-item and need to map the anchored type accordingly.
2807 let ty = if provided_methods.contains(name) {
2813 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2816 let mut header_len = format!(
2817 "{}{}{}{}{}{:#}fn {}{:#}",
2818 meth.visibility.print_with_space(),
2819 header.constness.print_with_space(),
2820 header.asyncness.print_with_space(),
2821 header.unsafety.print_with_space(),
2822 print_default_space(meth.is_default()),
2823 print_abi_with_space(header.abi),
2828 let (indent, end_newline) = if parent == ItemType::Trait {
2834 render_attributes(w, meth, false);
2837 "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2838 {generics}{decl}{spotlight}{where_clause}",
2839 if parent == ItemType::Trait { " " } else { "" },
2840 meth.visibility.print_with_space(),
2841 header.constness.print_with_space(),
2842 header.asyncness.print_with_space(),
2843 header.unsafety.print_with_space(),
2844 print_default_space(meth.is_default()),
2845 print_abi_with_space(header.abi),
2848 generics = g.print(),
2849 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
2850 spotlight = spotlight_decl(&d),
2851 where_clause = WhereClause { gens: g, indent, end_newline }
2855 clean::StrippedItem(..) => {}
2856 clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2857 clean::MethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2858 clean::AssocConstItem(ref ty, ref default) => assoc_const(
2864 if parent == ItemType::Trait { " " } else { "" },
2866 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
2872 if parent == ItemType::Trait { " " } else { "" },
2874 _ => panic!("render_assoc_item called on non-associated-item"),
2878 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
2879 wrap_into_docblock(w, |w| {
2880 write!(w, "<pre class='rust struct'>");
2881 render_attributes(w, it, true);
2882 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
2886 document(w, cx, it);
2890 .filter_map(|f| match f.inner {
2891 clean::StructFieldItem(ref ty) => Some((f, ty)),
2895 if let doctree::Plain = s.struct_type {
2896 if fields.peek().is_some() {
2899 "<h2 id='fields' class='fields small-section-header'>
2900 Fields{}<a href='#fields' class='anchor'></a></h2>",
2901 document_non_exhaustive_header(it)
2903 document_non_exhaustive(w, it);
2904 for (field, ty) in fields {
2905 let id = cx.derive_id(format!(
2907 ItemType::StructField,
2908 field.name.as_ref().unwrap()
2912 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
2913 <a href=\"#{id}\" class=\"anchor field\"></a>\
2914 <code>{name}: {ty}</code>\
2916 item_type = ItemType::StructField,
2918 name = field.name.as_ref().unwrap(),
2921 document(w, cx, field);
2925 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
2928 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
2929 wrap_into_docblock(w, |w| {
2930 write!(w, "<pre class='rust union'>");
2931 render_attributes(w, it, true);
2932 render_union(w, it, Some(&s.generics), &s.fields, "", true);
2936 document(w, cx, it);
2940 .filter_map(|f| match f.inner {
2941 clean::StructFieldItem(ref ty) => Some((f, ty)),
2945 if fields.peek().is_some() {
2948 "<h2 id='fields' class='fields small-section-header'>
2949 Fields<a href='#fields' class='anchor'></a></h2>"
2951 for (field, ty) in fields {
2952 let name = field.name.as_ref().expect("union field name");
2953 let id = format!("{}.{}", ItemType::StructField, name);
2956 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
2957 <a href=\"#{id}\" class=\"anchor field\"></a>\
2958 <code>{name}: {ty}</code>\
2962 shortty = ItemType::StructField,
2965 if let Some(stability_class) = field.stability_class() {
2966 write!(w, "<span class='stab {stab}'></span>", stab = stability_class);
2968 document(w, cx, field);
2971 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
2974 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
2975 wrap_into_docblock(w, |w| {
2976 write!(w, "<pre class='rust enum'>");
2977 render_attributes(w, it, true);
2981 it.visibility.print_with_space(),
2982 it.name.as_ref().unwrap(),
2984 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
2986 if e.variants.is_empty() && !e.variants_stripped {
2990 for v in &e.variants {
2992 let name = v.name.as_ref().unwrap();
2994 clean::VariantItem(ref var) => match var.kind {
2995 clean::VariantKind::CLike => write!(w, "{}", name),
2996 clean::VariantKind::Tuple(ref tys) => {
2997 write!(w, "{}(", name);
2998 for (i, ty) in tys.iter().enumerate() {
3000 write!(w, ", ")
3002 write!(w, "{}", ty.print());
3006 clean::VariantKind::Struct(ref s) => {
3007 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
3010 _ => unreachable!(),
3015 if e.variants_stripped {
3016 write!(w, " // some variants omitted\n");
3023 document(w, cx, it);
3024 if !e.variants.is_empty() {
3027 "<h2 id='variants' class='variants small-section-header'>
3028 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3029 document_non_exhaustive_header(it)
3031 document_non_exhaustive(w, it);
3032 for variant in &e.variants {
3034 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3037 "<div id=\"{id}\" class=\"variant small-section-header\">\
3038 <a href=\"#{id}\" class=\"anchor field\"></a>\
3041 name = variant.name.as_ref().unwrap()
3043 if let clean::VariantItem(ref var) = variant.inner {
3044 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3046 for (i, ty) in tys.iter().enumerate() {
3048 write!(w, ", ");
3050 write!(w, "{}", ty.print());
3055 write!(w, "</code></div>");
3056 document(w, cx, variant);
3057 document_non_exhaustive(w, variant);
3059 use crate::clean::{Variant, VariantKind};
3060 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.inner
3062 let variant_id = cx.derive_id(format!(
3065 variant.name.as_ref().unwrap()
3067 write!(w, "<div class='autohide sub-variant' id='{id}'>", id = variant_id);
3070 "<h3>Fields of <b>{name}</b></h3><div>",
3071 name = variant.name.as_ref().unwrap()
3073 for field in &s.fields {
3074 use crate::clean::StructFieldItem;
3075 if let StructFieldItem(ref ty) = field.inner {
3076 let id = cx.derive_id(format!(
3077 "variant.{}.field.{}",
3078 variant.name.as_ref().unwrap(),
3079 field.name.as_ref().unwrap()
3083 "<span id=\"{id}\" class=\"variant small-section-header\">\
3084 <a href=\"#{id}\" class=\"anchor field\"></a>\
3085 <code>{f}: {t}\
3088 f = field.name.as_ref().unwrap(),
3091 document(w, cx, field);
3094 write!(w, "</div></div>");
3096 render_stability_since(w, variant, it);
3099 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3102 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3109 sym::non_exhaustive,
3112 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3113 // left padding. For example:
3115 // #[foo] <----- "top" attribute
3117 // #[bar] <---- not "top" attribute
3120 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3125 .filter_map(|attr| {
3126 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3127 Some(pprust::attribute_to_string(&attr))
3134 if !attrs.is_empty() {
3137 "<span class=\"docblock attributes{}\">{}</span>",
3138 if top { " top-attr" } else { "" },
3147 g: Option<&clean::Generics>,
3148 ty: doctree::StructType,
3149 fields: &[clean::Item],
3156 it.visibility.print_with_space(),
3157 if structhead { "struct " } else { "" },
3158 it.name.as_ref().unwrap()
3160 if let Some(g) = g {
3161 write!(w, "{}", g.print())
3165 if let Some(g) = g {
3166 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3168 let mut has_visible_fields = false;
3170 for field in fields {
3171 if let clean::StructFieldItem(ref ty) = field.inner {
3176 field.visibility.print_with_space(),
3177 field.name.as_ref().unwrap(),
3180 has_visible_fields = true;
3184 if has_visible_fields {
3185 if it.has_stripped_fields().unwrap() {
3186 write!(w, "\n{} // some fields omitted", tab);
3188 write!(w, "\n{}", tab);
3189 } else if it.has_stripped_fields().unwrap() {
3190 // If there are no visible fields we can just display
3191 // `{ /* fields omitted */ }` to save space.
3192 write!(w, " /* fields omitted */ ");
3198 for (i, field) in fields.iter().enumerate() {
3203 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3204 clean::StructFieldItem(ref ty) => {
3205 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3207 _ => unreachable!(),
3211 if let Some(g) = g {
3212 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3217 // Needed for PhantomData.
3218 if let Some(g) = g {
3219 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3229 g: Option<&clean::Generics>,
3230 fields: &[clean::Item],
3237 it.visibility.print_with_space(),
3238 if structhead { "union " } else { "" },
3239 it.name.as_ref().unwrap()
3241 if let Some(g) = g {
3242 write!(w, "{}", g.print());
3243 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3246 write!(w, " {{\n{}", tab);
3247 for field in fields {
3248 if let clean::StructFieldItem(ref ty) = field.inner {
3252 field.visibility.print_with_space(),
3253 field.name.as_ref().unwrap(),
3260 if it.has_stripped_fields().unwrap() {
3261 write!(w, " // some fields omitted\n{}", tab);
3266 #[derive(Copy, Clone)]
3267 enum AssocItemLink<'a> {
3268 Anchor(Option<&'a str>),
3269 GotoSource(DefId, &'a FxHashSet<String>),
3272 impl<'a> AssocItemLink<'a> {
3273 fn anchor(&self, id: &'a String) -> Self {
3275 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3276 ref other => *other,
3281 fn render_assoc_items(
3284 containing_item: &clean::Item,
3286 what: AssocItemRender<'_>,
3289 let v = match cache.impls.get(&it) {
3293 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3294 if !non_trait.is_empty() {
3295 let render_mode = match what {
3296 AssocItemRender::All => {
3300 <h2 id='implementations' class='small-section-header'>\
3301 Implementations<a href='#implementations' class='anchor'></a>\
3307 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3311 <h2 id='deref-methods' class='small-section-header'>\
3312 Methods from {}<Target = {}>\
3313 <a href='#deref-methods' class='anchor'></a>\
3319 RenderMode::ForDeref { mut_: deref_mut_ }
3322 for i in &non_trait {
3327 AssocItemLink::Anchor(None),
3329 containing_item.stable_since(),
3339 if let AssocItemRender::DerefFor { .. } = what {
3342 if !traits.is_empty() {
3344 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3345 if let Some(impl_) = deref_impl {
3347 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3348 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3351 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3352 traits.iter().partition(|t| t.inner_impl().synthetic);
3353 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3354 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3356 let mut impls = Buffer::empty_from(&w);
3357 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3358 let impls = impls.into_inner();
3359 if !impls.is_empty() {
3363 <h2 id='trait-implementations' class='small-section-header'>\
3364 Trait Implementations<a href='#trait-implementations' class='anchor'></a>\
3366 <div id='trait-implementations-list'>{}</div>",
3371 if !synthetic.is_empty() {
3375 <h2 id='synthetic-implementations' class='small-section-header'>\
3376 Auto Trait Implementations\
3377 <a href='#synthetic-implementations' class='anchor'></a>\
3379 <div id='synthetic-implementations-list'>\
3382 render_impls(cx, w, &synthetic, containing_item, cache);
3383 write!(w, "</div>");
3386 if !blanket_impl.is_empty() {
3390 <h2 id='blanket-implementations' class='small-section-header'>\
3391 Blanket Implementations\
3392 <a href='#blanket-implementations' class='anchor'></a>\
3394 <div id='blanket-implementations-list'>\
3397 render_impls(cx, w, &blanket_impl, containing_item, cache);
3398 write!(w, "</div>");
3403 fn render_deref_methods(
3407 container_item: &clean::Item,
3411 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3412 let (target, real_target) = impl_
3416 .find_map(|item| match item.inner {
3417 clean::TypedefItem(ref t, true) => Some(match *t {
3418 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3419 _ => (&t.type_, &t.type_),
3423 .expect("Expected associated type binding");
3425 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3426 if let Some(did) = target.def_id() {
3427 render_assoc_items(w, cx, container_item, did, what, cache);
3429 if let Some(prim) = target.primitive_type() {
3430 if let Some(&did) = cache.primitive_locations.get(&prim) {
3431 render_assoc_items(w, cx, container_item, did, what, cache);
3437 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3438 let self_type_opt = match item.inner {
3439 clean::MethodItem(ref method) => method.decl.self_type(),
3440 clean::TyMethodItem(ref method) => method.decl.self_type(),
3444 if let Some(self_ty) = self_type_opt {
3445 let (by_mut_ref, by_box, by_value) = match self_ty {
3446 SelfTy::SelfBorrowed(_, mutability)
3447 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3448 (mutability == Mutability::Mut, false, false)
3450 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3451 (false, Some(did) == cache().owned_box_did, false)
3453 SelfTy::SelfValue => (false, false, true),
3454 _ => (false, false, false),
3457 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3463 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3464 let mut out = Buffer::html();
3465 let mut trait_ = String::new();
3467 if let Some(did) = decl.output.def_id() {
3469 if let Some(impls) = c.impls.get(&did) {
3471 let impl_ = i.inner_impl();
3472 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3474 out.push_str(&format!(
3475 "<h3 class=\"notable\">Notable traits for {}</h3>\
3476 <code class=\"content\">",
3479 trait_.push_str(&impl_.for_.print().to_string());
3482 //use the "where" class here to make it small
3483 out.push_str(&format!(
3484 "<span class=\"where fmt-newline\">{}</span>",
3487 let t_did = impl_.trait_.def_id().unwrap();
3488 for it in &impl_.items {
3489 if let clean::TypedefItem(ref tydef, _) = it.inner {
3490 out.push_str("<span class=\"where fmt-newline\"> ");
3496 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3499 out.push_str(";</span>");
3507 if !out.is_empty() {
3510 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ<div class='notable-traits-tooltiptext'><span class=\"docblock\">"
3513 out.push_str("</code></span></div></span></span>");
3523 link: AssocItemLink<'_>,
3524 render_mode: RenderMode,
3525 outer_version: Option<&str>,
3526 show_def_docs: bool,
3527 use_absolute: Option<bool>,
3528 is_on_foreign_type: bool,
3529 show_default_items: bool,
3530 // This argument is used to reference same type with different paths to avoid duplication
3531 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3535 if render_mode == RenderMode::Normal {
3536 let id = cx.derive_id(match i.inner_impl().trait_ {
3538 if is_on_foreign_type {
3539 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3541 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3544 None => "impl".to_string(),
3546 let aliases = if aliases.is_empty() {
3549 format!(" aliases=\"{}\"", aliases.join(","))
3551 if let Some(use_absolute) = use_absolute {
3552 write!(w, "<h3 id='{}' class='impl'{}><code class='in-band'>", id, aliases);
3553 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3555 for it in &i.inner_impl().items {
3556 if let clean::TypedefItem(ref tydef, _) = it.inner {
3557 write!(w, "<span class=\"where fmt-newline\"> ");
3558 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3559 write!(w, ";</span>");
3563 write!(w, "</code>");
3567 "<h3 id='{}' class='impl'{}><code class='in-band'>{}</code>",
3570 i.inner_impl().print()
3573 write!(w, "<a href='#{}' class='anchor'></a>", id);
3574 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3575 render_stability_since_raw(w, since, outer_version);
3576 if let Some(l) = cx.src_href(&i.impl_item, cache) {
3577 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>", l, "goto source code");
3580 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3581 let mut ids = cx.id_map.borrow_mut();
3584 "<div class='docblock'>{}</div>",
3587 &i.impl_item.links(),
3591 &cx.shared.playground
3602 link: AssocItemLink<'_>,
3603 render_mode: RenderMode,
3604 is_default_item: bool,
3605 outer_version: Option<&str>,
3606 trait_: Option<&clean::Trait>,
3607 show_def_docs: bool,
3610 let item_type = item.type_();
3611 let name = item.name.as_ref().unwrap();
3613 let render_method_item = match render_mode {
3614 RenderMode::Normal => true,
3615 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3618 let (is_hidden, extra_class) =
3619 if (trait_.is_none() || item.doc_value().is_some() || item.inner.is_type_alias())
3627 clean::MethodItem(clean::Method { .. })
3628 | clean::TyMethodItem(clean::TyMethod { .. }) => {
3629 // Only render when the method is not static or we allow static methods
3630 if render_method_item {
3631 let id = cx.derive_id(format!("{}.{}", item_type, name));
3632 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3633 write!(w, "<code>");
3634 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3635 write!(w, "</code>");
3636 render_stability_since_raw(w, item.stable_since(), outer_version);
3637 if let Some(l) = cx.src_href(item, cache) {
3640 "<a class='srclink' href='{}' title='{}'>[src]</a>",
3641 l, "goto source code"
3647 clean::TypedefItem(ref tydef, _) => {
3648 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3649 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3650 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3651 write!(w, "</code></h4>");
3653 clean::AssocConstItem(ref ty, ref default) => {
3654 let id = cx.derive_id(format!("{}.{}", item_type, name));
3655 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3656 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3657 write!(w, "</code>");
3658 render_stability_since_raw(w, item.stable_since(), outer_version);
3659 if let Some(l) = cx.src_href(item, cache) {
3662 "<a class='srclink' href='{}' title='{}'>[src]</a>",
3663 l, "goto source code"
3668 clean::AssocTypeItem(ref bounds, ref default) => {
3669 let id = cx.derive_id(format!("{}.{}", item_type, name));
3670 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3671 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3672 write!(w, "</code></h4>");
3674 clean::StrippedItem(..) => return,
3675 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3678 if render_method_item {
3679 if !is_default_item {
3680 if let Some(t) = trait_ {
3681 // The trait item may have been stripped so we might not
3682 // find any documentation or stability for it.
3683 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3684 // We need the stability of the item from the trait
3685 // because impls can't have a stability.
3686 document_stability(w, cx, it, is_hidden);
3687 if item.doc_value().is_some() {
3688 document_full(w, item, cx, "", is_hidden);
3689 } else if show_def_docs {
3690 // In case the item isn't documented,
3691 // provide short documentation from the trait.
3692 document_short(w, cx, it, link, "", is_hidden);
3696 document_stability(w, cx, item, is_hidden);
3698 document_full(w, item, cx, "", is_hidden);
3702 document_stability(w, cx, item, is_hidden);
3704 document_short(w, cx, item, link, "", is_hidden);
3710 let traits = &cache.traits;
3711 let trait_ = i.trait_did().map(|did| &traits[&did]);
3713 write!(w, "<div class='impl-items'>");
3714 for trait_item in &i.inner_impl().items {
3729 fn render_default_items(
3734 render_mode: RenderMode,
3735 outer_version: Option<&str>,
3736 show_def_docs: bool,
3739 for trait_item in &t.items {
3740 let n = trait_item.name.clone();
3741 if i.items.iter().any(|m| m.name == n) {
3744 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3745 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3762 // If we've implemented a trait, then also emit documentation for all
3763 // default items which weren't overridden in the implementation block.
3764 // We don't emit documentation for default items if they appear in the
3765 // Implementations on Foreign Types or Implementors sections.
3766 if show_default_items {
3767 if let Some(t) = trait_ {
3768 render_default_items(
3780 write!(w, "</div>");
3787 t: &clean::OpaqueTy,
3790 write!(w, "<pre class='rust opaque'>");
3791 render_attributes(w, it, false);
3794 "type {}{}{where_clause} = impl {bounds};</pre>",
3795 it.name.as_ref().unwrap(),
3797 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3798 bounds = bounds(&t.bounds, false)
3801 document(w, cx, it);
3803 // Render any items associated directly to this alias, as otherwise they
3804 // won't be visible anywhere in the docs. It would be nice to also show
3805 // associated items from the aliased type (see discussion in #32077), but
3806 // we need #14072 to make sense of the generics.
3807 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3810 fn item_trait_alias(
3814 t: &clean::TraitAlias,
3817 write!(w, "<pre class='rust trait-alias'>");
3818 render_attributes(w, it, false);
3821 "trait {}{}{} = {};</pre>",
3822 it.name.as_ref().unwrap(),
3824 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3825 bounds(&t.bounds, true)
3828 document(w, cx, it);
3830 // Render any items associated directly to this alias, as otherwise they
3831 // won't be visible anywhere in the docs. It would be nice to also show
3832 // associated items from the aliased type (see discussion in #32077), but
3833 // we need #14072 to make sense of the generics.
3834 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3837 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
3838 write!(w, "<pre class='rust typedef'>");
3839 render_attributes(w, it, false);
3842 "type {}{}{where_clause} = {type_};</pre>",
3843 it.name.as_ref().unwrap(),
3845 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3846 type_ = t.type_.print()
3849 document(w, cx, it);
3851 // Render any items associated directly to this alias, as otherwise they
3852 // won't be visible anywhere in the docs. It would be nice to also show
3853 // associated items from the aliased type (see discussion in #32077), but
3854 // we need #14072 to make sense of the generics.
3855 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3858 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
3859 writeln!(w, "<pre class='rust foreigntype'>extern {{");
3860 render_attributes(w, it, false);
3863 " {}type {};\n}}</pre>",
3864 it.visibility.print_with_space(),
3865 it.name.as_ref().unwrap(),
3868 document(w, cx, it);
3870 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3873 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
3874 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
3878 || it.is_primitive()
3886 "<p class='location'>{}{}</p>",
3888 clean::StructItem(..) => "Struct ",
3889 clean::TraitItem(..) => "Trait ",
3890 clean::PrimitiveItem(..) => "Primitive Type ",
3891 clean::UnionItem(..) => "Union ",
3892 clean::EnumItem(..) => "Enum ",
3893 clean::TypedefItem(..) => "Type Definition ",
3894 clean::ForeignTypeItem => "Foreign Type ",
3895 clean::ModuleItem(..) =>
3903 it.name.as_ref().unwrap()
3908 if let Some(ref version) = cache.crate_version {
3911 "<div class='block version'>\
3919 write!(buffer, "<div class=\"sidebar-elems\">");
3923 "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3924 it.name.as_ref().expect("crates always have a name")
3928 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
3929 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
3930 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
3931 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
3932 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
3933 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
3934 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
3935 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
3939 // The sidebar is designed to display sibling functions, modules and
3940 // other miscellaneous information. since there are lots of sibling
3941 // items (and that causes quadratic growth in large modules),
3942 // we refactor common parts into a shared JavaScript file per module.
3943 // still, we don't move everything into JS because we want to preserve
3944 // as much HTML as possible in order to allow non-JS-enabled browsers
3945 // to navigate the documentation (though slightly inefficiently).
3947 write!(buffer, "<p class='location'>");
3948 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3950 write!(buffer, "::<wbr>");
3954 "<a href='{}index.html'>{}</a>",
3955 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3959 write!(buffer, "</p>");
3961 // Sidebar refers to the enclosing module, not this module.
3962 let relpath = if it.is_mod() { "../" } else { "" };
3965 "<script>window.sidebarCurrent = {{\
3970 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3975 // There is no sidebar-items.js beyond the crate root path
3976 // FIXME maybe dynamic crate loading can be merged here
3978 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
3980 // Closes sidebar-elems div.
3981 write!(buffer, "</div>");
3984 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
3985 if used_links.insert(url.clone()) {
3989 while !used_links.insert(format!("{}-{}", url, add)) {
3992 format!("{}-{}", url, add)
3998 used_links: &mut FxHashSet<String>,
4003 .filter_map(|item| match item.name {
4004 Some(ref name) if !name.is_empty() && item.is_method() => {
4005 if !for_deref || should_render_item(item, deref_mut) {
4007 "<a href=\"#{}\">{}</a>",
4008 get_next_url(used_links, format!("method.{}", name)),
4017 .collect::<Vec<_>>()
4020 // The point is to url encode any potential character from a type with genericity.
4021 fn small_url_encode(s: &str) -> String {
4022 s.replace("<", "%3C")
4023 .replace(">", "%3E")
4024 .replace(" ", "%20")
4025 .replace("?", "%3F")
4026 .replace("'", "%27")
4027 .replace("&", "%26")
4028 .replace(",", "%2C")
4029 .replace(":", "%3A")
4030 .replace(";", "%3B")
4031 .replace("[", "%5B")
4032 .replace("]", "%5D")
4033 .replace("\"", "%22")
4036 fn sidebar_assoc_items(it: &clean::Item) -> String {
4037 let mut out = String::new();
4039 if let Some(v) = c.impls.get(&it.def_id) {
4040 let mut used_links = FxHashSet::default();
4043 let used_links_bor = &mut used_links;
4046 .filter(|i| i.inner_impl().trait_.is_none())
4047 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4048 .collect::<Vec<_>>();
4049 if !ret.is_empty() {
4050 // We want links' order to be reproducible so we don't use unstable sort.
4052 out.push_str(&format!(
4053 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4054 <div class=\"sidebar-links\">{}</div>",
4060 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4061 if let Some(impl_) = v
4063 .filter(|i| i.inner_impl().trait_.is_some())
4064 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4066 if let Some((target, real_target)) =
4067 impl_.inner_impl().items.iter().find_map(|item| match item.inner {
4068 clean::TypedefItem(ref t, true) => Some(match *t {
4069 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4070 _ => (&t.type_, &t.type_),
4077 .filter(|i| i.inner_impl().trait_.is_some())
4078 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4079 let inner_impl = target
4083 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4084 .and_then(|did| c.impls.get(&did));
4085 if let Some(impls) = inner_impl {
4086 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4087 out.push_str(&format!(
4088 "Methods from {}<Target={}>",
4091 impl_.inner_impl().trait_.as_ref().unwrap().print()
4093 Escape(&format!("{:#}", real_target.print()))
4095 out.push_str("</a>");
4098 .filter(|i| i.inner_impl().trait_.is_none())
4100 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4102 .collect::<Vec<_>>();
4103 // We want links' order to be reproducible so we don't use unstable sort.
4105 if !ret.is_empty() {
4106 out.push_str(&format!(
4107 "<div class=\"sidebar-links\">{}</div>",
4114 let format_impls = |impls: Vec<&Impl>| {
4115 let mut links = FxHashSet::default();
4120 let is_negative_impl = is_negative_impl(i.inner_impl());
4121 if let Some(ref i) = i.inner_impl().trait_ {
4122 let i_display = format!("{:#}", i.print());
4123 let out = Escape(&i_display);
4124 let encoded = small_url_encode(&format!("{:#}", i.print()));
4125 let generated = format!(
4126 "<a href=\"#impl-{}\">{}{}</a>",
4128 if is_negative_impl { "!" } else { "" },
4131 if links.insert(generated.clone()) { Some(generated) } else { None }
4136 .collect::<Vec<String>>();
4141 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4142 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4143 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4145 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4147 let concrete_format = format_impls(concrete);
4148 let synthetic_format = format_impls(synthetic);
4149 let blanket_format = format_impls(blanket_impl);
4151 if !concrete_format.is_empty() {
4153 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4154 Trait Implementations</a>",
4156 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4159 if !synthetic_format.is_empty() {
4161 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4162 Auto Trait Implementations</a>",
4164 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4167 if !blanket_format.is_empty() {
4169 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4170 Blanket Implementations</a>",
4172 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4180 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4181 let mut sidebar = String::new();
4182 let fields = get_struct_fields_name(&s.fields);
4184 if !fields.is_empty() {
4185 if let doctree::Plain = s.struct_type {
4186 sidebar.push_str(&format!(
4187 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4188 <div class=\"sidebar-links\">{}</div>",
4194 sidebar.push_str(&sidebar_assoc_items(it));
4196 if !sidebar.is_empty() {
4197 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4201 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4202 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4205 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4207 clean::ItemEnum::ImplItem(ref i) => {
4208 if let Some(ref trait_) = i.trait_ {
4210 format!("{:#}", i.for_.print()),
4211 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4221 fn is_negative_impl(i: &clean::Impl) -> bool {
4222 i.polarity == Some(clean::ImplPolarity::Negative)
4225 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4226 let mut sidebar = String::new();
4231 .filter_map(|m| match m.name {
4232 Some(ref name) if m.is_associated_type() => {
4233 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4237 .collect::<Vec<_>>();
4241 .filter_map(|m| match m.name {
4242 Some(ref name) if m.is_associated_const() => {
4243 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4247 .collect::<Vec<_>>();
4248 let mut required = t
4251 .filter_map(|m| match m.name {
4252 Some(ref name) if m.is_ty_method() => {
4253 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4257 .collect::<Vec<String>>();
4258 let mut provided = t
4261 .filter_map(|m| match m.name {
4262 Some(ref name) if m.is_method() => {
4263 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4267 .collect::<Vec<String>>();
4269 if !types.is_empty() {
4271 sidebar.push_str(&format!(
4272 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4273 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4277 if !consts.is_empty() {
4279 sidebar.push_str(&format!(
4280 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4281 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4285 if !required.is_empty() {
4287 sidebar.push_str(&format!(
4288 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4289 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4293 if !provided.is_empty() {
4295 sidebar.push_str(&format!(
4296 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4297 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4304 if let Some(implementors) = c.implementors.get(&it.def_id) {
4305 let mut res = implementors
4307 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4308 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4309 .collect::<Vec<_>>();
4311 if !res.is_empty() {
4313 sidebar.push_str(&format!(
4314 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4315 Implementations on Foreign Types</a><div \
4316 class=\"sidebar-links\">{}</div>",
4318 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4319 .collect::<Vec<_>>()
4325 sidebar.push_str(&sidebar_assoc_items(it));
4327 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4330 "<a class=\"sidebar-title\" \
4331 href=\"#synthetic-implementors\">Auto Implementors</a>",
4335 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4338 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4339 let sidebar = sidebar_assoc_items(it);
4341 if !sidebar.is_empty() {
4342 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4346 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4347 let sidebar = sidebar_assoc_items(it);
4349 if !sidebar.is_empty() {
4350 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4354 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4355 let mut fields = fields
4357 .filter(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false })
4358 .filter_map(|f| match f.name {
4360 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4364 .collect::<Vec<_>>();
4369 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4370 let mut sidebar = String::new();
4371 let fields = get_struct_fields_name(&u.fields);
4373 if !fields.is_empty() {
4374 sidebar.push_str(&format!(
4375 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4376 <div class=\"sidebar-links\">{}</div>",
4381 sidebar.push_str(&sidebar_assoc_items(it));
4383 if !sidebar.is_empty() {
4384 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4388 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4389 let mut sidebar = String::new();
4391 let mut variants = e
4394 .filter_map(|v| match v.name {
4395 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4398 .collect::<Vec<_>>();
4399 if !variants.is_empty() {
4400 variants.sort_unstable();
4401 sidebar.push_str(&format!(
4402 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4403 <div class=\"sidebar-links\">{}</div>",
4408 sidebar.push_str(&sidebar_assoc_items(it));
4410 if !sidebar.is_empty() {
4411 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4415 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4417 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4418 ItemType::Module => ("modules", "Modules"),
4419 ItemType::Struct => ("structs", "Structs"),
4420 ItemType::Union => ("unions", "Unions"),
4421 ItemType::Enum => ("enums", "Enums"),
4422 ItemType::Function => ("functions", "Functions"),
4423 ItemType::Typedef => ("types", "Type Definitions"),
4424 ItemType::Static => ("statics", "Statics"),
4425 ItemType::Constant => ("constants", "Constants"),
4426 ItemType::Trait => ("traits", "Traits"),
4427 ItemType::Impl => ("impls", "Implementations"),
4428 ItemType::TyMethod => ("tymethods", "Type Methods"),
4429 ItemType::Method => ("methods", "Methods"),
4430 ItemType::StructField => ("fields", "Struct Fields"),
4431 ItemType::Variant => ("variants", "Variants"),
4432 ItemType::Macro => ("macros", "Macros"),
4433 ItemType::Primitive => ("primitives", "Primitive Types"),
4434 ItemType::AssocType => ("associated-types", "Associated Types"),
4435 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4436 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4437 ItemType::Keyword => ("keywords", "Keywords"),
4438 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4439 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4440 ItemType::ProcDerive => ("derives", "Derive Macros"),
4441 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4445 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4446 let mut sidebar = String::new();
4448 if items.iter().any(|it| it.type_() == ItemType::ExternCrate || it.type_() == ItemType::Import)
4450 sidebar.push_str(&format!(
4451 "<li><a href=\"#{id}\">{name}</a></li>",
4457 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4458 // to print its headings
4460 ItemType::Primitive,
4474 ItemType::StructField,
4476 ItemType::AssocType,
4477 ItemType::AssocConst,
4478 ItemType::ForeignType,
4481 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4482 let (short, name) = item_ty_to_strs(&myty);
4483 sidebar.push_str(&format!(
4484 "<li><a href=\"#{id}\">{name}</a></li>",
4491 if !sidebar.is_empty() {
4492 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4496 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4497 let sidebar = sidebar_assoc_items(it);
4498 if !sidebar.is_empty() {
4499 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4503 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4504 wrap_into_docblock(w, |w| {
4505 w.write_str(&highlight::render_with_highlighting(
4515 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4516 let name = it.name.as_ref().expect("proc-macros always have names");
4518 MacroKind::Bang => {
4519 write!(w, "<pre class='rust macro'>");
4520 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4521 write!(w, "</pre>");
4523 MacroKind::Attr => {
4524 write!(w, "<pre class='rust attr'>");
4525 write!(w, "#[{}]", name);
4526 write!(w, "</pre>");
4528 MacroKind::Derive => {
4529 write!(w, "<pre class='rust derive'>");
4530 write!(w, "#[derive({})]", name);
4531 if !m.helpers.is_empty() {
4532 writeln!(w, "\n{{");
4533 writeln!(w, " // Attributes available to this derive:");
4534 for attr in &m.helpers {
4535 writeln!(w, " #[{}]", attr);
4539 write!(w, "</pre>");
4545 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4546 document(w, cx, it);
4547 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4550 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4554 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4556 fn make_item_keywords(it: &clean::Item) -> String {
4557 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4560 /// Returns a list of all paths used in the type.
4561 /// This is used to help deduplicate imported impls
4562 /// for reexported types. If any of the contained
4563 /// types are re-exported, we don't use the corresponding
4564 /// entry from the js file, as inlining will have already
4565 /// picked up the impl
4566 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4567 let mut out = Vec::new();
4568 let mut visited = FxHashSet::default();
4569 let mut work = VecDeque::new();
4570 let cache = cache();
4572 work.push_back(first_ty);
4574 while let Some(ty) = work.pop_front() {
4575 if !visited.insert(ty.clone()) {
4580 clean::Type::ResolvedPath { did, .. } => {
4581 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4582 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4584 if let Some(path) = fqp {
4585 out.push(path.join("::"));
4588 clean::Type::Tuple(tys) => {
4589 work.extend(tys.into_iter());
4591 clean::Type::Slice(ty) => {
4592 work.push_back(*ty);
4594 clean::Type::Array(ty, _) => {
4595 work.push_back(*ty);
4597 clean::Type::RawPointer(_, ty) => {
4598 work.push_back(*ty);
4600 clean::Type::BorrowedRef { type_, .. } => {
4601 work.push_back(*type_);
4603 clean::Type::QPath { self_type, trait_, .. } => {
4604 work.push_back(*self_type);
4605 work.push_back(*trait_);