1 // ignore-tidy-filelength
3 //! Rustdoc's HTML rendering module.
5 //! This modules contains the bulk of the logic necessary for rendering a
6 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
7 //! rendering process is largely driven by the `format!` syntax extension to
8 //! perform all I/O into files and streams.
10 //! The rendering process is largely driven by the `Context` and `Cache`
11 //! structures. The cache is pre-populated by crawling the crate in question,
12 //! and then it is shared among the various rendering threads. The cache is meant
13 //! to be a fairly large structure not implementing `Clone` (because it's shared
14 //! among threads). The context, however, should be a lightweight structure. This
15 //! is cloned per-thread and contains information about what is currently being
18 //! In order to speed up rendering (mostly because of markdown rendering), the
19 //! rendering process has been parallelized. This parallelization is only
20 //! exposed through the `crate` method on the context, and then also from the
21 //! fact that the shared cache is stored in TLS (and must be accessed as such).
23 //! In addition to rendering the crate itself, this module is also responsible
24 //! for creating the corresponding search index and source file renderings.
25 //! These threads are not parallelized (they haven't been a bottleneck yet), and
26 //! both occur before the crate is rendered.
34 use std::cell::{Cell, RefCell};
35 use std::cmp::Ordering;
36 use std::collections::{BTreeMap, VecDeque};
37 use std::default::Default;
39 use std::fmt::{self, Write};
40 use std::fs::{self, File};
41 use std::io::prelude::*;
42 use std::io::{self, BufReader};
43 use std::path::{Component, Path, PathBuf};
46 use std::string::ToString;
47 use std::sync::mpsc::{channel, Receiver};
50 use itertools::Itertools;
51 use rustc_ast_pretty::pprust;
52 use rustc_attr::{Deprecation, StabilityLevel};
53 use rustc_data_structures::flock;
54 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
55 use rustc_data_structures::sync::Lrc;
57 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
58 use rustc_hir::Mutability;
59 use rustc_middle::middle::stability;
60 use rustc_session::Session;
61 use rustc_span::edition::Edition;
62 use rustc_span::hygiene::MacroKind;
63 use rustc_span::source_map::FileName;
64 use rustc_span::symbol::{kw, sym, Symbol};
65 use serde::ser::SerializeSeq;
66 use serde::{Serialize, Serializer};
68 use crate::clean::{self, AttributesExt, GetDefId, RenderedLink, SelfTy, TypeKind};
69 use crate::config::{RenderInfo, RenderOptions};
70 use crate::docfs::{DocFS, PathError};
72 use crate::error::Error;
73 use crate::formats::cache::{cache, Cache};
74 use crate::formats::item_type::ItemType;
75 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
76 use crate::html::escape::Escape;
77 use crate::html::format::fmt_impl_for_trait_page;
78 use crate::html::format::Function;
79 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
80 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
81 use crate::html::markdown::{
82 self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine,
84 use crate::html::sources;
85 use crate::html::{highlight, layout, static_files};
86 use cache::{build_index, ExternalLocation};
88 /// A pair of name and its optional document.
89 crate type NameDoc = (String, Option<String>);
91 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
92 crate::html::format::display_fn(move |f| {
93 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
97 /// Major driving force in all rustdoc rendering. This contains information
98 /// about where in the tree-like hierarchy rendering is occurring and controls
99 /// how the current page is being rendered.
101 /// It is intended that this context is a lightweight object which can be fairly
102 /// easily cloned because it is cloned per work-job (about once per item in the
105 crate struct Context {
106 /// Current hierarchy of components leading down to what's currently being
108 crate current: Vec<String>,
109 /// The current destination folder of where HTML artifacts should be placed.
110 /// This changes as the context descends into the module hierarchy.
112 /// A flag, which when `true`, will render pages which redirect to the
113 /// real location of an item. This is used to allow external links to
114 /// publicly reused items to redirect to the right location.
115 crate render_redirect_pages: bool,
116 /// The map used to ensure all generated 'id=' attributes are unique.
117 id_map: Rc<RefCell<IdMap>>,
118 crate shared: Arc<SharedContext>,
119 all: Rc<RefCell<AllTypes>>,
120 /// Storage for the errors produced while generating documentation so they
121 /// can be printed together at the end.
122 crate errors: Rc<Receiver<String>>,
125 crate struct SharedContext {
126 crate sess: Lrc<Session>,
127 /// The path to the crate root source minus the file name.
128 /// Used for simplifying paths to the highlighted source code files.
129 crate src_root: PathBuf,
130 /// This describes the layout of each page, and is not modified after
131 /// creation of the context (contains info like the favicon and added html).
132 crate layout: layout::Layout,
133 /// This flag indicates whether `[src]` links should be generated or not. If
134 /// the source files are present in the html rendering, then this will be
136 crate include_sources: bool,
137 /// The local file sources we've emitted and their respective url-paths.
138 crate local_sources: FxHashMap<PathBuf, String>,
139 /// Whether the collapsed pass ran
140 crate collapsed: bool,
141 /// The base-URL of the issue tracker for when an item has been tagged with
143 crate issue_tracker_base_url: Option<String>,
144 /// The directories that have already been created in this doc run. Used to reduce the number
145 /// of spurious `create_dir_all` calls.
146 crate created_dirs: RefCell<FxHashSet<PathBuf>>,
147 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
148 /// should be ordered alphabetically or in order of appearance (in the source code).
149 crate sort_modules_alphabetically: bool,
150 /// Additional CSS files to be added to the generated docs.
151 crate style_files: Vec<StylePath>,
152 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
154 crate resource_suffix: String,
155 /// Optional path string to be used to load static files on output pages. If not set, uses
156 /// combinations of `../` to reach the documentation root.
157 crate static_root_path: Option<String>,
158 /// The fs handle we are working with.
160 /// The default edition used to parse doctests.
161 crate edition: Edition,
162 crate codes: ErrorCodes,
163 playground: Option<markdown::Playground>,
167 fn path(&self, filename: &str) -> PathBuf {
168 // We use splitn vs Path::extension here because we might get a filename
169 // like `style.min.css` and we want to process that into
170 // `style-suffix.min.css`. Path::extension would just return `css`
171 // which would result in `style.min-suffix.css` which isn't what we
173 let (base, ext) = filename.split_once('.').unwrap();
174 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext);
175 self.dst.join(&filename)
178 fn sess(&self) -> &Session {
184 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
185 let mut dirs = self.created_dirs.borrow_mut();
186 if !dirs.contains(dst) {
187 try_err!(self.fs.create_dir_all(dst), dst);
188 dirs.insert(dst.to_path_buf());
194 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
195 /// `collapsed_doc_value` of the given item.
196 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
198 item.collapsed_doc_value().map(|s| s.into())
200 item.doc_value().map(|s| s.into())
205 // Helper structs for rendering items/sidebars and carrying along contextual
208 /// Struct representing one entry in the JS search index. These are all emitted
209 /// by hand to a large JS file at the end of cache-creation.
211 crate struct IndexItem {
216 crate parent: Option<DefId>,
217 crate parent_idx: Option<usize>,
218 crate search_type: Option<IndexItemFunctionType>,
221 impl Serialize for IndexItem {
222 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
227 self.parent.is_some(),
228 self.parent_idx.is_some(),
229 "`{}` is missing idx",
233 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
234 .serialize(serializer)
238 /// A type used for the search index.
240 crate struct RenderType {
243 name: Option<String>,
244 generics: Option<Vec<Generic>>,
247 impl Serialize for RenderType {
248 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
252 if let Some(name) = &self.name {
253 let mut seq = serializer.serialize_seq(None)?;
254 if let Some(id) = self.idx {
255 seq.serialize_element(&id)?;
257 seq.serialize_element(&name)?;
259 if let Some(generics) = &self.generics {
260 seq.serialize_element(&generics)?;
264 serializer.serialize_none()
269 /// A type used for the search index.
271 crate struct Generic {
273 defid: Option<DefId>,
277 impl Serialize for Generic {
278 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
282 if let Some(id) = self.idx {
283 serializer.serialize_some(&id)
285 serializer.serialize_some(&self.name)
290 /// Full type of functions/methods in the search index.
292 crate struct IndexItemFunctionType {
293 inputs: Vec<TypeWithKind>,
294 output: Option<Vec<TypeWithKind>>,
297 impl Serialize for IndexItemFunctionType {
298 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
302 // If we couldn't figure out a type, just write `null`.
303 let mut iter = self.inputs.iter();
304 if match self.output {
305 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
306 None => iter.any(|ref i| i.ty.name.is_none()),
308 serializer.serialize_none()
310 let mut seq = serializer.serialize_seq(None)?;
311 seq.serialize_element(&self.inputs)?;
312 if let Some(output) = &self.output {
313 if output.len() > 1 {
314 seq.serialize_element(&output)?;
316 seq.serialize_element(&output[0])?;
325 crate struct TypeWithKind {
330 impl From<(RenderType, TypeKind)> for TypeWithKind {
331 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
332 TypeWithKind { ty: x.0, kind: x.1 }
336 impl Serialize for TypeWithKind {
337 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
341 let mut seq = serializer.serialize_seq(None)?;
342 seq.serialize_element(&self.ty.name)?;
343 let x: ItemType = self.kind.into();
344 seq.serialize_element(&x)?;
349 #[derive(Debug, Clone)]
350 crate struct StylePath {
351 /// The path to the theme
353 /// What the `disabled` attribute should be set to in the HTML tag
354 crate disabled: bool,
357 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
359 crate fn initial_ids() -> Vec<String> {
371 "synthetic-implementors",
373 "synthetic-implementors-list",
379 .map(|id| (String::from(*id)))
383 /// Generates the documentation for `crate` into the directory `dst`
384 impl FormatRenderer for Context {
386 mut krate: clean::Crate,
387 options: RenderOptions,
388 _render_info: RenderInfo,
392 ) -> Result<(Context, clean::Crate), Error> {
393 // need to save a copy of the options for rendering the index page
394 let md_opts = options.clone();
400 sort_modules_alphabetically,
406 generate_search_filter,
411 let src_root = match krate.src {
412 FileName::Real(ref p) => match p.local_path().parent() {
413 Some(p) => p.to_path_buf(),
414 None => PathBuf::new(),
418 // If user passed in `--playground-url` arg, we fill in crate name here
419 let mut playground = None;
420 if let Some(url) = playground_url {
422 Some(markdown::Playground { crate_name: Some(krate.name.to_string()), url });
424 let mut layout = layout::Layout {
426 favicon: String::new(),
429 krate: krate.name.to_string(),
430 css_file_extension: extension_css,
431 generate_search_filter,
433 let mut issue_tracker_base_url = None;
434 let mut include_sources = true;
436 // Crawl the crate attributes looking for attributes which control how we're
437 // going to emit HTML
438 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
439 for attr in attrs.lists(sym::doc) {
440 match (attr.name_or_empty(), attr.value_str()) {
441 (sym::html_favicon_url, Some(s)) => {
442 layout.favicon = s.to_string();
444 (sym::html_logo_url, Some(s)) => {
445 layout.logo = s.to_string();
447 (sym::html_playground_url, Some(s)) => {
448 playground = Some(markdown::Playground {
449 crate_name: Some(krate.name.to_string()),
453 (sym::issue_tracker_base_url, Some(s)) => {
454 issue_tracker_base_url = Some(s.to_string());
456 (sym::html_no_source, None) if attr.is_word() => {
457 include_sources = false;
463 let (sender, receiver) = channel();
464 let mut scx = SharedContext {
466 collapsed: krate.collapsed,
469 local_sources: Default::default(),
470 issue_tracker_base_url,
472 created_dirs: Default::default(),
473 sort_modules_alphabetically,
477 fs: DocFS::new(sender),
479 codes: ErrorCodes::from(unstable_features.is_nightly_build()),
483 // Add the default themes to the `Vec` of stylepaths
485 // Note that these must be added before `sources::render` is called
486 // so that the resulting source pages are styled
488 // `light.css` is not disabled because it is the stylesheet that stays loaded
489 // by the browser as the theme stylesheet. The theme system (hackily) works by
490 // changing the href to this stylesheet. All other themes are disabled to
491 // prevent rule conflicts
492 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
493 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
494 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
497 scx.ensure_dir(&dst)?;
498 krate = sources::render(&dst, &mut scx, krate)?;
500 // Build our search index
501 let index = build_index(&krate, cache);
503 let cache = Arc::new(cache);
504 let mut cx = Context {
507 render_redirect_pages: false,
508 id_map: Rc::new(RefCell::new(id_map)),
509 shared: Arc::new(scx),
510 all: Rc::new(RefCell::new(AllTypes::new())),
511 errors: Rc::new(receiver),
514 CURRENT_DEPTH.with(|s| s.set(0));
516 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
517 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
518 write_shared(&cx, &krate, index, &md_opts, &cache)?;
519 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
523 fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
524 Arc::get_mut(&mut self.shared).unwrap().fs.close();
525 let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
527 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
533 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
534 let final_file = self.dst.join(&*krate.name.as_str()).join("all.html");
535 let settings_file = self.dst.join("settings.html");
536 let crate_name = krate.name.clone();
538 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
539 if !root_path.ends_with('/') {
542 let mut page = layout::Page {
543 title: "List of all items in this crate",
546 static_root_path: self.shared.static_root_path.as_deref(),
547 description: "List of all items in this crate",
548 keywords: BASIC_KEYWORDS,
549 resource_suffix: &self.shared.resource_suffix,
551 static_extra_scripts: &[],
553 let sidebar = if let Some(ref version) = cache.crate_version {
555 "<p class=\"location\">Crate {}</p>\
556 <div class=\"block version\">\
559 <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>",
566 let all = self.all.replace(AllTypes::new());
567 let v = layout::render(
571 |buf: &mut Buffer| all.print(buf),
572 &self.shared.style_files,
574 self.shared.fs.write(&final_file, v.as_bytes())?;
576 // Generating settings page.
577 page.title = "Rustdoc settings";
578 page.description = "Settings of Rustdoc";
579 page.root_path = "./";
581 let mut style_files = self.shared.style_files.clone();
582 let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>";
583 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
584 let v = layout::render(
589 self.shared.static_root_path.as_deref().unwrap_or("./"),
590 &self.shared.resource_suffix,
591 &self.shared.style_files,
595 self.shared.fs.write(&settings_file, v.as_bytes())?;
604 ) -> Result<(), Error> {
605 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
606 // if they contain impls for public types. These modules can also
607 // contain items such as publicly re-exported structures.
609 // External crates will provide links to these structures, so
610 // these modules are recursed into, but not rendered normally
611 // (a flag on the context).
612 if !self.render_redirect_pages {
613 self.render_redirect_pages = item.is_stripped();
615 let scx = &self.shared;
616 self.dst.push(item_name);
617 self.current.push(item_name.to_owned());
619 info!("Recursing into {}", self.dst.display());
621 let buf = self.render_item(item, false, cache);
622 // buf will be empty if the module is stripped and there is no redirect for it
624 self.shared.ensure_dir(&self.dst)?;
625 let joint_dst = self.dst.join("index.html");
626 scx.fs.write(&joint_dst, buf.as_bytes())?;
629 // Render sidebar-items.js used throughout this module.
630 if !self.render_redirect_pages {
631 let module = match item.kind {
632 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
635 let items = self.build_sidebar_items(module);
636 let js_dst = self.dst.join("sidebar-items.js");
637 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
638 scx.fs.write(&js_dst, &v)?;
643 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
644 info!("Recursed; leaving {}", self.dst.display());
646 // Go back to where we were at
652 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
653 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
654 // if they contain impls for public types. These modules can also
655 // contain items such as publicly re-exported structures.
657 // External crates will provide links to these structures, so
658 // these modules are recursed into, but not rendered normally
659 // (a flag on the context).
660 if !self.render_redirect_pages {
661 self.render_redirect_pages = item.is_stripped();
664 let buf = self.render_item(&item, true, cache);
665 // buf will be empty if the item is stripped and there is no redirect for it
667 let name = item.name.as_ref().unwrap();
668 let item_type = item.type_();
669 let file_name = &item_path(item_type, &name.as_str());
670 self.shared.ensure_dir(&self.dst)?;
671 let joint_dst = self.dst.join(file_name);
672 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
674 if !self.render_redirect_pages {
675 self.all.borrow_mut().append(full_path(self, &item), &item_type);
677 // If the item is a macro, redirect from the old macro URL (with !)
678 // to the new one (without).
679 if item_type == ItemType::Macro {
680 let redir_name = format!("{}.{}!.html", item_type, name);
681 let redir_dst = self.dst.join(redir_name);
682 let v = layout::redirect(file_name);
683 self.shared.fs.write(&redir_dst, v.as_bytes())?;
692 krate: &clean::Crate,
693 search_index: String,
694 options: &RenderOptions,
696 ) -> Result<(), Error> {
697 // Write out the shared files. Note that these are shared among all rustdoc
698 // docs placed in the output directory, so this needs to be a synchronized
699 // operation with respect to all other rustdocs running around.
700 let lock_file = cx.dst.join(".lock");
701 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
703 // Add all the static files. These may already exist, but we just
704 // overwrite them anyway to make sure that they're fresh and up-to-date.
708 cx.path("rustdoc.css"),
709 static_files::RUSTDOC_CSS,
710 options.enable_minification,
714 cx.path("settings.css"),
715 static_files::SETTINGS_CSS,
716 options.enable_minification,
720 cx.path("noscript.css"),
721 static_files::NOSCRIPT_CSS,
722 options.enable_minification,
725 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
726 // then we'll run over the "official" styles.
727 let mut themes: FxHashSet<String> = FxHashSet::default();
729 for entry in &cx.shared.style_files {
730 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
732 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
734 // Handle the official themes
736 "light" => write_minify(
738 cx.path("light.css"),
739 static_files::themes::LIGHT,
740 options.enable_minification,
742 "dark" => write_minify(
745 static_files::themes::DARK,
746 options.enable_minification,
748 "ayu" => write_minify(
751 static_files::themes::AYU,
752 options.enable_minification,
755 // Handle added third-party themes
756 let content = try_err!(fs::read(&entry.path), &entry.path);
759 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
763 themes.insert(theme.to_owned());
766 let write = |p, c| cx.shared.fs.write(p, c);
767 if (*cx.shared).layout.logo.is_empty() {
768 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
770 if (*cx.shared).layout.favicon.is_empty() {
771 write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?;
772 write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?;
773 write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?;
775 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
776 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
777 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
779 let mut themes: Vec<&String> = themes.iter().collect();
781 // To avoid theme switch latencies as much as possible, we put everything theme related
782 // at the beginning of the html files into another js file.
783 let theme_js = format!(
784 r#"var themes = document.getElementById("theme-choices");
785 var themePicker = document.getElementById("theme-picker");
787 function showThemeButtonState() {{
788 themes.style.display = "block";
789 themePicker.style.borderBottomRightRadius = "0";
790 themePicker.style.borderBottomLeftRadius = "0";
793 function hideThemeButtonState() {{
794 themes.style.display = "none";
795 themePicker.style.borderBottomRightRadius = "3px";
796 themePicker.style.borderBottomLeftRadius = "3px";
799 function switchThemeButtonState() {{
800 if (themes.style.display === "block") {{
801 hideThemeButtonState();
803 showThemeButtonState();
807 function handleThemeButtonsBlur(e) {{
808 var active = document.activeElement;
809 var related = e.relatedTarget;
811 if (active.id !== "theme-picker" &&
812 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
814 (related.id !== "theme-picker" &&
815 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
816 hideThemeButtonState();
820 themePicker.onclick = switchThemeButtonState;
821 themePicker.onblur = handleThemeButtonsBlur;
822 {}.forEach(function(item) {{
823 var but = document.createElement("button");
824 but.textContent = item;
825 but.onclick = function(el) {{
826 switchTheme(currentTheme, mainTheme, item, true);
827 useSystemTheme(false);
829 but.onblur = handleThemeButtonsBlur;
830 themes.appendChild(but);
832 serde_json::to_string(&themes).unwrap()
835 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
839 static_files::MAIN_JS,
840 options.enable_minification,
844 cx.path("settings.js"),
845 static_files::SETTINGS_JS,
846 options.enable_minification,
848 if cx.shared.include_sources {
851 cx.path("source-script.js"),
852 static_files::sidebar::SOURCE_SCRIPT,
853 options.enable_minification,
860 cx.path("storage.js"),
862 "var resourcesSuffix = \"{}\";{}",
863 cx.shared.resource_suffix,
864 static_files::STORAGE_JS
866 options.enable_minification,
870 if let Some(ref css) = cx.shared.layout.css_file_extension {
871 let out = cx.path("theme.css");
872 let buffer = try_err!(fs::read_to_string(css), css);
873 if !options.enable_minification {
874 cx.shared.fs.write(&out, &buffer)?;
876 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
881 cx.path("normalize.css"),
882 static_files::NORMALIZE_CSS,
883 options.enable_minification,
885 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
886 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
887 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
888 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
889 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
890 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
891 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
892 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
893 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
894 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
895 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
896 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
897 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
899 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
900 let mut ret = Vec::new();
901 let mut krates = Vec::new();
904 for line in BufReader::new(File::open(path)?).lines() {
906 if !line.starts_with(key) {
909 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
912 ret.push(line.to_string());
914 line[key.len() + 2..]
917 .map(|s| s.to_owned())
918 .unwrap_or_else(String::new),
925 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
926 let mut ret = Vec::new();
927 let mut krates = Vec::new();
930 for line in BufReader::new(File::open(path)?).lines() {
932 if !line.starts_with('"') {
935 if line.starts_with(&format!("\"{}\"", krate)) {
938 if line.ends_with(",\\") {
939 ret.push(line[..line.len() - 2].to_string());
941 // Ends with "\\" (it's the case for the last added crate line)
942 ret.push(line[..line.len() - 1].to_string());
946 .find(|s| !s.is_empty())
947 .map(|s| s.to_owned())
948 .unwrap_or_else(String::new),
955 use std::ffi::OsString;
960 children: FxHashMap<OsString, Hierarchy>,
961 elems: FxHashSet<OsString>,
965 fn new(elem: OsString) -> Hierarchy {
966 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
969 fn to_json_string(&self) -> String {
970 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
971 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
975 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
976 .collect::<Vec<_>>();
977 files.sort_unstable_by(|a, b| a.cmp(b));
978 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
980 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
981 let files = files.join(",");
983 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
985 "{{\"name\":\"{name}\"{dirs}{files}}}",
986 name = self.elem.to_str().expect("invalid osstring conversion"),
993 if cx.shared.include_sources {
994 let mut hierarchy = Hierarchy::new(OsString::new());
999 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
1001 let mut h = &mut hierarchy;
1002 let mut elems = source
1004 .filter_map(|s| match s {
1005 Component::Normal(s) => Some(s.to_owned()),
1010 let cur_elem = elems.next().expect("empty file path");
1011 if elems.peek().is_none() {
1012 h.elems.insert(cur_elem);
1015 let e = cur_elem.clone();
1016 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1017 h = h.children.get_mut(&cur_elem).expect("not found child");
1022 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1023 let (mut all_sources, _krates) =
1024 try_err!(collect(&dst, &krate.name.as_str(), "sourcesIndex"), &dst);
1025 all_sources.push(format!(
1026 "sourcesIndex[\"{}\"] = {};",
1028 hierarchy.to_json_string()
1032 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1033 all_sources.join("\n")
1035 cx.shared.fs.write(&dst, v.as_bytes())?;
1038 // Update the search index
1039 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1040 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name.as_str()), &dst);
1041 all_indexes.push(search_index);
1043 // Sort the indexes by crate so the file will be generated identically even
1044 // with rustdoc running in parallel.
1047 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1048 v.push_str(&all_indexes.join(",\\\n"));
1049 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1050 // search might start (if it's set into the URL for example).
1051 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1052 cx.shared.fs.write(&dst, &v)?;
1054 if options.enable_index_page {
1055 if let Some(index_page) = options.index_page.clone() {
1056 let mut md_opts = options.clone();
1057 md_opts.output = cx.dst.clone();
1058 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1060 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1061 .map_err(|e| Error::new(e, &index_page))?;
1063 let dst = cx.dst.join("index.html");
1064 let page = layout::Page {
1065 title: "Index of crates",
1068 static_root_path: cx.shared.static_root_path.as_deref(),
1069 description: "List of crates",
1070 keywords: BASIC_KEYWORDS,
1071 resource_suffix: &cx.shared.resource_suffix,
1073 static_extra_scripts: &[],
1075 krates.push(krate.name.to_string());
1079 let content = format!(
1080 "<h1 class=\"fqn\">\
1081 <span class=\"in-band\">List of all crates</span>\
1082 </h1><ul class=\"crate mod\">{}</ul>",
1087 "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>",
1088 ensure_trailing_slash(s),
1092 .collect::<String>()
1094 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1095 cx.shared.fs.write(&dst, v.as_bytes())?;
1099 // Update the list of all implementors for traits
1100 let dst = cx.dst.join("implementors");
1101 for (&did, imps) in &cache.implementors {
1102 // Private modules can leak through to this phase of rustdoc, which
1103 // could contain implementations for otherwise private types. In some
1104 // rare cases we could find an implementation for an item which wasn't
1105 // indexed, so we just skip this step in that case.
1107 // FIXME: this is a vague explanation for why this can't be a `get`, in
1108 // theory it should be...
1109 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1111 None => match cache.external_paths.get(&did) {
1117 #[derive(Serialize)]
1118 struct Implementor {
1124 let implementors = imps
1127 // If the trait and implementation are in the same crate, then
1128 // there's no need to emit information about it (there's inlining
1129 // going on). If they're in different crates then the crate defining
1130 // the trait will be interested in our implementation.
1132 // If the implementation is from another crate then that crate
1134 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1138 text: imp.inner_impl().print().to_string(),
1139 synthetic: imp.inner_impl().synthetic,
1140 types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1144 .collect::<Vec<_>>();
1146 // Only create a js file if we have impls to add to it. If the trait is
1147 // documented locally though we always create the file to avoid dead
1149 if implementors.is_empty() && !cache.paths.contains_key(&did) {
1153 let implementors = format!(
1154 r#"implementors["{}"] = {};"#,
1156 serde_json::to_string(&implementors).unwrap()
1159 let mut mydst = dst.clone();
1160 for part in &remote_path[..remote_path.len() - 1] {
1163 cx.shared.ensure_dir(&mydst)?;
1164 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1166 let (mut all_implementors, _) =
1167 try_err!(collect(&mydst, &krate.name.as_str(), "implementors"), &mydst);
1168 all_implementors.push(implementors);
1169 // Sort the implementors by crate so the file will be generated
1170 // identically even with rustdoc running in parallel.
1171 all_implementors.sort();
1173 let mut v = String::from("(function() {var implementors = {};\n");
1174 for implementor in &all_implementors {
1175 writeln!(v, "{}", *implementor).unwrap();
1178 "if (window.register_implementors) {\
1179 window.register_implementors(implementors);\
1181 window.pending_implementors = implementors;\
1185 cx.shared.fs.write(&mydst, &v)?;
1194 enable_minification: bool,
1195 ) -> Result<(), Error> {
1196 if enable_minification {
1197 if dst.extension() == Some(&OsStr::new("css")) {
1198 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1199 fs.write(dst, res.as_bytes())
1201 fs.write(dst, minifier::js::minify(contents).as_bytes())
1204 fs.write(dst, contents.as_bytes())
1208 fn write_srclink(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1209 if let Some(l) = cx.src_href(item, cache) {
1212 "<a class=\"srclink\" href=\"{}\" title=\"{}\">[src]</a>",
1213 l, "goto source code"
1218 #[derive(Debug, Eq, PartialEq, Hash)]
1225 fn new(mut url: String, name: String) -> ItemEntry {
1226 while url.starts_with('/') {
1229 ItemEntry { url, name }
1234 crate fn print(&self) -> impl fmt::Display + '_ {
1235 crate::html::format::display_fn(move |f| {
1236 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
1241 impl PartialOrd for ItemEntry {
1242 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1243 Some(self.cmp(other))
1247 impl Ord for ItemEntry {
1248 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1249 self.name.cmp(&other.name)
1255 structs: FxHashSet<ItemEntry>,
1256 enums: FxHashSet<ItemEntry>,
1257 unions: FxHashSet<ItemEntry>,
1258 primitives: FxHashSet<ItemEntry>,
1259 traits: FxHashSet<ItemEntry>,
1260 macros: FxHashSet<ItemEntry>,
1261 functions: FxHashSet<ItemEntry>,
1262 typedefs: FxHashSet<ItemEntry>,
1263 opaque_tys: FxHashSet<ItemEntry>,
1264 statics: FxHashSet<ItemEntry>,
1265 constants: FxHashSet<ItemEntry>,
1266 keywords: FxHashSet<ItemEntry>,
1267 attributes: FxHashSet<ItemEntry>,
1268 derives: FxHashSet<ItemEntry>,
1269 trait_aliases: FxHashSet<ItemEntry>,
1273 fn new() -> AllTypes {
1274 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1276 structs: new_set(100),
1277 enums: new_set(100),
1278 unions: new_set(100),
1279 primitives: new_set(26),
1280 traits: new_set(100),
1281 macros: new_set(100),
1282 functions: new_set(100),
1283 typedefs: new_set(100),
1284 opaque_tys: new_set(100),
1285 statics: new_set(100),
1286 constants: new_set(100),
1287 keywords: new_set(100),
1288 attributes: new_set(100),
1289 derives: new_set(100),
1290 trait_aliases: new_set(100),
1294 fn append(&mut self, item_name: String, item_type: &ItemType) {
1295 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1296 if let Some(name) = url.pop() {
1297 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1299 let name = url.join("::");
1301 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1302 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1303 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1304 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1305 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1306 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1307 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1308 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1309 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1310 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1311 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1312 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1313 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1314 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1321 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1323 let mut e: Vec<&ItemEntry> = e.iter().collect();
1327 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">{}</ul>",
1331 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1337 fn print(self, f: &mut Buffer) {
1340 "<h1 class=\"fqn\">\
1341 <span class=\"out-of-band\">\
1342 <span id=\"render-detail\">\
1343 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1344 title=\"collapse all docs\">\
1345 [<span class=\"inner\">−</span>]\
1349 <span class=\"in-band\">List of all items</span>\
1352 print_entries(f, &self.structs, "Structs", "structs");
1353 print_entries(f, &self.enums, "Enums", "enums");
1354 print_entries(f, &self.unions, "Unions", "unions");
1355 print_entries(f, &self.primitives, "Primitives", "primitives");
1356 print_entries(f, &self.traits, "Traits", "traits");
1357 print_entries(f, &self.macros, "Macros", "macros");
1358 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1359 print_entries(f, &self.derives, "Derive Macros", "derives");
1360 print_entries(f, &self.functions, "Functions", "functions");
1361 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1362 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1363 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1364 print_entries(f, &self.statics, "Statics", "statics");
1365 print_entries(f, &self.constants, "Constants", "constants")
1372 description: &'static str,
1373 sub_settings: Vec<Setting>,
1376 js_data_name: &'static str,
1377 description: &'static str,
1378 default_value: bool,
1381 js_data_name: &'static str,
1382 description: &'static str,
1383 default_value: &'static str,
1384 options: Vec<(String, String)>,
1389 fn display(&self, root_path: &str, suffix: &str) -> String {
1391 Setting::Section { description, ref sub_settings } => format!(
1392 "<div class=\"setting-line\">\
1393 <div class=\"title\">{}</div>\
1394 <div class=\"sub-settings\">{}</div>
1397 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
1399 Setting::Toggle { js_data_name, description, default_value } => format!(
1400 "<div class=\"setting-line\">\
1401 <label class=\"toggle\">\
1402 <input type=\"checkbox\" id=\"{}\" {}>\
1403 <span class=\"slider\"></span>\
1408 if default_value { " checked" } else { "" },
1411 Setting::Select { js_data_name, description, default_value, ref options } => format!(
1412 "<div class=\"setting-line\">\
1414 <label class=\"select-wrapper\">\
1415 <select id=\"{}\" autocomplete=\"off\">{}</select>\
1416 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
1424 "<option value=\"{}\" {}>{}</option>",
1426 if &opt.0 == default_value { "selected" } else { "" },
1429 .collect::<String>(),
1437 impl From<(&'static str, &'static str, bool)> for Setting {
1438 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1439 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
1443 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1444 fn from(values: (&'static str, Vec<T>)) -> Setting {
1446 description: values.0,
1447 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1452 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
1453 let theme_names: Vec<(String, String)> = themes
1457 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
1460 Ok((theme.clone(), theme))
1462 .collect::<Result<_, Error>>()?;
1464 // (id, explanation, default value)
1465 let settings: &[Setting] = &[
1467 "Theme preferences",
1469 Setting::from(("use-system-theme", "Use system theme", true)),
1471 js_data_name: "preferred-dark-theme",
1472 description: "Preferred dark theme",
1473 default_value: "dark",
1474 options: theme_names.clone(),
1477 js_data_name: "preferred-light-theme",
1478 description: "Preferred light theme",
1479 default_value: "light",
1480 options: theme_names,
1486 "Auto-hide item declarations",
1488 ("auto-hide-struct", "Auto-hide structs declaration", true),
1489 ("auto-hide-enum", "Auto-hide enums declaration", false),
1490 ("auto-hide-union", "Auto-hide unions declaration", true),
1491 ("auto-hide-trait", "Auto-hide traits declaration", true),
1492 ("auto-hide-macro", "Auto-hide macros declaration", false),
1496 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1497 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1498 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1500 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1501 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1503 ("line-numbers", "Show line numbers on code examples", false).into(),
1504 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1508 "<h1 class=\"fqn\">\
1509 <span class=\"in-band\">Rustdoc settings</span>\
1511 <div class=\"settings\">{}</div>\
1512 <script src=\"{}settings{}.js\"></script>",
1513 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
1520 fn derive_id(&self, id: String) -> String {
1521 let mut map = self.id_map.borrow_mut();
1525 /// String representation of how to get back to the root path of the 'doc/'
1526 /// folder in terms of a relative URL.
1527 fn root_path(&self) -> String {
1528 "../".repeat(self.current.len())
1531 fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1532 // A little unfortunate that this is done like this, but it sure
1533 // does make formatting *a lot* nicer.
1534 CURRENT_DEPTH.with(|slot| {
1535 slot.set(self.current.len());
1538 let mut title = if it.is_primitive() || it.is_keyword() {
1539 // No need to include the namespace for primitive types and keywords
1542 self.current.join("::")
1545 if !title.is_empty() {
1546 title.push_str("::");
1548 title.push_str(&it.name.unwrap().as_str());
1550 title.push_str(" - Rust");
1551 let tyname = it.type_();
1552 let desc = if it.is_crate() {
1553 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1556 "API documentation for the Rust `{}` {} in crate `{}`.",
1557 it.name.as_ref().unwrap(),
1559 self.shared.layout.krate
1562 let keywords = make_item_keywords(it);
1563 let page = layout::Page {
1564 css_class: tyname.as_str(),
1565 root_path: &self.root_path(),
1566 static_root_path: self.shared.static_root_path.as_deref(),
1569 keywords: &keywords,
1570 resource_suffix: &self.shared.resource_suffix,
1572 static_extra_scripts: &[],
1576 self.id_map.borrow_mut().reset();
1577 self.id_map.borrow_mut().populate(initial_ids());
1580 if !self.render_redirect_pages {
1582 &self.shared.layout,
1584 |buf: &mut _| print_sidebar(self, it, buf, cache),
1585 |buf: &mut _| print_item(self, it, buf, cache),
1586 &self.shared.style_files,
1589 let mut url = self.root_path();
1590 if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1591 for name in &names[..names.len() - 1] {
1595 url.push_str(&item_path(ty, names.last().unwrap()));
1596 layout::redirect(&url)
1603 /// Construct a map of items shown in the sidebar to a plain-text summary of their docs.
1604 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1605 // BTreeMap instead of HashMap to get a sorted output
1606 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1607 for item in &m.items {
1608 if item.is_stripped() {
1612 let short = item.type_();
1613 let myname = match item.name {
1615 Some(ref s) => s.to_string(),
1617 let short = short.to_string();
1618 map.entry(short).or_default().push((
1620 Some(item.doc_value().map_or_else(|| String::new(), plain_text_summary)),
1624 if self.shared.sort_modules_alphabetically {
1625 for items in map.values_mut() {
1632 /// Generates a url appropriate for an `href` attribute back to the source of
1635 /// The url generated, when clicked, will redirect the browser back to the
1636 /// original source code.
1638 /// If `None` is returned, then a source link couldn't be generated. This
1639 /// may happen, for example, with externally inlined items where the source
1640 /// of their crate documentation isn't known.
1641 fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1642 let mut root = self.root_path();
1643 let mut path = String::new();
1644 let cnum = item.source.cnum(self.sess());
1646 // We can safely ignore synthetic `SourceFile`s.
1647 let file = match item.source.filename(self.sess()) {
1648 FileName::Real(ref path) => path.local_path().to_path_buf(),
1654 let (krate, path) = if cnum == LOCAL_CRATE {
1655 if let Some(path) = self.shared.local_sources.get(file) {
1656 (self.shared.layout.krate.as_str(), path)
1661 let (krate, src_root) = match *cache.extern_locations.get(&cnum)? {
1662 (name, ref src, ExternalLocation::Local) => (name, src),
1663 (name, ref src, ExternalLocation::Remote(ref s)) => {
1664 root = s.to_string();
1667 (_, _, ExternalLocation::Unknown) => return None,
1670 sources::clean_path(&src_root, file, false, |component| {
1671 path.push_str(&component.to_string_lossy());
1674 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1675 fname.push(".html");
1676 path.push_str(&fname.to_string_lossy());
1677 symbol = krate.as_str();
1681 let loline = item.source.lo(self.sess()).line;
1682 let hiline = item.source.hi(self.sess()).line;
1684 if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) };
1686 "{root}src/{krate}/{path}#{lines}",
1687 root = Escape(&root),
1695 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1697 F: FnOnce(&mut Buffer),
1699 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1704 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1705 debug_assert!(!item.is_stripped());
1706 // Write the breadcrumb trail header for the top
1707 write!(buf, "<h1 class=\"fqn\"><span class=\"out-of-band\">");
1708 render_stability_since_raw(
1710 item.stable_since().as_deref(),
1711 item.const_stable_since().as_deref(),
1717 "<span id=\"render-detail\">\
1718 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1719 title=\"collapse all docs\">\
1720 [<span class=\"inner\">−</span>]\
1727 // When this item is part of a `crate use` in a downstream crate, the
1728 // [src] link in the downstream documentation will actually come back to
1729 // this page, and this link will be auto-clicked. The `id` attribute is
1730 // used to find the link to auto-click.
1731 if cx.shared.include_sources && !item.is_primitive() {
1732 write_srclink(cx, item, buf, cache);
1735 write!(buf, "</span>"); // out-of-band
1736 write!(buf, "<span class=\"in-band\">");
1737 let name = match item.kind {
1738 clean::ModuleItem(ref m) => {
1745 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1746 clean::TraitItem(..) => "Trait ",
1747 clean::StructItem(..) => "Struct ",
1748 clean::UnionItem(..) => "Union ",
1749 clean::EnumItem(..) => "Enum ",
1750 clean::TypedefItem(..) => "Type Definition ",
1751 clean::MacroItem(..) => "Macro ",
1752 clean::ProcMacroItem(ref mac) => match mac.kind {
1753 MacroKind::Bang => "Macro ",
1754 MacroKind::Attr => "Attribute Macro ",
1755 MacroKind::Derive => "Derive Macro ",
1757 clean::PrimitiveItem(..) => "Primitive Type ",
1758 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1759 clean::ConstantItem(..) => "Constant ",
1760 clean::ForeignTypeItem => "Foreign Type ",
1761 clean::KeywordItem(..) => "Keyword ",
1762 clean::OpaqueTyItem(..) => "Opaque Type ",
1763 clean::TraitAliasItem(..) => "Trait Alias ",
1765 // We don't generate pages for any other type.
1769 buf.write_str(name);
1770 if !item.is_primitive() && !item.is_keyword() {
1771 let cur = &cx.current;
1772 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1773 for (i, component) in cur.iter().enumerate().take(amt) {
1776 "<a href=\"{}index.html\">{}</a>::<wbr>",
1777 "../".repeat(cur.len() - i - 1),
1782 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
1784 write!(buf, "</span></h1>"); // in-band
1787 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1788 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1789 item_function(buf, cx, item, f)
1791 clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1792 clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1793 clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1794 clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1795 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1796 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1797 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1798 clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1799 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1800 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1801 clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1802 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1803 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e, cache),
1804 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1806 // We don't generate pages for any other type.
1812 fn item_path(ty: ItemType, name: &str) -> String {
1814 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1815 _ => format!("{}.{}.html", ty, name),
1819 fn full_path(cx: &Context, item: &clean::Item) -> String {
1820 let mut s = cx.current.join("::");
1822 s.push_str(&item.name.unwrap().as_str());
1826 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item, parent: Option<&clean::Item>) {
1827 if let Some(ref name) = item.name {
1828 info!("Documenting {}", name);
1830 document_item_info(w, cx, item, false, parent);
1831 document_full(w, item, cx, "", false);
1834 /// Render md_text as markdown.
1839 links: Vec<RenderedLink>,
1843 let mut ids = cx.id_map.borrow_mut();
1846 "<div class=\"docblock{}\">{}{}</div>",
1847 if is_hidden { " hidden" } else { "" },
1855 &cx.shared.playground
1861 /// Writes a documentation block containing only the first paragraph of the documentation. If the
1862 /// docs are longer, a "Read more" link is appended to the end.
1867 link: AssocItemLink<'_>,
1870 parent: Option<&clean::Item>,
1871 show_def_docs: bool,
1873 document_item_info(w, cx, item, is_hidden, parent);
1877 if let Some(s) = item.doc_value() {
1878 let mut summary_html = MarkdownSummaryLine(s, &item.links()).into_string();
1880 if s.contains('\n') {
1881 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link));
1883 if let Some(idx) = summary_html.rfind("</p>") {
1884 summary_html.insert_str(idx, &link);
1886 summary_html.push_str(&link);
1892 "<div class='docblock{}'>{}{}</div>",
1893 if is_hidden { " hidden" } else { "" },
1897 } else if !prefix.is_empty() {
1900 "<div class=\"docblock{}\">{}</div>",
1901 if is_hidden { " hidden" } else { "" },
1907 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1908 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1909 debug!("Doc block: =====\n{}\n=====", s);
1910 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1911 } else if !prefix.is_empty() {
1914 "<div class=\"docblock{}\">{}</div>",
1915 if is_hidden { " hidden" } else { "" },
1921 /// Add extra information about an item such as:
1925 /// * Required features (through the `doc_cfg` feature)
1926 fn document_item_info(
1931 parent: Option<&clean::Item>,
1933 let item_infos = short_item_info(item, cx, parent);
1934 if !item_infos.is_empty() {
1935 write!(w, "<div class=\"item-info{}\">", if is_hidden { " hidden" } else { "" });
1936 for info in item_infos {
1937 write!(w, "{}", info);
1939 write!(w, "</div>");
1943 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1944 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1947 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1948 if item.is_non_exhaustive() {
1949 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1950 if item.is_struct() {
1952 } else if item.is_enum() {
1954 } else if item.is_variant() {
1961 if item.is_struct() {
1964 "Non-exhaustive structs could have additional fields added in future. \
1965 Therefore, non-exhaustive structs cannot be constructed in external crates \
1966 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1967 matched against without a wildcard <code>..</code>; and \
1968 struct update syntax will not work."
1970 } else if item.is_enum() {
1973 "Non-exhaustive enums could have additional variants added in future. \
1974 Therefore, when matching against variants of non-exhaustive enums, an \
1975 extra wildcard arm must be added to account for any future variants."
1977 } else if item.is_variant() {
1980 "Non-exhaustive enum variants could have additional fields added in future. \
1981 Therefore, non-exhaustive enum variants cannot be constructed in external \
1982 crates and cannot be matched against."
1987 "This type will require a wildcard arm in any match statements or constructors."
1991 write!(w, "</div>");
1995 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1996 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1997 /// Takes a non-numeric and a numeric part from the given &str.
1998 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1999 let i = s.find(|c: char| c.is_ascii_digit());
2000 let (a, b) = s.split_at(i.unwrap_or(s.len()));
2001 let i = b.find(|c: char| !c.is_ascii_digit());
2002 let (b, c) = b.split_at(i.unwrap_or(b.len()));
2007 while !lhs.is_empty() || !rhs.is_empty() {
2008 let (la, lb) = take_parts(&mut lhs);
2009 let (ra, rb) = take_parts(&mut rhs);
2010 // First process the non-numeric part.
2012 Ordering::Equal => (),
2015 // Then process the numeric part, if both sides have one (and they fit in a u64).
2016 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
2018 Ordering::Equal => (),
2022 // Then process the numeric part again, but this time as strings.
2024 Ordering::Equal => (),
2032 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
2033 document(w, cx, item, None);
2035 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2037 // the order of item types in the listing
2038 fn reorder(ty: ItemType) -> u8 {
2040 ItemType::ExternCrate => 0,
2041 ItemType::Import => 1,
2042 ItemType::Primitive => 2,
2043 ItemType::Module => 3,
2044 ItemType::Macro => 4,
2045 ItemType::Struct => 5,
2046 ItemType::Enum => 6,
2047 ItemType::Constant => 7,
2048 ItemType::Static => 8,
2049 ItemType::Trait => 9,
2050 ItemType::Function => 10,
2051 ItemType::Typedef => 12,
2052 ItemType::Union => 13,
2057 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2058 let ty1 = i1.type_();
2059 let ty2 = i2.type_();
2061 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
2063 let s1 = i1.stability.as_ref().map(|s| s.level);
2064 let s2 = i2.stability.as_ref().map(|s| s.level);
2065 if let (Some(a), Some(b)) = (s1, s2) {
2066 match (a.is_stable(), b.is_stable()) {
2067 (true, true) | (false, false) => {}
2068 (false, true) => return Ordering::Less,
2069 (true, false) => return Ordering::Greater,
2072 let lhs = i1.name.unwrap_or(kw::Invalid).as_str();
2073 let rhs = i2.name.unwrap_or(kw::Invalid).as_str();
2074 compare_names(&lhs, &rhs)
2077 if cx.shared.sort_modules_alphabetically {
2078 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2080 // This call is to remove re-export duplicates in cases such as:
2085 // crate trait Double { fn foo(); }
2089 // crate use foo::bar::*;
2090 // crate use foo::*;
2093 // `Double` will appear twice in the generated docs.
2095 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2096 // can be identical even if the elements are different (mostly in imports).
2097 // So in case this is an import, we keep everything by adding a "unique id"
2098 // (which is the position in the vector).
2099 indices.dedup_by_key(|i| {
2102 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
2104 if items[*i].is_import() { *i } else { 0 },
2108 debug!("{:?}", indices);
2109 let mut curty = None;
2110 for &idx in &indices {
2111 let myitem = &items[idx];
2112 if myitem.is_stripped() {
2116 let myty = Some(myitem.type_());
2117 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2118 // Put `extern crate` and `use` re-exports in the same section.
2120 } else if myty != curty {
2121 if curty.is_some() {
2122 write!(w, "</table>");
2125 let (short, name) = item_ty_to_strs(&myty.unwrap());
2128 "<h2 id=\"{id}\" class=\"section-header\">\
2129 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2130 id = cx.derive_id(short.to_owned()),
2136 clean::ExternCrateItem(ref name, ref src) => {
2137 use crate::html::format::anchor;
2140 Some(ref src) => write!(
2142 "<tr><td><code>{}extern crate {} as {};",
2143 myitem.visibility.print_with_space(),
2144 anchor(myitem.def_id, src),
2149 "<tr><td><code>{}extern crate {};",
2150 myitem.visibility.print_with_space(),
2151 anchor(myitem.def_id, name)
2154 write!(w, "</code></td></tr>");
2157 clean::ImportItem(ref import) => {
2160 "<tr><td><code>{}{}</code></td></tr>",
2161 myitem.visibility.print_with_space(),
2167 if myitem.name.is_none() {
2171 let unsafety_flag = match myitem.kind {
2172 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2173 if func.header.unsafety == hir::Unsafety::Unsafe =>
2175 "<a title=\"unsafe function\" href=\"#\"><sup>âš </sup></a>"
2180 let stab = myitem.stability_class();
2181 let add = if stab.is_some() { " " } else { "" };
2183 let doc_value = myitem.doc_value().unwrap_or("");
2186 "<tr class=\"{stab}{add}module-item\">\
2187 <td><a class=\"{class}\" href=\"{href}\" \
2188 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
2189 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
2191 name = *myitem.name.as_ref().unwrap(),
2192 stab_tags = extra_info_tags(myitem, item),
2193 docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2194 class = myitem.type_(),
2196 stab = stab.unwrap_or_else(String::new),
2197 unsafety_flag = unsafety_flag,
2198 href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()),
2199 title = [full_path(cx, myitem), myitem.type_().to_string()]
2201 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2202 .collect::<Vec<_>>()
2209 if curty.is_some() {
2210 write!(w, "</table>");
2214 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
2215 /// at the module level.
2216 fn extra_info_tags(item: &clean::Item, parent: &clean::Item) -> String {
2217 let mut tags = String::new();
2219 fn tag_html(class: &str, title: &str, contents: &str) -> String {
2220 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
2223 // The trailing space after each tag is to space it properly against the rest of the docs.
2224 if let Some(depr) = &item.deprecation {
2225 let mut message = "Deprecated";
2226 if !stability::deprecation_in_effect(
2227 depr.is_since_rustc_version,
2228 depr.since.map(|s| s.as_str()).as_deref(),
2230 message = "Deprecation planned";
2232 tags += &tag_html("deprecated", "", message);
2235 // The "rustc_private" crates are permanently unstable so it makes no sense
2236 // to render "unstable" everywhere.
2237 if item.stability.as_ref().map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2240 tags += &tag_html("unstable", "", "Experimental");
2243 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2244 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2245 (cfg, _) => cfg.as_deref().cloned(),
2248 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2249 if let Some(ref cfg) = cfg {
2250 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2256 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2257 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2258 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2259 (cfg, _) => cfg.as_deref().cloned(),
2263 "Portability {:?} - {:?} = {:?}",
2265 parent.and_then(|p| p.attrs.cfg.as_ref()),
2269 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2272 /// Render the stability, deprecation and portability information that is displayed at the top of
2273 /// the item's documentation.
2274 fn short_item_info(item: &clean::Item, cx: &Context, parent: Option<&clean::Item>) -> Vec<String> {
2275 let mut extra_info = vec![];
2276 let error_codes = cx.shared.codes;
2278 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
2281 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2282 // but only display the future-deprecation messages for #[rustc_deprecated].
2283 let mut message = if let Some(since) = since {
2284 let since = &since.as_str();
2285 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2286 if *since == "TBD" {
2287 format!("Deprecating in a future Rust version")
2289 format!("Deprecating in {}", Escape(since))
2292 format!("Deprecated since {}", Escape(since))
2295 String::from("Deprecated")
2298 if let Some(note) = note {
2299 let note = note.as_str();
2300 let mut ids = cx.id_map.borrow_mut();
2301 let html = MarkdownHtml(
2306 &cx.shared.playground,
2308 message.push_str(&format!(": {}", html.into_string()));
2310 extra_info.push(format!(
2311 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2316 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2317 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2318 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2321 .filter(|stab| stab.feature != sym::rustc_private)
2322 .map(|stab| (stab.level, stab.feature))
2325 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2327 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2328 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2329 feature.push_str(&format!(
2330 " <a href=\"{url}{issue}\">#{issue}</a>",
2336 message.push_str(&format!(" ({})", feature));
2338 if let Some(unstable_reason) = reason {
2339 let mut ids = cx.id_map.borrow_mut();
2341 "<details><summary>{}</summary>{}</details>",
2344 &unstable_reason.as_str(),
2348 &cx.shared.playground,
2354 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2357 if let Some(portability) = portability(item, parent) {
2358 extra_info.push(portability);
2364 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2365 write!(w, "<pre class=\"rust const\">");
2366 render_attributes(w, it, false);
2370 "{vis}const {name}: {typ}",
2371 vis = it.visibility.print_with_space(),
2372 name = it.name.as_ref().unwrap(),
2373 typ = c.type_.print(),
2376 if c.value.is_some() || c.is_literal {
2377 write!(w, " = {expr};", expr = Escape(&c.expr));
2382 if let Some(value) = &c.value {
2384 let value_lowercase = value.to_lowercase();
2385 let expr_lowercase = c.expr.to_lowercase();
2387 if value_lowercase != expr_lowercase
2388 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2390 write!(w, " // {value}", value = Escape(value));
2395 write!(w, "</pre>");
2396 document(w, cx, it, None)
2399 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2400 write!(w, "<pre class=\"rust static\">");
2401 render_attributes(w, it, false);
2404 "{vis}static {mutability}{name}: {typ}</pre>",
2405 vis = it.visibility.print_with_space(),
2406 mutability = s.mutability.print_with_space(),
2407 name = it.name.as_ref().unwrap(),
2408 typ = s.type_.print()
2410 document(w, cx, it, None)
2413 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2414 let header_len = format!(
2415 "{}{}{}{}{:#}fn {}{:#}",
2416 it.visibility.print_with_space(),
2417 f.header.constness.print_with_space(),
2418 f.header.asyncness.print_with_space(),
2419 f.header.unsafety.print_with_space(),
2420 print_abi_with_space(f.header.abi),
2421 it.name.as_ref().unwrap(),
2425 write!(w, "<pre class=\"rust fn\">");
2426 render_attributes(w, it, false);
2429 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2430 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2431 vis = it.visibility.print_with_space(),
2432 constness = f.header.constness.print_with_space(),
2433 asyncness = f.header.asyncness.print_with_space(),
2434 unsafety = f.header.unsafety.print_with_space(),
2435 abi = print_abi_with_space(f.header.abi),
2436 name = it.name.as_ref().unwrap(),
2437 generics = f.generics.print(),
2438 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2439 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2441 spotlight = spotlight_decl(&f.decl),
2443 document(w, cx, it, None)
2446 fn render_implementor(
2449 parent: &clean::Item,
2451 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2455 // If there's already another implementor that has the same abbridged name, use the
2456 // full path, for example in `std::iter::ExactSizeIterator`
2457 let use_absolute = match implementor.inner_impl().for_ {
2458 clean::ResolvedPath { ref path, is_generic: false, .. }
2459 | clean::BorrowedRef {
2460 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2462 } => implementor_dups[path.last_name()].1,
2470 AssocItemLink::Anchor(None),
2472 implementor.impl_item.stable_since().as_deref(),
2473 implementor.impl_item.const_stable_since().as_deref(),
2487 containing_item: &clean::Item,
2490 let mut impls = traits
2493 let did = i.trait_did().unwrap();
2494 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2495 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2503 containing_item.stable_since().as_deref(),
2504 containing_item.const_stable_since().as_deref(),
2514 .collect::<Vec<_>>();
2516 w.write_str(&impls.join(""));
2519 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2520 let mut bounds = String::new();
2521 if !t_bounds.is_empty() {
2523 bounds.push_str(": ");
2525 for (i, p) in t_bounds.iter().enumerate() {
2527 bounds.push_str(" + ");
2529 bounds.push_str(&p.print().to_string());
2535 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2536 let lhs = format!("{}", lhs.inner_impl().print());
2537 let rhs = format!("{}", rhs.inner_impl().print());
2539 // lhs and rhs are formatted as HTML, which may be unnecessary
2540 compare_names(&lhs, &rhs)
2543 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2544 let bounds = bounds(&t.bounds, false);
2545 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2546 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2547 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2548 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2550 // Output the trait definition
2551 wrap_into_docblock(w, |w| {
2552 write!(w, "<pre class=\"rust trait\">");
2553 render_attributes(w, it, true);
2556 "{}{}{}trait {}{}{}",
2557 it.visibility.print_with_space(),
2558 t.unsafety.print_with_space(),
2559 if t.is_auto { "auto " } else { "" },
2560 it.name.as_ref().unwrap(),
2565 if !t.generics.where_predicates.is_empty() {
2566 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2571 if t.items.is_empty() {
2574 // FIXME: we should be using a derived_id for the Anchors here
2577 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2580 if !types.is_empty() && !consts.is_empty() {
2584 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2587 if !consts.is_empty() && !required.is_empty() {
2590 for (pos, m) in required.iter().enumerate() {
2591 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2594 if pos < required.len() - 1 {
2595 write!(w, "<div class=\"item-spacer\"></div>");
2598 if !required.is_empty() && !provided.is_empty() {
2601 for (pos, m) in provided.iter().enumerate() {
2602 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2604 clean::MethodItem(ref inner, _)
2605 if !inner.generics.where_predicates.is_empty() =>
2607 write!(w, ",\n {{ ... }}\n");
2610 write!(w, " {{ ... }}\n");
2613 if pos < provided.len() - 1 {
2614 write!(w, "<div class=\"item-spacer\"></div>");
2622 // Trait documentation
2623 document(w, cx, it, None);
2625 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2628 "<h2 id=\"{0}\" class=\"small-section-header\">\
2629 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2631 id, title, extra_content
2635 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2636 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2639 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item, cache: &Cache) {
2640 let name = m.name.as_ref().unwrap();
2641 info!("Documenting {} on {:?}", name, t.name);
2642 let item_type = m.type_();
2643 let id = cx.derive_id(format!("{}.{}", item_type, name));
2644 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2645 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2646 write!(w, "</code>");
2647 render_stability_since(w, m, t);
2648 write_srclink(cx, m, w, cache);
2650 document(w, cx, m, Some(t));
2653 if !types.is_empty() {
2654 write_small_section_header(
2658 "<div class=\"methods\">",
2661 trait_item(w, cx, t, it, cache);
2663 write_loading_content(w, "</div>");
2666 if !consts.is_empty() {
2667 write_small_section_header(
2670 "Associated Constants",
2671 "<div class=\"methods\">",
2674 trait_item(w, cx, t, it, cache);
2676 write_loading_content(w, "</div>");
2679 // Output the documentation for each function individually
2680 if !required.is_empty() {
2681 write_small_section_header(
2685 "<div class=\"methods\">",
2688 trait_item(w, cx, m, it, cache);
2690 write_loading_content(w, "</div>");
2692 if !provided.is_empty() {
2693 write_small_section_header(
2697 "<div class=\"methods\">",
2700 trait_item(w, cx, m, it, cache);
2702 write_loading_content(w, "</div>");
2705 // If there are methods directly on this trait object, render them here.
2706 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2708 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2709 // The DefId is for the first Type found with that name. The bool is
2710 // if any Types with the same name but different DefId have been found.
2711 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2712 for implementor in implementors {
2713 match implementor.inner_impl().for_ {
2714 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2715 | clean::BorrowedRef {
2716 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2719 let &mut (prev_did, ref mut has_duplicates) =
2720 implementor_dups.entry(path.last_name()).or_insert((did, false));
2721 if prev_did != did {
2722 *has_duplicates = true;
2729 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2730 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2733 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2734 local.iter().partition(|i| i.inner_impl().synthetic);
2736 synthetic.sort_by(compare_impl);
2737 concrete.sort_by(compare_impl);
2739 if !foreign.is_empty() {
2740 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2742 for implementor in foreign {
2743 let assoc_link = AssocItemLink::GotoSource(
2744 implementor.impl_item.def_id,
2745 &implementor.inner_impl().provided_trait_methods,
2754 implementor.impl_item.stable_since().as_deref(),
2755 implementor.impl_item.const_stable_since().as_deref(),
2764 write_loading_content(w, "");
2767 write_small_section_header(
2771 "<div class=\"item-list\" id=\"implementors-list\">",
2773 for implementor in concrete {
2774 render_implementor(cx, implementor, it, w, &implementor_dups, &[], cache);
2776 write_loading_content(w, "</div>");
2779 write_small_section_header(
2781 "synthetic-implementors",
2782 "Auto implementors",
2783 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2785 for implementor in synthetic {
2792 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2796 write_loading_content(w, "</div>");
2799 // even without any implementations to write in, we still want the heading and list, so the
2800 // implementors javascript file pulled in below has somewhere to write the impls into
2801 write_small_section_header(
2805 "<div class=\"item-list\" id=\"implementors-list\">",
2807 write_loading_content(w, "</div>");
2810 write_small_section_header(
2812 "synthetic-implementors",
2813 "Auto implementors",
2814 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2816 write_loading_content(w, "</div>");
2822 "<script type=\"text/javascript\" \
2823 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2825 root_path = vec![".."; cx.current.len()].join("/"),
2826 path = if it.def_id.is_local() {
2827 cx.current.join("/")
2829 let (ref path, _) = cache.external_paths[&it.def_id];
2830 path[..path.len() - 1].join("/")
2833 name = *it.name.as_ref().unwrap()
2837 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2838 use crate::formats::item_type::ItemType::*;
2840 let name = it.name.as_ref().unwrap();
2841 let ty = match it.type_() {
2842 Typedef | AssocType => AssocType,
2846 let anchor = format!("#{}.{}", ty, name);
2848 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2849 AssocItemLink::Anchor(None) => anchor,
2850 AssocItemLink::GotoSource(did, _) => {
2851 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2860 _default: Option<&String>,
2861 link: AssocItemLink<'_>,
2866 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2868 it.visibility.print_with_space(),
2869 naive_assoc_href(it, link),
2870 it.name.as_ref().unwrap(),
2878 bounds: &[clean::GenericBound],
2879 default: Option<&clean::Type>,
2880 link: AssocItemLink<'_>,
2885 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2887 naive_assoc_href(it, link),
2888 it.name.as_ref().unwrap()
2890 if !bounds.is_empty() {
2891 write!(w, ": {}", print_generic_bounds(bounds))
2893 if let Some(default) = default {
2894 write!(w, " = {}", default.print())
2898 fn render_stability_since_raw(
2901 const_ver: Option<&str>,
2902 containing_ver: Option<&str>,
2903 containing_const_ver: Option<&str>,
2905 let ver = ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2907 let const_ver = const_ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2909 if let Some(v) = ver {
2910 if let Some(cv) = const_ver {
2911 if const_ver != containing_const_ver {
2914 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2917 } else if ver != containing_ver {
2920 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2925 if ver != containing_ver {
2928 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2936 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2937 render_stability_since_raw(
2939 item.stable_since().as_deref(),
2940 item.const_stable_since().as_deref(),
2941 containing_item.stable_since().as_deref(),
2942 containing_item.const_stable_since().as_deref(),
2946 fn render_assoc_item(
2949 link: AssocItemLink<'_>,
2955 header: hir::FnHeader,
2956 g: &clean::Generics,
2958 link: AssocItemLink<'_>,
2961 let name = meth.name.as_ref().unwrap();
2962 let anchor = format!("#{}.{}", meth.type_(), name);
2963 let href = match link {
2964 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2965 AssocItemLink::Anchor(None) => anchor,
2966 AssocItemLink::GotoSource(did, provided_methods) => {
2967 // We're creating a link from an impl-item to the corresponding
2968 // trait-item and need to map the anchored type accordingly.
2969 let ty = if provided_methods.contains(&*name.as_str()) {
2975 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2978 let mut header_len = format!(
2979 "{}{}{}{}{}{:#}fn {}{:#}",
2980 meth.visibility.print_with_space(),
2981 header.constness.print_with_space(),
2982 header.asyncness.print_with_space(),
2983 header.unsafety.print_with_space(),
2984 print_default_space(meth.is_default()),
2985 print_abi_with_space(header.abi),
2990 let (indent, end_newline) = if parent == ItemType::Trait {
2996 render_attributes(w, meth, false);
2999 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
3000 {generics}{decl}{spotlight}{where_clause}",
3001 if parent == ItemType::Trait { " " } else { "" },
3002 meth.visibility.print_with_space(),
3003 header.constness.print_with_space(),
3004 header.asyncness.print_with_space(),
3005 header.unsafety.print_with_space(),
3006 print_default_space(meth.is_default()),
3007 print_abi_with_space(header.abi),
3010 generics = g.print(),
3011 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
3012 spotlight = spotlight_decl(&d),
3013 where_clause = WhereClause { gens: g, indent, end_newline }
3017 clean::StrippedItem(..) => {}
3018 clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
3019 clean::MethodItem(ref m, _) => {
3020 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3022 clean::AssocConstItem(ref ty, ref default) => assoc_const(
3028 if parent == ItemType::Trait { " " } else { "" },
3030 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3036 if parent == ItemType::Trait { " " } else { "" },
3038 _ => panic!("render_assoc_item called on non-associated-item"),
3042 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
3043 wrap_into_docblock(w, |w| {
3044 write!(w, "<pre class=\"rust struct\">");
3045 render_attributes(w, it, true);
3046 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
3050 document(w, cx, it, None);
3054 .filter_map(|f| match f.kind {
3055 clean::StructFieldItem(ref ty) => Some((f, ty)),
3059 if let doctree::Plain = s.struct_type {
3060 if fields.peek().is_some() {
3063 "<h2 id=\"fields\" class=\"fields small-section-header\">
3064 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3065 document_non_exhaustive_header(it)
3067 document_non_exhaustive(w, it);
3068 for (field, ty) in fields {
3069 let id = cx.derive_id(format!(
3071 ItemType::StructField,
3072 field.name.as_ref().unwrap()
3076 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3077 <a href=\"#{id}\" class=\"anchor field\"></a>\
3078 <code>{name}: {ty}</code>\
3080 item_type = ItemType::StructField,
3082 name = field.name.as_ref().unwrap(),
3085 document(w, cx, field, Some(it));
3089 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3092 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
3093 wrap_into_docblock(w, |w| {
3094 write!(w, "<pre class=\"rust union\">");
3095 render_attributes(w, it, true);
3096 render_union(w, it, Some(&s.generics), &s.fields, "", true);
3100 document(w, cx, it, None);
3104 .filter_map(|f| match f.kind {
3105 clean::StructFieldItem(ref ty) => Some((f, ty)),
3109 if fields.peek().is_some() {
3112 "<h2 id=\"fields\" class=\"fields small-section-header\">
3113 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3115 for (field, ty) in fields {
3116 let name = field.name.as_ref().expect("union field name");
3117 let id = format!("{}.{}", ItemType::StructField, name);
3120 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3121 <a href=\"#{id}\" class=\"anchor field\"></a>\
3122 <code>{name}: {ty}</code>\
3126 shortty = ItemType::StructField,
3129 if let Some(stability_class) = field.stability_class() {
3130 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3132 document(w, cx, field, Some(it));
3135 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3138 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
3139 wrap_into_docblock(w, |w| {
3140 write!(w, "<pre class=\"rust enum\">");
3141 render_attributes(w, it, true);
3145 it.visibility.print_with_space(),
3146 it.name.as_ref().unwrap(),
3148 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
3150 if e.variants.is_empty() && !e.variants_stripped {
3154 for v in &e.variants {
3156 let name = v.name.as_ref().unwrap();
3158 clean::VariantItem(ref var) => match var.kind {
3159 clean::VariantKind::CLike => write!(w, "{}", name),
3160 clean::VariantKind::Tuple(ref tys) => {
3161 write!(w, "{}(", name);
3162 for (i, ty) in tys.iter().enumerate() {
3164 write!(w, ", ")
3166 write!(w, "{}", ty.print());
3170 clean::VariantKind::Struct(ref s) => {
3171 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
3174 _ => unreachable!(),
3179 if e.variants_stripped {
3180 write!(w, " // some variants omitted\n");
3187 document(w, cx, it, None);
3188 if !e.variants.is_empty() {
3191 "<h2 id=\"variants\" class=\"variants small-section-header\">
3192 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3193 document_non_exhaustive_header(it)
3195 document_non_exhaustive(w, it);
3196 for variant in &e.variants {
3198 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3201 "<div id=\"{id}\" class=\"variant small-section-header\">\
3202 <a href=\"#{id}\" class=\"anchor field\"></a>\
3205 name = variant.name.as_ref().unwrap()
3207 if let clean::VariantItem(ref var) = variant.kind {
3208 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3210 for (i, ty) in tys.iter().enumerate() {
3212 write!(w, ", ");
3214 write!(w, "{}", ty.print());
3219 write!(w, "</code></div>");
3220 document(w, cx, variant, Some(it));
3221 document_non_exhaustive(w, variant);
3223 use crate::clean::{Variant, VariantKind};
3224 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.kind {
3225 let variant_id = cx.derive_id(format!(
3228 variant.name.as_ref().unwrap()
3230 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3233 "<h3>Fields of <b>{name}</b></h3><div>",
3234 name = variant.name.as_ref().unwrap()
3236 for field in &s.fields {
3237 use crate::clean::StructFieldItem;
3238 if let StructFieldItem(ref ty) = field.kind {
3239 let id = cx.derive_id(format!(
3240 "variant.{}.field.{}",
3241 variant.name.as_ref().unwrap(),
3242 field.name.as_ref().unwrap()
3246 "<span id=\"{id}\" class=\"variant small-section-header\">\
3247 <a href=\"#{id}\" class=\"anchor field\"></a>\
3248 <code>{f}: {t}</code>\
3251 f = field.name.as_ref().unwrap(),
3254 document(w, cx, field, Some(variant));
3257 write!(w, "</div></div>");
3259 render_stability_since(w, variant, it);
3262 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3265 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3272 sym::non_exhaustive,
3275 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3276 // left padding. For example:
3278 // #[foo] <----- "top" attribute
3280 // #[bar] <---- not "top" attribute
3283 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3288 .filter_map(|attr| {
3289 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3290 Some(pprust::attribute_to_string(&attr))
3297 if !attrs.is_empty() {
3300 "<span class=\"docblock attributes{}\">{}</span>",
3301 if top { " top-attr" } else { "" },
3310 g: Option<&clean::Generics>,
3311 ty: doctree::StructType,
3312 fields: &[clean::Item],
3319 it.visibility.print_with_space(),
3320 if structhead { "struct " } else { "" },
3321 it.name.as_ref().unwrap()
3323 if let Some(g) = g {
3324 write!(w, "{}", g.print())
3328 if let Some(g) = g {
3329 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3331 let mut has_visible_fields = false;
3333 for field in fields {
3334 if let clean::StructFieldItem(ref ty) = field.kind {
3339 field.visibility.print_with_space(),
3340 field.name.as_ref().unwrap(),
3343 has_visible_fields = true;
3347 if has_visible_fields {
3348 if it.has_stripped_fields().unwrap() {
3349 write!(w, "\n{} // some fields omitted", tab);
3351 write!(w, "\n{}", tab);
3352 } else if it.has_stripped_fields().unwrap() {
3353 // If there are no visible fields we can just display
3354 // `{ /* fields omitted */ }` to save space.
3355 write!(w, " /* fields omitted */ ");
3361 for (i, field) in fields.iter().enumerate() {
3366 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3367 clean::StructFieldItem(ref ty) => {
3368 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3370 _ => unreachable!(),
3374 if let Some(g) = g {
3375 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3380 // Needed for PhantomData.
3381 if let Some(g) = g {
3382 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3392 g: Option<&clean::Generics>,
3393 fields: &[clean::Item],
3400 it.visibility.print_with_space(),
3401 if structhead { "union " } else { "" },
3402 it.name.as_ref().unwrap()
3404 if let Some(g) = g {
3405 write!(w, "{}", g.print());
3406 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3409 write!(w, " {{\n{}", tab);
3410 for field in fields {
3411 if let clean::StructFieldItem(ref ty) = field.kind {
3415 field.visibility.print_with_space(),
3416 field.name.as_ref().unwrap(),
3423 if it.has_stripped_fields().unwrap() {
3424 write!(w, " // some fields omitted\n{}", tab);
3429 #[derive(Copy, Clone)]
3430 enum AssocItemLink<'a> {
3431 Anchor(Option<&'a str>),
3432 GotoSource(DefId, &'a FxHashSet<String>),
3435 impl<'a> AssocItemLink<'a> {
3436 fn anchor(&self, id: &'a String) -> Self {
3438 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3439 ref other => *other,
3444 fn render_assoc_items(
3447 containing_item: &clean::Item,
3449 what: AssocItemRender<'_>,
3452 info!("Documenting associated items of {:?}", containing_item.name);
3453 let v = match cache.impls.get(&it) {
3457 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3458 if !non_trait.is_empty() {
3459 let render_mode = match what {
3460 AssocItemRender::All => {
3463 "<h2 id=\"implementations\" class=\"small-section-header\">\
3464 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3469 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3472 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
3473 Methods from {}<Target = {}>\
3474 <a href=\"#deref-methods\" class=\"anchor\"></a>\
3479 RenderMode::ForDeref { mut_: deref_mut_ }
3482 for i in &non_trait {
3488 AssocItemLink::Anchor(None),
3490 containing_item.stable_since().as_deref(),
3491 containing_item.const_stable_since().as_deref(),
3501 if let AssocItemRender::DerefFor { .. } = what {
3504 if !traits.is_empty() {
3506 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3507 if let Some(impl_) = deref_impl {
3509 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3510 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3513 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3514 traits.iter().partition(|t| t.inner_impl().synthetic);
3515 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3516 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3518 let mut impls = Buffer::empty_from(&w);
3519 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3520 let impls = impls.into_inner();
3521 if !impls.is_empty() {
3524 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3525 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3527 <div id=\"trait-implementations-list\">{}</div>",
3532 if !synthetic.is_empty() {
3535 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3536 Auto Trait Implementations\
3537 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3539 <div id=\"synthetic-implementations-list\">"
3541 render_impls(cx, w, &synthetic, containing_item, cache);
3542 write!(w, "</div>");
3545 if !blanket_impl.is_empty() {
3548 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3549 Blanket Implementations\
3550 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3552 <div id=\"blanket-implementations-list\">"
3554 render_impls(cx, w, &blanket_impl, containing_item, cache);
3555 write!(w, "</div>");
3560 fn render_deref_methods(
3564 container_item: &clean::Item,
3568 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3569 let (target, real_target) = impl_
3573 .find_map(|item| match item.kind {
3574 clean::TypedefItem(ref t, true) => Some(match *t {
3575 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3576 _ => (&t.type_, &t.type_),
3580 .expect("Expected associated type binding");
3582 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3583 if let Some(did) = target.def_id() {
3584 render_assoc_items(w, cx, container_item, did, what, cache);
3586 if let Some(prim) = target.primitive_type() {
3587 if let Some(&did) = cache.primitive_locations.get(&prim) {
3588 render_assoc_items(w, cx, container_item, did, what, cache);
3594 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3595 let self_type_opt = match item.kind {
3596 clean::MethodItem(ref method, _) => method.decl.self_type(),
3597 clean::TyMethodItem(ref method) => method.decl.self_type(),
3601 if let Some(self_ty) = self_type_opt {
3602 let (by_mut_ref, by_box, by_value) = match self_ty {
3603 SelfTy::SelfBorrowed(_, mutability)
3604 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3605 (mutability == Mutability::Mut, false, false)
3607 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3608 (false, Some(did) == cache().owned_box_did, false)
3610 SelfTy::SelfValue => (false, false, true),
3611 _ => (false, false, false),
3614 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3620 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3621 let mut out = Buffer::html();
3622 let mut trait_ = String::new();
3624 if let Some(did) = decl.output.def_id() {
3626 if let Some(impls) = c.impls.get(&did) {
3628 let impl_ = i.inner_impl();
3629 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3631 out.push_str(&format!(
3632 "<h3 class=\"notable\">Notable traits for {}</h3>\
3633 <code class=\"content\">",
3636 trait_.push_str(&impl_.for_.print().to_string());
3639 //use the "where" class here to make it small
3640 out.push_str(&format!(
3641 "<span class=\"where fmt-newline\">{}</span>",
3644 let t_did = impl_.trait_.def_id().unwrap();
3645 for it in &impl_.items {
3646 if let clean::TypedefItem(ref tydef, _) = it.kind {
3647 out.push_str("<span class=\"where fmt-newline\"> ");
3653 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3656 out.push_str(";</span>");
3664 if !out.is_empty() {
3667 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3668 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3670 out.push_str("</code></span></div></span></span>");
3680 parent: &clean::Item,
3681 link: AssocItemLink<'_>,
3682 render_mode: RenderMode,
3683 outer_version: Option<&str>,
3684 outer_const_version: Option<&str>,
3685 show_def_docs: bool,
3686 use_absolute: Option<bool>,
3687 is_on_foreign_type: bool,
3688 show_default_items: bool,
3689 // This argument is used to reference same type with different paths to avoid duplication
3690 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3694 let traits = &cache.traits;
3695 let trait_ = i.trait_did().map(|did| &traits[&did]);
3697 if render_mode == RenderMode::Normal {
3698 let id = cx.derive_id(match i.inner_impl().trait_ {
3700 if is_on_foreign_type {
3701 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3703 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3706 None => "impl".to_string(),
3708 let aliases = if aliases.is_empty() {
3711 format!(" aliases=\"{}\"", aliases.join(","))
3713 if let Some(use_absolute) = use_absolute {
3714 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3715 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3717 for it in &i.inner_impl().items {
3718 if let clean::TypedefItem(ref tydef, _) = it.kind {
3719 write!(w, "<span class=\"where fmt-newline\"> ");
3720 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3721 write!(w, ";</span>");
3725 write!(w, "</code>");
3729 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3732 i.inner_impl().print()
3735 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3736 render_stability_since_raw(
3738 i.impl_item.stable_since().as_deref(),
3739 i.impl_item.const_stable_since().as_deref(),
3741 outer_const_version,
3743 write_srclink(cx, &i.impl_item, w, cache);
3746 if trait_.is_some() {
3747 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3748 write!(w, "<div class=\"item-info\">{}</div>", portability);
3752 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3753 let mut ids = cx.id_map.borrow_mut();
3756 "<div class=\"docblock\">{}</div>",
3759 &i.impl_item.links(),
3763 &cx.shared.playground
3774 parent: &clean::Item,
3775 link: AssocItemLink<'_>,
3776 render_mode: RenderMode,
3777 is_default_item: bool,
3778 outer_version: Option<&str>,
3779 outer_const_version: Option<&str>,
3780 trait_: Option<&clean::Trait>,
3781 show_def_docs: bool,
3784 let item_type = item.type_();
3785 let name = item.name.as_ref().unwrap();
3787 let render_method_item = match render_mode {
3788 RenderMode::Normal => true,
3789 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3792 let (is_hidden, extra_class) =
3793 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3801 clean::MethodItem(..) | clean::TyMethodItem(_) => {
3802 // Only render when the method is not static or we allow static methods
3803 if render_method_item {
3804 let id = cx.derive_id(format!("{}.{}", item_type, name));
3805 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3806 write!(w, "<code>");
3807 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3808 write!(w, "</code>");
3809 render_stability_since_raw(
3811 item.stable_since().as_deref(),
3812 item.const_stable_since().as_deref(),
3814 outer_const_version,
3816 write_srclink(cx, item, w, cache);
3820 clean::TypedefItem(ref tydef, _) => {
3821 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3822 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3823 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3824 write!(w, "</code></h4>");
3826 clean::AssocConstItem(ref ty, ref default) => {
3827 let id = cx.derive_id(format!("{}.{}", item_type, name));
3828 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3829 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3830 write!(w, "</code>");
3831 render_stability_since_raw(
3833 item.stable_since().as_deref(),
3834 item.const_stable_since().as_deref(),
3836 outer_const_version,
3838 write_srclink(cx, item, w, cache);
3841 clean::AssocTypeItem(ref bounds, ref default) => {
3842 let id = cx.derive_id(format!("{}.{}", item_type, name));
3843 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3844 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3845 write!(w, "</code></h4>");
3847 clean::StrippedItem(..) => return,
3848 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3851 if render_method_item {
3852 if !is_default_item {
3853 if let Some(t) = trait_ {
3854 // The trait item may have been stripped so we might not
3855 // find any documentation or stability for it.
3856 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3857 // We need the stability of the item from the trait
3858 // because impls can't have a stability.
3859 if item.doc_value().is_some() {
3860 document_item_info(w, cx, it, is_hidden, Some(parent));
3861 document_full(w, item, cx, "", is_hidden);
3863 // In case the item isn't documented,
3864 // provide short documentation from the trait.
3878 document_item_info(w, cx, item, is_hidden, Some(parent));
3880 document_full(w, item, cx, "", is_hidden);
3884 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3889 write!(w, "<div class=\"impl-items\">");
3890 for trait_item in &i.inner_impl().items {
3895 if trait_.is_some() { &i.impl_item } else { parent },
3900 outer_const_version,
3907 fn render_default_items(
3912 parent: &clean::Item,
3913 render_mode: RenderMode,
3914 outer_version: Option<&str>,
3915 outer_const_version: Option<&str>,
3916 show_def_docs: bool,
3919 for trait_item in &t.items {
3920 let n = trait_item.name.clone();
3921 if i.items.iter().any(|m| m.name == n) {
3924 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3925 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3936 outer_const_version,
3944 // If we've implemented a trait, then also emit documentation for all
3945 // default items which weren't overridden in the implementation block.
3946 // We don't emit documentation for default items if they appear in the
3947 // Implementations on Foreign Types or Implementors sections.
3948 if show_default_items {
3949 if let Some(t) = trait_ {
3950 render_default_items(
3958 outer_const_version,
3964 write!(w, "</div>");
3971 t: &clean::OpaqueTy,
3974 write!(w, "<pre class=\"rust opaque\">");
3975 render_attributes(w, it, false);
3978 "type {}{}{where_clause} = impl {bounds};</pre>",
3979 it.name.as_ref().unwrap(),
3981 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3982 bounds = bounds(&t.bounds, false)
3985 document(w, cx, it, None);
3987 // Render any items associated directly to this alias, as otherwise they
3988 // won't be visible anywhere in the docs. It would be nice to also show
3989 // associated items from the aliased type (see discussion in #32077), but
3990 // we need #14072 to make sense of the generics.
3991 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3994 fn item_trait_alias(
3998 t: &clean::TraitAlias,
4001 write!(w, "<pre class=\"rust trait-alias\">");
4002 render_attributes(w, it, false);
4005 "trait {}{}{} = {};</pre>",
4006 it.name.as_ref().unwrap(),
4008 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4009 bounds(&t.bounds, true)
4012 document(w, cx, it, None);
4014 // Render any items associated directly to this alias, as otherwise they
4015 // won't be visible anywhere in the docs. It would be nice to also show
4016 // associated items from the aliased type (see discussion in #32077), but
4017 // we need #14072 to make sense of the generics.
4018 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4021 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
4022 write!(w, "<pre class=\"rust typedef\">");
4023 render_attributes(w, it, false);
4026 "type {}{}{where_clause} = {type_};</pre>",
4027 it.name.as_ref().unwrap(),
4029 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4030 type_ = t.type_.print()
4033 document(w, cx, it, None);
4035 // Render any items associated directly to this alias, as otherwise they
4036 // won't be visible anywhere in the docs. It would be nice to also show
4037 // associated items from the aliased type (see discussion in #32077), but
4038 // we need #14072 to make sense of the generics.
4039 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4042 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4043 writeln!(w, "<pre class=\"rust foreigntype\">extern {{");
4044 render_attributes(w, it, false);
4047 " {}type {};\n}}</pre>",
4048 it.visibility.print_with_space(),
4049 it.name.as_ref().unwrap(),
4052 document(w, cx, it, None);
4054 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4057 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
4058 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4062 || it.is_primitive()
4070 "<p class=\"location\">{}{}</p>",
4072 clean::StructItem(..) => "Struct ",
4073 clean::TraitItem(..) => "Trait ",
4074 clean::PrimitiveItem(..) => "Primitive Type ",
4075 clean::UnionItem(..) => "Union ",
4076 clean::EnumItem(..) => "Enum ",
4077 clean::TypedefItem(..) => "Type Definition ",
4078 clean::ForeignTypeItem => "Foreign Type ",
4079 clean::ModuleItem(..) =>
4087 it.name.as_ref().unwrap()
4092 if let Some(ref version) = cache.crate_version {
4095 "<div class=\"block version\">\
4103 write!(buffer, "<div class=\"sidebar-elems\">");
4107 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4108 it.name.as_ref().expect("crates always have a name")
4112 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
4113 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
4114 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
4115 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
4116 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
4117 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
4118 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4119 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
4123 // The sidebar is designed to display sibling functions, modules and
4124 // other miscellaneous information. since there are lots of sibling
4125 // items (and that causes quadratic growth in large modules),
4126 // we refactor common parts into a shared JavaScript file per module.
4127 // still, we don't move everything into JS because we want to preserve
4128 // as much HTML as possible in order to allow non-JS-enabled browsers
4129 // to navigate the documentation (though slightly inefficiently).
4131 write!(buffer, "<p class=\"location\">");
4132 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4134 write!(buffer, "::<wbr>");
4138 "<a href=\"{}index.html\">{}</a>",
4139 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4143 write!(buffer, "</p>");
4145 // Sidebar refers to the enclosing module, not this module.
4146 let relpath = if it.is_mod() { "../" } else { "" };
4149 "<script>window.sidebarCurrent = {{\
4152 relpath: \"{path}\"\
4154 name = it.name.unwrap_or(kw::Invalid),
4159 // There is no sidebar-items.js beyond the crate root path
4160 // FIXME maybe dynamic crate loading can be merged here
4162 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4164 // Closes sidebar-elems div.
4165 write!(buffer, "</div>");
4168 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4169 if used_links.insert(url.clone()) {
4173 while !used_links.insert(format!("{}-{}", url, add)) {
4176 format!("{}-{}", url, add)
4182 used_links: &mut FxHashSet<String>,
4187 .filter_map(|item| match item.name {
4188 Some(ref name) if !name.is_empty() && item.is_method() => {
4189 if !for_deref || should_render_item(item, deref_mut) {
4191 "<a href=\"#{}\">{}</a>",
4192 get_next_url(used_links, format!("method.{}", name)),
4201 .collect::<Vec<_>>()
4204 // The point is to url encode any potential character from a type with genericity.
4205 fn small_url_encode(s: &str) -> String {
4206 s.replace("<", "%3C")
4207 .replace(">", "%3E")
4208 .replace(" ", "%20")
4209 .replace("?", "%3F")
4210 .replace("'", "%27")
4211 .replace("&", "%26")
4212 .replace(",", "%2C")
4213 .replace(":", "%3A")
4214 .replace(";", "%3B")
4215 .replace("[", "%5B")
4216 .replace("]", "%5D")
4217 .replace("\"", "%22")
4220 fn sidebar_assoc_items(it: &clean::Item) -> String {
4221 let mut out = String::new();
4223 if let Some(v) = c.impls.get(&it.def_id) {
4224 let mut used_links = FxHashSet::default();
4227 let used_links_bor = &mut used_links;
4230 .filter(|i| i.inner_impl().trait_.is_none())
4231 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4232 .collect::<Vec<_>>();
4233 if !ret.is_empty() {
4234 // We want links' order to be reproducible so we don't use unstable sort.
4236 out.push_str(&format!(
4237 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4238 <div class=\"sidebar-links\">{}</div>",
4244 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4245 if let Some(impl_) = v
4247 .filter(|i| i.inner_impl().trait_.is_some())
4248 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4250 if let Some((target, real_target)) =
4251 impl_.inner_impl().items.iter().find_map(|item| match item.kind {
4252 clean::TypedefItem(ref t, true) => Some(match *t {
4253 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4254 _ => (&t.type_, &t.type_),
4261 .filter(|i| i.inner_impl().trait_.is_some())
4262 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4263 let inner_impl = target
4267 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4268 .and_then(|did| c.impls.get(&did));
4269 if let Some(impls) = inner_impl {
4270 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4271 out.push_str(&format!(
4272 "Methods from {}<Target={}>",
4275 impl_.inner_impl().trait_.as_ref().unwrap().print()
4277 Escape(&format!("{:#}", real_target.print()))
4279 out.push_str("</a>");
4282 .filter(|i| i.inner_impl().trait_.is_none())
4284 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4286 .collect::<Vec<_>>();
4287 // We want links' order to be reproducible so we don't use unstable sort.
4289 if !ret.is_empty() {
4290 out.push_str(&format!(
4291 "<div class=\"sidebar-links\">{}</div>",
4298 let format_impls = |impls: Vec<&Impl>| {
4299 let mut links = FxHashSet::default();
4304 let is_negative_impl = is_negative_impl(i.inner_impl());
4305 if let Some(ref i) = i.inner_impl().trait_ {
4306 let i_display = format!("{:#}", i.print());
4307 let out = Escape(&i_display);
4308 let encoded = small_url_encode(&format!("{:#}", i.print()));
4309 let generated = format!(
4310 "<a href=\"#impl-{}\">{}{}</a>",
4312 if is_negative_impl { "!" } else { "" },
4315 if links.insert(generated.clone()) { Some(generated) } else { None }
4320 .collect::<Vec<String>>();
4325 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4326 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4327 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4329 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4331 let concrete_format = format_impls(concrete);
4332 let synthetic_format = format_impls(synthetic);
4333 let blanket_format = format_impls(blanket_impl);
4335 if !concrete_format.is_empty() {
4337 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4338 Trait Implementations</a>",
4340 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4343 if !synthetic_format.is_empty() {
4345 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4346 Auto Trait Implementations</a>",
4348 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4351 if !blanket_format.is_empty() {
4353 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4354 Blanket Implementations</a>",
4356 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4364 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4365 let mut sidebar = String::new();
4366 let fields = get_struct_fields_name(&s.fields);
4368 if !fields.is_empty() {
4369 if let doctree::Plain = s.struct_type {
4370 sidebar.push_str(&format!(
4371 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4372 <div class=\"sidebar-links\">{}</div>",
4378 sidebar.push_str(&sidebar_assoc_items(it));
4380 if !sidebar.is_empty() {
4381 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4385 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4386 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4389 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4391 clean::ItemKind::ImplItem(ref i) => {
4392 if let Some(ref trait_) = i.trait_ {
4394 format!("{:#}", i.for_.print()),
4395 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4405 fn is_negative_impl(i: &clean::Impl) -> bool {
4406 i.polarity == Some(clean::ImplPolarity::Negative)
4409 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4410 let mut sidebar = String::new();
4415 .filter_map(|m| match m.name {
4416 Some(ref name) if m.is_associated_type() => {
4417 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4421 .collect::<Vec<_>>();
4425 .filter_map(|m| match m.name {
4426 Some(ref name) if m.is_associated_const() => {
4427 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4431 .collect::<Vec<_>>();
4432 let mut required = t
4435 .filter_map(|m| match m.name {
4436 Some(ref name) if m.is_ty_method() => {
4437 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4441 .collect::<Vec<String>>();
4442 let mut provided = t
4445 .filter_map(|m| match m.name {
4446 Some(ref name) if m.is_method() => {
4447 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4451 .collect::<Vec<String>>();
4453 if !types.is_empty() {
4455 sidebar.push_str(&format!(
4456 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4457 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4461 if !consts.is_empty() {
4463 sidebar.push_str(&format!(
4464 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4465 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4469 if !required.is_empty() {
4471 sidebar.push_str(&format!(
4472 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4473 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4477 if !provided.is_empty() {
4479 sidebar.push_str(&format!(
4480 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4481 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4488 if let Some(implementors) = c.implementors.get(&it.def_id) {
4489 let mut res = implementors
4491 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4492 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4493 .collect::<Vec<_>>();
4495 if !res.is_empty() {
4497 sidebar.push_str(&format!(
4498 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4499 Implementations on Foreign Types</a>\
4500 <div class=\"sidebar-links\">{}</div>",
4502 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4503 .collect::<Vec<_>>()
4509 sidebar.push_str(&sidebar_assoc_items(it));
4511 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4514 "<a class=\"sidebar-title\" \
4515 href=\"#synthetic-implementors\">Auto Implementors</a>",
4519 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4522 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4523 let sidebar = sidebar_assoc_items(it);
4525 if !sidebar.is_empty() {
4526 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4530 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4531 let sidebar = sidebar_assoc_items(it);
4533 if !sidebar.is_empty() {
4534 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4538 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4539 let mut fields = fields
4541 .filter(|f| if let clean::StructFieldItem(..) = f.kind { true } else { false })
4542 .filter_map(|f| match f.name {
4544 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4548 .collect::<Vec<_>>();
4553 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4554 let mut sidebar = String::new();
4555 let fields = get_struct_fields_name(&u.fields);
4557 if !fields.is_empty() {
4558 sidebar.push_str(&format!(
4559 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4560 <div class=\"sidebar-links\">{}</div>",
4565 sidebar.push_str(&sidebar_assoc_items(it));
4567 if !sidebar.is_empty() {
4568 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4572 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4573 let mut sidebar = String::new();
4575 let mut variants = e
4578 .filter_map(|v| match v.name {
4579 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4582 .collect::<Vec<_>>();
4583 if !variants.is_empty() {
4584 variants.sort_unstable();
4585 sidebar.push_str(&format!(
4586 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4587 <div class=\"sidebar-links\">{}</div>",
4592 sidebar.push_str(&sidebar_assoc_items(it));
4594 if !sidebar.is_empty() {
4595 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4599 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4601 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4602 ItemType::Module => ("modules", "Modules"),
4603 ItemType::Struct => ("structs", "Structs"),
4604 ItemType::Union => ("unions", "Unions"),
4605 ItemType::Enum => ("enums", "Enums"),
4606 ItemType::Function => ("functions", "Functions"),
4607 ItemType::Typedef => ("types", "Type Definitions"),
4608 ItemType::Static => ("statics", "Statics"),
4609 ItemType::Constant => ("constants", "Constants"),
4610 ItemType::Trait => ("traits", "Traits"),
4611 ItemType::Impl => ("impls", "Implementations"),
4612 ItemType::TyMethod => ("tymethods", "Type Methods"),
4613 ItemType::Method => ("methods", "Methods"),
4614 ItemType::StructField => ("fields", "Struct Fields"),
4615 ItemType::Variant => ("variants", "Variants"),
4616 ItemType::Macro => ("macros", "Macros"),
4617 ItemType::Primitive => ("primitives", "Primitive Types"),
4618 ItemType::AssocType => ("associated-types", "Associated Types"),
4619 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4620 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4621 ItemType::Keyword => ("keywords", "Keywords"),
4622 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4623 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4624 ItemType::ProcDerive => ("derives", "Derive Macros"),
4625 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4629 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4630 let mut sidebar = String::new();
4632 if items.iter().any(|it| {
4633 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4635 sidebar.push_str(&format!(
4636 "<li><a href=\"#{id}\">{name}</a></li>",
4642 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4643 // to print its headings
4645 ItemType::Primitive,
4659 ItemType::StructField,
4661 ItemType::AssocType,
4662 ItemType::AssocConst,
4663 ItemType::ForeignType,
4666 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4667 let (short, name) = item_ty_to_strs(&myty);
4668 sidebar.push_str(&format!(
4669 "<li><a href=\"#{id}\">{name}</a></li>",
4676 if !sidebar.is_empty() {
4677 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4681 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4682 let sidebar = sidebar_assoc_items(it);
4683 if !sidebar.is_empty() {
4684 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4688 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4689 wrap_into_docblock(w, |w| {
4690 w.write_str(&highlight::render_with_highlighting(
4697 document(w, cx, it, None)
4700 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4701 let name = it.name.as_ref().expect("proc-macros always have names");
4703 MacroKind::Bang => {
4704 write!(w, "<pre class=\"rust macro\">");
4705 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4706 write!(w, "</pre>");
4708 MacroKind::Attr => {
4709 write!(w, "<pre class=\"rust attr\">");
4710 write!(w, "#[{}]", name);
4711 write!(w, "</pre>");
4713 MacroKind::Derive => {
4714 write!(w, "<pre class=\"rust derive\">");
4715 write!(w, "#[derive({})]", name);
4716 if !m.helpers.is_empty() {
4717 writeln!(w, "\n{{");
4718 writeln!(w, " // Attributes available to this derive:");
4719 for attr in &m.helpers {
4720 writeln!(w, " #[{}]", attr);
4724 write!(w, "</pre>");
4727 document(w, cx, it, None)
4730 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4731 document(w, cx, it, None);
4732 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4735 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4736 document(w, cx, it, None)
4739 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4741 fn make_item_keywords(it: &clean::Item) -> String {
4742 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4745 /// Returns a list of all paths used in the type.
4746 /// This is used to help deduplicate imported impls
4747 /// for reexported types. If any of the contained
4748 /// types are re-exported, we don't use the corresponding
4749 /// entry from the js file, as inlining will have already
4750 /// picked up the impl
4751 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4752 let mut out = Vec::new();
4753 let mut visited = FxHashSet::default();
4754 let mut work = VecDeque::new();
4755 let cache = cache();
4757 work.push_back(first_ty);
4759 while let Some(ty) = work.pop_front() {
4760 if !visited.insert(ty.clone()) {
4765 clean::Type::ResolvedPath { did, .. } => {
4766 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4767 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4769 if let Some(path) = fqp {
4770 out.push(path.join("::"));
4773 clean::Type::Tuple(tys) => {
4774 work.extend(tys.into_iter());
4776 clean::Type::Slice(ty) => {
4777 work.push_back(*ty);
4779 clean::Type::Array(ty, _) => {
4780 work.push_back(*ty);
4782 clean::Type::RawPointer(_, ty) => {
4783 work.push_back(*ty);
4785 clean::Type::BorrowedRef { type_, .. } => {
4786 work.push_back(*type_);
4788 clean::Type::QPath { self_type, trait_, .. } => {
4789 work.push_back(*self_type);
4790 work.push_back(*trait_);