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;
49 use itertools::Itertools;
50 use rustc_ast_pretty::pprust;
51 use rustc_data_structures::flock;
52 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
53 use rustc_feature::UnstableFeatures;
55 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
56 use rustc_hir::Mutability;
57 use rustc_middle::middle::stability;
58 use rustc_span::edition::Edition;
59 use rustc_span::hygiene::MacroKind;
60 use rustc_span::source_map::FileName;
61 use rustc_span::symbol::{sym, Symbol};
62 use serde::ser::SerializeSeq;
63 use serde::{Serialize, Serializer};
65 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, TypeKind};
66 use crate::config::RenderInfo;
67 use crate::config::RenderOptions;
68 use crate::docfs::{DocFS, ErrorStorage, PathError};
70 use crate::error::Error;
71 use crate::formats::cache::{cache, Cache};
72 use crate::formats::item_type::ItemType;
73 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
74 use crate::html::escape::Escape;
75 use crate::html::format::fmt_impl_for_trait_page;
76 use crate::html::format::Function;
77 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
78 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
79 use crate::html::markdown::{self, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine};
80 use crate::html::sources;
81 use crate::html::{highlight, layout, static_files};
82 use cache::{build_index, ExternalLocation};
84 /// A pair of name and its optional document.
85 pub type NameDoc = (String, Option<String>);
87 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
88 crate::html::format::display_fn(move |f| {
89 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
93 /// Major driving force in all rustdoc rendering. This contains information
94 /// about where in the tree-like hierarchy rendering is occurring and controls
95 /// how the current page is being rendered.
97 /// It is intended that this context is a lightweight object which can be fairly
98 /// easily cloned because it is cloned per work-job (about once per item in the
101 crate struct Context {
102 /// Current hierarchy of components leading down to what's currently being
104 pub current: Vec<String>,
105 /// The current destination folder of where HTML artifacts should be placed.
106 /// This changes as the context descends into the module hierarchy.
108 /// A flag, which when `true`, will render pages which redirect to the
109 /// real location of an item. This is used to allow external links to
110 /// publicly reused items to redirect to the right location.
111 pub render_redirect_pages: bool,
112 /// The map used to ensure all generated 'id=' attributes are unique.
113 id_map: Rc<RefCell<IdMap>>,
114 pub shared: Arc<SharedContext>,
115 all: Rc<RefCell<AllTypes>>,
116 pub errors: Arc<ErrorStorage>,
119 crate struct SharedContext {
120 /// The path to the crate root source minus the file name.
121 /// Used for simplifying paths to the highlighted source code files.
122 pub src_root: PathBuf,
123 /// This describes the layout of each page, and is not modified after
124 /// creation of the context (contains info like the favicon and added html).
125 pub layout: layout::Layout,
126 /// This flag indicates whether `[src]` links should be generated or not. If
127 /// the source files are present in the html rendering, then this will be
129 pub include_sources: bool,
130 /// The local file sources we've emitted and their respective url-paths.
131 pub local_sources: FxHashMap<PathBuf, String>,
132 /// Whether the collapsed pass ran
134 /// The base-URL of the issue tracker for when an item has been tagged with
136 pub issue_tracker_base_url: Option<String>,
137 /// The directories that have already been created in this doc run. Used to reduce the number
138 /// of spurious `create_dir_all` calls.
139 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
140 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
141 /// should be ordered alphabetically or in order of appearance (in the source code).
142 pub sort_modules_alphabetically: bool,
143 /// Additional CSS files to be added to the generated docs.
144 pub style_files: Vec<StylePath>,
145 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
147 pub resource_suffix: String,
148 /// Optional path string to be used to load static files on output pages. If not set, uses
149 /// combinations of `../` to reach the documentation root.
150 pub static_root_path: Option<String>,
151 /// The fs handle we are working with.
153 /// The default edition used to parse doctests.
154 pub edition: Edition,
155 pub codes: ErrorCodes,
156 playground: Option<markdown::Playground>,
160 fn path(&self, filename: &str) -> PathBuf {
161 // We use splitn vs Path::extension here because we might get a filename
162 // like `style.min.css` and we want to process that into
163 // `style-suffix.min.css`. Path::extension would just return `css`
164 // which would result in `style.min-suffix.css` which isn't what we
166 let mut iter = filename.splitn(2, '.');
167 let base = iter.next().unwrap();
168 let ext = iter.next().unwrap();
169 let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext,);
170 self.dst.join(&filename)
175 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
176 let mut dirs = self.created_dirs.borrow_mut();
177 if !dirs.contains(dst) {
178 try_err!(self.fs.create_dir_all(dst), dst);
179 dirs.insert(dst.to_path_buf());
185 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
186 /// `collapsed_doc_value` of the given item.
187 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
189 item.collapsed_doc_value().map(|s| s.into())
191 item.doc_value().map(|s| s.into())
196 // Helper structs for rendering items/sidebars and carrying along contextual
199 /// Struct representing one entry in the JS search index. These are all emitted
200 /// by hand to a large JS file at the end of cache-creation.
202 pub struct IndexItem {
207 pub parent: Option<DefId>,
208 pub parent_idx: Option<usize>,
209 pub search_type: Option<IndexItemFunctionType>,
212 impl Serialize for IndexItem {
213 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
218 self.parent.is_some(),
219 self.parent_idx.is_some(),
220 "`{}` is missing idx",
224 (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
225 .serialize(serializer)
229 /// A type used for the search index.
231 pub struct RenderType {
234 name: Option<String>,
235 generics: Option<Vec<Generic>>,
238 impl Serialize for RenderType {
239 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
243 if let Some(name) = &self.name {
244 let mut seq = serializer.serialize_seq(None)?;
245 if let Some(id) = self.idx {
246 seq.serialize_element(&id)?;
248 seq.serialize_element(&name)?;
250 if let Some(generics) = &self.generics {
251 seq.serialize_element(&generics)?;
255 serializer.serialize_none()
260 /// A type used for the search index.
264 defid: Option<DefId>,
268 impl Serialize for Generic {
269 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
273 if let Some(id) = self.idx {
274 serializer.serialize_some(&id)
276 serializer.serialize_some(&self.name)
281 /// Full type of functions/methods in the search index.
283 pub struct IndexItemFunctionType {
284 inputs: Vec<TypeWithKind>,
285 output: Option<Vec<TypeWithKind>>,
288 impl Serialize for IndexItemFunctionType {
289 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
293 // If we couldn't figure out a type, just write `null`.
294 let mut iter = self.inputs.iter();
295 if match self.output {
296 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
297 None => iter.any(|ref i| i.ty.name.is_none()),
299 serializer.serialize_none()
301 let mut seq = serializer.serialize_seq(None)?;
302 seq.serialize_element(&self.inputs)?;
303 if let Some(output) = &self.output {
304 if output.len() > 1 {
305 seq.serialize_element(&output)?;
307 seq.serialize_element(&output[0])?;
316 pub struct TypeWithKind {
321 impl From<(RenderType, TypeKind)> for TypeWithKind {
322 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
323 TypeWithKind { ty: x.0, kind: x.1 }
327 impl Serialize for TypeWithKind {
328 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
332 let mut seq = serializer.serialize_seq(None)?;
333 seq.serialize_element(&self.ty.name)?;
334 let x: ItemType = self.kind.into();
335 seq.serialize_element(&x)?;
340 #[derive(Debug, Clone)]
341 pub struct StylePath {
342 /// The path to the theme
344 /// What the `disabled` attribute should be set to in the HTML tag
348 thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
350 pub fn initial_ids() -> Vec<String> {
362 "synthetic-implementors",
364 "synthetic-implementors-list",
370 .map(|id| (String::from(*id)))
374 /// Generates the documentation for `crate` into the directory `dst`
375 impl FormatRenderer for Context {
377 mut krate: clean::Crate,
378 options: RenderOptions,
379 _render_info: RenderInfo,
382 ) -> Result<(Context, clean::Crate), Error> {
383 // need to save a copy of the options for rendering the index page
384 let md_opts = options.clone();
390 sort_modules_alphabetically,
395 generate_search_filter,
399 let src_root = match krate.src {
400 FileName::Real(ref p) => match p.local_path().parent() {
401 Some(p) => p.to_path_buf(),
402 None => PathBuf::new(),
406 let errors = Arc::new(ErrorStorage::new());
407 // If user passed in `--playground-url` arg, we fill in crate name here
408 let mut playground = None;
409 if let Some(url) = playground_url {
410 playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url });
412 let mut layout = layout::Layout {
414 favicon: String::new(),
416 krate: krate.name.clone(),
417 css_file_extension: extension_css,
418 generate_search_filter,
420 let mut issue_tracker_base_url = None;
421 let mut include_sources = true;
423 // Crawl the crate attributes looking for attributes which control how we're
424 // going to emit HTML
425 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
426 for attr in attrs.lists(sym::doc) {
427 match (attr.name_or_empty(), attr.value_str()) {
428 (sym::html_favicon_url, Some(s)) => {
429 layout.favicon = s.to_string();
431 (sym::html_logo_url, Some(s)) => {
432 layout.logo = s.to_string();
434 (sym::html_playground_url, Some(s)) => {
435 playground = Some(markdown::Playground {
436 crate_name: Some(krate.name.clone()),
440 (sym::issue_tracker_base_url, Some(s)) => {
441 issue_tracker_base_url = Some(s.to_string());
443 (sym::html_no_source, None) if attr.is_word() => {
444 include_sources = false;
450 let mut scx = SharedContext {
451 collapsed: krate.collapsed,
454 local_sources: Default::default(),
455 issue_tracker_base_url,
457 created_dirs: Default::default(),
458 sort_modules_alphabetically,
462 fs: DocFS::new(&errors),
464 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
468 // Add the default themes to the `Vec` of stylepaths
470 // Note that these must be added before `sources::render` is called
471 // so that the resulting source pages are styled
473 // `light.css` is not disabled because it is the stylesheet that stays loaded
474 // by the browser as the theme stylesheet. The theme system (hackily) works by
475 // changing the href to this stylesheet. All other themes are disabled to
476 // prevent rule conflicts
477 scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
478 scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
479 scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
482 scx.ensure_dir(&dst)?;
483 krate = sources::render(&dst, &mut scx, krate)?;
485 // Build our search index
486 let index = build_index(&krate, cache);
488 let cache = Arc::new(cache);
489 let mut cx = Context {
492 render_redirect_pages: false,
493 id_map: Rc::new(RefCell::new(id_map)),
494 shared: Arc::new(scx),
495 all: Rc::new(RefCell::new(AllTypes::new())),
499 CURRENT_DEPTH.with(|s| s.set(0));
501 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
502 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
503 write_shared(&cx, &krate, index, &md_opts, &cache)?;
504 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
508 fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
510 Arc::get_mut(&mut self.errors).map_or_else(|| 0, |errors| errors.write_errors(diag));
512 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
518 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
519 let final_file = self.dst.join(&krate.name).join("all.html");
520 let settings_file = self.dst.join("settings.html");
521 let crate_name = krate.name.clone();
523 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
524 if !root_path.ends_with('/') {
527 let mut page = layout::Page {
528 title: "List of all items in this crate",
531 static_root_path: self.shared.static_root_path.as_deref(),
532 description: "List of all items in this crate",
533 keywords: BASIC_KEYWORDS,
534 resource_suffix: &self.shared.resource_suffix,
536 static_extra_scripts: &[],
538 let sidebar = if let Some(ref version) = cache.crate_version {
540 "<p class='location'>Crate {}</p>\
541 <div class='block version'>\
544 <a id='all-types' href='index.html'><p>Back to index</p></a>",
551 let all = self.all.replace(AllTypes::new());
552 let v = layout::render(
556 |buf: &mut Buffer| all.print(buf),
557 &self.shared.style_files,
559 self.shared.fs.write(&final_file, v.as_bytes())?;
561 // Generating settings page.
562 page.title = "Rustdoc settings";
563 page.description = "Settings of Rustdoc";
564 page.root_path = "./";
566 let mut style_files = self.shared.style_files.clone();
567 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
568 style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
569 let v = layout::render(
574 self.shared.static_root_path.as_deref().unwrap_or("./"),
575 &self.shared.resource_suffix,
579 self.shared.fs.write(&settings_file, v.as_bytes())?;
588 ) -> Result<(), Error> {
589 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
590 // if they contain impls for public types. These modules can also
591 // contain items such as publicly re-exported structures.
593 // External crates will provide links to these structures, so
594 // these modules are recursed into, but not rendered normally
595 // (a flag on the context).
596 if !self.render_redirect_pages {
597 self.render_redirect_pages = item.is_stripped();
599 let scx = &self.shared;
600 self.dst.push(item_name);
601 self.current.push(item_name.to_owned());
603 info!("Recursing into {}", self.dst.display());
605 let buf = self.render_item(item, false, cache);
606 // buf will be empty if the module is stripped and there is no redirect for it
608 self.shared.ensure_dir(&self.dst)?;
609 let joint_dst = self.dst.join("index.html");
610 scx.fs.write(&joint_dst, buf.as_bytes())?;
613 // Render sidebar-items.js used throughout this module.
614 if !self.render_redirect_pages {
615 let module = match item.inner {
616 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
619 let items = self.build_sidebar_items(module);
620 let js_dst = self.dst.join("sidebar-items.js");
621 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
622 scx.fs.write(&js_dst, &v)?;
627 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
628 info!("Recursed; leaving {}", self.dst.display());
630 // Go back to where we were at
636 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
637 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
638 // if they contain impls for public types. These modules can also
639 // contain items such as publicly re-exported structures.
641 // External crates will provide links to these structures, so
642 // these modules are recursed into, but not rendered normally
643 // (a flag on the context).
644 if !self.render_redirect_pages {
645 self.render_redirect_pages = item.is_stripped();
648 let buf = self.render_item(&item, true, cache);
649 // buf will be empty if the item is stripped and there is no redirect for it
651 let name = item.name.as_ref().unwrap();
652 let item_type = item.type_();
653 let file_name = &item_path(item_type, name);
654 self.shared.ensure_dir(&self.dst)?;
655 let joint_dst = self.dst.join(file_name);
656 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
658 if !self.render_redirect_pages {
659 self.all.borrow_mut().append(full_path(self, &item), &item_type);
661 // If the item is a macro, redirect from the old macro URL (with !)
662 // to the new one (without).
663 if item_type == ItemType::Macro {
664 let redir_name = format!("{}.{}!.html", item_type, name);
665 let redir_dst = self.dst.join(redir_name);
666 let v = layout::redirect(file_name);
667 self.shared.fs.write(&redir_dst, v.as_bytes())?;
676 krate: &clean::Crate,
677 search_index: String,
678 options: &RenderOptions,
680 ) -> Result<(), Error> {
681 // Write out the shared files. Note that these are shared among all rustdoc
682 // docs placed in the output directory, so this needs to be a synchronized
683 // operation with respect to all other rustdocs running around.
684 let lock_file = cx.dst.join(".lock");
685 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
687 // Add all the static files. These may already exist, but we just
688 // overwrite them anyway to make sure that they're fresh and up-to-date.
692 cx.path("rustdoc.css"),
693 static_files::RUSTDOC_CSS,
694 options.enable_minification,
698 cx.path("settings.css"),
699 static_files::SETTINGS_CSS,
700 options.enable_minification,
704 cx.path("noscript.css"),
705 static_files::NOSCRIPT_CSS,
706 options.enable_minification,
709 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
710 // then we'll run over the "official" styles.
711 let mut themes: FxHashSet<String> = FxHashSet::default();
713 for entry in &cx.shared.style_files {
714 let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
716 try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
718 // Handle the official themes
720 "light" => write_minify(
722 cx.path("light.css"),
723 static_files::themes::LIGHT,
724 options.enable_minification,
726 "dark" => write_minify(
729 static_files::themes::DARK,
730 options.enable_minification,
732 "ayu" => write_minify(
735 static_files::themes::AYU,
736 options.enable_minification,
739 // Handle added third-party themes
740 let content = try_err!(fs::read(&entry.path), &entry.path);
743 .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
747 themes.insert(theme.to_owned());
750 let write = |p, c| cx.shared.fs.write(p, c);
751 if (*cx.shared).layout.logo.is_empty() {
752 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
754 if (*cx.shared).layout.favicon.is_empty() {
755 write(cx.path("favicon.ico"), static_files::RUST_FAVICON)?;
757 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
758 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
759 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
761 let mut themes: Vec<&String> = themes.iter().collect();
763 // To avoid theme switch latencies as much as possible, we put everything theme related
764 // at the beginning of the html files into another js file.
765 let theme_js = format!(
766 r#"var themes = document.getElementById("theme-choices");
767 var themePicker = document.getElementById("theme-picker");
769 function showThemeButtonState() {{
770 themes.style.display = "block";
771 themePicker.style.borderBottomRightRadius = "0";
772 themePicker.style.borderBottomLeftRadius = "0";
775 function hideThemeButtonState() {{
776 themes.style.display = "none";
777 themePicker.style.borderBottomRightRadius = "3px";
778 themePicker.style.borderBottomLeftRadius = "3px";
781 function switchThemeButtonState() {{
782 if (themes.style.display === "block") {{
783 hideThemeButtonState();
785 showThemeButtonState();
789 function handleThemeButtonsBlur(e) {{
790 var active = document.activeElement;
791 var related = e.relatedTarget;
793 if (active.id !== "themePicker" &&
794 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
796 (related.id !== "themePicker" &&
797 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
798 hideThemeButtonState();
802 themePicker.onclick = switchThemeButtonState;
803 themePicker.onblur = handleThemeButtonsBlur;
804 {}.forEach(function(item) {{
805 var but = document.createElement('button');
806 but.textContent = item;
807 but.onclick = function(el) {{
808 switchTheme(currentTheme, mainTheme, item, true);
810 but.onblur = handleThemeButtonsBlur;
811 themes.appendChild(but);
813 serde_json::to_string(&themes).unwrap()
816 write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
820 static_files::MAIN_JS,
821 options.enable_minification,
825 cx.path("settings.js"),
826 static_files::SETTINGS_JS,
827 options.enable_minification,
829 if cx.shared.include_sources {
832 cx.path("source-script.js"),
833 static_files::sidebar::SOURCE_SCRIPT,
834 options.enable_minification,
841 cx.path("storage.js"),
843 "var resourcesSuffix = \"{}\";{}",
844 cx.shared.resource_suffix,
845 static_files::STORAGE_JS
847 options.enable_minification,
851 if let Some(ref css) = cx.shared.layout.css_file_extension {
852 let out = cx.path("theme.css");
853 let buffer = try_err!(fs::read_to_string(css), css);
854 if !options.enable_minification {
855 cx.shared.fs.write(&out, &buffer)?;
857 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
862 cx.path("normalize.css"),
863 static_files::NORMALIZE_CSS,
864 options.enable_minification,
866 write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
867 write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
868 write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
869 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
870 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
871 write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
872 write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
873 write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
874 write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
875 write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
876 write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
877 write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
878 write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
880 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
881 let mut ret = Vec::new();
882 let mut krates = Vec::new();
885 for line in BufReader::new(File::open(path)?).lines() {
887 if !line.starts_with(key) {
890 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
893 ret.push(line.to_string());
895 line[key.len() + 2..]
898 .map(|s| s.to_owned())
899 .unwrap_or_else(String::new),
906 fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
907 let mut ret = Vec::new();
908 let mut krates = Vec::new();
911 for line in BufReader::new(File::open(path)?).lines() {
913 if !line.starts_with('"') {
916 if line.starts_with(&format!("\"{}\"", krate)) {
919 if line.ends_with(",\\") {
920 ret.push(line[..line.len() - 2].to_string());
922 // Ends with "\\" (it's the case for the last added crate line)
923 ret.push(line[..line.len() - 1].to_string());
927 .find(|s| !s.is_empty())
928 .map(|s| s.to_owned())
929 .unwrap_or_else(String::new),
936 use std::ffi::OsString;
941 children: FxHashMap<OsString, Hierarchy>,
942 elems: FxHashSet<OsString>,
946 fn new(elem: OsString) -> Hierarchy {
947 Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
950 fn to_json_string(&self) -> String {
951 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
952 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
956 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
957 .collect::<Vec<_>>();
958 files.sort_unstable_by(|a, b| a.cmp(b));
959 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
961 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
962 let files = files.join(",");
964 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
966 "{{\"name\":\"{name}\"{dirs}{files}}}",
967 name = self.elem.to_str().expect("invalid osstring conversion"),
974 if cx.shared.include_sources {
975 let mut hierarchy = Hierarchy::new(OsString::new());
980 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
982 let mut h = &mut hierarchy;
983 let mut elems = source
985 .filter_map(|s| match s {
986 Component::Normal(s) => Some(s.to_owned()),
991 let cur_elem = elems.next().expect("empty file path");
992 if elems.peek().is_none() {
993 h.elems.insert(cur_elem);
996 let e = cur_elem.clone();
997 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
998 h = h.children.get_mut(&cur_elem).expect("not found child");
1003 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1004 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1005 all_sources.push(format!(
1006 "sourcesIndex[\"{}\"] = {};",
1008 hierarchy.to_json_string()
1012 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1013 all_sources.join("\n")
1015 cx.shared.fs.write(&dst, v.as_bytes())?;
1018 // Update the search index
1019 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1020 let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name), &dst);
1021 all_indexes.push(search_index);
1023 // Sort the indexes by crate so the file will be generated identically even
1024 // with rustdoc running in parallel.
1027 let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1028 v.push_str(&all_indexes.join(",\\\n"));
1029 // "addSearchOptions" has to be called first so the crate filtering can be set before the
1030 // search might start (if it's set into the URL for example).
1031 v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1032 cx.shared.fs.write(&dst, &v)?;
1034 if options.enable_index_page {
1035 if let Some(index_page) = options.index_page.clone() {
1036 let mut md_opts = options.clone();
1037 md_opts.output = cx.dst.clone();
1038 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1040 crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1041 .map_err(|e| Error::new(e, &index_page))?;
1043 let dst = cx.dst.join("index.html");
1044 let page = layout::Page {
1045 title: "Index of crates",
1048 static_root_path: cx.shared.static_root_path.as_deref(),
1049 description: "List of crates",
1050 keywords: BASIC_KEYWORDS,
1051 resource_suffix: &cx.shared.resource_suffix,
1053 static_extra_scripts: &[],
1055 krates.push(krate.name.clone());
1059 let content = format!(
1061 <span class='in-band'>List of all crates</span>\
1062 </h1><ul class='mod'>{}</ul>",
1066 format!("<li><a href=\"{}index.html\">{}</li>", ensure_trailing_slash(s), s)
1068 .collect::<String>()
1070 let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1071 cx.shared.fs.write(&dst, v.as_bytes())?;
1075 // Update the list of all implementors for traits
1076 let dst = cx.dst.join("implementors");
1077 for (&did, imps) in &cache.implementors {
1078 // Private modules can leak through to this phase of rustdoc, which
1079 // could contain implementations for otherwise private types. In some
1080 // rare cases we could find an implementation for an item which wasn't
1081 // indexed, so we just skip this step in that case.
1083 // FIXME: this is a vague explanation for why this can't be a `get`, in
1084 // theory it should be...
1085 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1087 None => match cache.external_paths.get(&did) {
1093 #[derive(Serialize)]
1094 struct Implementor {
1100 let implementors = imps
1103 // If the trait and implementation are in the same crate, then
1104 // there's no need to emit information about it (there's inlining
1105 // going on). If they're in different crates then the crate defining
1106 // the trait will be interested in our implementation.
1108 // If the implementation is from another crate then that crate
1110 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1114 text: imp.inner_impl().print().to_string(),
1115 synthetic: imp.inner_impl().synthetic,
1116 types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1120 .collect::<Vec<_>>();
1122 // Only create a js file if we have impls to add to it. If the trait is
1123 // documented locally though we always create the file to avoid dead
1125 if implementors.is_empty() && !cache.paths.contains_key(&did) {
1129 let implementors = format!(
1130 r#"implementors["{}"] = {};"#,
1132 serde_json::to_string(&implementors).unwrap()
1135 let mut mydst = dst.clone();
1136 for part in &remote_path[..remote_path.len() - 1] {
1139 cx.shared.ensure_dir(&mydst)?;
1140 mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1142 let (mut all_implementors, _) =
1143 try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1144 all_implementors.push(implementors);
1145 // Sort the implementors by crate so the file will be generated
1146 // identically even with rustdoc running in parallel.
1147 all_implementors.sort();
1149 let mut v = String::from("(function() {var implementors = {};\n");
1150 for implementor in &all_implementors {
1151 writeln!(v, "{}", *implementor).unwrap();
1154 "if (window.register_implementors) {\
1155 window.register_implementors(implementors);\
1157 window.pending_implementors = implementors;\
1161 cx.shared.fs.write(&mydst, &v)?;
1170 enable_minification: bool,
1171 ) -> Result<(), Error> {
1172 if enable_minification {
1173 if dst.extension() == Some(&OsStr::new("css")) {
1174 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1175 fs.write(dst, res.as_bytes())
1177 fs.write(dst, minifier::js::minify(contents).as_bytes())
1180 fs.write(dst, contents.as_bytes())
1184 #[derive(Debug, Eq, PartialEq, Hash)]
1191 fn new(mut url: String, name: String) -> ItemEntry {
1192 while url.starts_with('/') {
1195 ItemEntry { url, name }
1200 crate fn print(&self) -> impl fmt::Display + '_ {
1201 crate::html::format::display_fn(move |f| {
1202 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1207 impl PartialOrd for ItemEntry {
1208 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1209 Some(self.cmp(other))
1213 impl Ord for ItemEntry {
1214 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1215 self.name.cmp(&other.name)
1221 structs: FxHashSet<ItemEntry>,
1222 enums: FxHashSet<ItemEntry>,
1223 unions: FxHashSet<ItemEntry>,
1224 primitives: FxHashSet<ItemEntry>,
1225 traits: FxHashSet<ItemEntry>,
1226 macros: FxHashSet<ItemEntry>,
1227 functions: FxHashSet<ItemEntry>,
1228 typedefs: FxHashSet<ItemEntry>,
1229 opaque_tys: FxHashSet<ItemEntry>,
1230 statics: FxHashSet<ItemEntry>,
1231 constants: FxHashSet<ItemEntry>,
1232 keywords: FxHashSet<ItemEntry>,
1233 attributes: FxHashSet<ItemEntry>,
1234 derives: FxHashSet<ItemEntry>,
1235 trait_aliases: FxHashSet<ItemEntry>,
1239 fn new() -> AllTypes {
1240 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1242 structs: new_set(100),
1243 enums: new_set(100),
1244 unions: new_set(100),
1245 primitives: new_set(26),
1246 traits: new_set(100),
1247 macros: new_set(100),
1248 functions: new_set(100),
1249 typedefs: new_set(100),
1250 opaque_tys: new_set(100),
1251 statics: new_set(100),
1252 constants: new_set(100),
1253 keywords: new_set(100),
1254 attributes: new_set(100),
1255 derives: new_set(100),
1256 trait_aliases: new_set(100),
1260 fn append(&mut self, item_name: String, item_type: &ItemType) {
1261 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1262 if let Some(name) = url.pop() {
1263 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1265 let name = url.join("::");
1267 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1268 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1269 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1270 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1271 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1272 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1273 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1274 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1275 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1276 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1277 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1278 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1279 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1280 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1287 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1289 let mut e: Vec<&ItemEntry> = e.iter().collect();
1293 "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1297 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1303 fn print(self, f: &mut Buffer) {
1307 <span class='out-of-band'>\
1308 <span id='render-detail'>\
1309 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1310 [<span class='inner'>−</span>]\
1314 <span class='in-band'>List of all items</span>\
1317 print_entries(f, &self.structs, "Structs", "structs");
1318 print_entries(f, &self.enums, "Enums", "enums");
1319 print_entries(f, &self.unions, "Unions", "unions");
1320 print_entries(f, &self.primitives, "Primitives", "primitives");
1321 print_entries(f, &self.traits, "Traits", "traits");
1322 print_entries(f, &self.macros, "Macros", "macros");
1323 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1324 print_entries(f, &self.derives, "Derive Macros", "derives");
1325 print_entries(f, &self.functions, "Functions", "functions");
1326 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1327 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1328 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1329 print_entries(f, &self.statics, "Statics", "statics");
1330 print_entries(f, &self.constants, "Constants", "constants")
1336 Section { description: &'static str, sub_settings: Vec<Setting> },
1337 Entry { js_data_name: &'static str, description: &'static str, default_value: bool },
1341 fn display(&self) -> String {
1343 Setting::Section { ref description, ref sub_settings } => format!(
1344 "<div class='setting-line'>\
1345 <div class='title'>{}</div>\
1346 <div class='sub-settings'>{}</div>
1349 sub_settings.iter().map(|s| s.display()).collect::<String>()
1351 Setting::Entry { ref js_data_name, ref description, ref default_value } => format!(
1352 "<div class='setting-line'>\
1353 <label class='toggle'>\
1354 <input type='checkbox' id='{}' {}>\
1355 <span class='slider'></span>\
1360 if *default_value { " checked" } else { "" },
1367 impl From<(&'static str, &'static str, bool)> for Setting {
1368 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1369 Setting::Entry { js_data_name: values.0, description: values.1, default_value: values.2 }
1373 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1374 fn from(values: (&'static str, Vec<T>)) -> Setting {
1376 description: values.0,
1377 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1382 fn settings(root_path: &str, suffix: &str) -> String {
1383 // (id, explanation, default value)
1384 let settings: &[Setting] = &[
1386 "Auto-hide item declarations",
1388 ("auto-hide-struct", "Auto-hide structs declaration", true),
1389 ("auto-hide-enum", "Auto-hide enums declaration", false),
1390 ("auto-hide-union", "Auto-hide unions declaration", true),
1391 ("auto-hide-trait", "Auto-hide traits declaration", true),
1392 ("auto-hide-macro", "Auto-hide macros declaration", false),
1396 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1397 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1398 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1400 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1401 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1403 ("line-numbers", "Show line numbers on code examples", false).into(),
1404 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1408 <span class='in-band'>Rustdoc settings</span>\
1410 <div class='settings'>{}</div>\
1411 <script src='{}settings{}.js'></script>",
1412 settings.iter().map(|s| s.display()).collect::<String>(),
1419 fn derive_id(&self, id: String) -> String {
1420 let mut map = self.id_map.borrow_mut();
1424 /// String representation of how to get back to the root path of the 'doc/'
1425 /// folder in terms of a relative URL.
1426 fn root_path(&self) -> String {
1427 "../".repeat(self.current.len())
1430 fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1431 // A little unfortunate that this is done like this, but it sure
1432 // does make formatting *a lot* nicer.
1433 CURRENT_DEPTH.with(|slot| {
1434 slot.set(self.current.len());
1437 let mut title = if it.is_primitive() || it.is_keyword() {
1438 // No need to include the namespace for primitive types and keywords
1441 self.current.join("::")
1444 if !title.is_empty() {
1445 title.push_str("::");
1447 title.push_str(it.name.as_ref().unwrap());
1449 title.push_str(" - Rust");
1450 let tyname = it.type_();
1451 let desc = if it.is_crate() {
1452 format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1455 "API documentation for the Rust `{}` {} in crate `{}`.",
1456 it.name.as_ref().unwrap(),
1458 self.shared.layout.krate
1461 let keywords = make_item_keywords(it);
1462 let page = layout::Page {
1463 css_class: tyname.as_str(),
1464 root_path: &self.root_path(),
1465 static_root_path: self.shared.static_root_path.as_deref(),
1468 keywords: &keywords,
1469 resource_suffix: &self.shared.resource_suffix,
1471 static_extra_scripts: &[],
1475 self.id_map.borrow_mut().reset();
1476 self.id_map.borrow_mut().populate(initial_ids());
1479 if !self.render_redirect_pages {
1481 &self.shared.layout,
1483 |buf: &mut _| print_sidebar(self, it, buf, cache),
1484 |buf: &mut _| print_item(self, it, buf, cache),
1485 &self.shared.style_files,
1488 let mut url = self.root_path();
1489 if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1490 for name in &names[..names.len() - 1] {
1494 url.push_str(&item_path(ty, names.last().unwrap()));
1495 layout::redirect(&url)
1502 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1503 // BTreeMap instead of HashMap to get a sorted output
1504 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1505 for item in &m.items {
1506 if item.is_stripped() {
1510 let short = item.type_();
1511 let myname = match item.name {
1513 Some(ref s) => s.to_string(),
1515 let short = short.to_string();
1518 .push((myname, Some(plain_summary_line(item.doc_value()))));
1521 if self.shared.sort_modules_alphabetically {
1522 for items in map.values_mut() {
1529 /// Generates a url appropriate for an `href` attribute back to the source of
1532 /// The url generated, when clicked, will redirect the browser back to the
1533 /// original source code.
1535 /// If `None` is returned, then a source link couldn't be generated. This
1536 /// may happen, for example, with externally inlined items where the source
1537 /// of their crate documentation isn't known.
1538 fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1539 let mut root = self.root_path();
1541 let mut path = String::new();
1543 // We can safely ignore synthetic `SourceFile`s.
1544 let file = match item.source.filename {
1545 FileName::Real(ref path) => path.local_path().to_path_buf(),
1550 let (krate, path) = if item.source.cnum == LOCAL_CRATE {
1551 if let Some(path) = self.shared.local_sources.get(file) {
1552 (&self.shared.layout.krate, path)
1557 let (krate, src_root) = match *cache.extern_locations.get(&item.source.cnum)? {
1558 (ref name, ref src, ExternalLocation::Local) => (name, src),
1559 (ref name, ref src, ExternalLocation::Remote(ref s)) => {
1560 root = s.to_string();
1563 (_, _, ExternalLocation::Unknown) => return None,
1566 sources::clean_path(&src_root, file, false, |component| {
1567 path.push_str(&component.to_string_lossy());
1570 let mut fname = file.file_name().expect("source has no filename").to_os_string();
1571 fname.push(".html");
1572 path.push_str(&fname.to_string_lossy());
1576 let lines = if item.source.loline == item.source.hiline {
1577 item.source.loline.to_string()
1579 format!("{}-{}", item.source.loline, item.source.hiline)
1582 "{root}src/{krate}/{path}#{lines}",
1583 root = Escape(&root),
1591 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1593 F: FnOnce(&mut Buffer),
1595 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1600 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1601 debug_assert!(!item.is_stripped());
1602 // Write the breadcrumb trail header for the top
1603 write!(buf, "<h1 class='fqn'><span class='out-of-band'>");
1604 if let Some(version) = item.stable_since() {
1607 "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1613 "<span id='render-detail'>\
1614 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1615 title=\"collapse all docs\">\
1616 [<span class='inner'>−</span>]\
1623 // When this item is part of a `pub use` in a downstream crate, the
1624 // [src] link in the downstream documentation will actually come back to
1625 // this page, and this link will be auto-clicked. The `id` attribute is
1626 // used to find the link to auto-click.
1627 if cx.shared.include_sources && !item.is_primitive() {
1628 if let Some(l) = cx.src_href(item, cache) {
1629 write!(buf, "<a class='srclink' href='{}' title='{}'>[src]</a>", l, "goto source code");
1633 write!(buf, "</span>"); // out-of-band
1634 write!(buf, "<span class='in-band'>");
1635 let name = match item.inner {
1636 clean::ModuleItem(ref m) => {
1643 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1644 clean::TraitItem(..) => "Trait ",
1645 clean::StructItem(..) => "Struct ",
1646 clean::UnionItem(..) => "Union ",
1647 clean::EnumItem(..) => "Enum ",
1648 clean::TypedefItem(..) => "Type Definition ",
1649 clean::MacroItem(..) => "Macro ",
1650 clean::ProcMacroItem(ref mac) => match mac.kind {
1651 MacroKind::Bang => "Macro ",
1652 MacroKind::Attr => "Attribute Macro ",
1653 MacroKind::Derive => "Derive Macro ",
1655 clean::PrimitiveItem(..) => "Primitive Type ",
1656 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1657 clean::ConstantItem(..) => "Constant ",
1658 clean::ForeignTypeItem => "Foreign Type ",
1659 clean::KeywordItem(..) => "Keyword ",
1660 clean::OpaqueTyItem(..) => "Opaque Type ",
1661 clean::TraitAliasItem(..) => "Trait Alias ",
1663 // We don't generate pages for any other type.
1667 buf.write_str(name);
1668 if !item.is_primitive() && !item.is_keyword() {
1669 let cur = &cx.current;
1670 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1671 for (i, component) in cur.iter().enumerate().take(amt) {
1674 "<a href='{}index.html'>{}</a>::<wbr>",
1675 "../".repeat(cur.len() - i - 1),
1680 write!(buf, "<a class=\"{}\" href=''>{}</a>", item.type_(), item.name.as_ref().unwrap());
1682 write!(buf, "</span></h1>"); // in-band
1685 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1686 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1687 item_function(buf, cx, item, f)
1689 clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1690 clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1691 clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1692 clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1693 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1694 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1695 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1696 clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1697 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1698 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1699 clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1700 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1701 clean::OpaqueTyItem(ref e, _) => item_opaque_ty(buf, cx, item, e, cache),
1702 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1704 // We don't generate pages for any other type.
1710 fn item_path(ty: ItemType, name: &str) -> String {
1712 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1713 _ => format!("{}.{}.html", ty, name),
1717 fn full_path(cx: &Context, item: &clean::Item) -> String {
1718 let mut s = cx.current.join("::");
1720 s.push_str(item.name.as_ref().unwrap());
1725 crate fn plain_summary_line(s: Option<&str>) -> String {
1726 let s = s.unwrap_or("");
1727 // This essentially gets the first paragraph of text in one line.
1730 .skip_while(|line| line.chars().all(|c| c.is_whitespace()))
1731 .take_while(|line| line.chars().any(|c| !c.is_whitespace()))
1732 .fold(String::new(), |mut acc, line| {
1737 // remove final whitespace
1739 markdown::plain_summary_line(&line[..])
1742 crate fn shorten(s: String) -> String {
1743 if s.chars().count() > 60 {
1748 // + 1 for the added character after the word.
1749 len += p.chars().count() + 1;
1752 .collect::<Vec<_>>()
1761 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item) {
1762 if let Some(ref name) = item.name {
1763 info!("Documenting {}", name);
1765 document_stability(w, cx, item, false);
1766 document_full(w, item, cx, "", false);
1769 /// Render md_text as markdown.
1774 links: Vec<(String, String)>,
1778 let mut ids = cx.id_map.borrow_mut();
1781 "<div class='docblock{}'>{}{}</div>",
1782 if is_hidden { " hidden" } else { "" },
1790 &cx.shared.playground
1800 link: AssocItemLink<'_>,
1804 if let Some(s) = item.doc_value() {
1805 let markdown = if s.contains('\n') {
1807 "{} [Read more]({})",
1808 &plain_summary_line(Some(s)),
1809 naive_assoc_href(item, link)
1812 plain_summary_line(Some(s))
1814 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden);
1815 } else if !prefix.is_empty() {
1818 "<div class='docblock{}'>{}</div>",
1819 if is_hidden { " hidden" } else { "" },
1825 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1826 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1827 debug!("Doc block: =====\n{}\n=====", s);
1828 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1829 } else if !prefix.is_empty() {
1832 "<div class='docblock{}'>{}</div>",
1833 if is_hidden { " hidden" } else { "" },
1839 fn document_stability(w: &mut Buffer, cx: &Context, item: &clean::Item, is_hidden: bool) {
1840 let stabilities = short_stability(item, cx);
1841 if !stabilities.is_empty() {
1842 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" });
1843 for stability in stabilities {
1844 write!(w, "{}", stability);
1846 write!(w, "</div>");
1850 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1851 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1854 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1855 if item.is_non_exhaustive() {
1856 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
1857 if item.is_struct() {
1859 } else if item.is_enum() {
1861 } else if item.is_variant() {
1868 if item.is_struct() {
1871 "Non-exhaustive structs could have additional fields added in future. \
1872 Therefore, non-exhaustive structs cannot be constructed in external crates \
1873 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1874 matched against without a wildcard <code>..</code>; and \
1875 struct update syntax will not work."
1877 } else if item.is_enum() {
1880 "Non-exhaustive enums could have additional variants added in future. \
1881 Therefore, when matching against variants of non-exhaustive enums, an \
1882 extra wildcard arm must be added to account for any future variants."
1884 } else if item.is_variant() {
1887 "Non-exhaustive enum variants could have additional fields added in future. \
1888 Therefore, non-exhaustive enum variants cannot be constructed in external \
1889 crates and cannot be matched against."
1894 "This type will require a wildcard arm in any match statements or \
1899 write!(w, "</div>");
1903 fn name_key(name: &str) -> (&str, u64, usize) {
1904 let end = name.bytes().rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
1906 // find number at end
1907 let split = name[0..end].bytes().rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
1909 // count leading zeroes
1911 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1913 // sort leading zeroes last
1914 let num_zeroes = after_zeroes - split;
1916 match name[split..end].parse() {
1917 Ok(n) => (&name[..split], n, num_zeroes),
1918 Err(_) => (name, 0, num_zeroes),
1922 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
1923 document(w, cx, item);
1925 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1927 // the order of item types in the listing
1928 fn reorder(ty: ItemType) -> u8 {
1930 ItemType::ExternCrate => 0,
1931 ItemType::Import => 1,
1932 ItemType::Primitive => 2,
1933 ItemType::Module => 3,
1934 ItemType::Macro => 4,
1935 ItemType::Struct => 5,
1936 ItemType::Enum => 6,
1937 ItemType::Constant => 7,
1938 ItemType::Static => 8,
1939 ItemType::Trait => 9,
1940 ItemType::Function => 10,
1941 ItemType::Typedef => 12,
1942 ItemType::Union => 13,
1947 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1948 let ty1 = i1.type_();
1949 let ty2 = i2.type_();
1951 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
1953 let s1 = i1.stability.as_ref().map(|s| s.level);
1954 let s2 = i2.stability.as_ref().map(|s| s.level);
1956 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1957 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1960 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1961 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1962 name_key(lhs).cmp(&name_key(rhs))
1965 if cx.shared.sort_modules_alphabetically {
1966 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1968 // This call is to remove re-export duplicates in cases such as:
1973 // pub trait Double { fn foo(); }
1977 // pub use foo::bar::*;
1981 // `Double` will appear twice in the generated docs.
1983 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1984 // can be identical even if the elements are different (mostly in imports).
1985 // So in case this is an import, we keep everything by adding a "unique id"
1986 // (which is the position in the vector).
1987 indices.dedup_by_key(|i| {
1990 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
1992 if items[*i].is_import() { *i } else { 0 },
1996 debug!("{:?}", indices);
1997 let mut curty = None;
1998 for &idx in &indices {
1999 let myitem = &items[idx];
2000 if myitem.is_stripped() {
2004 let myty = Some(myitem.type_());
2005 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2006 // Put `extern crate` and `use` re-exports in the same section.
2008 } else if myty != curty {
2009 if curty.is_some() {
2010 write!(w, "</table>");
2013 let (short, name) = item_ty_to_strs(&myty.unwrap());
2016 "<h2 id='{id}' class='section-header'>\
2017 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2018 id = cx.derive_id(short.to_owned()),
2023 match myitem.inner {
2024 clean::ExternCrateItem(ref name, ref src) => {
2025 use crate::html::format::anchor;
2028 Some(ref src) => write!(
2030 "<tr><td><code>{}extern crate {} as {};",
2031 myitem.visibility.print_with_space(),
2032 anchor(myitem.def_id, src),
2037 "<tr><td><code>{}extern crate {};",
2038 myitem.visibility.print_with_space(),
2039 anchor(myitem.def_id, name)
2042 write!(w, "</code></td></tr>");
2045 clean::ImportItem(ref import) => {
2048 "<tr><td><code>{}{}</code></td></tr>",
2049 myitem.visibility.print_with_space(),
2055 if myitem.name.is_none() {
2059 let unsafety_flag = match myitem.inner {
2060 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2061 if func.header.unsafety == hir::Unsafety::Unsafe =>
2063 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2068 let stab = myitem.stability_class();
2069 let add = if stab.is_some() { " " } else { "" };
2071 let doc_value = myitem.doc_value().unwrap_or("");
2075 <tr class='{stab}{add}module-item'>\
2076 <td><a class=\"{class}\" href=\"{href}\" \
2077 title='{title}'>{name}</a>{unsafety_flag}</td>\
2078 <td class='docblock-short'>{stab_tags}{docs}</td>\
2080 name = *myitem.name.as_ref().unwrap(),
2081 stab_tags = stability_tags(myitem),
2082 docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2083 class = myitem.type_(),
2085 stab = stab.unwrap_or_else(String::new),
2086 unsafety_flag = unsafety_flag,
2087 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2088 title = [full_path(cx, myitem), myitem.type_().to_string()]
2090 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2091 .collect::<Vec<_>>()
2098 if curty.is_some() {
2099 write!(w, "</table>");
2103 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2105 fn stability_tags(item: &clean::Item) -> String {
2106 let mut tags = String::new();
2108 fn tag_html(class: &str, contents: &str) -> String {
2109 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2112 // The trailing space after each tag is to space it properly against the rest of the docs.
2113 if let Some(depr) = &item.deprecation {
2114 let mut message = "Deprecated";
2115 if !stability::deprecation_in_effect(depr.is_since_rustc_version, depr.since.as_deref()) {
2116 message = "Deprecation planned";
2118 tags += &tag_html("deprecated", message);
2121 // The "rustc_private" crates are permanently unstable so it makes no sense
2122 // to render "unstable" everywhere.
2126 .map(|s| s.level == stability::Unstable && s.feature.as_deref() != Some("rustc_private"))
2129 tags += &tag_html("unstable", "Experimental");
2132 if let Some(ref cfg) = item.attrs.cfg {
2133 tags += &tag_html("portability", &cfg.render_short_html());
2139 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2141 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2142 let mut stability = vec![];
2143 let error_codes = cx.shared.codes;
2145 if let Some(Deprecation { ref note, ref since, is_since_rustc_version }) = item.deprecation {
2146 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2147 // but only display the future-deprecation messages for #[rustc_deprecated].
2148 let mut message = if let Some(since) = since {
2149 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2150 format!("Deprecating in {}", Escape(&since))
2152 format!("Deprecated since {}", Escape(&since))
2155 String::from("Deprecated")
2158 if let Some(note) = note {
2159 let mut ids = cx.id_map.borrow_mut();
2160 let html = MarkdownHtml(
2165 &cx.shared.playground,
2167 message.push_str(&format!(": {}", html.into_string()));
2169 stability.push(format!(
2170 "<div class='stab deprecated'><span class='emoji'>👎</span> {}</div>",
2175 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2176 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2177 if let Some(stab) = item.stability.as_ref().filter(|stab| {
2178 stab.level == stability::Unstable && stab.feature.as_deref() != Some("rustc_private")
2181 "<span class='emoji'>🔬</span> This is a nightly-only experimental API.".to_owned();
2183 if let Some(feature) = stab.feature.as_deref() {
2184 let mut feature = format!("<code>{}</code>", Escape(&feature));
2185 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2186 feature.push_str(&format!(
2187 " <a href=\"{url}{issue}\">#{issue}</a>",
2193 message.push_str(&format!(" ({})", feature));
2196 if let Some(unstable_reason) = &stab.unstable_reason {
2197 let mut ids = cx.id_map.borrow_mut();
2199 "<details><summary>{}</summary>{}</details>",
2206 &cx.shared.playground,
2212 stability.push(format!("<div class='stab unstable'>{}</div>", message));
2215 if let Some(ref cfg) = item.attrs.cfg {
2216 stability.push(format!("<div class='stab portability'>{}</div>", cfg.render_long_html()));
2222 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2223 write!(w, "<pre class='rust const'>");
2224 render_attributes(w, it, false);
2230 vis = it.visibility.print_with_space(),
2231 name = it.name.as_ref().unwrap(),
2232 typ = c.type_.print(),
2235 if c.value.is_some() || c.is_literal {
2236 write!(w, " = {expr};", expr = Escape(&c.expr));
2241 if let Some(value) = &c.value {
2243 let value_lowercase = value.to_lowercase();
2244 let expr_lowercase = c.expr.to_lowercase();
2246 if value_lowercase != expr_lowercase
2247 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2249 write!(w, " // {value}", value = Escape(value));
2254 write!(w, "</pre>");
2258 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2259 write!(w, "<pre class='rust static'>");
2260 render_attributes(w, it, false);
2263 "{vis}static {mutability}\
2264 {name}: {typ}</pre>",
2265 vis = it.visibility.print_with_space(),
2266 mutability = s.mutability.print_with_space(),
2267 name = it.name.as_ref().unwrap(),
2268 typ = s.type_.print()
2273 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2274 let header_len = format!(
2275 "{}{}{}{}{:#}fn {}{:#}",
2276 it.visibility.print_with_space(),
2277 f.header.constness.print_with_space(),
2278 f.header.asyncness.print_with_space(),
2279 f.header.unsafety.print_with_space(),
2280 print_abi_with_space(f.header.abi),
2281 it.name.as_ref().unwrap(),
2285 write!(w, "<pre class='rust fn'>");
2286 render_attributes(w, it, false);
2289 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2290 {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2291 vis = it.visibility.print_with_space(),
2292 constness = f.header.constness.print_with_space(),
2293 asyncness = f.header.asyncness.print_with_space(),
2294 unsafety = f.header.unsafety.print_with_space(),
2295 abi = print_abi_with_space(f.header.abi),
2296 name = it.name.as_ref().unwrap(),
2297 generics = f.generics.print(),
2298 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2299 decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2301 spotlight = spotlight_decl(&f.decl),
2306 fn render_implementor(
2310 implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2314 // If there's already another implementor that has the same abbridged name, use the
2315 // full path, for example in `std::iter::ExactSizeIterator`
2316 let use_absolute = match implementor.inner_impl().for_ {
2317 clean::ResolvedPath { ref path, is_generic: false, .. }
2318 | clean::BorrowedRef {
2319 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2321 } => implementor_dups[path.last_name()].1,
2328 AssocItemLink::Anchor(None),
2330 implementor.impl_item.stable_since(),
2344 containing_item: &clean::Item,
2347 let mut impls = traits
2350 let did = i.trait_did().unwrap();
2351 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2352 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2359 containing_item.stable_since(),
2369 .collect::<Vec<_>>();
2371 w.write_str(&impls.join(""));
2374 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2375 let mut bounds = String::new();
2376 if !t_bounds.is_empty() {
2378 bounds.push_str(": ");
2380 for (i, p) in t_bounds.iter().enumerate() {
2382 bounds.push_str(" + ");
2384 bounds.push_str(&p.print().to_string());
2390 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2391 let lhs = format!("{}", lhs.inner_impl().print());
2392 let rhs = format!("{}", rhs.inner_impl().print());
2394 // lhs and rhs are formatted as HTML, which may be unnecessary
2395 name_key(&lhs).cmp(&name_key(&rhs))
2398 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2399 let bounds = bounds(&t.bounds, false);
2400 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2401 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2402 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2403 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2405 // Output the trait definition
2406 wrap_into_docblock(w, |w| {
2407 write!(w, "<pre class='rust trait'>");
2408 render_attributes(w, it, true);
2411 "{}{}{}trait {}{}{}",
2412 it.visibility.print_with_space(),
2413 t.unsafety.print_with_space(),
2414 if t.is_auto { "auto " } else { "" },
2415 it.name.as_ref().unwrap(),
2420 if !t.generics.where_predicates.is_empty() {
2421 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2426 if t.items.is_empty() {
2429 // FIXME: we should be using a derived_id for the Anchors here
2432 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2435 if !types.is_empty() && !consts.is_empty() {
2439 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2442 if !consts.is_empty() && !required.is_empty() {
2445 for (pos, m) in required.iter().enumerate() {
2446 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2449 if pos < required.len() - 1 {
2450 write!(w, "<div class='item-spacer'></div>");
2453 if !required.is_empty() && !provided.is_empty() {
2456 for (pos, m) in provided.iter().enumerate() {
2457 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2459 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2460 write!(w, ",\n {{ ... }}\n");
2463 write!(w, " {{ ... }}\n");
2466 if pos < provided.len() - 1 {
2467 write!(w, "<div class='item-spacer'></div>");
2475 // Trait documentation
2476 document(w, cx, it);
2478 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2482 <h2 id='{0}' class='small-section-header'>\
2483 {1}<a href='#{0}' class='anchor'></a>\
2485 id, title, extra_content
2489 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2490 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
2493 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item) {
2494 let name = m.name.as_ref().unwrap();
2495 let item_type = m.type_();
2496 let id = cx.derive_id(format!("{}.{}", item_type, name));
2497 write!(w, "<h3 id='{id}' class='method'><code>", id = id,);
2498 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2499 write!(w, "</code>");
2500 render_stability_since(w, m, t);
2505 if !types.is_empty() {
2506 write_small_section_header(
2510 "<div class='methods'>",
2513 trait_item(w, cx, *t, it);
2515 write_loading_content(w, "</div>");
2518 if !consts.is_empty() {
2519 write_small_section_header(
2522 "Associated Constants",
2523 "<div class='methods'>",
2526 trait_item(w, cx, *t, it);
2528 write_loading_content(w, "</div>");
2531 // Output the documentation for each function individually
2532 if !required.is_empty() {
2533 write_small_section_header(
2537 "<div class='methods'>",
2539 for m in &required {
2540 trait_item(w, cx, *m, it);
2542 write_loading_content(w, "</div>");
2544 if !provided.is_empty() {
2545 write_small_section_header(
2549 "<div class='methods'>",
2551 for m in &provided {
2552 trait_item(w, cx, *m, it);
2554 write_loading_content(w, "</div>");
2557 // If there are methods directly on this trait object, render them here.
2558 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2560 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2561 // The DefId is for the first Type found with that name. The bool is
2562 // if any Types with the same name but different DefId have been found.
2563 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2564 for implementor in implementors {
2565 match implementor.inner_impl().for_ {
2566 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2567 | clean::BorrowedRef {
2568 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2571 let &mut (prev_did, ref mut has_duplicates) =
2572 implementor_dups.entry(path.last_name()).or_insert((did, false));
2573 if prev_did != did {
2574 *has_duplicates = true;
2581 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2582 i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2585 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2586 local.iter().partition(|i| i.inner_impl().synthetic);
2588 synthetic.sort_by(compare_impl);
2589 concrete.sort_by(compare_impl);
2591 if !foreign.is_empty() {
2592 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2594 for implementor in foreign {
2595 let assoc_link = AssocItemLink::GotoSource(
2596 implementor.impl_item.def_id,
2597 &implementor.inner_impl().provided_trait_methods,
2605 implementor.impl_item.stable_since(),
2614 write_loading_content(w, "");
2617 write_small_section_header(
2621 "<div class='item-list' id='implementors-list'>",
2623 for implementor in concrete {
2624 render_implementor(cx, implementor, w, &implementor_dups, &[], cache);
2626 write_loading_content(w, "</div>");
2629 write_small_section_header(
2631 "synthetic-implementors",
2632 "Auto implementors",
2633 "<div class='item-list' id='synthetic-implementors-list'>",
2635 for implementor in synthetic {
2641 &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2645 write_loading_content(w, "</div>");
2648 // even without any implementations to write in, we still want the heading and list, so the
2649 // implementors javascript file pulled in below has somewhere to write the impls into
2650 write_small_section_header(
2654 "<div class='item-list' id='implementors-list'>",
2656 write_loading_content(w, "</div>");
2659 write_small_section_header(
2661 "synthetic-implementors",
2662 "Auto implementors",
2663 "<div class='item-list' id='synthetic-implementors-list'>",
2665 write_loading_content(w, "</div>");
2671 "<script type=\"text/javascript\" \
2672 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2674 root_path = vec![".."; cx.current.len()].join("/"),
2675 path = if it.def_id.is_local() {
2676 cx.current.join("/")
2678 let (ref path, _) = cache.external_paths[&it.def_id];
2679 path[..path.len() - 1].join("/")
2682 name = *it.name.as_ref().unwrap()
2686 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2687 use crate::formats::item_type::ItemType::*;
2689 let name = it.name.as_ref().unwrap();
2690 let ty = match it.type_() {
2691 Typedef | AssocType => AssocType,
2695 let anchor = format!("#{}.{}", ty, name);
2697 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2698 AssocItemLink::Anchor(None) => anchor,
2699 AssocItemLink::GotoSource(did, _) => {
2700 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2709 _default: Option<&String>,
2710 link: AssocItemLink<'_>,
2715 "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2717 it.visibility.print_with_space(),
2718 naive_assoc_href(it, link),
2719 it.name.as_ref().unwrap(),
2727 bounds: &[clean::GenericBound],
2728 default: Option<&clean::Type>,
2729 link: AssocItemLink<'_>,
2734 "{}type <a href='{}' class=\"type\">{}</a>",
2736 naive_assoc_href(it, link),
2737 it.name.as_ref().unwrap()
2739 if !bounds.is_empty() {
2740 write!(w, ": {}", print_generic_bounds(bounds))
2742 if let Some(default) = default {
2743 write!(w, " = {}", default.print())
2747 fn render_stability_since_raw(w: &mut Buffer, ver: Option<&str>, containing_ver: Option<&str>) {
2748 if let Some(v) = ver {
2749 if containing_ver != ver && !v.is_empty() {
2750 write!(w, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", v)
2755 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2756 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2759 fn render_assoc_item(
2762 link: AssocItemLink<'_>,
2768 header: hir::FnHeader,
2769 g: &clean::Generics,
2771 link: AssocItemLink<'_>,
2774 let name = meth.name.as_ref().unwrap();
2775 let anchor = format!("#{}.{}", meth.type_(), name);
2776 let href = match link {
2777 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2778 AssocItemLink::Anchor(None) => anchor,
2779 AssocItemLink::GotoSource(did, provided_methods) => {
2780 // We're creating a link from an impl-item to the corresponding
2781 // trait-item and need to map the anchored type accordingly.
2782 let ty = if provided_methods.contains(name) {
2788 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2791 let mut header_len = format!(
2792 "{}{}{}{}{}{:#}fn {}{:#}",
2793 meth.visibility.print_with_space(),
2794 header.constness.print_with_space(),
2795 header.asyncness.print_with_space(),
2796 header.unsafety.print_with_space(),
2797 print_default_space(meth.is_default()),
2798 print_abi_with_space(header.abi),
2803 let (indent, end_newline) = if parent == ItemType::Trait {
2809 render_attributes(w, meth, false);
2812 "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2813 {generics}{decl}{spotlight}{where_clause}",
2814 if parent == ItemType::Trait { " " } else { "" },
2815 meth.visibility.print_with_space(),
2816 header.constness.print_with_space(),
2817 header.asyncness.print_with_space(),
2818 header.unsafety.print_with_space(),
2819 print_default_space(meth.is_default()),
2820 print_abi_with_space(header.abi),
2823 generics = g.print(),
2824 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
2825 spotlight = spotlight_decl(&d),
2826 where_clause = WhereClause { gens: g, indent, end_newline }
2830 clean::StrippedItem(..) => {}
2831 clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2832 clean::MethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2833 clean::AssocConstItem(ref ty, ref default) => assoc_const(
2839 if parent == ItemType::Trait { " " } else { "" },
2841 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
2847 if parent == ItemType::Trait { " " } else { "" },
2849 _ => panic!("render_assoc_item called on non-associated-item"),
2853 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
2854 wrap_into_docblock(w, |w| {
2855 write!(w, "<pre class='rust struct'>");
2856 render_attributes(w, it, true);
2857 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
2861 document(w, cx, it);
2865 .filter_map(|f| match f.inner {
2866 clean::StructFieldItem(ref ty) => Some((f, ty)),
2870 if let doctree::Plain = s.struct_type {
2871 if fields.peek().is_some() {
2874 "<h2 id='fields' class='fields small-section-header'>
2875 Fields{}<a href='#fields' class='anchor'></a></h2>",
2876 document_non_exhaustive_header(it)
2878 document_non_exhaustive(w, it);
2879 for (field, ty) in fields {
2880 let id = cx.derive_id(format!(
2882 ItemType::StructField,
2883 field.name.as_ref().unwrap()
2887 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
2888 <a href=\"#{id}\" class=\"anchor field\"></a>\
2889 <code>{name}: {ty}</code>\
2891 item_type = ItemType::StructField,
2893 name = field.name.as_ref().unwrap(),
2896 document(w, cx, field);
2900 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
2903 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
2904 wrap_into_docblock(w, |w| {
2905 write!(w, "<pre class='rust union'>");
2906 render_attributes(w, it, true);
2907 render_union(w, it, Some(&s.generics), &s.fields, "", true);
2911 document(w, cx, it);
2915 .filter_map(|f| match f.inner {
2916 clean::StructFieldItem(ref ty) => Some((f, ty)),
2920 if fields.peek().is_some() {
2923 "<h2 id='fields' class='fields small-section-header'>
2924 Fields<a href='#fields' class='anchor'></a></h2>"
2926 for (field, ty) in fields {
2927 let name = field.name.as_ref().expect("union field name");
2928 let id = format!("{}.{}", ItemType::StructField, name);
2931 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
2932 <a href=\"#{id}\" class=\"anchor field\"></a>\
2933 <code>{name}: {ty}</code>\
2937 shortty = ItemType::StructField,
2940 if let Some(stability_class) = field.stability_class() {
2941 write!(w, "<span class='stab {stab}'></span>", stab = stability_class);
2943 document(w, cx, field);
2946 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
2949 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
2950 wrap_into_docblock(w, |w| {
2951 write!(w, "<pre class='rust enum'>");
2952 render_attributes(w, it, true);
2956 it.visibility.print_with_space(),
2957 it.name.as_ref().unwrap(),
2959 WhereClause { gens: &e.generics, indent: 0, end_newline: true }
2961 if e.variants.is_empty() && !e.variants_stripped {
2965 for v in &e.variants {
2967 let name = v.name.as_ref().unwrap();
2969 clean::VariantItem(ref var) => match var.kind {
2970 clean::VariantKind::CLike => write!(w, "{}", name),
2971 clean::VariantKind::Tuple(ref tys) => {
2972 write!(w, "{}(", name);
2973 for (i, ty) in tys.iter().enumerate() {
2975 write!(w, ", ")
2977 write!(w, "{}", ty.print());
2981 clean::VariantKind::Struct(ref s) => {
2982 render_struct(w, v, None, s.struct_type, &s.fields, " ", false);
2985 _ => unreachable!(),
2990 if e.variants_stripped {
2991 write!(w, " // some variants omitted\n");
2998 document(w, cx, it);
2999 if !e.variants.is_empty() {
3002 "<h2 id='variants' class='variants small-section-header'>
3003 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3004 document_non_exhaustive_header(it)
3006 document_non_exhaustive(w, it);
3007 for variant in &e.variants {
3009 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3012 "<div id=\"{id}\" class=\"variant small-section-header\">\
3013 <a href=\"#{id}\" class=\"anchor field\"></a>\
3016 name = variant.name.as_ref().unwrap()
3018 if let clean::VariantItem(ref var) = variant.inner {
3019 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3021 for (i, ty) in tys.iter().enumerate() {
3023 write!(w, ", ");
3025 write!(w, "{}", ty.print());
3030 write!(w, "</code></div>");
3031 document(w, cx, variant);
3032 document_non_exhaustive(w, variant);
3034 use crate::clean::{Variant, VariantKind};
3035 if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.inner
3037 let variant_id = cx.derive_id(format!(
3040 variant.name.as_ref().unwrap()
3042 write!(w, "<div class='autohide sub-variant' id='{id}'>", id = variant_id);
3045 "<h3>Fields of <b>{name}</b></h3><div>",
3046 name = variant.name.as_ref().unwrap()
3048 for field in &s.fields {
3049 use crate::clean::StructFieldItem;
3050 if let StructFieldItem(ref ty) = field.inner {
3051 let id = cx.derive_id(format!(
3052 "variant.{}.field.{}",
3053 variant.name.as_ref().unwrap(),
3054 field.name.as_ref().unwrap()
3058 "<span id=\"{id}\" class=\"variant small-section-header\">\
3059 <a href=\"#{id}\" class=\"anchor field\"></a>\
3060 <code>{f}: {t}\
3063 f = field.name.as_ref().unwrap(),
3066 document(w, cx, field);
3069 write!(w, "</div></div>");
3071 render_stability_since(w, variant, it);
3074 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3077 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3084 sym::non_exhaustive,
3087 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3088 // left padding. For example:
3090 // #[foo] <----- "top" attribute
3092 // #[bar] <---- not "top" attribute
3095 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3100 .filter_map(|attr| {
3101 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3102 Some(pprust::attribute_to_string(&attr))
3109 if !attrs.is_empty() {
3112 "<span class=\"docblock attributes{}\">{}</span>",
3113 if top { " top-attr" } else { "" },
3122 g: Option<&clean::Generics>,
3123 ty: doctree::StructType,
3124 fields: &[clean::Item],
3131 it.visibility.print_with_space(),
3132 if structhead { "struct " } else { "" },
3133 it.name.as_ref().unwrap()
3135 if let Some(g) = g {
3136 write!(w, "{}", g.print())
3140 if let Some(g) = g {
3141 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3143 let mut has_visible_fields = false;
3145 for field in fields {
3146 if let clean::StructFieldItem(ref ty) = field.inner {
3151 field.visibility.print_with_space(),
3152 field.name.as_ref().unwrap(),
3155 has_visible_fields = true;
3159 if has_visible_fields {
3160 if it.has_stripped_fields().unwrap() {
3161 write!(w, "\n{} // some fields omitted", tab);
3163 write!(w, "\n{}", tab);
3164 } else if it.has_stripped_fields().unwrap() {
3165 // If there are no visible fields we can just display
3166 // `{ /* fields omitted */ }` to save space.
3167 write!(w, " /* fields omitted */ ");
3173 for (i, field) in fields.iter().enumerate() {
3178 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3179 clean::StructFieldItem(ref ty) => {
3180 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3182 _ => unreachable!(),
3186 if let Some(g) = g {
3187 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3192 // Needed for PhantomData.
3193 if let Some(g) = g {
3194 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3204 g: Option<&clean::Generics>,
3205 fields: &[clean::Item],
3212 it.visibility.print_with_space(),
3213 if structhead { "union " } else { "" },
3214 it.name.as_ref().unwrap()
3216 if let Some(g) = g {
3217 write!(w, "{}", g.print());
3218 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3221 write!(w, " {{\n{}", tab);
3222 for field in fields {
3223 if let clean::StructFieldItem(ref ty) = field.inner {
3227 field.visibility.print_with_space(),
3228 field.name.as_ref().unwrap(),
3235 if it.has_stripped_fields().unwrap() {
3236 write!(w, " // some fields omitted\n{}", tab);
3241 #[derive(Copy, Clone)]
3242 enum AssocItemLink<'a> {
3243 Anchor(Option<&'a str>),
3244 GotoSource(DefId, &'a FxHashSet<String>),
3247 impl<'a> AssocItemLink<'a> {
3248 fn anchor(&self, id: &'a String) -> Self {
3250 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3251 ref other => *other,
3256 fn render_assoc_items(
3259 containing_item: &clean::Item,
3261 what: AssocItemRender<'_>,
3264 let v = match cache.impls.get(&it) {
3268 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3269 if !non_trait.is_empty() {
3270 let render_mode = match what {
3271 AssocItemRender::All => {
3275 <h2 id='implementations' class='small-section-header'>\
3276 Implementations<a href='#implementations' class='anchor'></a>\
3282 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3286 <h2 id='deref-methods' class='small-section-header'>\
3287 Methods from {}<Target = {}>\
3288 <a href='#deref-methods' class='anchor'></a>\
3294 RenderMode::ForDeref { mut_: deref_mut_ }
3297 for i in &non_trait {
3302 AssocItemLink::Anchor(None),
3304 containing_item.stable_since(),
3314 if let AssocItemRender::DerefFor { .. } = what {
3317 if !traits.is_empty() {
3319 traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3320 if let Some(impl_) = deref_impl {
3322 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3323 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3326 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3327 traits.iter().partition(|t| t.inner_impl().synthetic);
3328 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3329 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3331 let mut impls = Buffer::empty_from(&w);
3332 render_impls(cx, &mut impls, &concrete, containing_item, cache);
3333 let impls = impls.into_inner();
3334 if !impls.is_empty() {
3338 <h2 id='trait-implementations' class='small-section-header'>\
3339 Trait Implementations<a href='#trait-implementations' class='anchor'></a>\
3341 <div id='trait-implementations-list'>{}</div>",
3346 if !synthetic.is_empty() {
3350 <h2 id='synthetic-implementations' class='small-section-header'>\
3351 Auto Trait Implementations\
3352 <a href='#synthetic-implementations' class='anchor'></a>\
3354 <div id='synthetic-implementations-list'>\
3357 render_impls(cx, w, &synthetic, containing_item, cache);
3358 write!(w, "</div>");
3361 if !blanket_impl.is_empty() {
3365 <h2 id='blanket-implementations' class='small-section-header'>\
3366 Blanket Implementations\
3367 <a href='#blanket-implementations' class='anchor'></a>\
3369 <div id='blanket-implementations-list'>\
3372 render_impls(cx, w, &blanket_impl, containing_item, cache);
3373 write!(w, "</div>");
3378 fn render_deref_methods(
3382 container_item: &clean::Item,
3386 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3387 let (target, real_target) = impl_
3391 .find_map(|item| match item.inner {
3392 clean::TypedefItem(ref t, true) => Some(match *t {
3393 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3394 _ => (&t.type_, &t.type_),
3398 .expect("Expected associated type binding");
3400 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3401 if let Some(did) = target.def_id() {
3402 render_assoc_items(w, cx, container_item, did, what, cache);
3404 if let Some(prim) = target.primitive_type() {
3405 if let Some(&did) = cache.primitive_locations.get(&prim) {
3406 render_assoc_items(w, cx, container_item, did, what, cache);
3412 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3413 let self_type_opt = match item.inner {
3414 clean::MethodItem(ref method) => method.decl.self_type(),
3415 clean::TyMethodItem(ref method) => method.decl.self_type(),
3419 if let Some(self_ty) = self_type_opt {
3420 let (by_mut_ref, by_box, by_value) = match self_ty {
3421 SelfTy::SelfBorrowed(_, mutability)
3422 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3423 (mutability == Mutability::Mut, false, false)
3425 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3426 (false, Some(did) == cache().owned_box_did, false)
3428 SelfTy::SelfValue => (false, false, true),
3429 _ => (false, false, false),
3432 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3438 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3439 let mut out = Buffer::html();
3440 let mut trait_ = String::new();
3442 if let Some(did) = decl.output.def_id() {
3444 if let Some(impls) = c.impls.get(&did) {
3446 let impl_ = i.inner_impl();
3447 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3449 out.push_str(&format!(
3450 "<h3 class=\"important\">Important traits for {}</h3>\
3451 <code class=\"content\">",
3454 trait_.push_str(&impl_.for_.print().to_string());
3457 //use the "where" class here to make it small
3458 out.push_str(&format!(
3459 "<span class=\"where fmt-newline\">{}</span>",
3462 let t_did = impl_.trait_.def_id().unwrap();
3463 for it in &impl_.items {
3464 if let clean::TypedefItem(ref tydef, _) = it.inner {
3465 out.push_str("<span class=\"where fmt-newline\"> ");
3471 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3474 out.push_str(";</span>");
3482 if !out.is_empty() {
3485 "<span class=\"important-traits\"><span class=\"important-traits-tooltip\">ⓘ<div class='important-traits-tooltiptext'><span class=\"docblock\">"
3488 out.push_str("</code></span></div></span></span>");
3498 link: AssocItemLink<'_>,
3499 render_mode: RenderMode,
3500 outer_version: Option<&str>,
3501 show_def_docs: bool,
3502 use_absolute: Option<bool>,
3503 is_on_foreign_type: bool,
3504 show_default_items: bool,
3505 // This argument is used to reference same type with different paths to avoid duplication
3506 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3510 if render_mode == RenderMode::Normal {
3511 let id = cx.derive_id(match i.inner_impl().trait_ {
3513 if is_on_foreign_type {
3514 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3516 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3519 None => "impl".to_string(),
3521 let aliases = if aliases.is_empty() {
3524 format!(" aliases=\"{}\"", aliases.join(","))
3526 if let Some(use_absolute) = use_absolute {
3527 write!(w, "<h3 id='{}' class='impl'{}><code class='in-band'>", id, aliases);
3528 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3530 for it in &i.inner_impl().items {
3531 if let clean::TypedefItem(ref tydef, _) = it.inner {
3532 write!(w, "<span class=\"where fmt-newline\"> ");
3533 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3534 write!(w, ";</span>");
3538 write!(w, "</code>");
3542 "<h3 id='{}' class='impl'{}><code class='in-band'>{}</code>",
3545 i.inner_impl().print()
3548 write!(w, "<a href='#{}' class='anchor'></a>", id);
3549 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3550 render_stability_since_raw(w, since, outer_version);
3551 if let Some(l) = cx.src_href(&i.impl_item, cache) {
3552 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>", l, "goto source code");
3555 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3556 let mut ids = cx.id_map.borrow_mut();
3559 "<div class='docblock'>{}</div>",
3562 &i.impl_item.links(),
3566 &cx.shared.playground
3577 link: AssocItemLink<'_>,
3578 render_mode: RenderMode,
3579 is_default_item: bool,
3580 outer_version: Option<&str>,
3581 trait_: Option<&clean::Trait>,
3582 show_def_docs: bool,
3585 let item_type = item.type_();
3586 let name = item.name.as_ref().unwrap();
3588 let render_method_item = match render_mode {
3589 RenderMode::Normal => true,
3590 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3593 let (is_hidden, extra_class) =
3594 if (trait_.is_none() || item.doc_value().is_some() || item.inner.is_associated())
3602 clean::MethodItem(clean::Method { .. })
3603 | clean::TyMethodItem(clean::TyMethod { .. }) => {
3604 // Only render when the method is not static or we allow static methods
3605 if render_method_item {
3606 let id = cx.derive_id(format!("{}.{}", item_type, name));
3607 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3608 write!(w, "<code>");
3609 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3610 write!(w, "</code>");
3611 render_stability_since_raw(w, item.stable_since(), outer_version);
3612 if let Some(l) = cx.src_href(item, cache) {
3615 "<a class='srclink' href='{}' title='{}'>[src]</a>",
3616 l, "goto source code"
3622 clean::TypedefItem(ref tydef, _) => {
3623 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3624 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3625 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3626 write!(w, "</code></h4>");
3628 clean::AssocConstItem(ref ty, ref default) => {
3629 let id = cx.derive_id(format!("{}.{}", item_type, name));
3630 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3631 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3632 write!(w, "</code>");
3633 render_stability_since_raw(w, item.stable_since(), outer_version);
3634 if let Some(l) = cx.src_href(item, cache) {
3637 "<a class='srclink' href='{}' title='{}'>[src]</a>",
3638 l, "goto source code"
3643 clean::AssocTypeItem(ref bounds, ref default) => {
3644 let id = cx.derive_id(format!("{}.{}", item_type, name));
3645 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3646 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3647 write!(w, "</code></h4>");
3649 clean::StrippedItem(..) => return,
3650 _ => panic!("can't make docs for trait item with name {:?}", item.name),
3653 if render_method_item {
3654 if !is_default_item {
3655 if let Some(t) = trait_ {
3656 // The trait item may have been stripped so we might not
3657 // find any documentation or stability for it.
3658 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3659 // We need the stability of the item from the trait
3660 // because impls can't have a stability.
3661 document_stability(w, cx, it, is_hidden);
3662 if item.doc_value().is_some() {
3663 document_full(w, item, cx, "", is_hidden);
3664 } else if show_def_docs {
3665 // In case the item isn't documented,
3666 // provide short documentation from the trait.
3667 document_short(w, cx, it, link, "", is_hidden);
3671 document_stability(w, cx, item, is_hidden);
3673 document_full(w, item, cx, "", is_hidden);
3677 document_stability(w, cx, item, is_hidden);
3679 document_short(w, cx, item, link, "", is_hidden);
3685 let traits = &cache.traits;
3686 let trait_ = i.trait_did().map(|did| &traits[&did]);
3688 write!(w, "<div class='impl-items'>");
3689 for trait_item in &i.inner_impl().items {
3704 fn render_default_items(
3709 render_mode: RenderMode,
3710 outer_version: Option<&str>,
3711 show_def_docs: bool,
3714 for trait_item in &t.items {
3715 let n = trait_item.name.clone();
3716 if i.items.iter().any(|m| m.name == n) {
3719 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3720 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3737 // If we've implemented a trait, then also emit documentation for all
3738 // default items which weren't overridden in the implementation block.
3739 // We don't emit documentation for default items if they appear in the
3740 // Implementations on Foreign Types or Implementors sections.
3741 if show_default_items {
3742 if let Some(t) = trait_ {
3743 render_default_items(
3755 write!(w, "</div>");
3762 t: &clean::OpaqueTy,
3765 write!(w, "<pre class='rust opaque'>");
3766 render_attributes(w, it, false);
3769 "type {}{}{where_clause} = impl {bounds};</pre>",
3770 it.name.as_ref().unwrap(),
3772 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3773 bounds = bounds(&t.bounds, false)
3776 document(w, cx, it);
3778 // Render any items associated directly to this alias, as otherwise they
3779 // won't be visible anywhere in the docs. It would be nice to also show
3780 // associated items from the aliased type (see discussion in #32077), but
3781 // we need #14072 to make sense of the generics.
3782 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3785 fn item_trait_alias(
3789 t: &clean::TraitAlias,
3792 write!(w, "<pre class='rust trait-alias'>");
3793 render_attributes(w, it, false);
3796 "trait {}{}{} = {};</pre>",
3797 it.name.as_ref().unwrap(),
3799 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3800 bounds(&t.bounds, true)
3803 document(w, cx, it);
3805 // Render any items associated directly to this alias, as otherwise they
3806 // won't be visible anywhere in the docs. It would be nice to also show
3807 // associated items from the aliased type (see discussion in #32077), but
3808 // we need #14072 to make sense of the generics.
3809 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3812 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
3813 write!(w, "<pre class='rust typedef'>");
3814 render_attributes(w, it, false);
3817 "type {}{}{where_clause} = {type_};</pre>",
3818 it.name.as_ref().unwrap(),
3820 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3821 type_ = t.type_.print()
3824 document(w, cx, it);
3826 // Render any items associated directly to this alias, as otherwise they
3827 // won't be visible anywhere in the docs. It would be nice to also show
3828 // associated items from the aliased type (see discussion in #32077), but
3829 // we need #14072 to make sense of the generics.
3830 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3833 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
3834 writeln!(w, "<pre class='rust foreigntype'>extern {{");
3835 render_attributes(w, it, false);
3838 " {}type {};\n}}</pre>",
3839 it.visibility.print_with_space(),
3840 it.name.as_ref().unwrap(),
3843 document(w, cx, it);
3845 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3848 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
3849 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
3853 || it.is_primitive()
3861 "<p class='location'>{}{}</p>",
3863 clean::StructItem(..) => "Struct ",
3864 clean::TraitItem(..) => "Trait ",
3865 clean::PrimitiveItem(..) => "Primitive Type ",
3866 clean::UnionItem(..) => "Union ",
3867 clean::EnumItem(..) => "Enum ",
3868 clean::TypedefItem(..) => "Type Definition ",
3869 clean::ForeignTypeItem => "Foreign Type ",
3870 clean::ModuleItem(..) =>
3878 it.name.as_ref().unwrap()
3883 if let Some(ref version) = cache.crate_version {
3886 "<div class='block version'>\
3894 write!(buffer, "<div class=\"sidebar-elems\">");
3898 "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3899 it.name.as_ref().expect("crates always have a name")
3903 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
3904 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
3905 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
3906 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
3907 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
3908 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
3909 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
3910 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
3914 // The sidebar is designed to display sibling functions, modules and
3915 // other miscellaneous information. since there are lots of sibling
3916 // items (and that causes quadratic growth in large modules),
3917 // we refactor common parts into a shared JavaScript file per module.
3918 // still, we don't move everything into JS because we want to preserve
3919 // as much HTML as possible in order to allow non-JS-enabled browsers
3920 // to navigate the documentation (though slightly inefficiently).
3922 write!(buffer, "<p class='location'>");
3923 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3925 write!(buffer, "::<wbr>");
3929 "<a href='{}index.html'>{}</a>",
3930 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3934 write!(buffer, "</p>");
3936 // Sidebar refers to the enclosing module, not this module.
3937 let relpath = if it.is_mod() { "../" } else { "" };
3940 "<script>window.sidebarCurrent = {{\
3945 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3950 // There is no sidebar-items.js beyond the crate root path
3951 // FIXME maybe dynamic crate loading can be merged here
3953 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
3955 // Closes sidebar-elems div.
3956 write!(buffer, "</div>");
3959 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
3960 if used_links.insert(url.clone()) {
3964 while !used_links.insert(format!("{}-{}", url, add)) {
3967 format!("{}-{}", url, add)
3973 used_links: &mut FxHashSet<String>,
3978 .filter_map(|item| match item.name {
3979 Some(ref name) if !name.is_empty() && item.is_method() => {
3980 if !for_deref || should_render_item(item, deref_mut) {
3982 "<a href=\"#{}\">{}</a>",
3983 get_next_url(used_links, format!("method.{}", name)),
3992 .collect::<Vec<_>>()
3995 // The point is to url encode any potential character from a type with genericity.
3996 fn small_url_encode(s: &str) -> String {
3997 s.replace("<", "%3C")
3998 .replace(">", "%3E")
3999 .replace(" ", "%20")
4000 .replace("?", "%3F")
4001 .replace("'", "%27")
4002 .replace("&", "%26")
4003 .replace(",", "%2C")
4004 .replace(":", "%3A")
4005 .replace(";", "%3B")
4006 .replace("[", "%5B")
4007 .replace("]", "%5D")
4008 .replace("\"", "%22")
4011 fn sidebar_assoc_items(it: &clean::Item) -> String {
4012 let mut out = String::new();
4014 if let Some(v) = c.impls.get(&it.def_id) {
4015 let mut used_links = FxHashSet::default();
4018 let used_links_bor = &mut used_links;
4021 .filter(|i| i.inner_impl().trait_.is_none())
4022 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4023 .collect::<Vec<_>>();
4024 if !ret.is_empty() {
4025 // We want links' order to be reproducible so we don't use unstable sort.
4027 out.push_str(&format!(
4028 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4029 <div class=\"sidebar-links\">{}</div>",
4035 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4036 if let Some(impl_) = v
4038 .filter(|i| i.inner_impl().trait_.is_some())
4039 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4041 if let Some((target, real_target)) =
4042 impl_.inner_impl().items.iter().find_map(|item| match item.inner {
4043 clean::TypedefItem(ref t, true) => Some(match *t {
4044 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4045 _ => (&t.type_, &t.type_),
4052 .filter(|i| i.inner_impl().trait_.is_some())
4053 .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4054 let inner_impl = target
4058 .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4059 .and_then(|did| c.impls.get(&did));
4060 if let Some(impls) = inner_impl {
4061 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4062 out.push_str(&format!(
4063 "Methods from {}<Target={}>",
4066 impl_.inner_impl().trait_.as_ref().unwrap().print()
4068 Escape(&format!("{:#}", real_target.print()))
4070 out.push_str("</a>");
4073 .filter(|i| i.inner_impl().trait_.is_none())
4075 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4077 .collect::<Vec<_>>();
4078 // We want links' order to be reproducible so we don't use unstable sort.
4080 if !ret.is_empty() {
4081 out.push_str(&format!(
4082 "<div class=\"sidebar-links\">{}</div>",
4089 let format_impls = |impls: Vec<&Impl>| {
4090 let mut links = FxHashSet::default();
4095 let is_negative_impl = is_negative_impl(i.inner_impl());
4096 if let Some(ref i) = i.inner_impl().trait_ {
4097 let i_display = format!("{:#}", i.print());
4098 let out = Escape(&i_display);
4099 let encoded = small_url_encode(&format!("{:#}", i.print()));
4100 let generated = format!(
4101 "<a href=\"#impl-{}\">{}{}</a>",
4103 if is_negative_impl { "!" } else { "" },
4106 if links.insert(generated.clone()) { Some(generated) } else { None }
4111 .collect::<Vec<String>>();
4116 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4117 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4118 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4120 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4122 let concrete_format = format_impls(concrete);
4123 let synthetic_format = format_impls(synthetic);
4124 let blanket_format = format_impls(blanket_impl);
4126 if !concrete_format.is_empty() {
4128 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4129 Trait Implementations</a>",
4131 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4134 if !synthetic_format.is_empty() {
4136 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4137 Auto Trait Implementations</a>",
4139 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4142 if !blanket_format.is_empty() {
4144 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4145 Blanket Implementations</a>",
4147 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4155 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4156 let mut sidebar = String::new();
4157 let fields = get_struct_fields_name(&s.fields);
4159 if !fields.is_empty() {
4160 if let doctree::Plain = s.struct_type {
4161 sidebar.push_str(&format!(
4162 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4163 <div class=\"sidebar-links\">{}</div>",
4169 sidebar.push_str(&sidebar_assoc_items(it));
4171 if !sidebar.is_empty() {
4172 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4176 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4177 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4180 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4182 clean::ItemEnum::ImplItem(ref i) => {
4183 if let Some(ref trait_) = i.trait_ {
4185 format!("{:#}", i.for_.print()),
4186 get_id_for_impl_on_foreign_type(&i.for_, trait_),
4196 fn is_negative_impl(i: &clean::Impl) -> bool {
4197 i.polarity == Some(clean::ImplPolarity::Negative)
4200 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4201 let mut sidebar = String::new();
4206 .filter_map(|m| match m.name {
4207 Some(ref name) if m.is_associated_type() => {
4208 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4212 .collect::<Vec<_>>();
4216 .filter_map(|m| match m.name {
4217 Some(ref name) if m.is_associated_const() => {
4218 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4222 .collect::<Vec<_>>();
4223 let mut required = t
4226 .filter_map(|m| match m.name {
4227 Some(ref name) if m.is_ty_method() => {
4228 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4232 .collect::<Vec<String>>();
4233 let mut provided = t
4236 .filter_map(|m| match m.name {
4237 Some(ref name) if m.is_method() => {
4238 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4242 .collect::<Vec<String>>();
4244 if !types.is_empty() {
4246 sidebar.push_str(&format!(
4247 "<a class=\"sidebar-title\" href=\"#associated-types\">\
4248 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4252 if !consts.is_empty() {
4254 sidebar.push_str(&format!(
4255 "<a class=\"sidebar-title\" href=\"#associated-const\">\
4256 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4260 if !required.is_empty() {
4262 sidebar.push_str(&format!(
4263 "<a class=\"sidebar-title\" href=\"#required-methods\">\
4264 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4268 if !provided.is_empty() {
4270 sidebar.push_str(&format!(
4271 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4272 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4279 if let Some(implementors) = c.implementors.get(&it.def_id) {
4280 let mut res = implementors
4282 .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4283 .filter_map(|i| extract_for_impl_name(&i.impl_item))
4284 .collect::<Vec<_>>();
4286 if !res.is_empty() {
4288 sidebar.push_str(&format!(
4289 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4290 Implementations on Foreign Types</a><div \
4291 class=\"sidebar-links\">{}</div>",
4293 .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4294 .collect::<Vec<_>>()
4300 sidebar.push_str(&sidebar_assoc_items(it));
4302 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4305 "<a class=\"sidebar-title\" \
4306 href=\"#synthetic-implementors\">Auto Implementors</a>",
4310 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4313 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4314 let sidebar = sidebar_assoc_items(it);
4316 if !sidebar.is_empty() {
4317 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4321 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4322 let sidebar = sidebar_assoc_items(it);
4324 if !sidebar.is_empty() {
4325 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4329 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4330 let mut fields = fields
4332 .filter(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false })
4333 .filter_map(|f| match f.name {
4335 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4339 .collect::<Vec<_>>();
4344 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4345 let mut sidebar = String::new();
4346 let fields = get_struct_fields_name(&u.fields);
4348 if !fields.is_empty() {
4349 sidebar.push_str(&format!(
4350 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4351 <div class=\"sidebar-links\">{}</div>",
4356 sidebar.push_str(&sidebar_assoc_items(it));
4358 if !sidebar.is_empty() {
4359 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4363 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4364 let mut sidebar = String::new();
4366 let mut variants = e
4369 .filter_map(|v| match v.name {
4370 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4373 .collect::<Vec<_>>();
4374 if !variants.is_empty() {
4375 variants.sort_unstable();
4376 sidebar.push_str(&format!(
4377 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4378 <div class=\"sidebar-links\">{}</div>",
4383 sidebar.push_str(&sidebar_assoc_items(it));
4385 if !sidebar.is_empty() {
4386 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4390 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4392 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4393 ItemType::Module => ("modules", "Modules"),
4394 ItemType::Struct => ("structs", "Structs"),
4395 ItemType::Union => ("unions", "Unions"),
4396 ItemType::Enum => ("enums", "Enums"),
4397 ItemType::Function => ("functions", "Functions"),
4398 ItemType::Typedef => ("types", "Type Definitions"),
4399 ItemType::Static => ("statics", "Statics"),
4400 ItemType::Constant => ("constants", "Constants"),
4401 ItemType::Trait => ("traits", "Traits"),
4402 ItemType::Impl => ("impls", "Implementations"),
4403 ItemType::TyMethod => ("tymethods", "Type Methods"),
4404 ItemType::Method => ("methods", "Methods"),
4405 ItemType::StructField => ("fields", "Struct Fields"),
4406 ItemType::Variant => ("variants", "Variants"),
4407 ItemType::Macro => ("macros", "Macros"),
4408 ItemType::Primitive => ("primitives", "Primitive Types"),
4409 ItemType::AssocType => ("associated-types", "Associated Types"),
4410 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4411 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4412 ItemType::Keyword => ("keywords", "Keywords"),
4413 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4414 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4415 ItemType::ProcDerive => ("derives", "Derive Macros"),
4416 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4420 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4421 let mut sidebar = String::new();
4423 if items.iter().any(|it| it.type_() == ItemType::ExternCrate || it.type_() == ItemType::Import)
4425 sidebar.push_str(&format!(
4426 "<li><a href=\"#{id}\">{name}</a></li>",
4432 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4433 // to print its headings
4435 ItemType::Primitive,
4449 ItemType::StructField,
4451 ItemType::AssocType,
4452 ItemType::AssocConst,
4453 ItemType::ForeignType,
4456 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4457 let (short, name) = item_ty_to_strs(&myty);
4458 sidebar.push_str(&format!(
4459 "<li><a href=\"#{id}\">{name}</a></li>",
4466 if !sidebar.is_empty() {
4467 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4471 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4472 let sidebar = sidebar_assoc_items(it);
4473 if !sidebar.is_empty() {
4474 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4478 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4479 wrap_into_docblock(w, |w| {
4480 w.write_str(&highlight::render_with_highlighting(
4490 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4491 let name = it.name.as_ref().expect("proc-macros always have names");
4493 MacroKind::Bang => {
4494 write!(w, "<pre class='rust macro'>");
4495 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4496 write!(w, "</pre>");
4498 MacroKind::Attr => {
4499 write!(w, "<pre class='rust attr'>");
4500 write!(w, "#[{}]", name);
4501 write!(w, "</pre>");
4503 MacroKind::Derive => {
4504 write!(w, "<pre class='rust derive'>");
4505 write!(w, "#[derive({})]", name);
4506 if !m.helpers.is_empty() {
4507 writeln!(w, "\n{{");
4508 writeln!(w, " // Attributes available to this derive:");
4509 for attr in &m.helpers {
4510 writeln!(w, " #[{}]", attr);
4514 write!(w, "</pre>");
4520 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4521 document(w, cx, it);
4522 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4525 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4529 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4531 fn make_item_keywords(it: &clean::Item) -> String {
4532 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4535 /// Returns a list of all paths used in the type.
4536 /// This is used to help deduplicate imported impls
4537 /// for reexported types. If any of the contained
4538 /// types are re-exported, we don't use the corresponding
4539 /// entry from the js file, as inlining will have already
4540 /// picked up the impl
4541 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4542 let mut out = Vec::new();
4543 let mut visited = FxHashSet::default();
4544 let mut work = VecDeque::new();
4545 let cache = cache();
4547 work.push_back(first_ty);
4549 while let Some(ty) = work.pop_front() {
4550 if !visited.insert(ty.clone()) {
4555 clean::Type::ResolvedPath { did, .. } => {
4556 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4557 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4559 if let Some(path) = fqp {
4560 out.push(path.join("::"));
4563 clean::Type::Tuple(tys) => {
4564 work.extend(tys.into_iter());
4566 clean::Type::Slice(ty) => {
4567 work.push_back(*ty);
4569 clean::Type::Array(ty, _) => {
4570 work.push_back(*ty);
4572 clean::Type::RawPointer(_, ty) => {
4573 work.push_back(*ty);
4575 clean::Type::BorrowedRef { type_, .. } => {
4576 work.push_back(*type_);
4578 clean::Type::QPath { self_type, trait_, .. } => {
4579 work.push_back(*self_type);
4580 work.push_back(*trait_);