1 // ignore-tidy-filelength
3 //! Rustdoc's HTML rendering module.
5 //! This modules contains the bulk of the logic necessary for rendering a
6 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
7 //! rendering process is largely driven by the `format!` syntax extension to
8 //! perform all I/O into files and streams.
10 //! The rendering process is largely driven by the `Context` and `Cache`
11 //! structures. The cache is pre-populated by crawling the crate in question,
12 //! and then it is shared among the various rendering threads. The cache is meant
13 //! to be a fairly large structure not implementing `Clone` (because it's shared
14 //! among threads). The context, however, should be a lightweight structure. This
15 //! is cloned per-thread and contains information about what is currently being
18 //! In order to speed up rendering (mostly because of markdown rendering), the
19 //! rendering process has been parallelized. This parallelization is only
20 //! exposed through the `crate` method on the context, and then also from the
21 //! fact that the shared cache is stored in TLS (and must be accessed as such).
23 //! In addition to rendering the crate itself, this module is also responsible
24 //! for creating the corresponding search index and source file renderings.
25 //! These threads are not parallelized (they haven't been a bottleneck yet), and
26 //! both occur before the crate is rendered.
34 use std::cell::{Cell, RefCell};
35 use std::cmp::Ordering;
36 use std::collections::{BTreeMap, VecDeque};
37 use std::default::Default;
39 use std::fmt::{self, Write};
40 use std::fs::{self, File};
41 use std::io::prelude::*;
42 use std::io::{self, BufReader};
43 use std::path::{Component, Path, PathBuf};
46 use std::string::ToString;
47 use std::sync::mpsc::{channel, Receiver};
50 use itertools::Itertools;
51 use rustc_ast_pretty::pprust;
52 use rustc_attr::StabilityLevel;
53 use rustc_data_structures::flock;
54 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
55 use rustc_data_structures::sync::Lrc;
57 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
58 use rustc_hir::Mutability;
59 use rustc_middle::middle::stability;
60 use rustc_session::Session;
61 use rustc_span::edition::Edition;
62 use rustc_span::hygiene::MacroKind;
63 use rustc_span::source_map::FileName;
64 use rustc_span::symbol::{kw, sym, Symbol};
65 use serde::ser::SerializeSeq;
66 use serde::{Serialize, Serializer};
68 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, RenderedLink, SelfTy, TypeKind};
69 use crate::config::{RenderInfo, RenderOptions};
70 use crate::docfs::{DocFS, PathError};
72 use crate::error::Error;
73 use crate::formats::cache::{cache, Cache};
74 use crate::formats::item_type::ItemType;
75 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
76 use crate::html::escape::Escape;
77 use crate::html::format::fmt_impl_for_trait_page;
78 use crate::html::format::Function;
79 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
80 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
81 use crate::html::markdown::{
82 self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine,
84 use crate::html::sources;
85 use crate::html::{highlight, layout, static_files};
86 use cache::{build_index, ExternalLocation};
88 /// A pair of name and its optional document.
89 crate type NameDoc = (String, Option<String>);
91 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
92 crate::html::format::display_fn(move |f| {
93 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
97 /// Major driving force in all rustdoc rendering. This contains information
98 /// about where in the tree-like hierarchy rendering is occurring and controls
99 /// how the current page is being rendered.
101 /// It is intended that this context is a lightweight object which can be fairly
102 /// easily cloned because it is cloned per work-job (about once per item in the
105 crate struct Context {
106 /// Current hierarchy of components leading down to what's currently being
108 crate current: Vec<String>,
109 /// The current destination folder of where HTML artifacts should be placed.
110 /// This changes as the context descends into the module hierarchy.
112 /// A flag, which when `true`, will render pages which redirect to the
113 /// real location of an item. This is used to allow external links to
114 /// publicly reused items to redirect to the right location.
115 crate render_redirect_pages: bool,
116 /// The map used to ensure all generated 'id=' attributes are unique.
117 id_map: Rc<RefCell<IdMap>>,
118 crate shared: Arc<SharedContext>,
119 all: Rc<RefCell<AllTypes>>,
120 /// Storage for the errors produced while generating documentation so they
121 /// can be printed together at the end.
122 crate errors: Rc<Receiver<String>>,
125 crate struct SharedContext {
126 crate sess: Lrc<Session>,
127 /// The path to the crate root source minus the file name.
128 /// Used for simplifying paths to the highlighted source code files.
129 crate src_root: PathBuf,
130 /// This describes the layout of each page, and is not modified after
131 /// creation of the context (contains info like the favicon and added html).
132 crate layout: layout::Layout,
133 /// This flag indicates whether `[src]` links should be generated or not. If
134 /// the source files are present in the html rendering, then this will be
136 crate include_sources: bool,
137 /// The local file sources we've emitted and their respective url-paths.
138 crate local_sources: FxHashMap<PathBuf, String>,
139 /// Whether the collapsed pass ran
140 crate collapsed: bool,
141 /// The base-URL of the issue tracker for when an item has been tagged with
143 crate issue_tracker_base_url: Option<String>,
144 /// The directories that have already been created in this doc run. Used to reduce the number
145 /// of spurious `create_dir_all` calls.
146 crate created_dirs: RefCell<FxHashSet<PathBuf>>,
147 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
148 /// should be ordered alphabetically or in order of appearance (in the source code).
149 crate sort_modules_alphabetically: bool,
150 /// Additional CSS files to be added to the generated docs.
151 crate style_files: Vec<StylePath>,
152 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
154 crate resource_suffix: String,
155 /// Optional path string to be used to load static files on output pages. If not set, uses
156 /// combinations of `../` to reach the documentation root.
157 crate static_root_path: Option<String>,
158 /// The fs handle we are working with.
160 /// The default edition used to parse doctests.
161 crate edition: Edition,
162 crate codes: ErrorCodes,
163 playground: Option<markdown::Playground>,
167 fn path(&self, filename: &str) -> PathBuf {
168 // We use splitn vs Path::extension here because we might get a filename
169 // like `style.min.css` and we want to process that into
170 // `style-suffix.min.css`. Path::extension would just return `css`
171 // which would result in `style.min-suffix.css` which isn't what we
173 let (base, ext) = filename.split_once('.').unwrap();
174 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext);
175 self.dst.join(&filename)
178 fn sess(&self) -> &Session {
184 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
185 let mut dirs = self.created_dirs.borrow_mut();
186 if !dirs.contains(dst) {
187 try_err!(self.fs.create_dir_all(dst), dst);
188 dirs.insert(dst.to_path_buf());
194 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
195 /// `collapsed_doc_value` of the given item.
196 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
198 item.collapsed_doc_value().map(|s| s.into())
200 item.doc_value().map(|s| s.into())
205 // Helper structs for rendering items/sidebars and carrying along contextual
208 /// Struct representing one entry in the JS search index. These are all emitted
209 /// by hand to a large JS file at the end of cache-creation.
211 crate struct IndexItem {
216 crate parent: Option<DefId>,
217 crate parent_idx: Option<usize>,
218 crate search_type: Option<IndexItemFunctionType>,
221 impl Serialize for IndexItem {
222 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
227 self.parent.is_some(),
228 self.parent_idx.is_some(),
229 "`{}` is missing idx",
233 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
234 .serialize(serializer)
238 /// A type used for the search index.
240 crate struct RenderType {
243 name: Option<String>,
244 generics: Option<Vec<Generic>>,
247 impl Serialize for RenderType {
248 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
252 if let Some(name) = &self.name {
253 let mut seq = serializer.serialize_seq(None)?;
254 if let Some(id) = self.idx {
255 seq.serialize_element(&id)?;
257 seq.serialize_element(&name)?;
259 if let Some(generics) = &self.generics {
260 seq.serialize_element(&generics)?;
264 serializer.serialize_none()
269 /// A type used for the search index.
271 crate struct Generic {
273 defid: Option<DefId>,
277 impl Serialize for Generic {
278 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
282 if let Some(id) = self.idx {
283 serializer.serialize_some(&id)
285 serializer.serialize_some(&self.name)
290 /// Full type of functions/methods in the search index.
292 crate struct IndexItemFunctionType {
293 inputs: Vec<TypeWithKind>,
294 output: Option<Vec<TypeWithKind>>,
297 impl Serialize for IndexItemFunctionType {
298 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
302 // If we couldn't figure out a type, just write `null`.
303 let mut iter = self.inputs.iter();
304 if match self.output {
305 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
306 None => iter.any(|ref i| i.ty.name.is_none()),
308 serializer.serialize_none()
310 let mut seq = serializer.serialize_seq(None)?;
311 seq.serialize_element(&self.inputs)?;
312 if let Some(output) = &self.output {
313 if output.len() > 1 {
314 seq.serialize_element(&output)?;
316 seq.serialize_element(&output[0])?;
325 crate struct TypeWithKind {
330 impl From<(RenderType, TypeKind)> for TypeWithKind {
331 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
332 TypeWithKind { ty: x.0, kind: x.1 }
336 impl Serialize for TypeWithKind {
337 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
341 let mut seq = serializer.serialize_seq(None)?;
342 seq.serialize_element(&self.ty.name)?;
343 let x: ItemType = self.kind.into();
344 seq.serialize_element(&x)?;
349 #[derive(Debug, Clone)]
350 crate struct StylePath {
351 /// The path to the theme
353 /// What the `disabled` attribute should be set to in the HTML tag
354 crate disabled: bool,
357 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
359 crate fn initial_ids() -> Vec<String> {
371 "synthetic-implementors",
373 "synthetic-implementors-list",
379 .map(|id| (String::from(*id)))
383 /// Generates the documentation for `crate` into the directory `dst`
384 impl FormatRenderer for Context {
386 mut krate: clean::Crate,
387 options: RenderOptions,
388 _render_info: RenderInfo,
392 ) -> Result<(Context, clean::Crate), Error> {
393 // need to save a copy of the options for rendering the index page
394 let md_opts = options.clone();
400 sort_modules_alphabetically,
406 generate_search_filter,
411 let src_root = match krate.src {
412 FileName::Real(ref p) => match p.local_path().parent() {
413 Some(p) => p.to_path_buf(),
414 None => PathBuf::new(),
418 // If user passed in `--playground-url` arg, we fill in crate name here
419 let mut playground = None;
420 if let Some(url) = playground_url {
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(depr.is_since_rustc_version, depr.since.as_deref()) {
2227 message = "Deprecation planned";
2229 tags += &tag_html("deprecated", "", message);
2232 // The "rustc_private" crates are permanently unstable so it makes no sense
2233 // to render "unstable" everywhere.
2234 if item.stability.as_ref().map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
2237 tags += &tag_html("unstable", "", "Experimental");
2240 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
2241 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2242 (cfg, _) => cfg.as_deref().cloned(),
2245 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
2246 if let Some(ref cfg) = cfg {
2247 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
2253 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
2254 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
2255 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
2256 (cfg, _) => cfg.as_deref().cloned(),
2260 "Portability {:?} - {:?} = {:?}",
2262 parent.and_then(|p| p.attrs.cfg.as_ref()),
2266 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
2269 /// Render the stability, deprecation and portability information that is displayed at the top of
2270 /// the item's documentation.
2271 fn short_item_info(item: &clean::Item, cx: &Context, parent: Option<&clean::Item>) -> Vec<String> {
2272 let mut extra_info = vec![];
2273 let error_codes = cx.shared.codes;
2275 if let Some(Deprecation { ref note, ref since, is_since_rustc_version }) = item.deprecation {
2276 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2277 // but only display the future-deprecation messages for #[rustc_deprecated].
2278 let mut message = if let Some(since) = since {
2279 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2280 format!("Deprecating in {}", Escape(&since))
2282 format!("Deprecated since {}", Escape(&since))
2285 String::from("Deprecated")
2288 if let Some(note) = note {
2289 let mut ids = cx.id_map.borrow_mut();
2290 let html = MarkdownHtml(
2295 &cx.shared.playground,
2297 message.push_str(&format!(": {}", html.into_string()));
2299 extra_info.push(format!(
2300 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
2305 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2306 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2307 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
2310 .filter(|stab| stab.feature != sym::rustc_private)
2311 .map(|stab| (stab.level, stab.feature))
2314 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
2316 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
2317 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
2318 feature.push_str(&format!(
2319 " <a href=\"{url}{issue}\">#{issue}</a>",
2325 message.push_str(&format!(" ({})", feature));
2327 if let Some(unstable_reason) = reason {
2328 let mut ids = cx.id_map.borrow_mut();
2330 "<details><summary>{}</summary>{}</details>",
2333 &unstable_reason.as_str(),
2337 &cx.shared.playground,
2343 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
2346 if let Some(portability) = portability(item, parent) {
2347 extra_info.push(portability);
2353 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2354 write!(w, "<pre class=\"rust const\">");
2355 render_attributes(w, it, false);
2359 "{vis}const {name}: {typ}",
2360 vis = it.visibility.print_with_space(),
2361 name = it.name.as_ref().unwrap(),
2362 typ = c.type_.print(),
2365 if c.value.is_some() || c.is_literal {
2366 write!(w, " = {expr};", expr = Escape(&c.expr));
2371 if let Some(value) = &c.value {
2373 let value_lowercase = value.to_lowercase();
2374 let expr_lowercase = c.expr.to_lowercase();
2376 if value_lowercase != expr_lowercase
2377 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2379 write!(w, " // {value}", value = Escape(value));
2384 write!(w, "</pre>");
2385 document(w, cx, it, None)
2388 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2389 write!(w, "<pre class=\"rust static\">");
2390 render_attributes(w, it, false);
2393 "{vis}static {mutability}{name}: {typ}</pre>",
2394 vis = it.visibility.print_with_space(),
2395 mutability = s.mutability.print_with_space(),
2396 name = it.name.as_ref().unwrap(),
2397 typ = s.type_.print()
2399 document(w, cx, it, None)
2402 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2403 let header_len = format!(
2404 "{}{}{}{}{:#}fn {}{:#}",
2405 it.visibility.print_with_space(),
2406 f.header.constness.print_with_space(),
2407 f.header.asyncness.print_with_space(),
2408 f.header.unsafety.print_with_space(),
2409 print_abi_with_space(f.header.abi),
2410 it.name.as_ref().unwrap(),
2414 write!(w, "<pre class=\"rust fn\">");
2415 render_attributes(w, it, false);
2418 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2419 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2420 vis = it.visibility.print_with_space(),
2421 constness = f.header.constness.print_with_space(),
2422 asyncness = f.header.asyncness.print_with_space(),
2423 unsafety = f.header.unsafety.print_with_space(),
2424 abi = print_abi_with_space(f.header.abi),
2425 name = it.name.as_ref().unwrap(),
2426 generics = f.generics.print(),
2427 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2428 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2430 spotlight = spotlight_decl(&f.decl),
2432 document(w, cx, it, None)
2435 fn render_implementor(
2438 parent: &clean::Item,
2440 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2444 // If there's already another implementor that has the same abbridged name, use the
2445 // full path, for example in `std::iter::ExactSizeIterator`
2446 let use_absolute = match implementor.inner_impl().for_ {
2447 clean::ResolvedPath { ref path, is_generic: false, .. }
2448 | clean::BorrowedRef {
2449 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2451 } => implementor_dups[path.last_name()].1,
2459 AssocItemLink::Anchor(None),
2461 implementor.impl_item.stable_since().as_deref(),
2462 implementor.impl_item.const_stable_since().as_deref(),
2476 containing_item: &clean::Item,
2479 let mut impls = traits
2482 let did = i.trait_did().unwrap();
2483 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2484 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2492 containing_item.stable_since().as_deref(),
2493 containing_item.const_stable_since().as_deref(),
2503 .collect::<Vec<_>>();
2505 w.write_str(&impls.join(""));
2508 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2509 let mut bounds = String::new();
2510 if !t_bounds.is_empty() {
2512 bounds.push_str(": ");
2514 for (i, p) in t_bounds.iter().enumerate() {
2516 bounds.push_str(" + ");
2518 bounds.push_str(&p.print().to_string());
2524 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2525 let lhs = format!("{}", lhs.inner_impl().print());
2526 let rhs = format!("{}", rhs.inner_impl().print());
2528 // lhs and rhs are formatted as HTML, which may be unnecessary
2529 compare_names(&lhs, &rhs)
2532 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2533 let bounds = bounds(&t.bounds, false);
2534 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2535 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2536 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2537 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2539 // Output the trait definition
2540 wrap_into_docblock(w, |w| {
2541 write!(w, "<pre class=\"rust trait\">");
2542 render_attributes(w, it, true);
2545 "{}{}{}trait {}{}{}",
2546 it.visibility.print_with_space(),
2547 t.unsafety.print_with_space(),
2548 if t.is_auto { "auto " } else { "" },
2549 it.name.as_ref().unwrap(),
2554 if !t.generics.where_predicates.is_empty() {
2555 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2560 if t.items.is_empty() {
2563 // FIXME: we should be using a derived_id for the Anchors here
2566 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2569 if !types.is_empty() && !consts.is_empty() {
2573 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2576 if !consts.is_empty() && !required.is_empty() {
2579 for (pos, m) in required.iter().enumerate() {
2580 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2583 if pos < required.len() - 1 {
2584 write!(w, "<div class=\"item-spacer\"></div>");
2587 if !required.is_empty() && !provided.is_empty() {
2590 for (pos, m) in provided.iter().enumerate() {
2591 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2593 clean::MethodItem(ref inner, _)
2594 if !inner.generics.where_predicates.is_empty() =>
2596 write!(w, ",\n {{ ... }}\n");
2599 write!(w, " {{ ... }}\n");
2602 if pos < provided.len() - 1 {
2603 write!(w, "<div class=\"item-spacer\"></div>");
2611 // Trait documentation
2612 document(w, cx, it, None);
2614 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2617 "<h2 id=\"{0}\" class=\"small-section-header\">\
2618 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
2620 id, title, extra_content
2624 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2625 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
2628 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item, cache: &Cache) {
2629 let name = m.name.as_ref().unwrap();
2630 info!("Documenting {} on {:?}", name, t.name);
2631 let item_type = m.type_();
2632 let id = cx.derive_id(format!("{}.{}", item_type, name));
2633 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
2634 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2635 write!(w, "</code>");
2636 render_stability_since(w, m, t);
2637 write_srclink(cx, m, w, cache);
2639 document(w, cx, m, Some(t));
2642 if !types.is_empty() {
2643 write_small_section_header(
2647 "<div class=\"methods\">",
2650 trait_item(w, cx, t, it, cache);
2652 write_loading_content(w, "</div>");
2655 if !consts.is_empty() {
2656 write_small_section_header(
2659 "Associated Constants",
2660 "<div class=\"methods\">",
2663 trait_item(w, cx, t, it, cache);
2665 write_loading_content(w, "</div>");
2668 // Output the documentation for each function individually
2669 if !required.is_empty() {
2670 write_small_section_header(
2674 "<div class=\"methods\">",
2677 trait_item(w, cx, m, it, cache);
2679 write_loading_content(w, "</div>");
2681 if !provided.is_empty() {
2682 write_small_section_header(
2686 "<div class=\"methods\">",
2689 trait_item(w, cx, m, it, cache);
2691 write_loading_content(w, "</div>");
2694 // If there are methods directly on this trait object, render them here.
2695 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2697 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2698 // The DefId is for the first Type found with that name. The bool is
2699 // if any Types with the same name but different DefId have been found.
2700 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2701 for implementor in implementors {
2702 match implementor.inner_impl().for_ {
2703 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2704 | clean::BorrowedRef {
2705 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2708 let &mut (prev_did, ref mut has_duplicates) =
2709 implementor_dups.entry(path.last_name()).or_insert((did, false));
2710 if prev_did != did {
2711 *has_duplicates = true;
2718 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2719 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2722 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2723 local.iter().partition(|i| i.inner_impl().synthetic);
2725 synthetic.sort_by(compare_impl);
2726 concrete.sort_by(compare_impl);
2728 if !foreign.is_empty() {
2729 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2731 for implementor in foreign {
2732 let assoc_link = AssocItemLink::GotoSource(
2733 implementor.impl_item.def_id,
2734 &implementor.inner_impl().provided_trait_methods,
2743 implementor.impl_item.stable_since().as_deref(),
2744 implementor.impl_item.const_stable_since().as_deref(),
2753 write_loading_content(w, "");
2756 write_small_section_header(
2760 "<div class=\"item-list\" id=\"implementors-list\">",
2762 for implementor in concrete {
2763 render_implementor(cx, implementor, it, w, &implementor_dups, &[], cache);
2765 write_loading_content(w, "</div>");
2768 write_small_section_header(
2770 "synthetic-implementors",
2771 "Auto implementors",
2772 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2774 for implementor in synthetic {
2781 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2785 write_loading_content(w, "</div>");
2788 // even without any implementations to write in, we still want the heading and list, so the
2789 // implementors javascript file pulled in below has somewhere to write the impls into
2790 write_small_section_header(
2794 "<div class=\"item-list\" id=\"implementors-list\">",
2796 write_loading_content(w, "</div>");
2799 write_small_section_header(
2801 "synthetic-implementors",
2802 "Auto implementors",
2803 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
2805 write_loading_content(w, "</div>");
2811 "<script type=\"text/javascript\" \
2812 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2814 root_path = vec![".."; cx.current.len()].join("/"),
2815 path = if it.def_id.is_local() {
2816 cx.current.join("/")
2818 let (ref path, _) = cache.external_paths[&it.def_id];
2819 path[..path.len() - 1].join("/")
2822 name = *it.name.as_ref().unwrap()
2826 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2827 use crate::formats::item_type::ItemType::*;
2829 let name = it.name.as_ref().unwrap();
2830 let ty = match it.type_() {
2831 Typedef | AssocType => AssocType,
2835 let anchor = format!("#{}.{}", ty, name);
2837 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2838 AssocItemLink::Anchor(None) => anchor,
2839 AssocItemLink::GotoSource(did, _) => {
2840 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2849 _default: Option<&String>,
2850 link: AssocItemLink<'_>,
2855 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
2857 it.visibility.print_with_space(),
2858 naive_assoc_href(it, link),
2859 it.name.as_ref().unwrap(),
2867 bounds: &[clean::GenericBound],
2868 default: Option<&clean::Type>,
2869 link: AssocItemLink<'_>,
2874 "{}type <a href=\"{}\" class=\"type\">{}</a>",
2876 naive_assoc_href(it, link),
2877 it.name.as_ref().unwrap()
2879 if !bounds.is_empty() {
2880 write!(w, ": {}", print_generic_bounds(bounds))
2882 if let Some(default) = default {
2883 write!(w, " = {}", default.print())
2887 fn render_stability_since_raw(
2890 const_ver: Option<&str>,
2891 containing_ver: Option<&str>,
2892 containing_const_ver: Option<&str>,
2894 let ver = ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2896 let const_ver = const_ver.and_then(|inner| if !inner.is_empty() { Some(inner) } else { None });
2898 if let Some(v) = ver {
2899 if let Some(cv) = const_ver {
2900 if const_ver != containing_const_ver {
2903 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
2906 } else if ver != containing_ver {
2909 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2914 if ver != containing_ver {
2917 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
2925 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2926 render_stability_since_raw(
2928 item.stable_since().as_deref(),
2929 item.const_stable_since().as_deref(),
2930 containing_item.stable_since().as_deref(),
2931 containing_item.const_stable_since().as_deref(),
2935 fn render_assoc_item(
2938 link: AssocItemLink<'_>,
2944 header: hir::FnHeader,
2945 g: &clean::Generics,
2947 link: AssocItemLink<'_>,
2950 let name = meth.name.as_ref().unwrap();
2951 let anchor = format!("#{}.{}", meth.type_(), name);
2952 let href = match link {
2953 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2954 AssocItemLink::Anchor(None) => anchor,
2955 AssocItemLink::GotoSource(did, provided_methods) => {
2956 // We're creating a link from an impl-item to the corresponding
2957 // trait-item and need to map the anchored type accordingly.
2958 let ty = if provided_methods.contains(&*name.as_str()) {
2964 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2967 let mut header_len = format!(
2968 "{}{}{}{}{}{:#}fn {}{:#}",
2969 meth.visibility.print_with_space(),
2970 header.constness.print_with_space(),
2971 header.asyncness.print_with_space(),
2972 header.unsafety.print_with_space(),
2973 print_default_space(meth.is_default()),
2974 print_abi_with_space(header.abi),
2979 let (indent, end_newline) = if parent == ItemType::Trait {
2985 render_attributes(w, meth, false);
2988 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
2989 {generics}{decl}{spotlight}{where_clause}",
2990 if parent == ItemType::Trait { " " } else { "" },
2991 meth.visibility.print_with_space(),
2992 header.constness.print_with_space(),
2993 header.asyncness.print_with_space(),
2994 header.unsafety.print_with_space(),
2995 print_default_space(meth.is_default()),
2996 print_abi_with_space(header.abi),
2999 generics = g.print(),
3000 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
3001 spotlight = spotlight_decl(&d),
3002 where_clause = WhereClause { gens: g, indent, end_newline }
3006 clean::StrippedItem(..) => {}
3007 clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
3008 clean::MethodItem(ref m, _) => {
3009 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3011 clean::AssocConstItem(ref ty, ref default) => assoc_const(
3017 if parent == ItemType::Trait { " " } else { "" },
3019 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
3025 if parent == ItemType::Trait { " " } else { "" },
3027 _ => panic!("render_assoc_item called on non-associated-item"),
3031 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
3032 wrap_into_docblock(w, |w| {
3033 write!(w, "<pre class=\"rust struct\">");
3034 render_attributes(w, it, true);
3035 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
3039 document(w, cx, it, None);
3043 .filter_map(|f| match f.kind {
3044 clean::StructFieldItem(ref ty) => Some((f, ty)),
3048 if let doctree::Plain = s.struct_type {
3049 if fields.peek().is_some() {
3052 "<h2 id=\"fields\" class=\"fields small-section-header\">
3053 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
3054 document_non_exhaustive_header(it)
3056 document_non_exhaustive(w, it);
3057 for (field, ty) in fields {
3058 let id = cx.derive_id(format!(
3060 ItemType::StructField,
3061 field.name.as_ref().unwrap()
3065 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3066 <a href=\"#{id}\" class=\"anchor field\"></a>\
3067 <code>{name}: {ty}</code>\
3069 item_type = ItemType::StructField,
3071 name = field.name.as_ref().unwrap(),
3074 document(w, cx, field, Some(it));
3078 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3081 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
3082 wrap_into_docblock(w, |w| {
3083 write!(w, "<pre class=\"rust union\">");
3084 render_attributes(w, it, true);
3085 render_union(w, it, Some(&s.generics), &s.fields, "", true);
3089 document(w, cx, it, None);
3093 .filter_map(|f| match f.kind {
3094 clean::StructFieldItem(ref ty) => Some((f, ty)),
3098 if fields.peek().is_some() {
3101 "<h2 id=\"fields\" class=\"fields small-section-header\">
3102 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
3104 for (field, ty) in fields {
3105 let name = field.name.as_ref().expect("union field name");
3106 let id = format!("{}.{}", ItemType::StructField, name);
3109 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3110 <a href=\"#{id}\" class=\"anchor field\"></a>\
3111 <code>{name}: {ty}</code>\
3115 shortty = ItemType::StructField,
3118 if let Some(stability_class) = field.stability_class() {
3119 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
3121 document(w, cx, field, Some(it));
3124 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3127 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
3128 wrap_into_docblock(w, |w| {
3129 write!(w, "<pre class=\"rust enum\">");
3130 render_attributes(w, it, true);
3134 it.visibility.print_with_space(),
3135 it.name.as_ref().unwrap(),
3137 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
3139 if e.variants.is_empty() && !e.variants_stripped {
3143 for v in &e.variants {
3145 let name = v.name.as_ref().unwrap();
3147 clean::VariantItem(ref var) => match var.kind {
3148 clean::VariantKind::CLike => write!(w, "{}", name),
3149 clean::VariantKind::Tuple(ref tys) => {
3150 write!(w, "{}(", name);
3151 for (i, ty) in tys.iter().enumerate() {
3153 write!(w, ", ")
3155 write!(w, "{}", ty.print());
3159 clean::VariantKind::Struct(ref s) => {
3160 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
3163 _ => unreachable!(),
3168 if e.variants_stripped {
3169 write!(w, " // some variants omitted\n");
3176 document(w, cx, it, None);
3177 if !e.variants.is_empty() {
3180 "<h2 id=\"variants\" class=\"variants small-section-header\">
3181 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
3182 document_non_exhaustive_header(it)
3184 document_non_exhaustive(w, it);
3185 for variant in &e.variants {
3187 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3190 "<div id=\"{id}\" class=\"variant small-section-header\">\
3191 <a href=\"#{id}\" class=\"anchor field\"></a>\
3194 name = variant.name.as_ref().unwrap()
3196 if let clean::VariantItem(ref var) = variant.kind {
3197 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3199 for (i, ty) in tys.iter().enumerate() {
3201 write!(w, ", ");
3203 write!(w, "{}", ty.print());
3208 write!(w, "</code></div>");
3209 document(w, cx, variant, Some(it));
3210 document_non_exhaustive(w, variant);
3212 use crate::clean::{Variant, VariantKind};
3213 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.kind {
3214 let variant_id = cx.derive_id(format!(
3217 variant.name.as_ref().unwrap()
3219 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
3222 "<h3>Fields of <b>{name}</b></h3><div>",
3223 name = variant.name.as_ref().unwrap()
3225 for field in &s.fields {
3226 use crate::clean::StructFieldItem;
3227 if let StructFieldItem(ref ty) = field.kind {
3228 let id = cx.derive_id(format!(
3229 "variant.{}.field.{}",
3230 variant.name.as_ref().unwrap(),
3231 field.name.as_ref().unwrap()
3235 "<span id=\"{id}\" class=\"variant small-section-header\">\
3236 <a href=\"#{id}\" class=\"anchor field\"></a>\
3237 <code>{f}: {t}</code>\
3240 f = field.name.as_ref().unwrap(),
3243 document(w, cx, field, Some(variant));
3246 write!(w, "</div></div>");
3248 render_stability_since(w, variant, it);
3251 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3254 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3261 sym::non_exhaustive,
3264 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3265 // left padding. For example:
3267 // #[foo] <----- "top" attribute
3269 // #[bar] <---- not "top" attribute
3272 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3277 .filter_map(|attr| {
3278 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3279 Some(pprust::attribute_to_string(&attr))
3286 if !attrs.is_empty() {
3289 "<span class=\"docblock attributes{}\">{}</span>",
3290 if top { " top-attr" } else { "" },
3299 g: Option<&clean::Generics>,
3300 ty: doctree::StructType,
3301 fields: &[clean::Item],
3308 it.visibility.print_with_space(),
3309 if structhead { "struct " } else { "" },
3310 it.name.as_ref().unwrap()
3312 if let Some(g) = g {
3313 write!(w, "{}", g.print())
3317 if let Some(g) = g {
3318 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3320 let mut has_visible_fields = false;
3322 for field in fields {
3323 if let clean::StructFieldItem(ref ty) = field.kind {
3328 field.visibility.print_with_space(),
3329 field.name.as_ref().unwrap(),
3332 has_visible_fields = true;
3336 if has_visible_fields {
3337 if it.has_stripped_fields().unwrap() {
3338 write!(w, "\n{} // some fields omitted", tab);
3340 write!(w, "\n{}", tab);
3341 } else if it.has_stripped_fields().unwrap() {
3342 // If there are no visible fields we can just display
3343 // `{ /* fields omitted */ }` to save space.
3344 write!(w, " /* fields omitted */ ");
3350 for (i, field) in fields.iter().enumerate() {
3355 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3356 clean::StructFieldItem(ref ty) => {
3357 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3359 _ => unreachable!(),
3363 if let Some(g) = g {
3364 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3369 // Needed for PhantomData.
3370 if let Some(g) = g {
3371 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3381 g: Option<&clean::Generics>,
3382 fields: &[clean::Item],
3389 it.visibility.print_with_space(),
3390 if structhead { "union " } else { "" },
3391 it.name.as_ref().unwrap()
3393 if let Some(g) = g {
3394 write!(w, "{}", g.print());
3395 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3398 write!(w, " {{\n{}", tab);
3399 for field in fields {
3400 if let clean::StructFieldItem(ref ty) = field.kind {
3404 field.visibility.print_with_space(),
3405 field.name.as_ref().unwrap(),
3412 if it.has_stripped_fields().unwrap() {
3413 write!(w, " // some fields omitted\n{}", tab);
3418 #[derive(Copy, Clone)]
3419 enum AssocItemLink<'a> {
3420 Anchor(Option<&'a str>),
3421 GotoSource(DefId, &'a FxHashSet<String>),
3424 impl<'a> AssocItemLink<'a> {
3425 fn anchor(&self, id: &'a String) -> Self {
3427 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3428 ref other => *other,
3433 fn render_assoc_items(
3436 containing_item: &clean::Item,
3438 what: AssocItemRender<'_>,
3441 info!("Documenting associated items of {:?}", containing_item.name);
3442 let v = match cache.impls.get(&it) {
3446 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3447 if !non_trait.is_empty() {
3448 let render_mode = match what {
3449 AssocItemRender::All => {
3452 "<h2 id=\"implementations\" class=\"small-section-header\">\
3453 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
3458 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3461 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
3462 Methods from {}<Target = {}>\
3463 <a href=\"#deref-methods\" class=\"anchor\"></a>\
3468 RenderMode::ForDeref { mut_: deref_mut_ }
3471 for i in &non_trait {
3477 AssocItemLink::Anchor(None),
3479 containing_item.stable_since().as_deref(),
3480 containing_item.const_stable_since().as_deref(),
3490 if let AssocItemRender::DerefFor { .. } = what {
3493 if !traits.is_empty() {
3495 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3496 if let Some(impl_) = deref_impl {
3498 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3499 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3502 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3503 traits.iter().partition(|t| t.inner_impl().synthetic);
3504 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3505 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3507 let mut impls = Buffer::empty_from(&w);
3508 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3509 let impls = impls.into_inner();
3510 if !impls.is_empty() {
3513 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
3514 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
3516 <div id=\"trait-implementations-list\">{}</div>",
3521 if !synthetic.is_empty() {
3524 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
3525 Auto Trait Implementations\
3526 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
3528 <div id=\"synthetic-implementations-list\">"
3530 render_impls(cx, w, &synthetic, containing_item, cache);
3531 write!(w, "</div>");
3534 if !blanket_impl.is_empty() {
3537 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
3538 Blanket Implementations\
3539 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
3541 <div id=\"blanket-implementations-list\">"
3543 render_impls(cx, w, &blanket_impl, containing_item, cache);
3544 write!(w, "</div>");
3549 fn render_deref_methods(
3553 container_item: &clean::Item,
3557 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3558 let (target, real_target) = impl_
3562 .find_map(|item| match item.kind {
3563 clean::TypedefItem(ref t, true) => Some(match *t {
3564 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3565 _ => (&t.type_, &t.type_),
3569 .expect("Expected associated type binding");
3571 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3572 if let Some(did) = target.def_id() {
3573 render_assoc_items(w, cx, container_item, did, what, cache);
3575 if let Some(prim) = target.primitive_type() {
3576 if let Some(&did) = cache.primitive_locations.get(&prim) {
3577 render_assoc_items(w, cx, container_item, did, what, cache);
3583 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3584 let self_type_opt = match item.kind {
3585 clean::MethodItem(ref method, _) => method.decl.self_type(),
3586 clean::TyMethodItem(ref method) => method.decl.self_type(),
3590 if let Some(self_ty) = self_type_opt {
3591 let (by_mut_ref, by_box, by_value) = match self_ty {
3592 SelfTy::SelfBorrowed(_, mutability)
3593 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3594 (mutability == Mutability::Mut, false, false)
3596 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3597 (false, Some(did) == cache().owned_box_did, false)
3599 SelfTy::SelfValue => (false, false, true),
3600 _ => (false, false, false),
3603 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3609 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3610 let mut out = Buffer::html();
3611 let mut trait_ = String::new();
3613 if let Some(did) = decl.output.def_id() {
3615 if let Some(impls) = c.impls.get(&did) {
3617 let impl_ = i.inner_impl();
3618 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3620 out.push_str(&format!(
3621 "<h3 class=\"notable\">Notable traits for {}</h3>\
3622 <code class=\"content\">",
3625 trait_.push_str(&impl_.for_.print().to_string());
3628 //use the "where" class here to make it small
3629 out.push_str(&format!(
3630 "<span class=\"where fmt-newline\">{}</span>",
3633 let t_did = impl_.trait_.def_id().unwrap();
3634 for it in &impl_.items {
3635 if let clean::TypedefItem(ref tydef, _) = it.kind {
3636 out.push_str("<span class=\"where fmt-newline\"> ");
3642 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3645 out.push_str(";</span>");
3653 if !out.is_empty() {
3656 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
3657 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
3659 out.push_str("</code></span></div></span></span>");
3669 parent: &clean::Item,
3670 link: AssocItemLink<'_>,
3671 render_mode: RenderMode,
3672 outer_version: Option<&str>,
3673 outer_const_version: Option<&str>,
3674 show_def_docs: bool,
3675 use_absolute: Option<bool>,
3676 is_on_foreign_type: bool,
3677 show_default_items: bool,
3678 // This argument is used to reference same type with different paths to avoid duplication
3679 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3683 let traits = &cache.traits;
3684 let trait_ = i.trait_did().map(|did| &traits[&did]);
3686 if render_mode == RenderMode::Normal {
3687 let id = cx.derive_id(match i.inner_impl().trait_ {
3689 if is_on_foreign_type {
3690 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3692 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3695 None => "impl".to_string(),
3697 let aliases = if aliases.is_empty() {
3700 format!(" aliases=\"{}\"", aliases.join(","))
3702 if let Some(use_absolute) = use_absolute {
3703 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
3704 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3706 for it in &i.inner_impl().items {
3707 if let clean::TypedefItem(ref tydef, _) = it.kind {
3708 write!(w, "<span class=\"where fmt-newline\"> ");
3709 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3710 write!(w, ";</span>");
3714 write!(w, "</code>");
3718 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
3721 i.inner_impl().print()
3724 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
3725 render_stability_since_raw(
3727 i.impl_item.stable_since().as_deref(),
3728 i.impl_item.const_stable_since().as_deref(),
3730 outer_const_version,
3732 write_srclink(cx, &i.impl_item, w, cache);
3735 if trait_.is_some() {
3736 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
3737 write!(w, "<div class=\"item-info\">{}</div>", portability);
3741 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3742 let mut ids = cx.id_map.borrow_mut();
3745 "<div class=\"docblock\">{}</div>",
3748 &i.impl_item.links(),
3752 &cx.shared.playground
3763 parent: &clean::Item,
3764 link: AssocItemLink<'_>,
3765 render_mode: RenderMode,
3766 is_default_item: bool,
3767 outer_version: Option<&str>,
3768 outer_const_version: Option<&str>,
3769 trait_: Option<&clean::Trait>,
3770 show_def_docs: bool,
3773 let item_type = item.type_();
3774 let name = item.name.as_ref().unwrap();
3776 let render_method_item = match render_mode {
3777 RenderMode::Normal => true,
3778 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3781 let (is_hidden, extra_class) =
3782 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
3790 clean::MethodItem(..) | clean::TyMethodItem(_) => {
3791 // Only render when the method is not static or we allow static methods
3792 if render_method_item {
3793 let id = cx.derive_id(format!("{}.{}", item_type, name));
3794 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
3795 write!(w, "<code>");
3796 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3797 write!(w, "</code>");
3798 render_stability_since_raw(
3800 item.stable_since().as_deref(),
3801 item.const_stable_since().as_deref(),
3803 outer_const_version,
3805 write_srclink(cx, item, w, cache);
3809 clean::TypedefItem(ref tydef, _) => {
3810 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3811 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3812 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3813 write!(w, "</code></h4>");
3815 clean::AssocConstItem(ref ty, ref default) => {
3816 let id = cx.derive_id(format!("{}.{}", item_type, name));
3817 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3818 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3819 write!(w, "</code>");
3820 render_stability_since_raw(
3822 item.stable_since().as_deref(),
3823 item.const_stable_since().as_deref(),
3825 outer_const_version,
3827 write_srclink(cx, item, w, cache);
3830 clean::AssocTypeItem(ref bounds, ref default) => {
3831 let id = cx.derive_id(format!("{}.{}", item_type, name));
3832 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
3833 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3834 write!(w, "</code></h4>");
3836 clean::StrippedItem(..) => return,
3837 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3840 if render_method_item {
3841 if !is_default_item {
3842 if let Some(t) = trait_ {
3843 // The trait item may have been stripped so we might not
3844 // find any documentation or stability for it.
3845 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3846 // We need the stability of the item from the trait
3847 // because impls can't have a stability.
3848 if item.doc_value().is_some() {
3849 document_item_info(w, cx, it, is_hidden, Some(parent));
3850 document_full(w, item, cx, "", is_hidden);
3852 // In case the item isn't documented,
3853 // provide short documentation from the trait.
3867 document_item_info(w, cx, item, is_hidden, Some(parent));
3869 document_full(w, item, cx, "", is_hidden);
3873 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
3878 write!(w, "<div class=\"impl-items\">");
3879 for trait_item in &i.inner_impl().items {
3884 if trait_.is_some() { &i.impl_item } else { parent },
3889 outer_const_version,
3896 fn render_default_items(
3901 parent: &clean::Item,
3902 render_mode: RenderMode,
3903 outer_version: Option<&str>,
3904 outer_const_version: Option<&str>,
3905 show_def_docs: bool,
3908 for trait_item in &t.items {
3909 let n = trait_item.name.clone();
3910 if i.items.iter().any(|m| m.name == n) {
3913 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3914 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3925 outer_const_version,
3933 // If we've implemented a trait, then also emit documentation for all
3934 // default items which weren't overridden in the implementation block.
3935 // We don't emit documentation for default items if they appear in the
3936 // Implementations on Foreign Types or Implementors sections.
3937 if show_default_items {
3938 if let Some(t) = trait_ {
3939 render_default_items(
3947 outer_const_version,
3953 write!(w, "</div>");
3960 t: &clean::OpaqueTy,
3963 write!(w, "<pre class=\"rust opaque\">");
3964 render_attributes(w, it, false);
3967 "type {}{}{where_clause} = impl {bounds};</pre>",
3968 it.name.as_ref().unwrap(),
3970 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3971 bounds = bounds(&t.bounds, false)
3974 document(w, cx, it, None);
3976 // Render any items associated directly to this alias, as otherwise they
3977 // won't be visible anywhere in the docs. It would be nice to also show
3978 // associated items from the aliased type (see discussion in #32077), but
3979 // we need #14072 to make sense of the generics.
3980 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3983 fn item_trait_alias(
3987 t: &clean::TraitAlias,
3990 write!(w, "<pre class=\"rust trait-alias\">");
3991 render_attributes(w, it, false);
3994 "trait {}{}{} = {};</pre>",
3995 it.name.as_ref().unwrap(),
3997 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3998 bounds(&t.bounds, true)
4001 document(w, cx, it, None);
4003 // Render any items associated directly to this alias, as otherwise they
4004 // won't be visible anywhere in the docs. It would be nice to also show
4005 // associated items from the aliased type (see discussion in #32077), but
4006 // we need #14072 to make sense of the generics.
4007 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4010 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
4011 write!(w, "<pre class=\"rust typedef\">");
4012 render_attributes(w, it, false);
4015 "type {}{}{where_clause} = {type_};</pre>",
4016 it.name.as_ref().unwrap(),
4018 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4019 type_ = t.type_.print()
4022 document(w, cx, it, None);
4024 // Render any items associated directly to this alias, as otherwise they
4025 // won't be visible anywhere in the docs. It would be nice to also show
4026 // associated items from the aliased type (see discussion in #32077), but
4027 // we need #14072 to make sense of the generics.
4028 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4031 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4032 writeln!(w, "<pre class=\"rust foreigntype\">extern {{");
4033 render_attributes(w, it, false);
4036 " {}type {};\n}}</pre>",
4037 it.visibility.print_with_space(),
4038 it.name.as_ref().unwrap(),
4041 document(w, cx, it, None);
4043 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4046 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
4047 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
4051 || it.is_primitive()
4059 "<p class=\"location\">{}{}</p>",
4061 clean::StructItem(..) => "Struct ",
4062 clean::TraitItem(..) => "Trait ",
4063 clean::PrimitiveItem(..) => "Primitive Type ",
4064 clean::UnionItem(..) => "Union ",
4065 clean::EnumItem(..) => "Enum ",
4066 clean::TypedefItem(..) => "Type Definition ",
4067 clean::ForeignTypeItem => "Foreign Type ",
4068 clean::ModuleItem(..) =>
4076 it.name.as_ref().unwrap()
4081 if let Some(ref version) = cache.crate_version {
4084 "<div class=\"block version\">\
4092 write!(buffer, "<div class=\"sidebar-elems\">");
4096 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
4097 it.name.as_ref().expect("crates always have a name")
4101 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
4102 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
4103 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
4104 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
4105 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
4106 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
4107 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
4108 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
4112 // The sidebar is designed to display sibling functions, modules and
4113 // other miscellaneous information. since there are lots of sibling
4114 // items (and that causes quadratic growth in large modules),
4115 // we refactor common parts into a shared JavaScript file per module.
4116 // still, we don't move everything into JS because we want to preserve
4117 // as much HTML as possible in order to allow non-JS-enabled browsers
4118 // to navigate the documentation (though slightly inefficiently).
4120 write!(buffer, "<p class=\"location\">");
4121 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4123 write!(buffer, "::<wbr>");
4127 "<a href=\"{}index.html\">{}</a>",
4128 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4132 write!(buffer, "</p>");
4134 // Sidebar refers to the enclosing module, not this module.
4135 let relpath = if it.is_mod() { "../" } else { "" };
4138 "<script>window.sidebarCurrent = {{\
4141 relpath: \"{path}\"\
4143 name = it.name.unwrap_or(kw::Invalid),
4148 // There is no sidebar-items.js beyond the crate root path
4149 // FIXME maybe dynamic crate loading can be merged here
4151 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
4153 // Closes sidebar-elems div.
4154 write!(buffer, "</div>");
4157 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4158 if used_links.insert(url.clone()) {
4162 while !used_links.insert(format!("{}-{}", url, add)) {
4165 format!("{}-{}", url, add)
4171 used_links: &mut FxHashSet<String>,
4176 .filter_map(|item| match item.name {
4177 Some(ref name) if !name.is_empty() && item.is_method() => {
4178 if !for_deref || should_render_item(item, deref_mut) {
4180 "<a href=\"#{}\">{}</a>",
4181 get_next_url(used_links, format!("method.{}", name)),
4190 .collect::<Vec<_>>()
4193 // The point is to url encode any potential character from a type with genericity.
4194 fn small_url_encode(s: &str) -> String {
4195 s.replace("<", "%3C")
4196 .replace(">", "%3E")
4197 .replace(" ", "%20")
4198 .replace("?", "%3F")
4199 .replace("'", "%27")
4200 .replace("&", "%26")
4201 .replace(",", "%2C")
4202 .replace(":", "%3A")
4203 .replace(";", "%3B")
4204 .replace("[", "%5B")
4205 .replace("]", "%5D")
4206 .replace("\"", "%22")
4209 fn sidebar_assoc_items(it: &clean::Item) -> String {
4210 let mut out = String::new();
4212 if let Some(v) = c.impls.get(&it.def_id) {
4213 let mut used_links = FxHashSet::default();
4216 let used_links_bor = &mut used_links;
4219 .filter(|i| i.inner_impl().trait_.is_none())
4220 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4221 .collect::<Vec<_>>();
4222 if !ret.is_empty() {
4223 // We want links' order to be reproducible so we don't use unstable sort.
4225 out.push_str(&format!(
4226 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4227 <div class=\"sidebar-links\">{}</div>",
4233 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4234 if let Some(impl_) = v
4236 .filter(|i| i.inner_impl().trait_.is_some())
4237 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4239 if let Some((target, real_target)) =
4240 impl_.inner_impl().items.iter().find_map(|item| match item.kind {
4241 clean::TypedefItem(ref t, true) => Some(match *t {
4242 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4243 _ => (&t.type_, &t.type_),
4250 .filter(|i| i.inner_impl().trait_.is_some())
4251 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4252 let inner_impl = target
4256 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4257 .and_then(|did| c.impls.get(&did));
4258 if let Some(impls) = inner_impl {
4259 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4260 out.push_str(&format!(
4261 "Methods from {}<Target={}>",
4264 impl_.inner_impl().trait_.as_ref().unwrap().print()
4266 Escape(&format!("{:#}", real_target.print()))
4268 out.push_str("</a>");
4271 .filter(|i| i.inner_impl().trait_.is_none())
4273 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4275 .collect::<Vec<_>>();
4276 // We want links' order to be reproducible so we don't use unstable sort.
4278 if !ret.is_empty() {
4279 out.push_str(&format!(
4280 "<div class=\"sidebar-links\">{}</div>",
4287 let format_impls = |impls: Vec<&Impl>| {
4288 let mut links = FxHashSet::default();
4293 let is_negative_impl = is_negative_impl(i.inner_impl());
4294 if let Some(ref i) = i.inner_impl().trait_ {
4295 let i_display = format!("{:#}", i.print());
4296 let out = Escape(&i_display);
4297 let encoded = small_url_encode(&format!("{:#}", i.print()));
4298 let generated = format!(
4299 "<a href=\"#impl-{}\">{}{}</a>",
4301 if is_negative_impl { "!" } else { "" },
4304 if links.insert(generated.clone()) { Some(generated) } else { None }
4309 .collect::<Vec<String>>();
4314 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4315 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4316 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4318 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4320 let concrete_format = format_impls(concrete);
4321 let synthetic_format = format_impls(synthetic);
4322 let blanket_format = format_impls(blanket_impl);
4324 if !concrete_format.is_empty() {
4326 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4327 Trait Implementations</a>",
4329 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4332 if !synthetic_format.is_empty() {
4334 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4335 Auto Trait Implementations</a>",
4337 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4340 if !blanket_format.is_empty() {
4342 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4343 Blanket Implementations</a>",
4345 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4353 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4354 let mut sidebar = String::new();
4355 let fields = get_struct_fields_name(&s.fields);
4357 if !fields.is_empty() {
4358 if let doctree::Plain = s.struct_type {
4359 sidebar.push_str(&format!(
4360 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4361 <div class=\"sidebar-links\">{}</div>",
4367 sidebar.push_str(&sidebar_assoc_items(it));
4369 if !sidebar.is_empty() {
4370 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4374 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4375 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4378 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4380 clean::ItemKind::ImplItem(ref i) => {
4381 if let Some(ref trait_) = i.trait_ {
4383 format!("{:#}", i.for_.print()),
4384 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4394 fn is_negative_impl(i: &clean::Impl) -> bool {
4395 i.polarity == Some(clean::ImplPolarity::Negative)
4398 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4399 let mut sidebar = String::new();
4404 .filter_map(|m| match m.name {
4405 Some(ref name) if m.is_associated_type() => {
4406 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4410 .collect::<Vec<_>>();
4414 .filter_map(|m| match m.name {
4415 Some(ref name) if m.is_associated_const() => {
4416 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4420 .collect::<Vec<_>>();
4421 let mut required = t
4424 .filter_map(|m| match m.name {
4425 Some(ref name) if m.is_ty_method() => {
4426 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4430 .collect::<Vec<String>>();
4431 let mut provided = t
4434 .filter_map(|m| match m.name {
4435 Some(ref name) if m.is_method() => {
4436 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4440 .collect::<Vec<String>>();
4442 if !types.is_empty() {
4444 sidebar.push_str(&format!(
4445 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4446 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4450 if !consts.is_empty() {
4452 sidebar.push_str(&format!(
4453 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4454 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4458 if !required.is_empty() {
4460 sidebar.push_str(&format!(
4461 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4462 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4466 if !provided.is_empty() {
4468 sidebar.push_str(&format!(
4469 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4470 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4477 if let Some(implementors) = c.implementors.get(&it.def_id) {
4478 let mut res = implementors
4480 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4481 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4482 .collect::<Vec<_>>();
4484 if !res.is_empty() {
4486 sidebar.push_str(&format!(
4487 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4488 Implementations on Foreign Types</a>\
4489 <div class=\"sidebar-links\">{}</div>",
4491 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4492 .collect::<Vec<_>>()
4498 sidebar.push_str(&sidebar_assoc_items(it));
4500 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4503 "<a class=\"sidebar-title\" \
4504 href=\"#synthetic-implementors\">Auto Implementors</a>",
4508 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4511 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4512 let sidebar = sidebar_assoc_items(it);
4514 if !sidebar.is_empty() {
4515 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4519 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4520 let sidebar = sidebar_assoc_items(it);
4522 if !sidebar.is_empty() {
4523 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4527 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4528 let mut fields = fields
4530 .filter(|f| if let clean::StructFieldItem(..) = f.kind { true } else { false })
4531 .filter_map(|f| match f.name {
4533 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4537 .collect::<Vec<_>>();
4542 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4543 let mut sidebar = String::new();
4544 let fields = get_struct_fields_name(&u.fields);
4546 if !fields.is_empty() {
4547 sidebar.push_str(&format!(
4548 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4549 <div class=\"sidebar-links\">{}</div>",
4554 sidebar.push_str(&sidebar_assoc_items(it));
4556 if !sidebar.is_empty() {
4557 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4561 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4562 let mut sidebar = String::new();
4564 let mut variants = e
4567 .filter_map(|v| match v.name {
4568 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4571 .collect::<Vec<_>>();
4572 if !variants.is_empty() {
4573 variants.sort_unstable();
4574 sidebar.push_str(&format!(
4575 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4576 <div class=\"sidebar-links\">{}</div>",
4581 sidebar.push_str(&sidebar_assoc_items(it));
4583 if !sidebar.is_empty() {
4584 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4588 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4590 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4591 ItemType::Module => ("modules", "Modules"),
4592 ItemType::Struct => ("structs", "Structs"),
4593 ItemType::Union => ("unions", "Unions"),
4594 ItemType::Enum => ("enums", "Enums"),
4595 ItemType::Function => ("functions", "Functions"),
4596 ItemType::Typedef => ("types", "Type Definitions"),
4597 ItemType::Static => ("statics", "Statics"),
4598 ItemType::Constant => ("constants", "Constants"),
4599 ItemType::Trait => ("traits", "Traits"),
4600 ItemType::Impl => ("impls", "Implementations"),
4601 ItemType::TyMethod => ("tymethods", "Type Methods"),
4602 ItemType::Method => ("methods", "Methods"),
4603 ItemType::StructField => ("fields", "Struct Fields"),
4604 ItemType::Variant => ("variants", "Variants"),
4605 ItemType::Macro => ("macros", "Macros"),
4606 ItemType::Primitive => ("primitives", "Primitive Types"),
4607 ItemType::AssocType => ("associated-types", "Associated Types"),
4608 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4609 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4610 ItemType::Keyword => ("keywords", "Keywords"),
4611 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4612 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4613 ItemType::ProcDerive => ("derives", "Derive Macros"),
4614 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4618 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4619 let mut sidebar = String::new();
4621 if items.iter().any(|it| {
4622 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
4624 sidebar.push_str(&format!(
4625 "<li><a href=\"#{id}\">{name}</a></li>",
4631 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4632 // to print its headings
4634 ItemType::Primitive,
4648 ItemType::StructField,
4650 ItemType::AssocType,
4651 ItemType::AssocConst,
4652 ItemType::ForeignType,
4655 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4656 let (short, name) = item_ty_to_strs(&myty);
4657 sidebar.push_str(&format!(
4658 "<li><a href=\"#{id}\">{name}</a></li>",
4665 if !sidebar.is_empty() {
4666 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4670 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4671 let sidebar = sidebar_assoc_items(it);
4672 if !sidebar.is_empty() {
4673 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4677 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4678 wrap_into_docblock(w, |w| {
4679 w.write_str(&highlight::render_with_highlighting(
4686 document(w, cx, it, None)
4689 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4690 let name = it.name.as_ref().expect("proc-macros always have names");
4692 MacroKind::Bang => {
4693 write!(w, "<pre class=\"rust macro\">");
4694 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4695 write!(w, "</pre>");
4697 MacroKind::Attr => {
4698 write!(w, "<pre class=\"rust attr\">");
4699 write!(w, "#[{}]", name);
4700 write!(w, "</pre>");
4702 MacroKind::Derive => {
4703 write!(w, "<pre class=\"rust derive\">");
4704 write!(w, "#[derive({})]", name);
4705 if !m.helpers.is_empty() {
4706 writeln!(w, "\n{{");
4707 writeln!(w, " // Attributes available to this derive:");
4708 for attr in &m.helpers {
4709 writeln!(w, " #[{}]", attr);
4713 write!(w, "</pre>");
4716 document(w, cx, it, None)
4719 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4720 document(w, cx, it, None);
4721 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4724 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4725 document(w, cx, it, None)
4728 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4730 fn make_item_keywords(it: &clean::Item) -> String {
4731 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4734 /// Returns a list of all paths used in the type.
4735 /// This is used to help deduplicate imported impls
4736 /// for reexported types. If any of the contained
4737 /// types are re-exported, we don't use the corresponding
4738 /// entry from the js file, as inlining will have already
4739 /// picked up the impl
4740 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4741 let mut out = Vec::new();
4742 let mut visited = FxHashSet::default();
4743 let mut work = VecDeque::new();
4744 let cache = cache();
4746 work.push_back(first_ty);
4748 while let Some(ty) = work.pop_front() {
4749 if !visited.insert(ty.clone()) {
4754 clean::Type::ResolvedPath { did, .. } => {
4755 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4756 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4758 if let Some(path) = fqp {
4759 out.push(path.join("::"));
4762 clean::Type::Tuple(tys) => {
4763 work.extend(tys.into_iter());
4765 clean::Type::Slice(ty) => {
4766 work.push_back(*ty);
4768 clean::Type::Array(ty, _) => {
4769 work.push_back(*ty);
4771 clean::Type::RawPointer(_, ty) => {
4772 work.push_back(*ty);
4774 clean::Type::BorrowedRef { type_, .. } => {
4775 work.push_back(*type_);
4777 clean::Type::QPath { self_type, trait_, .. } => {
4778 work.push_back(*self_type);
4779 work.push_back(*trait_);