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.
29 use std::cell::{Cell, RefCell};
30 use std::cmp::Ordering;
31 use std::collections::{BTreeMap, VecDeque};
32 use std::default::Default;
34 use std::fmt::{self, Formatter, Write as FmtWrite};
36 use std::fs::{self, File};
37 use std::io::prelude::*;
38 use std::io::{self, BufReader};
39 use std::path::{PathBuf, Path, Component};
45 use serialize::json::{ToJson, Json, as_json};
47 use syntax::edition::Edition;
48 use syntax::feature_gate::UnstableFeatures;
49 use syntax::print::pprust;
50 use syntax::source_map::FileName;
51 use syntax::symbol::{Symbol, sym};
52 use syntax_expand::base::MacroKind;
53 use rustc::hir::def_id::DefId;
54 use rustc::middle::privacy::AccessLevels;
55 use rustc::middle::stability;
57 use rustc::util::nodemap::{FxHashMap, FxHashSet};
58 use rustc_data_structures::flock;
60 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
61 use crate::config::RenderOptions;
62 use crate::docfs::{DocFS, ErrorStorage, PathError};
64 use crate::html::escape::Escape;
65 use crate::html::format::{Buffer, PrintWithSpace, print_abi_with_space};
66 use crate::html::format::{print_generic_bounds, WhereClause, href, print_default_space};
67 use crate::html::format::{Function};
68 use crate::html::format::fmt_impl_for_trait_page;
69 use crate::html::item_type::ItemType;
70 use crate::html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
71 use crate::html::{highlight, layout, static_files};
72 use crate::html::sources;
82 crate use cache::ExternalLocation::{self, *};
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() {
100 pub error: io::Error,
103 impl error::Error for Error {
104 fn description(&self) -> &str {
105 self.error.description()
109 impl std::fmt::Display for Error {
110 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
111 let file = self.file.display().to_string();
113 write!(f, "{}", self.error)
115 write!(f, "\"{}\": {}", self.file.display(), self.error)
120 impl PathError for Error {
121 fn new<P: AsRef<Path>>(e: io::Error, path: P) -> Error {
123 file: path.as_ref().to_path_buf(),
129 macro_rules! try_none {
130 ($e:expr, $file:expr) => ({
134 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
140 macro_rules! try_err {
141 ($e:expr, $file:expr) => ({
144 Err(e) => return Err(Error::new(e, $file)),
149 /// Major driving force in all rustdoc rendering. This contains information
150 /// about where in the tree-like hierarchy rendering is occurring and controls
151 /// how the current page is being rendered.
153 /// It is intended that this context is a lightweight object which can be fairly
154 /// easily cloned because it is cloned per work-job (about once per item in the
158 /// Current hierarchy of components leading down to what's currently being
160 pub current: Vec<String>,
161 /// The current destination folder of where HTML artifacts should be placed.
162 /// This changes as the context descends into the module hierarchy.
164 /// A flag, which when `true`, will render pages which redirect to the
165 /// real location of an item. This is used to allow external links to
166 /// publicly reused items to redirect to the right location.
167 pub render_redirect_pages: bool,
168 /// The map used to ensure all generated 'id=' attributes are unique.
169 id_map: Rc<RefCell<IdMap>>,
170 pub shared: Arc<SharedContext>,
171 pub cache: Arc<Cache>,
174 crate struct SharedContext {
175 /// The path to the crate root source minus the file name.
176 /// Used for simplifying paths to the highlighted source code files.
177 pub src_root: PathBuf,
178 /// This describes the layout of each page, and is not modified after
179 /// creation of the context (contains info like the favicon and added html).
180 pub layout: layout::Layout,
181 /// This flag indicates whether `[src]` links should be generated or not. If
182 /// the source files are present in the html rendering, then this will be
184 pub include_sources: bool,
185 /// The local file sources we've emitted and their respective url-paths.
186 pub local_sources: FxHashMap<PathBuf, String>,
187 /// Whether the collapsed pass ran
189 /// The base-URL of the issue tracker for when an item has been tagged with
191 pub issue_tracker_base_url: Option<String>,
192 /// The directories that have already been created in this doc run. Used to reduce the number
193 /// of spurious `create_dir_all` calls.
194 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
195 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
196 /// should be ordered alphabetically or in order of appearance (in the source code).
197 pub sort_modules_alphabetically: bool,
198 /// Additional themes to be added to the generated docs.
199 pub themes: Vec<PathBuf>,
200 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
202 pub resource_suffix: String,
203 /// Optional path string to be used to load static files on output pages. If not set, uses
204 /// combinations of `../` to reach the documentation root.
205 pub static_root_path: Option<String>,
206 /// Option disabled by default to generate files used by RLS and some other tools.
207 pub generate_redirect_pages: bool,
208 /// The fs handle we are working with.
210 /// The default edition used to parse doctests.
211 pub edition: Edition,
212 pub codes: ErrorCodes,
213 playground: Option<markdown::Playground>,
217 fn path(&self, filename: &str) -> PathBuf {
218 // We use splitn vs Path::extension here because we might get a filename
219 // like `style.min.css` and we want to process that into
220 // `style-suffix.min.css`. Path::extension would just return `css`
221 // which would result in `style.min-suffix.css` which isn't what we
223 let mut iter = filename.splitn(2, '.');
224 let base = iter.next().unwrap();
225 let ext = iter.next().unwrap();
226 let filename = format!(
229 self.shared.resource_suffix,
232 self.dst.join(&filename)
237 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
238 let mut dirs = self.created_dirs.borrow_mut();
239 if !dirs.contains(dst) {
240 try_err!(self.fs.create_dir_all(dst), dst);
241 dirs.insert(dst.to_path_buf());
247 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
248 /// `collapsed_doc_value` of the given item.
249 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
251 item.collapsed_doc_value().map(|s| s.into())
253 item.doc_value().map(|s| s.into())
258 /// Metadata about implementations for a type or trait.
259 #[derive(Clone, Debug)]
261 pub impl_item: clean::Item,
265 fn inner_impl(&self) -> &clean::Impl {
266 match self.impl_item.inner {
267 clean::ImplItem(ref impl_) => impl_,
268 _ => panic!("non-impl item found in impl")
272 fn trait_did(&self) -> Option<DefId> {
273 self.inner_impl().trait_.def_id()
277 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
278 /// Later on moved into `CACHE_KEY`.
280 pub struct RenderInfo {
281 pub inlined: FxHashSet<DefId>,
282 pub external_paths: crate::core::ExternalPaths,
283 pub exact_paths: FxHashMap<DefId, Vec<String>>,
284 pub access_levels: AccessLevels<DefId>,
285 pub deref_trait_did: Option<DefId>,
286 pub deref_mut_trait_did: Option<DefId>,
287 pub owned_box_did: Option<DefId>,
290 // Helper structs for rendering items/sidebars and carrying along contextual
293 /// Struct representing one entry in the JS search index. These are all emitted
294 /// by hand to a large JS file at the end of cache-creation.
301 parent: Option<DefId>,
302 parent_idx: Option<usize>,
303 search_type: Option<IndexItemFunctionType>,
306 impl ToJson for IndexItem {
307 fn to_json(&self) -> Json {
308 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
310 let mut data = Vec::with_capacity(6);
311 data.push((self.ty as usize).to_json());
312 data.push(self.name.to_json());
313 data.push(self.path.to_json());
314 data.push(self.desc.to_json());
315 data.push(self.parent_idx.to_json());
316 data.push(self.search_type.to_json());
322 /// A type used for the search index.
325 name: Option<String>,
326 generics: Option<Vec<String>>,
329 impl ToJson for Type {
330 fn to_json(&self) -> Json {
333 let mut data = Vec::with_capacity(2);
334 data.push(name.to_json());
335 if let Some(ref generics) = self.generics {
336 data.push(generics.to_json());
345 /// Full type of functions/methods in the search index.
347 struct IndexItemFunctionType {
349 output: Option<Vec<Type>>,
352 impl ToJson for IndexItemFunctionType {
353 fn to_json(&self) -> Json {
354 // If we couldn't figure out a type, just write `null`.
355 let mut iter = self.inputs.iter();
356 if match self.output {
357 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()),
358 None => iter.any(|ref i| i.name.is_none()),
362 let mut data = Vec::with_capacity(2);
363 data.push(self.inputs.to_json());
364 if let Some(ref output) = self.output {
365 if output.len() > 1 {
366 data.push(output.to_json());
368 data.push(output[0].to_json());
376 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
377 thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
379 pub fn initial_ids() -> Vec<String> {
391 "synthetic-implementors",
393 "synthetic-implementors-list",
397 ].iter().map(|id| (String::from(*id))).collect()
400 /// Generates the documentation for `crate` into the directory `dst`
401 pub fn run(mut krate: clean::Crate,
402 options: RenderOptions,
403 renderinfo: RenderInfo,
404 diag: &errors::Handler,
405 edition: Edition) -> Result<(), Error> {
406 // need to save a copy of the options for rendering the index page
407 let md_opts = options.clone();
413 sort_modules_alphabetically,
416 extern_html_root_urls,
419 generate_search_filter,
420 generate_redirect_pages,
424 let src_root = match krate.src {
425 FileName::Real(ref p) => match p.parent() {
426 Some(p) => p.to_path_buf(),
427 None => PathBuf::new(),
431 let mut errors = Arc::new(ErrorStorage::new());
432 // If user passed in `--playground-url` arg, we fill in crate name here
433 let mut playground = None;
434 if let Some(url) = playground_url {
435 playground = Some(markdown::Playground {
436 crate_name: Some(krate.name.clone()),
440 let mut layout = layout::Layout {
442 favicon: String::new(),
444 krate: krate.name.clone(),
445 css_file_extension: extension_css,
446 generate_search_filter,
448 let mut issue_tracker_base_url = None;
449 let mut include_sources = true;
451 // Crawl the crate attributes looking for attributes which control how we're
452 // going to emit HTML
453 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
454 for attr in attrs.lists(sym::doc) {
455 match (attr.name_or_empty(), attr.value_str()) {
456 (sym::html_favicon_url, Some(s)) => {
457 layout.favicon = s.to_string();
459 (sym::html_logo_url, Some(s)) => {
460 layout.logo = s.to_string();
462 (sym::html_playground_url, Some(s)) => {
463 playground = Some(markdown::Playground {
464 crate_name: Some(krate.name.clone()),
468 (sym::issue_tracker_base_url, Some(s)) => {
469 issue_tracker_base_url = Some(s.to_string());
471 (sym::html_no_source, None) if attr.is_word() => {
472 include_sources = false;
478 let mut scx = SharedContext {
479 collapsed: krate.collapsed,
482 local_sources: Default::default(),
483 issue_tracker_base_url,
485 created_dirs: Default::default(),
486 sort_modules_alphabetically,
490 generate_redirect_pages,
491 fs: DocFS::new(&errors),
493 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
498 scx.ensure_dir(&dst)?;
499 krate = sources::render(&dst, &mut scx, krate)?;
500 let (new_crate, index, cache) = Cache::from_krate(
502 &extern_html_root_urls,
507 let cache = Arc::new(cache);
508 let mut cx = Context {
511 render_redirect_pages: false,
512 id_map: Rc::new(RefCell::new(id_map)),
513 shared: Arc::new(scx),
514 cache: cache.clone(),
517 // Freeze the cache now that the index has been built. Put an Arc into TLS
518 // for future parallelization opportunities
519 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
520 CURRENT_DEPTH.with(|s| s.set(0));
522 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
523 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
524 write_shared(&cx, &krate, index, &md_opts, diag)?;
525 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
527 // And finally render the whole crate's documentation
528 let ret = cx.krate(krate);
529 let nb_errors = Arc::get_mut(&mut errors).map_or_else(|| 0, |errors| errors.write_errors(diag));
532 } else if nb_errors > 0 {
533 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
541 krate: &clean::Crate,
542 search_index: String,
543 options: &RenderOptions,
544 diag: &errors::Handler,
545 ) -> Result<(), Error> {
546 // Write out the shared files. Note that these are shared among all rustdoc
547 // docs placed in the output directory, so this needs to be a synchronized
548 // operation with respect to all other rustdocs running around.
549 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
551 // Add all the static files. These may already exist, but we just
552 // overwrite them anyway to make sure that they're fresh and up-to-date.
554 write_minify(&cx.shared.fs, cx.path("rustdoc.css"),
555 static_files::RUSTDOC_CSS,
556 options.enable_minification)?;
557 write_minify(&cx.shared.fs, cx.path("settings.css"),
558 static_files::SETTINGS_CSS,
559 options.enable_minification)?;
560 write_minify(&cx.shared.fs, cx.path("noscript.css"),
561 static_files::NOSCRIPT_CSS,
562 options.enable_minification)?;
564 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
565 // then we'll run over the "official" styles.
566 let mut themes: FxHashSet<String> = FxHashSet::default();
568 for entry in &cx.shared.themes {
569 let content = try_err!(fs::read(&entry), &entry);
570 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
571 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
572 cx.shared.fs.write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
573 themes.insert(theme.to_owned());
576 let write = |p, c| { cx.shared.fs.write(p, c) };
577 if (*cx.shared).layout.logo.is_empty() {
578 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
580 if (*cx.shared).layout.favicon.is_empty() {
581 write(cx.path("favicon.ico"), static_files::RUST_FAVICON)?;
583 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
584 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
585 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
586 write_minify(&cx.shared.fs,
587 cx.path("light.css"), static_files::themes::LIGHT, options.enable_minification)?;
588 themes.insert("light".to_owned());
589 write_minify(&cx.shared.fs,
590 cx.path("dark.css"), static_files::themes::DARK, options.enable_minification)?;
591 themes.insert("dark".to_owned());
593 let mut themes: Vec<&String> = themes.iter().collect();
595 // To avoid theme switch latencies as much as possible, we put everything theme related
596 // at the beginning of the html files into another js file.
597 let theme_js = format!(
598 r#"var themes = document.getElementById("theme-choices");
599 var themePicker = document.getElementById("theme-picker");
601 function showThemeButtonState() {{
602 themes.style.display = "block";
603 themePicker.style.borderBottomRightRadius = "0";
604 themePicker.style.borderBottomLeftRadius = "0";
607 function hideThemeButtonState() {{
608 themes.style.display = "none";
609 themePicker.style.borderBottomRightRadius = "3px";
610 themePicker.style.borderBottomLeftRadius = "3px";
613 function switchThemeButtonState() {{
614 if (themes.style.display === "block") {{
615 hideThemeButtonState();
617 showThemeButtonState();
621 function handleThemeButtonsBlur(e) {{
622 var active = document.activeElement;
623 var related = e.relatedTarget;
625 if (active.id !== "themePicker" &&
626 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
628 (related.id !== "themePicker" &&
629 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
630 hideThemeButtonState();
634 themePicker.onclick = switchThemeButtonState;
635 themePicker.onblur = handleThemeButtonsBlur;
636 [{}].forEach(function(item) {{
637 var but = document.createElement('button');
638 but.innerHTML = item;
639 but.onclick = function(el) {{
640 switchTheme(currentTheme, mainTheme, item, true);
642 but.onblur = handleThemeButtonsBlur;
643 themes.appendChild(but);
646 .map(|s| format!("\"{}\"", s))
647 .collect::<Vec<String>>()
649 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
653 write_minify(&cx.shared.fs, cx.path("main.js"),
654 static_files::MAIN_JS,
655 options.enable_minification)?;
656 write_minify(&cx.shared.fs, cx.path("settings.js"),
657 static_files::SETTINGS_JS,
658 options.enable_minification)?;
659 if cx.shared.include_sources {
662 cx.path("source-script.js"),
663 static_files::sidebar::SOURCE_SCRIPT,
664 options.enable_minification)?;
670 cx.path("storage.js"),
671 &format!("var resourcesSuffix = \"{}\";{}",
672 cx.shared.resource_suffix,
673 static_files::STORAGE_JS),
674 options.enable_minification)?;
677 if let Some(ref css) = cx.shared.layout.css_file_extension {
678 let out = cx.path("theme.css");
679 let buffer = try_err!(fs::read_to_string(css), css);
680 if !options.enable_minification {
681 cx.shared.fs.write(&out, &buffer)?;
683 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
686 write_minify(&cx.shared.fs, cx.path("normalize.css"),
687 static_files::NORMALIZE_CSS,
688 options.enable_minification)?;
689 write(cx.dst.join("FiraSans-Regular.woff"),
690 static_files::fira_sans::REGULAR)?;
691 write(cx.dst.join("FiraSans-Medium.woff"),
692 static_files::fira_sans::MEDIUM)?;
693 write(cx.dst.join("FiraSans-LICENSE.txt"),
694 static_files::fira_sans::LICENSE)?;
695 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
696 static_files::source_serif_pro::REGULAR)?;
697 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
698 static_files::source_serif_pro::BOLD)?;
699 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
700 static_files::source_serif_pro::ITALIC)?;
701 write(cx.dst.join("SourceSerifPro-LICENSE.md"),
702 static_files::source_serif_pro::LICENSE)?;
703 write(cx.dst.join("SourceCodePro-Regular.woff"),
704 static_files::source_code_pro::REGULAR)?;
705 write(cx.dst.join("SourceCodePro-Semibold.woff"),
706 static_files::source_code_pro::SEMIBOLD)?;
707 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
708 static_files::source_code_pro::LICENSE)?;
709 write(cx.dst.join("LICENSE-MIT.txt"),
710 static_files::LICENSE_MIT)?;
711 write(cx.dst.join("LICENSE-APACHE.txt"),
712 static_files::LICENSE_APACHE)?;
713 write(cx.dst.join("COPYRIGHT.txt"),
714 static_files::COPYRIGHT)?;
720 for_search_index: bool,
721 ) -> io::Result<(Vec<String>, Vec<String>, Vec<String>)> {
722 let mut ret = Vec::new();
723 let mut krates = Vec::new();
724 let mut variables = Vec::new();
727 for line in BufReader::new(File::open(path)?).lines() {
729 if for_search_index && line.starts_with("var R") {
730 variables.push(line.clone());
733 if !line.starts_with(key) {
736 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
739 ret.push(line.to_string());
740 krates.push(line[key.len() + 2..].split('"')
742 .map(|s| s.to_owned())
743 .unwrap_or_else(|| String::new()));
746 Ok((ret, krates, variables))
749 fn show_item(item: &IndexItem, krate: &str) -> String {
750 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
751 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
752 if let Some(p) = item.parent_idx {
753 format!(",'parent':{}", p)
759 let dst = cx.dst.join(&format!("aliases{}.js", cx.shared.resource_suffix));
761 let (mut all_aliases, _, _) = try_err!(collect(&dst, &krate.name, "ALIASES", false), &dst);
762 let mut output = String::with_capacity(100);
763 for (alias, items) in &cx.cache.aliases {
764 if items.is_empty() {
767 output.push_str(&format!("\"{}\":[{}],",
770 .map(|v| show_item(v, &krate.name))
774 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
776 let mut v = Buffer::html();
777 writeln!(&mut v, "var ALIASES = {{}};");
778 for aliases in &all_aliases {
779 writeln!(&mut v, "{}", aliases);
781 cx.shared.fs.write(&dst, v.into_inner().into_bytes())?;
784 use std::ffi::OsString;
789 children: FxHashMap<OsString, Hierarchy>,
790 elems: FxHashSet<OsString>,
794 fn new(elem: OsString) -> Hierarchy {
797 children: FxHashMap::default(),
798 elems: FxHashSet::default(),
802 fn to_json_string(&self) -> String {
803 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
804 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
805 let mut files = self.elems.iter()
806 .map(|s| format!("\"{}\"",
808 .expect("invalid osstring conversion")))
809 .collect::<Vec<_>>();
810 files.sort_unstable_by(|a, b| a.cmp(b));
811 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
812 let dirs = if subs.is_empty() {
815 format!(",\"dirs\":[{}]", subs)
817 let files = files.join(",");
818 let files = if files.is_empty() {
821 format!(",\"files\":[{}]", files)
823 format!("{{\"name\":\"{name}\"{dirs}{files}}}",
824 name=self.elem.to_str().expect("invalid osstring conversion"),
830 if cx.shared.include_sources {
831 let mut hierarchy = Hierarchy::new(OsString::new());
832 for source in cx.shared.local_sources.iter()
833 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
835 let mut h = &mut hierarchy;
836 let mut elems = source.components()
839 Component::Normal(s) => Some(s.to_owned()),
845 let cur_elem = elems.next().expect("empty file path");
846 if elems.peek().is_none() {
847 h.elems.insert(cur_elem);
850 let e = cur_elem.clone();
851 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
852 h = h.children.get_mut(&cur_elem).expect("not found child");
857 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
858 let (mut all_sources, _krates, _) = try_err!(collect(&dst, &krate.name, "sourcesIndex",
861 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
863 hierarchy.to_json_string()));
865 let v = format!("var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
866 all_sources.join("\n"));
867 cx.shared.fs.write(&dst, v.as_bytes())?;
870 // Update the search index
871 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
872 let (mut all_indexes, mut krates, variables) = try_err!(collect(&dst,
876 all_indexes.push(search_index);
878 // Sort the indexes by crate so the file will be generated identically even
879 // with rustdoc running in parallel.
882 let mut v = String::from("var N=null,E=\"\",T=\"t\",U=\"u\",searchIndex={};\n");
883 v.push_str(&minify_replacer(
884 &format!("{}\n{}", variables.join(""), all_indexes.join("\n")),
885 options.enable_minification));
886 v.push_str("initSearch(searchIndex);addSearchOptions(searchIndex);");
887 cx.shared.fs.write(&dst, &v)?;
889 if options.enable_index_page {
890 if let Some(index_page) = options.index_page.clone() {
891 let mut md_opts = options.clone();
892 md_opts.output = cx.dst.clone();
893 md_opts.external_html = (*cx.shared).layout.external_html.clone();
895 crate::markdown::render(index_page, md_opts, diag, cx.shared.edition);
897 let dst = cx.dst.join("index.html");
898 let page = layout::Page {
899 title: "Index of crates",
902 static_root_path: cx.shared.static_root_path.as_deref(),
903 description: "List of crates",
904 keywords: BASIC_KEYWORDS,
905 resource_suffix: &cx.shared.resource_suffix,
907 static_extra_scripts: &[],
909 krates.push(krate.name.clone());
913 let content = format!(
915 <span class='in-band'>List of all crates</span>\
916 </h1><ul class='mod'>{}</ul>",
920 format!("<li><a href=\"{}index.html\">{}</li>",
921 ensure_trailing_slash(s), s)
923 .collect::<String>());
924 let v = layout::render(&cx.shared.layout,
927 cx.shared.fs.write(&dst, v.as_bytes())?;
931 // Update the list of all implementors for traits
932 let dst = cx.dst.join("implementors");
933 for (&did, imps) in &cx.cache.implementors {
934 // Private modules can leak through to this phase of rustdoc, which
935 // could contain implementations for otherwise private types. In some
936 // rare cases we could find an implementation for an item which wasn't
937 // indexed, so we just skip this step in that case.
939 // FIXME: this is a vague explanation for why this can't be a `get`, in
940 // theory it should be...
941 let &(ref remote_path, remote_item_type) = match cx.cache.paths.get(&did) {
943 None => match cx.cache.external_paths.get(&did) {
949 let mut have_impls = false;
950 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
952 // If the trait and implementation are in the same crate, then
953 // there's no need to emit information about it (there's inlining
954 // going on). If they're in different crates then the crate defining
955 // the trait will be interested in our implementation.
956 if imp.impl_item.def_id.krate == did.krate { continue }
957 // If the implementation is from another crate then that crate
959 if !imp.impl_item.def_id.is_local() { continue }
961 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
962 as_json(&imp.inner_impl().print().to_string()),
963 imp.inner_impl().synthetic,
964 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
966 implementors.push_str("];");
968 // Only create a js file if we have impls to add to it. If the trait is
969 // documented locally though we always create the file to avoid dead
971 if !have_impls && !cx.cache.paths.contains_key(&did) {
975 let mut mydst = dst.clone();
976 for part in &remote_path[..remote_path.len() - 1] {
979 cx.shared.ensure_dir(&mydst)?;
980 mydst.push(&format!("{}.{}.js",
982 remote_path[remote_path.len() - 1]));
984 let (mut all_implementors, _, _) = try_err!(collect(&mydst, &krate.name, "implementors",
987 all_implementors.push(implementors);
988 // Sort the implementors by crate so the file will be generated
989 // identically even with rustdoc running in parallel.
990 all_implementors.sort();
992 let mut v = String::from("(function() {var implementors = {};\n");
993 for implementor in &all_implementors {
994 writeln!(v, "{}", *implementor).unwrap();
997 if (window.register_implementors) {
998 window.register_implementors(implementors);
1000 window.pending_implementors = implementors;
1004 cx.shared.fs.write(&mydst, &v)?;
1009 fn write_minify(fs:&DocFS, dst: PathBuf, contents: &str, enable_minification: bool
1010 ) -> Result<(), Error> {
1011 if enable_minification {
1012 if dst.extension() == Some(&OsStr::new("css")) {
1013 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1014 fs.write(dst, res.as_bytes())
1016 fs.write(dst, minifier::js::minify(contents).as_bytes())
1019 fs.write(dst, contents.as_bytes())
1025 enable_minification: bool,
1027 use minifier::js::{simple_minify, Keyword, ReservedChar, Token, Tokens};
1029 if enable_minification {
1030 let tokens: Tokens<'_> = simple_minify(contents)
1032 .filter(|(f, next)| {
1033 // We keep backlines.
1034 minifier::js::clean_token_except(f, next, &|c: &Token<'_>| {
1035 c.get_char() != Some(ReservedChar::Backline)
1039 minifier::js::replace_token_with(f, &|t: &Token<'_>| {
1041 Token::Keyword(Keyword::Null) => Some(Token::Other("N")),
1042 Token::String(s) => {
1043 let s = &s[1..s.len() -1]; // The quotes are included
1045 Some(Token::Other("E"))
1046 } else if s == "t" {
1047 Some(Token::Other("T"))
1048 } else if s == "u" {
1049 Some(Token::Other("U"))
1058 .collect::<Vec<_>>()
1060 let o = tokens.apply(|f| {
1061 // We add a backline after the newly created variables.
1062 minifier::js::aggregate_strings_into_array_with_separation_filter(
1065 Token::Char(ReservedChar::Backline),
1066 // This closure prevents crates' names from being aggregated.
1068 // The point here is to check if the string is preceded by '[' and
1069 // "searchIndex". If so, it means this is a crate name and that it
1070 // shouldn't be aggregated.
1073 !tokens[pos - 1].eq_char(ReservedChar::OpenBracket) ||
1074 tokens[pos - 2].get_other() != Some("searchIndex")
1081 format!("{}\n", contents)
1085 #[derive(Debug, Eq, PartialEq, Hash)]
1092 fn new(mut url: String, name: String) -> ItemEntry {
1093 while url.starts_with('/') {
1104 crate fn print(&self) -> impl fmt::Display + '_ {
1105 crate::html::format::display_fn(move |f| {
1106 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1111 impl PartialOrd for ItemEntry {
1112 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1113 Some(self.cmp(other))
1117 impl Ord for ItemEntry {
1118 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1119 self.name.cmp(&other.name)
1125 structs: FxHashSet<ItemEntry>,
1126 enums: FxHashSet<ItemEntry>,
1127 unions: FxHashSet<ItemEntry>,
1128 primitives: FxHashSet<ItemEntry>,
1129 traits: FxHashSet<ItemEntry>,
1130 macros: FxHashSet<ItemEntry>,
1131 functions: FxHashSet<ItemEntry>,
1132 typedefs: FxHashSet<ItemEntry>,
1133 opaque_tys: FxHashSet<ItemEntry>,
1134 statics: FxHashSet<ItemEntry>,
1135 constants: FxHashSet<ItemEntry>,
1136 keywords: FxHashSet<ItemEntry>,
1137 attributes: FxHashSet<ItemEntry>,
1138 derives: FxHashSet<ItemEntry>,
1139 trait_aliases: FxHashSet<ItemEntry>,
1143 fn new() -> AllTypes {
1144 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1146 structs: new_set(100),
1147 enums: new_set(100),
1148 unions: new_set(100),
1149 primitives: new_set(26),
1150 traits: new_set(100),
1151 macros: new_set(100),
1152 functions: new_set(100),
1153 typedefs: new_set(100),
1154 opaque_tys: new_set(100),
1155 statics: new_set(100),
1156 constants: new_set(100),
1157 keywords: new_set(100),
1158 attributes: new_set(100),
1159 derives: new_set(100),
1160 trait_aliases: new_set(100),
1164 fn append(&mut self, item_name: String, item_type: &ItemType) {
1165 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1166 if let Some(name) = url.pop() {
1167 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1169 let name = url.join("::");
1171 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1172 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1173 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1174 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1175 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1176 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1177 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1178 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1179 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1180 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1181 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1182 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1183 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1184 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1191 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1193 let mut e: Vec<&ItemEntry> = e.iter().collect();
1195 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1199 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>());
1204 fn print(self, f: &mut Buffer) {
1207 <span class='out-of-band'>\
1208 <span id='render-detail'>\
1209 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1210 [<span class='inner'>−</span>]\
1214 <span class='in-band'>List of all items</span>\
1216 print_entries(f, &self.structs, "Structs", "structs");
1217 print_entries(f, &self.enums, "Enums", "enums");
1218 print_entries(f, &self.unions, "Unions", "unions");
1219 print_entries(f, &self.primitives, "Primitives", "primitives");
1220 print_entries(f, &self.traits, "Traits", "traits");
1221 print_entries(f, &self.macros, "Macros", "macros");
1222 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1223 print_entries(f, &self.derives, "Derive Macros", "derives");
1224 print_entries(f, &self.functions, "Functions", "functions");
1225 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1226 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1227 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1228 print_entries(f, &self.statics, "Statics", "statics");
1229 print_entries(f, &self.constants, "Constants", "constants")
1233 fn settings(root_path: &str, suffix: &str) -> String {
1234 // (id, explanation, default value)
1236 ("item-declarations", "Auto-hide item declarations.", true),
1237 ("item-attributes", "Auto-hide item attributes.", true),
1238 ("trait-implementations", "Auto-hide trait implementations documentation",
1240 ("method-docs", "Auto-hide item methods' documentation", false),
1241 ("go-to-only-result", "Directly go to item in search if there is only one result",
1243 ("line-numbers", "Show line numbers on code examples", false),
1247 <span class='in-band'>Rustdoc settings</span>\
1249 <div class='settings'>{}</div>\
1250 <script src='{}settings{}.js'></script>",
1252 .map(|(id, text, enabled)| {
1253 format!("<div class='setting-line'>\
1254 <label class='toggle'>\
1255 <input type='checkbox' id='{}' {}>\
1256 <span class='slider'></span>\
1259 </div>", id, if *enabled { " checked" } else { "" }, text)
1261 .collect::<String>(),
1267 fn derive_id(&self, id: String) -> String {
1268 let mut map = self.id_map.borrow_mut();
1272 /// String representation of how to get back to the root path of the 'doc/'
1273 /// folder in terms of a relative URL.
1274 fn root_path(&self) -> String {
1275 "../".repeat(self.current.len())
1278 /// Main method for rendering a crate.
1280 /// This currently isn't parallelized, but it'd be pretty easy to add
1281 /// parallelization to this function.
1282 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1283 let mut item = match krate.module.take() {
1285 None => return Ok(()),
1287 let final_file = self.dst.join(&krate.name)
1289 let settings_file = self.dst.join("settings.html");
1291 let crate_name = krate.name.clone();
1292 item.name = Some(krate.name);
1294 let mut all = AllTypes::new();
1297 // Render the crate documentation
1298 let mut work = vec![(self.clone(), item)];
1300 while let Some((mut cx, item)) = work.pop() {
1301 cx.item(item, &mut all, |cx, item| {
1302 work.push((cx.clone(), item))
1307 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1308 if !root_path.ends_with('/') {
1309 root_path.push('/');
1311 let mut page = layout::Page {
1312 title: "List of all items in this crate",
1315 static_root_path: self.shared.static_root_path.as_deref(),
1316 description: "List of all items in this crate",
1317 keywords: BASIC_KEYWORDS,
1318 resource_suffix: &self.shared.resource_suffix,
1320 static_extra_scripts: &[],
1322 let sidebar = if let Some(ref version) = self.cache.crate_version {
1323 format!("<p class='location'>Crate {}</p>\
1324 <div class='block version'>\
1327 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1328 crate_name, version)
1332 let v = layout::render(&self.shared.layout,
1333 &page, sidebar, |buf: &mut Buffer| all.print(buf),
1334 &self.shared.themes);
1335 self.shared.fs.write(&final_file, v.as_bytes())?;
1337 // Generating settings page.
1338 page.title = "Rustdoc settings";
1339 page.description = "Settings of Rustdoc";
1340 page.root_path = "./";
1342 let mut themes = self.shared.themes.clone();
1343 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1344 themes.push(PathBuf::from("settings.css"));
1345 let v = layout::render(
1346 &self.shared.layout,
1347 &page, sidebar, settings(
1348 self.shared.static_root_path.as_deref().unwrap_or("./"),
1349 &self.shared.resource_suffix
1352 self.shared.fs.write(&settings_file, v.as_bytes())?;
1357 fn render_item(&self,
1359 pushname: bool) -> String {
1360 // A little unfortunate that this is done like this, but it sure
1361 // does make formatting *a lot* nicer.
1362 CURRENT_DEPTH.with(|slot| {
1363 slot.set(self.current.len());
1366 let mut title = if it.is_primitive() || it.is_keyword() {
1367 // No need to include the namespace for primitive types and keywords
1370 self.current.join("::")
1373 if !title.is_empty() {
1374 title.push_str("::");
1376 title.push_str(it.name.as_ref().unwrap());
1378 title.push_str(" - Rust");
1379 let tyname = it.type_();
1380 let desc = if it.is_crate() {
1381 format!("API documentation for the Rust `{}` crate.",
1382 self.shared.layout.krate)
1384 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1385 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1387 let keywords = make_item_keywords(it);
1388 let page = layout::Page {
1389 css_class: tyname.as_str(),
1390 root_path: &self.root_path(),
1391 static_root_path: self.shared.static_root_path.as_deref(),
1394 keywords: &keywords,
1395 resource_suffix: &self.shared.resource_suffix,
1397 static_extra_scripts: &[],
1401 self.id_map.borrow_mut().reset();
1402 self.id_map.borrow_mut().populate(initial_ids());
1405 if !self.render_redirect_pages {
1406 layout::render(&self.shared.layout, &page,
1407 |buf: &mut _| print_sidebar(self, it, buf),
1408 |buf: &mut _| print_item(self, it, buf),
1409 &self.shared.themes)
1411 let mut url = self.root_path();
1412 if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) {
1413 for name in &names[..names.len() - 1] {
1417 url.push_str(&item_path(ty, names.last().unwrap()));
1418 layout::redirect(&url)
1425 /// Non-parallelized version of rendering an item. This will take the input
1426 /// item, render its contents, and then invoke the specified closure with
1427 /// all sub-items which need to be rendered.
1429 /// The rendering driver uses this closure to queue up more work.
1430 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
1431 where F: FnMut(&mut Context, clean::Item),
1433 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
1434 // if they contain impls for public types. These modules can also
1435 // contain items such as publicly re-exported structures.
1437 // External crates will provide links to these structures, so
1438 // these modules are recursed into, but not rendered normally
1439 // (a flag on the context).
1440 if !self.render_redirect_pages {
1441 self.render_redirect_pages = item.is_stripped();
1445 // modules are special because they add a namespace. We also need to
1446 // recurse into the items of the module as well.
1447 let name = item.name.as_ref().unwrap().to_string();
1448 let scx = &self.shared;
1449 if name.is_empty() {
1450 panic!("Unexpected empty destination: {:?}", self.current);
1452 let prev = self.dst.clone();
1453 self.dst.push(&name);
1454 self.current.push(name);
1456 info!("Recursing into {}", self.dst.display());
1458 let buf = self.render_item(&item, false);
1459 // buf will be empty if the module is stripped and there is no redirect for it
1460 if !buf.is_empty() {
1461 self.shared.ensure_dir(&self.dst)?;
1462 let joint_dst = self.dst.join("index.html");
1463 scx.fs.write(&joint_dst, buf.as_bytes())?;
1466 let m = match item.inner {
1467 clean::StrippedItem(box clean::ModuleItem(m)) |
1468 clean::ModuleItem(m) => m,
1472 // Render sidebar-items.js used throughout this module.
1473 if !self.render_redirect_pages {
1474 let items = self.build_sidebar_items(&m);
1475 let js_dst = self.dst.join("sidebar-items.js");
1476 let v = format!("initSidebarItems({});", as_json(&items));
1477 scx.fs.write(&js_dst, &v)?;
1480 for item in m.items {
1484 info!("Recursed; leaving {}", self.dst.display());
1486 // Go back to where we were at
1488 self.current.pop().unwrap();
1489 } else if item.name.is_some() {
1490 let buf = self.render_item(&item, true);
1491 // buf will be empty if the item is stripped and there is no redirect for it
1492 if !buf.is_empty() {
1493 let name = item.name.as_ref().unwrap();
1494 let item_type = item.type_();
1495 let file_name = &item_path(item_type, name);
1496 self.shared.ensure_dir(&self.dst)?;
1497 let joint_dst = self.dst.join(file_name);
1498 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
1500 if !self.render_redirect_pages {
1501 all.append(full_path(self, &item), &item_type);
1503 if self.shared.generate_redirect_pages {
1504 // Redirect from a sane URL using the namespace to Rustdoc's
1505 // URL for the page.
1506 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1507 let redir_dst = self.dst.join(redir_name);
1508 let v = layout::redirect(file_name);
1509 self.shared.fs.write(&redir_dst, v.as_bytes())?;
1511 // If the item is a macro, redirect from the old macro URL (with !)
1512 // to the new one (without).
1513 if item_type == ItemType::Macro {
1514 let redir_name = format!("{}.{}!.html", item_type, name);
1515 let redir_dst = self.dst.join(redir_name);
1516 let v = layout::redirect(file_name);
1517 self.shared.fs.write(&redir_dst, v.as_bytes())?;
1524 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1525 // BTreeMap instead of HashMap to get a sorted output
1526 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1527 for item in &m.items {
1528 if item.is_stripped() { continue }
1530 let short = item.type_();
1531 let myname = match item.name {
1533 Some(ref s) => s.to_string(),
1535 let short = short.to_string();
1536 map.entry(short).or_default()
1537 .push((myname, Some(plain_summary_line(item.doc_value()))));
1540 if self.shared.sort_modules_alphabetically {
1541 for (_, items) in &mut map {
1550 /// Generates a url appropriate for an `href` attribute back to the source of
1553 /// The url generated, when clicked, will redirect the browser back to the
1554 /// original source code.
1556 /// If `None` is returned, then a source link couldn't be generated. This
1557 /// may happen, for example, with externally inlined items where the source
1558 /// of their crate documentation isn't known.
1559 fn src_href(&self, item: &clean::Item) -> Option<String> {
1560 let mut root = self.root_path();
1562 let mut path = String::new();
1564 // We can safely ignore macros from other libraries
1565 let file = match item.source.filename {
1566 FileName::Real(ref path) => path,
1570 let (krate, path) = if item.def_id.is_local() {
1571 if let Some(path) = self.shared.local_sources.get(file) {
1572 (&self.shared.layout.krate, path)
1577 let (krate, src_root) = match *self.cache.extern_locations.get(&item.def_id.krate)? {
1578 (ref name, ref src, Local) => (name, src),
1579 (ref name, ref src, Remote(ref s)) => {
1580 root = s.to_string();
1583 (_, _, Unknown) => return None,
1586 sources::clean_path(&src_root, file, false, |component| {
1587 path.push_str(&component.to_string_lossy());
1590 let mut fname = file.file_name().expect("source has no filename")
1592 fname.push(".html");
1593 path.push_str(&fname.to_string_lossy());
1597 let lines = if item.source.loline == item.source.hiline {
1598 item.source.loline.to_string()
1600 format!("{}-{}", item.source.loline, item.source.hiline)
1602 Some(format!("{root}src/{krate}/{path}#{lines}",
1603 root = Escape(&root),
1610 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1611 where F: FnOnce(&mut Buffer)
1613 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1618 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer) {
1619 debug_assert!(!item.is_stripped());
1620 // Write the breadcrumb trail header for the top
1621 write!(buf, "<h1 class='fqn'><span class='out-of-band'>");
1622 if let Some(version) = item.stable_since() {
1623 write!(buf, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1627 "<span id='render-detail'>\
1628 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1629 title=\"collapse all docs\">\
1630 [<span class='inner'>−</span>]\
1636 // When this item is part of a `pub use` in a downstream crate, the
1637 // [src] link in the downstream documentation will actually come back to
1638 // this page, and this link will be auto-clicked. The `id` attribute is
1639 // used to find the link to auto-click.
1640 if cx.shared.include_sources && !item.is_primitive() {
1641 if let Some(l) = cx.src_href(item) {
1642 write!(buf, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1643 l, "goto source code");
1647 write!(buf, "</span>"); // out-of-band
1648 write!(buf, "<span class='in-band'>");
1649 let name = match item.inner {
1650 clean::ModuleItem(ref m) => if m.is_crate {
1655 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1656 clean::TraitItem(..) => "Trait ",
1657 clean::StructItem(..) => "Struct ",
1658 clean::UnionItem(..) => "Union ",
1659 clean::EnumItem(..) => "Enum ",
1660 clean::TypedefItem(..) => "Type Definition ",
1661 clean::MacroItem(..) => "Macro ",
1662 clean::ProcMacroItem(ref mac) => match mac.kind {
1663 MacroKind::Bang => "Macro ",
1664 MacroKind::Attr => "Attribute Macro ",
1665 MacroKind::Derive => "Derive Macro ",
1667 clean::PrimitiveItem(..) => "Primitive Type ",
1668 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1669 clean::ConstantItem(..) => "Constant ",
1670 clean::ForeignTypeItem => "Foreign Type ",
1671 clean::KeywordItem(..) => "Keyword ",
1672 clean::OpaqueTyItem(..) => "Opaque Type ",
1673 clean::TraitAliasItem(..) => "Trait Alias ",
1675 // We don't generate pages for any other type.
1679 buf.write_str(name);
1680 if !item.is_primitive() && !item.is_keyword() {
1681 let cur = &cx.current;
1682 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1683 for (i, component) in cur.iter().enumerate().take(amt) {
1684 write!(buf, "<a href='{}index.html'>{}</a>::<wbr>",
1685 "../".repeat(cur.len() - i - 1),
1689 write!(buf, "<a class=\"{}\" href=''>{}</a>",
1690 item.type_(), item.name.as_ref().unwrap());
1692 write!(buf, "</span></h1>"); // in-band
1695 clean::ModuleItem(ref m) =>
1696 item_module(buf, cx, item, &m.items),
1697 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1698 item_function(buf, cx, item, f),
1699 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
1700 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
1701 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
1702 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
1703 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t),
1704 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1705 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1706 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
1707 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1708 item_static(buf, cx, item, i),
1709 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1710 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
1711 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1712 clean::OpaqueTyItem(ref e, _) => item_opaque_ty(buf, cx, item, e),
1713 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
1715 // We don't generate pages for any other type.
1721 fn item_path(ty: ItemType, name: &str) -> String {
1723 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1724 _ => format!("{}.{}.html", ty, name),
1728 fn full_path(cx: &Context, item: &clean::Item) -> String {
1729 let mut s = cx.current.join("::");
1731 s.push_str(item.name.as_ref().unwrap());
1736 fn plain_summary_line(s: Option<&str>) -> String {
1737 let s = s.unwrap_or("");
1738 // This essentially gets the first paragraph of text in one line.
1739 let mut line = s.lines()
1740 .skip_while(|line| line.chars().all(|c| c.is_whitespace()))
1741 .take_while(|line| line.chars().any(|c| !c.is_whitespace()))
1742 .fold(String::new(), |mut acc, line| {
1747 // remove final whitespace
1749 markdown::plain_summary_line(&line[..])
1752 fn shorten(s: String) -> String {
1753 if s.chars().count() > 60 {
1755 let mut ret = s.split_whitespace()
1757 // + 1 for the added character after the word.
1758 len += p.chars().count() + 1;
1761 .collect::<Vec<_>>()
1770 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item) {
1771 if let Some(ref name) = item.name {
1772 info!("Documenting {}", name);
1774 document_stability(w, cx, item, false);
1775 document_full(w, item, cx, "", false);
1778 /// Render md_text as markdown.
1783 links: Vec<(String, String)>,
1787 let mut ids = cx.id_map.borrow_mut();
1788 write!(w, "<div class='docblock{}'>{}{}</div>",
1789 if is_hidden { " hidden" } else { "" },
1791 Markdown(md_text, &links, &mut ids,
1792 cx.shared.codes, cx.shared.edition, &cx.shared.playground).to_string())
1799 link: AssocItemLink<'_>,
1803 if let Some(s) = item.doc_value() {
1804 let markdown = if s.contains('\n') {
1805 format!("{} [Read more]({})",
1806 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1808 plain_summary_line(Some(s))
1810 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden);
1811 } else if !prefix.is_empty() {
1812 write!(w, "<div class='docblock{}'>{}</div>",
1813 if is_hidden { " hidden" } else { "" },
1818 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1819 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1820 debug!("Doc block: =====\n{}\n=====", s);
1821 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1822 } else if !prefix.is_empty() {
1823 write!(w, "<div class='docblock{}'>{}</div>",
1824 if is_hidden { " hidden" } else { "" },
1829 fn document_stability(w: &mut Buffer, cx: &Context, item: &clean::Item, is_hidden: bool) {
1830 let stabilities = short_stability(item, cx);
1831 if !stabilities.is_empty() {
1832 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" });
1833 for stability in stabilities {
1834 write!(w, "{}", stability);
1836 write!(w, "</div>");
1840 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1841 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1844 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1845 if item.is_non_exhaustive() {
1846 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
1847 if item.is_struct() {
1849 } else if item.is_enum() {
1851 } else if item.is_variant() {
1858 if item.is_struct() {
1859 write!(w, "Non-exhaustive structs could have additional fields added in future. \
1860 Therefore, non-exhaustive structs cannot be constructed in external crates \
1861 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1862 matched against without a wildcard <code>..</code>; and \
1863 struct update syntax will not work.");
1864 } else if item.is_enum() {
1865 write!(w, "Non-exhaustive enums could have additional variants added in future. \
1866 Therefore, when matching against variants of non-exhaustive enums, an \
1867 extra wildcard arm must be added to account for any future variants.");
1868 } else if item.is_variant() {
1869 write!(w, "Non-exhaustive enum variants could have additional fields added in future. \
1870 Therefore, non-exhaustive enum variants cannot be constructed in external \
1871 crates and cannot be matched against.");
1873 write!(w, "This type will require a wildcard arm in any match statements or \
1877 write!(w, "</div>");
1881 fn name_key(name: &str) -> (&str, u64, usize) {
1882 let end = name.bytes()
1883 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
1885 // find number at end
1886 let split = name[0..end].bytes()
1887 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
1889 // count leading zeroes
1891 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1893 // sort leading zeroes last
1894 let num_zeroes = after_zeroes - split;
1896 match name[split..end].parse() {
1897 Ok(n) => (&name[..split], n, num_zeroes),
1898 Err(_) => (name, 0, num_zeroes),
1902 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
1903 document(w, cx, item);
1905 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1907 // the order of item types in the listing
1908 fn reorder(ty: ItemType) -> u8 {
1910 ItemType::ExternCrate => 0,
1911 ItemType::Import => 1,
1912 ItemType::Primitive => 2,
1913 ItemType::Module => 3,
1914 ItemType::Macro => 4,
1915 ItemType::Struct => 5,
1916 ItemType::Enum => 6,
1917 ItemType::Constant => 7,
1918 ItemType::Static => 8,
1919 ItemType::Trait => 9,
1920 ItemType::Function => 10,
1921 ItemType::Typedef => 12,
1922 ItemType::Union => 13,
1927 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1928 let ty1 = i1.type_();
1929 let ty2 = i2.type_();
1931 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1933 let s1 = i1.stability.as_ref().map(|s| s.level);
1934 let s2 = i2.stability.as_ref().map(|s| s.level);
1936 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1937 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1940 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1941 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1942 name_key(lhs).cmp(&name_key(rhs))
1945 if cx.shared.sort_modules_alphabetically {
1946 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1948 // This call is to remove re-export duplicates in cases such as:
1953 // pub trait Double { fn foo(); }
1957 // pub use foo::bar::*;
1961 // `Double` will appear twice in the generated docs.
1963 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1964 // can be identical even if the elements are different (mostly in imports).
1965 // So in case this is an import, we keep everything by adding a "unique id"
1966 // (which is the position in the vector).
1967 indices.dedup_by_key(|i| (items[*i].def_id,
1968 if items[*i].name.as_ref().is_some() {
1969 Some(full_path(cx, &items[*i]))
1974 if items[*i].is_import() {
1980 debug!("{:?}", indices);
1981 let mut curty = None;
1982 for &idx in &indices {
1983 let myitem = &items[idx];
1984 if myitem.is_stripped() {
1988 let myty = Some(myitem.type_());
1989 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1990 // Put `extern crate` and `use` re-exports in the same section.
1992 } else if myty != curty {
1993 if curty.is_some() {
1994 write!(w, "</table>");
1997 let (short, name) = item_ty_to_strs(&myty.unwrap());
1998 write!(w, "<h2 id='{id}' class='section-header'>\
1999 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2000 id = cx.derive_id(short.to_owned()), name = name);
2003 match myitem.inner {
2004 clean::ExternCrateItem(ref name, ref src) => {
2005 use crate::html::format::anchor;
2009 write!(w, "<tr><td><code>{}extern crate {} as {};",
2010 myitem.visibility.print_with_space(),
2011 anchor(myitem.def_id, src),
2015 write!(w, "<tr><td><code>{}extern crate {};",
2016 myitem.visibility.print_with_space(),
2017 anchor(myitem.def_id, name))
2020 write!(w, "</code></td></tr>");
2023 clean::ImportItem(ref import) => {
2024 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2025 myitem.visibility.print_with_space(), import.print());
2029 if myitem.name.is_none() { continue }
2031 let unsafety_flag = match myitem.inner {
2032 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2033 if func.header.unsafety == hir::Unsafety::Unsafe => {
2034 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2039 let stab = myitem.stability_class();
2040 let add = if stab.is_some() {
2046 let doc_value = myitem.doc_value().unwrap_or("");
2048 <tr class='{stab}{add}module-item'>\
2049 <td><a class=\"{class}\" href=\"{href}\" \
2050 title='{title}'>{name}</a>{unsafety_flag}</td>\
2051 <td class='docblock-short'>{stab_tags}{docs}</td>\
2053 name = *myitem.name.as_ref().unwrap(),
2054 stab_tags = stability_tags(myitem),
2055 docs = MarkdownSummaryLine(doc_value, &myitem.links()).to_string(),
2056 class = myitem.type_(),
2058 stab = stab.unwrap_or_else(|| String::new()),
2059 unsafety_flag = unsafety_flag,
2060 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2061 title = [full_path(cx, myitem), myitem.type_().to_string()]
2063 .filter_map(|s| if !s.is_empty() {
2068 .collect::<Vec<_>>()
2075 if curty.is_some() {
2076 write!(w, "</table>");
2080 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2082 fn stability_tags(item: &clean::Item) -> String {
2083 let mut tags = String::new();
2085 fn tag_html(class: &str, contents: &str) -> String {
2086 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2089 // The trailing space after each tag is to space it properly against the rest of the docs.
2090 if item.deprecation().is_some() {
2091 let mut message = "Deprecated";
2092 if let Some(ref stab) = item.stability {
2093 if let Some(ref depr) = stab.deprecation {
2094 if let Some(ref since) = depr.since {
2095 if !stability::deprecation_in_effect(&since) {
2096 message = "Deprecation planned";
2101 tags += &tag_html("deprecated", message);
2104 if let Some(stab) = item
2107 .filter(|s| s.level == stability::Unstable)
2109 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2110 tags += &tag_html("internal", "Internal");
2112 tags += &tag_html("unstable", "Experimental");
2116 if let Some(ref cfg) = item.attrs.cfg {
2117 tags += &tag_html("portability", &cfg.render_short_html());
2123 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2125 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2126 let mut stability = vec![];
2127 let error_codes = cx.shared.codes;
2129 if let Some(Deprecation { note, since }) = &item.deprecation() {
2130 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2131 // but only display the future-deprecation messages for #[rustc_deprecated].
2132 let mut message = if let Some(since) = since {
2133 format!("Deprecated since {}", Escape(since))
2135 String::from("Deprecated")
2137 if let Some(ref stab) = item.stability {
2138 if let Some(ref depr) = stab.deprecation {
2139 if let Some(ref since) = depr.since {
2140 if !stability::deprecation_in_effect(&since) {
2141 message = format!("Deprecating in {}", Escape(&since));
2147 if let Some(note) = note {
2148 let mut ids = cx.id_map.borrow_mut();
2149 let html = MarkdownHtml(
2150 ¬e, &mut ids, error_codes, cx.shared.edition, &cx.shared.playground);
2151 message.push_str(&format!(": {}", html.to_string()));
2153 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2156 if let Some(stab) = item
2159 .filter(|stab| stab.level == stability::Unstable)
2161 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2163 let mut message = if is_rustc_private {
2164 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2166 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2170 if let Some(feature) = stab.feature.as_ref() {
2171 let mut feature = format!("<code>{}</code>", Escape(&feature));
2172 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2173 feature.push_str(&format!(
2174 " <a href=\"{url}{issue}\">#{issue}</a>",
2180 message.push_str(&format!(" ({})", feature));
2183 if let Some(unstable_reason) = &stab.unstable_reason {
2184 // Provide a more informative message than the compiler help.
2185 let unstable_reason = if is_rustc_private {
2186 "This crate is being loaded from the sysroot, a permanently unstable location \
2187 for private compiler dependencies. It is not intended for general use. Prefer \
2188 using a public version of this crate from \
2189 [crates.io](https://crates.io) via [`Cargo.toml`]\
2190 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2195 let mut ids = cx.id_map.borrow_mut();
2197 "<details><summary>{}</summary>{}</details>",
2204 &cx.shared.playground,
2209 let class = if is_rustc_private {
2214 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2217 if let Some(ref cfg) = item.attrs.cfg {
2218 stability.push(format!(
2219 "<div class='stab portability'>{}</div>",
2220 cfg.render_long_html()
2227 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2228 write!(w, "<pre class='rust const'>");
2229 render_attributes(w, it, false);
2230 write!(w, "{vis}const \
2231 {name}: {typ}</pre>",
2232 vis = it.visibility.print_with_space(),
2233 name = it.name.as_ref().unwrap(),
2234 typ = c.type_.print());
2238 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2239 write!(w, "<pre class='rust static'>");
2240 render_attributes(w, it, false);
2241 write!(w, "{vis}static {mutability}\
2242 {name}: {typ}</pre>",
2243 vis = it.visibility.print_with_space(),
2244 mutability = s.mutability.print_with_space(),
2245 name = it.name.as_ref().unwrap(),
2246 typ = s.type_.print());
2250 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2251 let header_len = format!(
2252 "{}{}{}{}{:#}fn {}{:#}",
2253 it.visibility.print_with_space(),
2254 f.header.constness.print_with_space(),
2255 f.header.unsafety.print_with_space(),
2256 f.header.asyncness.print_with_space(),
2257 print_abi_with_space(f.header.abi),
2258 it.name.as_ref().unwrap(),
2261 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it));
2262 render_attributes(w, it, false);
2264 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2265 {name}{generics}{decl}{where_clause}</pre>",
2266 vis = it.visibility.print_with_space(),
2267 constness = f.header.constness.print_with_space(),
2268 unsafety = f.header.unsafety.print_with_space(),
2269 asyncness = f.header.asyncness.print_with_space(),
2270 abi = print_abi_with_space(f.header.abi),
2271 name = it.name.as_ref().unwrap(),
2272 generics = f.generics.print(),
2273 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2278 asyncness: f.header.asyncness,
2283 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut Buffer,
2284 implementor_dups: &FxHashMap<&str, (DefId, bool)>) {
2285 // If there's already another implementor that has the same abbridged name, use the
2286 // full path, for example in `std::iter::ExactSizeIterator`
2287 let use_absolute = match implementor.inner_impl().for_ {
2288 clean::ResolvedPath { ref path, is_generic: false, .. } |
2289 clean::BorrowedRef {
2290 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2292 } => implementor_dups[path.last_name()].1,
2295 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
2296 implementor.impl_item.stable_since(), false, Some(use_absolute), false, false);
2299 fn render_impls(cx: &Context, w: &mut Buffer,
2301 containing_item: &clean::Item) {
2303 let did = i.trait_did().unwrap();
2304 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2305 render_impl(w, cx, i, assoc_link,
2306 RenderMode::Normal, containing_item.stable_since(), true, None, false, true);
2310 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2311 let mut bounds = String::new();
2312 if !t_bounds.is_empty() {
2314 bounds.push_str(": ");
2316 for (i, p) in t_bounds.iter().enumerate() {
2318 bounds.push_str(" + ");
2320 bounds.push_str(&p.print().to_string());
2326 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2327 let lhs = format!("{}", lhs.inner_impl().print());
2328 let rhs = format!("{}", rhs.inner_impl().print());
2330 // lhs and rhs are formatted as HTML, which may be unnecessary
2331 name_key(&lhs).cmp(&name_key(&rhs))
2340 let bounds = bounds(&t.bounds, false);
2341 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2342 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2343 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2344 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2346 // Output the trait definition
2347 wrap_into_docblock(w, |w| {
2348 write!(w, "<pre class='rust trait'>");
2349 render_attributes(w, it, true);
2350 write!(w, "{}{}{}trait {}{}{}",
2351 it.visibility.print_with_space(),
2352 t.unsafety.print_with_space(),
2353 if t.is_auto { "auto " } else { "" },
2354 it.name.as_ref().unwrap(),
2358 if !t.generics.where_predicates.is_empty() {
2359 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2364 if t.items.is_empty() {
2367 // FIXME: we should be using a derived_id for the Anchors here
2370 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2373 if !types.is_empty() && !consts.is_empty() {
2377 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2380 if !consts.is_empty() && !required.is_empty() {
2383 for (pos, m) in required.iter().enumerate() {
2384 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2387 if pos < required.len() - 1 {
2388 write!(w, "<div class='item-spacer'></div>");
2391 if !required.is_empty() && !provided.is_empty() {
2394 for (pos, m) in provided.iter().enumerate() {
2395 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2397 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2398 write!(w, ",\n {{ ... }}\n");
2401 write!(w, " {{ ... }}\n");
2404 if pos < provided.len() - 1 {
2405 write!(w, "<div class='item-spacer'></div>");
2413 // Trait documentation
2414 document(w, cx, it);
2416 fn write_small_section_header(
2420 extra_content: &str,
2423 <h2 id='{0}' class='small-section-header'>\
2424 {1}<a href='#{0}' class='anchor'></a>\
2425 </h2>{2}", id, title, extra_content)
2428 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2429 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
2432 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item) {
2433 let name = m.name.as_ref().unwrap();
2434 let item_type = m.type_();
2435 let id = cx.derive_id(format!("{}.{}", item_type, name));
2436 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
2437 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
2438 extra = render_spotlight_traits(m),
2441 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2442 write!(w, "</code>");
2443 render_stability_since(w, m, t);
2448 if !types.is_empty() {
2449 write_small_section_header(w, "associated-types", "Associated Types",
2450 "<div class='methods'>");
2452 trait_item(w, cx, *t, it);
2454 write_loading_content(w, "</div>");
2457 if !consts.is_empty() {
2458 write_small_section_header(w, "associated-const", "Associated Constants",
2459 "<div class='methods'>");
2461 trait_item(w, cx, *t, it);
2463 write_loading_content(w, "</div>");
2466 // Output the documentation for each function individually
2467 if !required.is_empty() {
2468 write_small_section_header(w, "required-methods", "Required methods",
2469 "<div class='methods'>");
2470 for m in &required {
2471 trait_item(w, cx, *m, it);
2473 write_loading_content(w, "</div>");
2475 if !provided.is_empty() {
2476 write_small_section_header(w, "provided-methods", "Provided methods",
2477 "<div class='methods'>");
2478 for m in &provided {
2479 trait_item(w, cx, *m, it);
2481 write_loading_content(w, "</div>");
2484 // If there are methods directly on this trait object, render them here.
2485 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All);
2487 let mut synthetic_types = Vec::new();
2489 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2490 // The DefId is for the first Type found with that name. The bool is
2491 // if any Types with the same name but different DefId have been found.
2492 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2493 for implementor in implementors {
2494 match implementor.inner_impl().for_ {
2495 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2496 clean::BorrowedRef {
2497 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2500 let &mut (prev_did, ref mut has_duplicates) =
2501 implementor_dups.entry(path.last_name()).or_insert((did, false));
2502 if prev_did != did {
2503 *has_duplicates = true;
2510 let (local, foreign) = implementors.iter()
2511 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2512 .map_or(true, |d| cx.cache.paths.contains_key(&d)));
2515 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
2516 .partition(|i| i.inner_impl().synthetic);
2518 synthetic.sort_by(compare_impl);
2519 concrete.sort_by(compare_impl);
2521 if !foreign.is_empty() {
2522 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2524 for implementor in foreign {
2525 let assoc_link = AssocItemLink::GotoSource(
2526 implementor.impl_item.def_id,
2527 &implementor.inner_impl().provided_trait_methods
2529 render_impl(w, cx, &implementor, assoc_link,
2530 RenderMode::Normal, implementor.impl_item.stable_since(), false,
2533 write_loading_content(w, "");
2536 write_small_section_header(w, "implementors", "Implementors",
2537 "<div class='item-list' id='implementors-list'>");
2538 for implementor in concrete {
2539 render_implementor(cx, implementor, w, &implementor_dups);
2541 write_loading_content(w, "</div>");
2544 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
2545 "<div class='item-list' id='synthetic-implementors-list'>");
2546 for implementor in synthetic {
2547 synthetic_types.extend(
2548 collect_paths_for_type(implementor.inner_impl().for_.clone())
2550 render_implementor(cx, implementor, w, &implementor_dups);
2552 write_loading_content(w, "</div>");
2555 // even without any implementations to write in, we still want the heading and list, so the
2556 // implementors javascript file pulled in below has somewhere to write the impls into
2557 write_small_section_header(w, "implementors", "Implementors",
2558 "<div class='item-list' id='implementors-list'>");
2559 write_loading_content(w, "</div>");
2562 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
2563 "<div class='item-list' id='synthetic-implementors-list'>");
2564 write_loading_content(w, "</div>");
2567 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2568 as_json(&synthetic_types));
2570 write!(w, r#"<script type="text/javascript" async
2571 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2573 root_path = vec![".."; cx.current.len()].join("/"),
2574 path = if it.def_id.is_local() {
2575 cx.current.join("/")
2577 let (ref path, _) = cx.cache.external_paths[&it.def_id];
2578 path[..path.len() - 1].join("/")
2581 name = *it.name.as_ref().unwrap());
2584 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2585 use crate::html::item_type::ItemType::*;
2587 let name = it.name.as_ref().unwrap();
2588 let ty = match it.type_() {
2589 Typedef | AssocType => AssocType,
2593 let anchor = format!("#{}.{}", ty, name);
2595 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2596 AssocItemLink::Anchor(None) => anchor,
2597 AssocItemLink::GotoSource(did, _) => {
2598 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2603 fn assoc_const(w: &mut Buffer,
2606 _default: Option<&String>,
2607 link: AssocItemLink<'_>,
2609 write!(w, "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2611 it.visibility.print_with_space(),
2612 naive_assoc_href(it, link),
2613 it.name.as_ref().unwrap(),
2617 fn assoc_type(w: &mut Buffer, it: &clean::Item,
2618 bounds: &[clean::GenericBound],
2619 default: Option<&clean::Type>,
2620 link: AssocItemLink<'_>,
2622 write!(w, "{}type <a href='{}' class=\"type\">{}</a>",
2624 naive_assoc_href(it, link),
2625 it.name.as_ref().unwrap());
2626 if !bounds.is_empty() {
2627 write!(w, ": {}", print_generic_bounds(bounds))
2629 if let Some(default) = default {
2630 write!(w, " = {}", default.print())
2634 fn render_stability_since_raw(w: &mut Buffer, ver: Option<&str>, containing_ver: Option<&str>) {
2635 if let Some(v) = ver {
2636 if containing_ver != ver && v.len() > 0 {
2637 write!(w, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", v)
2642 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2643 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2646 fn render_assoc_item(w: &mut Buffer,
2648 link: AssocItemLink<'_>,
2650 fn method(w: &mut Buffer,
2652 header: hir::FnHeader,
2653 g: &clean::Generics,
2655 link: AssocItemLink<'_>,
2657 let name = meth.name.as_ref().unwrap();
2658 let anchor = format!("#{}.{}", meth.type_(), name);
2659 let href = match link {
2660 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2661 AssocItemLink::Anchor(None) => anchor,
2662 AssocItemLink::GotoSource(did, provided_methods) => {
2663 // We're creating a link from an impl-item to the corresponding
2664 // trait-item and need to map the anchored type accordingly.
2665 let ty = if provided_methods.contains(name) {
2671 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2674 let mut header_len = format!(
2675 "{}{}{}{}{}{:#}fn {}{:#}",
2676 meth.visibility.print_with_space(),
2677 header.constness.print_with_space(),
2678 header.unsafety.print_with_space(),
2679 header.asyncness.print_with_space(),
2680 print_default_space(meth.is_default()),
2681 print_abi_with_space(header.abi),
2685 let (indent, end_newline) = if parent == ItemType::Trait {
2691 render_attributes(w, meth, false);
2692 write!(w, "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2693 {generics}{decl}{where_clause}",
2694 if parent == ItemType::Trait { " " } else { "" },
2695 meth.visibility.print_with_space(),
2696 header.constness.print_with_space(),
2697 header.unsafety.print_with_space(),
2698 header.asyncness.print_with_space(),
2699 print_default_space(meth.is_default()),
2700 print_abi_with_space(header.abi),
2703 generics = g.print(),
2708 asyncness: header.asyncness,
2710 where_clause = WhereClause {
2717 clean::StrippedItem(..) => {},
2718 clean::TyMethodItem(ref m) => {
2719 method(w, item, m.header, &m.generics, &m.decl, link, parent)
2721 clean::MethodItem(ref m) => {
2722 method(w, item, m.header, &m.generics, &m.decl, link, parent)
2724 clean::AssocConstItem(ref ty, ref default) => {
2725 assoc_const(w, item, ty, default.as_ref(), link,
2726 if parent == ItemType::Trait { " " } else { "" })
2728 clean::AssocTypeItem(ref bounds, ref default) => {
2729 assoc_type(w, item, bounds, default.as_ref(), link,
2730 if parent == ItemType::Trait { " " } else { "" })
2732 _ => panic!("render_assoc_item called on non-associated-item")
2736 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct) {
2737 wrap_into_docblock(w, |w| {
2738 write!(w, "<pre class='rust struct'>");
2739 render_attributes(w, it, true);
2750 document(w, cx, it);
2751 let mut fields = s.fields.iter().filter_map(|f| {
2753 clean::StructFieldItem(ref ty) => Some((f, ty)),
2757 if let doctree::Plain = s.struct_type {
2758 if fields.peek().is_some() {
2759 write!(w, "<h2 id='fields' class='fields small-section-header'>
2760 Fields{}<a href='#fields' class='anchor'></a></h2>",
2761 document_non_exhaustive_header(it));
2762 document_non_exhaustive(w, it);
2763 for (field, ty) in fields {
2764 let id = cx.derive_id(format!("{}.{}",
2765 ItemType::StructField,
2766 field.name.as_ref().unwrap()));
2767 let ns_id = cx.derive_id(format!("{}.{}",
2768 field.name.as_ref().unwrap(),
2769 ItemType::StructField.name_space()));
2770 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
2771 <a href=\"#{id}\" class=\"anchor field\"></a>\
2772 <code id=\"{ns_id}\">{name}: {ty}</code>\
2774 item_type = ItemType::StructField,
2777 name = field.name.as_ref().unwrap(),
2779 document(w, cx, field);
2783 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2786 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union) {
2787 wrap_into_docblock(w, |w| {
2788 write!(w, "<pre class='rust union'>");
2789 render_attributes(w, it, true);
2799 document(w, cx, it);
2800 let mut fields = s.fields.iter().filter_map(|f| {
2802 clean::StructFieldItem(ref ty) => Some((f, ty)),
2806 if fields.peek().is_some() {
2807 write!(w, "<h2 id='fields' class='fields small-section-header'>
2808 Fields<a href='#fields' class='anchor'></a></h2>");
2809 for (field, ty) in fields {
2810 let name = field.name.as_ref().expect("union field name");
2811 let id = format!("{}.{}", ItemType::StructField, name);
2812 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
2813 <a href=\"#{id}\" class=\"anchor field\"></a>\
2814 <code>{name}: {ty}</code>\
2818 shortty = ItemType::StructField,
2820 if let Some(stability_class) = field.stability_class() {
2821 write!(w, "<span class='stab {stab}'></span>",
2822 stab = stability_class);
2824 document(w, cx, field);
2827 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2830 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum) {
2831 wrap_into_docblock(w, |w| {
2832 write!(w, "<pre class='rust enum'>");
2833 render_attributes(w, it, true);
2834 write!(w, "{}enum {}{}{}",
2835 it.visibility.print_with_space(),
2836 it.name.as_ref().unwrap(),
2838 WhereClause { gens: &e.generics, indent: 0, end_newline: true });
2839 if e.variants.is_empty() && !e.variants_stripped {
2843 for v in &e.variants {
2845 let name = v.name.as_ref().unwrap();
2847 clean::VariantItem(ref var) => {
2849 clean::VariantKind::CLike => write!(w, "{}", name),
2850 clean::VariantKind::Tuple(ref tys) => {
2851 write!(w, "{}(", name);
2852 for (i, ty) in tys.iter().enumerate() {
2854 write!(w, ", ")
2856 write!(w, "{}", ty.print());
2860 clean::VariantKind::Struct(ref s) => {
2876 if e.variants_stripped {
2877 write!(w, " // some variants omitted\n");
2884 document(w, cx, it);
2885 if !e.variants.is_empty() {
2886 write!(w, "<h2 id='variants' class='variants small-section-header'>
2887 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
2888 document_non_exhaustive_header(it));
2889 document_non_exhaustive(w, it);
2890 for variant in &e.variants {
2891 let id = cx.derive_id(format!("{}.{}",
2893 variant.name.as_ref().unwrap()));
2894 let ns_id = cx.derive_id(format!("{}.{}",
2895 variant.name.as_ref().unwrap(),
2896 ItemType::Variant.name_space()));
2897 write!(w, "<div id=\"{id}\" class=\"variant small-section-header\">\
2898 <a href=\"#{id}\" class=\"anchor field\"></a>\
2899 <code id='{ns_id}'>{name}",
2902 name = variant.name.as_ref().unwrap());
2903 if let clean::VariantItem(ref var) = variant.inner {
2904 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2906 for (i, ty) in tys.iter().enumerate() {
2908 write!(w, ", ");
2910 write!(w, "{}", ty.print());
2915 write!(w, "</code></div>");
2916 document(w, cx, variant);
2917 document_non_exhaustive(w, variant);
2919 use crate::clean::{Variant, VariantKind};
2920 if let clean::VariantItem(Variant {
2921 kind: VariantKind::Struct(ref s)
2922 }) = variant.inner {
2923 let variant_id = cx.derive_id(format!("{}.{}.fields",
2925 variant.name.as_ref().unwrap()));
2926 write!(w, "<div class='autohide sub-variant' id='{id}'>",
2928 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
2929 name = variant.name.as_ref().unwrap());
2930 for field in &s.fields {
2931 use crate::clean::StructFieldItem;
2932 if let StructFieldItem(ref ty) = field.inner {
2933 let id = cx.derive_id(format!("variant.{}.field.{}",
2934 variant.name.as_ref().unwrap(),
2935 field.name.as_ref().unwrap()));
2936 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
2937 variant.name.as_ref().unwrap(),
2938 ItemType::Variant.name_space(),
2939 field.name.as_ref().unwrap(),
2940 ItemType::StructField.name_space()));
2941 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2942 <a href=\"#{id}\" class=\"anchor field\"></a>\
2943 <code id='{ns_id}'>{f}: {t}\
2947 f = field.name.as_ref().unwrap(),
2949 document(w, cx, field);
2952 write!(w, "</div></div>");
2954 render_stability_since(w, variant, it);
2957 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2960 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2961 let path = pprust::path_to_string(&attr.path);
2965 } else if let Some(v) = attr.value_str() {
2966 Some(format!("{} = {:?}", path, v.as_str()))
2967 } else if let Some(values) = attr.meta_item_list() {
2968 let display: Vec<_> = values.iter().filter_map(|attr| {
2969 attr.meta_item().and_then(|mi| render_attribute(mi))
2972 if display.len() > 0 {
2973 Some(format!("{}({})", path, display.join(", ")))
2982 const ATTRIBUTE_WHITELIST: &'static [Symbol] = &[
2992 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
2993 // left padding. For example:
2995 // #[foo] <----- "top" attribute
2997 // #[bar] <---- not "top" attribute
3000 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3001 let mut attrs = String::new();
3003 for attr in &it.attrs.other_attrs {
3004 if !ATTRIBUTE_WHITELIST.contains(&attr.name_or_empty()) {
3007 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3008 attrs.push_str(&format!("#[{}]\n", s));
3011 if attrs.len() > 0 {
3012 write!(w, "<span class=\"docblock attributes{}\">{}</span>",
3013 if top { " top-attr" } else { "" }, &attrs);
3017 fn render_struct(w: &mut Buffer, it: &clean::Item,
3018 g: Option<&clean::Generics>,
3019 ty: doctree::StructType,
3020 fields: &[clean::Item],
3024 it.visibility.print_with_space(),
3025 if structhead {"struct "} else {""},
3026 it.name.as_ref().unwrap());
3027 if let Some(g) = g {
3028 write!(w, "{}", g.print())
3032 if let Some(g) = g {
3033 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3035 let mut has_visible_fields = false;
3037 for field in fields {
3038 if let clean::StructFieldItem(ref ty) = field.inner {
3039 write!(w, "\n{} {}{}: {},",
3041 field.visibility.print_with_space(),
3042 field.name.as_ref().unwrap(),
3044 has_visible_fields = true;
3048 if has_visible_fields {
3049 if it.has_stripped_fields().unwrap() {
3050 write!(w, "\n{} // some fields omitted", tab);
3052 write!(w, "\n{}", tab);
3053 } else if it.has_stripped_fields().unwrap() {
3054 // If there are no visible fields we can just display
3055 // `{ /* fields omitted */ }` to save space.
3056 write!(w, " /* fields omitted */ ");
3062 for (i, field) in fields.iter().enumerate() {
3067 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3070 clean::StructFieldItem(ref ty) => {
3071 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3077 if let Some(g) = g {
3078 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3083 // Needed for PhantomData.
3084 if let Some(g) = g {
3085 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3092 fn render_union(w: &mut Buffer, it: &clean::Item,
3093 g: Option<&clean::Generics>,
3094 fields: &[clean::Item],
3098 it.visibility.print_with_space(),
3099 if structhead {"union "} else {""},
3100 it.name.as_ref().unwrap());
3101 if let Some(g) = g {
3102 write!(w, "{}", g.print());
3103 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3106 write!(w, " {{\n{}", tab);
3107 for field in fields {
3108 if let clean::StructFieldItem(ref ty) = field.inner {
3109 write!(w, " {}{}: {},\n{}",
3110 field.visibility.print_with_space(),
3111 field.name.as_ref().unwrap(),
3117 if it.has_stripped_fields().unwrap() {
3118 write!(w, " // some fields omitted\n{}", tab);
3123 #[derive(Copy, Clone)]
3124 enum AssocItemLink<'a> {
3125 Anchor(Option<&'a str>),
3126 GotoSource(DefId, &'a FxHashSet<String>),
3129 impl<'a> AssocItemLink<'a> {
3130 fn anchor(&self, id: &'a String) -> Self {
3132 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3133 ref other => *other,
3138 enum AssocItemRender<'a> {
3140 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3143 #[derive(Copy, Clone, PartialEq)]
3146 ForDeref { mut_: bool },
3149 fn render_assoc_items(w: &mut Buffer,
3151 containing_item: &clean::Item,
3153 what: AssocItemRender<'_>) {
3155 let v = match c.impls.get(&it) {
3159 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3160 i.inner_impl().trait_.is_none()
3162 if !non_trait.is_empty() {
3163 let render_mode = match what {
3164 AssocItemRender::All => {
3166 <h2 id='methods' class='small-section-header'>\
3167 Methods<a href='#methods' class='anchor'></a>\
3172 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3174 <h2 id='deref-methods' class='small-section-header'>\
3175 Methods from {}<Target = {}>\
3176 <a href='#deref-methods' class='anchor'></a>\
3178 ", trait_.print(), type_.print());
3179 RenderMode::ForDeref { mut_: deref_mut_ }
3182 for i in &non_trait {
3183 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3184 containing_item.stable_since(), true, None, false, true);
3187 if let AssocItemRender::DerefFor { .. } = what {
3190 if !traits.is_empty() {
3191 let deref_impl = traits.iter().find(|t| {
3192 t.inner_impl().trait_.def_id() == c.deref_trait_did
3194 if let Some(impl_) = deref_impl {
3195 let has_deref_mut = traits.iter().find(|t| {
3196 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3198 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
3201 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3203 .partition(|t| t.inner_impl().synthetic);
3204 let (blanket_impl, concrete): (Vec<&&Impl>, _) = concrete
3206 .partition(|t| t.inner_impl().blanket_impl.is_some());
3208 let mut impls = Buffer::empty_from(&w);
3209 render_impls(cx, &mut impls, &concrete, containing_item);
3210 let impls = impls.into_inner();
3211 if !impls.is_empty() {
3213 <h2 id='implementations' class='small-section-header'>\
3214 Trait Implementations<a href='#implementations' class='anchor'></a>\
3216 <div id='implementations-list'>{}</div>", impls);
3219 if !synthetic.is_empty() {
3221 <h2 id='synthetic-implementations' class='small-section-header'>\
3222 Auto Trait Implementations\
3223 <a href='#synthetic-implementations' class='anchor'></a>\
3225 <div id='synthetic-implementations-list'>\
3227 render_impls(cx, w, &synthetic, containing_item);
3228 write!(w, "</div>");
3231 if !blanket_impl.is_empty() {
3233 <h2 id='blanket-implementations' class='small-section-header'>\
3234 Blanket Implementations\
3235 <a href='#blanket-implementations' class='anchor'></a>\
3237 <div id='blanket-implementations-list'>\
3239 render_impls(cx, w, &blanket_impl, containing_item);
3240 write!(w, "</div>");
3245 fn render_deref_methods(w: &mut Buffer, cx: &Context, impl_: &Impl,
3246 container_item: &clean::Item, deref_mut: bool) {
3247 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3248 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3250 clean::TypedefItem(ref t, true) => Some(&t.type_),
3253 }).next().expect("Expected associated type binding");
3254 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3255 deref_mut_: deref_mut };
3256 if let Some(did) = target.def_id() {
3257 render_assoc_items(w, cx, container_item, did, what)
3259 if let Some(prim) = target.primitive_type() {
3260 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
3261 render_assoc_items(w, cx, container_item, did, what);
3267 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3268 let self_type_opt = match item.inner {
3269 clean::MethodItem(ref method) => method.decl.self_type(),
3270 clean::TyMethodItem(ref method) => method.decl.self_type(),
3274 if let Some(self_ty) = self_type_opt {
3275 let (by_mut_ref, by_box, by_value) = match self_ty {
3276 SelfTy::SelfBorrowed(_, mutability) |
3277 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3278 (mutability == Mutability::Mutable, false, false)
3280 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3281 (false, Some(did) == cache().owned_box_did, false)
3283 SelfTy::SelfValue => (false, false, true),
3284 _ => (false, false, false),
3287 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3293 fn render_spotlight_traits(item: &clean::Item) -> String {
3295 clean::FunctionItem(clean::Function { ref decl, .. }) |
3296 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3297 clean::MethodItem(clean::Method { ref decl, .. }) |
3298 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3299 spotlight_decl(decl)
3305 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3306 let mut out = Buffer::html();
3307 let mut trait_ = String::new();
3309 if let Some(did) = decl.output.def_id() {
3311 if let Some(impls) = c.impls.get(&did) {
3313 let impl_ = i.inner_impl();
3314 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3317 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3318 <code class=\"content\">",
3319 impl_.for_.print()));
3320 trait_.push_str(&impl_.for_.print().to_string());
3323 //use the "where" class here to make it small
3325 &format!("<span class=\"where fmt-newline\">{}</span>", impl_.print()));
3326 let t_did = impl_.trait_.def_id().unwrap();
3327 for it in &impl_.items {
3328 if let clean::TypedefItem(ref tydef, _) = it.inner {
3329 out.push_str("<span class=\"where fmt-newline\"> ");
3330 assoc_type(&mut out, it, &[],
3332 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3334 out.push_str(";</span>");
3342 if !out.is_empty() {
3343 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3344 <span class='tooltiptext'>Important traits for {}</span></div>\
3345 <div class=\"content hidden\">",
3347 out.push_str("</code></div></div>");
3353 fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>,
3354 render_mode: RenderMode, outer_version: Option<&str>, show_def_docs: bool,
3355 use_absolute: Option<bool>, is_on_foreign_type: bool,
3356 show_default_items: bool) {
3357 if render_mode == RenderMode::Normal {
3358 let id = cx.derive_id(match i.inner_impl().trait_ {
3359 Some(ref t) => if is_on_foreign_type {
3360 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3362 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3364 None => "impl".to_string(),
3366 if let Some(use_absolute) = use_absolute {
3367 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id);
3368 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3370 for it in &i.inner_impl().items {
3371 if let clean::TypedefItem(ref tydef, _) = it.inner {
3372 write!(w, "<span class=\"where fmt-newline\"> ");
3373 assoc_type(w, it, &vec![], Some(&tydef.type_),
3374 AssocItemLink::Anchor(None),
3376 write!(w, ";</span>");
3380 write!(w, "</code>");
3382 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
3383 id, i.inner_impl().print()
3386 write!(w, "<a href='#{}' class='anchor'></a>", id);
3387 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3388 render_stability_since_raw(w, since, outer_version);
3389 if let Some(l) = cx.src_href(&i.impl_item) {
3390 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3391 l, "goto source code");
3394 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3395 let mut ids = cx.id_map.borrow_mut();
3396 write!(w, "<div class='docblock'>{}</div>",
3397 Markdown(&*dox, &i.impl_item.links(), &mut ids,
3398 cx.shared.codes, cx.shared.edition, &cx.shared.playground).to_string());
3402 fn doc_impl_item(w: &mut Buffer, cx: &Context, item: &clean::Item,
3403 link: AssocItemLink<'_>, render_mode: RenderMode,
3404 is_default_item: bool, outer_version: Option<&str>,
3405 trait_: Option<&clean::Trait>, show_def_docs: bool) {
3406 let item_type = item.type_();
3407 let name = item.name.as_ref().unwrap();
3409 let render_method_item = match render_mode {
3410 RenderMode::Normal => true,
3411 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3414 let (is_hidden, extra_class) = if (trait_.is_none() ||
3415 item.doc_value().is_some() ||
3416 item.inner.is_associated()) &&
3423 clean::MethodItem(clean::Method { ref decl, .. }) |
3424 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
3425 // Only render when the method is not static or we allow static methods
3426 if render_method_item {
3427 let id = cx.derive_id(format!("{}.{}", item_type, name));
3428 let ns_id = cx.derive_id(format!("{}.{}",
3429 name, item_type.name_space()));
3430 write!(w, "<h4 id='{}' class=\"{}{}\">",
3431 id, item_type, extra_class);
3432 write!(w, "{}", spotlight_decl(decl));
3433 write!(w, "<code id='{}'>", ns_id);
3434 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3435 write!(w, "</code>");
3436 render_stability_since_raw(w, item.stable_since(), outer_version);
3437 if let Some(l) = cx.src_href(item) {
3438 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3439 l, "goto source code");
3444 clean::TypedefItem(ref tydef, _) => {
3445 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3446 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3447 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3448 write!(w, "<code id='{}'>", ns_id);
3449 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3450 write!(w, "</code></h4>");
3452 clean::AssocConstItem(ref ty, ref default) => {
3453 let id = cx.derive_id(format!("{}.{}", item_type, name));
3454 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3455 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3456 write!(w, "<code id='{}'>", ns_id);
3457 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3458 write!(w, "</code>");
3459 render_stability_since_raw(w, item.stable_since(), outer_version);
3460 if let Some(l) = cx.src_href(item) {
3461 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3462 l, "goto source code");
3466 clean::AssocTypeItem(ref bounds, ref default) => {
3467 let id = cx.derive_id(format!("{}.{}", item_type, name));
3468 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3469 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3470 write!(w, "<code id='{}'>", ns_id);
3471 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3472 write!(w, "</code></h4>");
3474 clean::StrippedItem(..) => return,
3475 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3478 if render_method_item {
3479 if !is_default_item {
3480 if let Some(t) = trait_ {
3481 // The trait item may have been stripped so we might not
3482 // find any documentation or stability for it.
3483 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3484 // We need the stability of the item from the trait
3485 // because impls can't have a stability.
3486 document_stability(w, cx, it, is_hidden);
3487 if item.doc_value().is_some() {
3488 document_full(w, item, cx, "", is_hidden);
3489 } else if show_def_docs {
3490 // In case the item isn't documented,
3491 // provide short documentation from the trait.
3492 document_short(w, cx, it, link, "", is_hidden);
3496 document_stability(w, cx, item, is_hidden);
3498 document_full(w, item, cx, "", is_hidden);
3502 document_stability(w, cx, item, is_hidden);
3504 document_short(w, cx, item, link, "", is_hidden);
3510 let traits = &cx.cache.traits;
3511 let trait_ = i.trait_did().map(|did| &traits[&did]);
3513 write!(w, "<div class='impl-items'>");
3514 for trait_item in &i.inner_impl().items {
3515 doc_impl_item(w, cx, trait_item, link, render_mode,
3516 false, outer_version, trait_, show_def_docs);
3519 fn render_default_items(w: &mut Buffer,
3523 render_mode: RenderMode,
3524 outer_version: Option<&str>,
3525 show_def_docs: bool) {
3526 for trait_item in &t.items {
3527 let n = trait_item.name.clone();
3528 if i.items.iter().find(|m| m.name == n).is_some() {
3531 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3532 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3534 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3535 outer_version, None, show_def_docs);
3539 // If we've implemented a trait, then also emit documentation for all
3540 // default items which weren't overridden in the implementation block.
3541 // We don't emit documentation for default items if they appear in the
3542 // Implementations on Foreign Types or Implementors sections.
3543 if show_default_items {
3544 if let Some(t) = trait_ {
3545 render_default_items(w, cx, t, &i.inner_impl(),
3546 render_mode, outer_version, show_def_docs);
3549 write!(w, "</div>");
3556 t: &clean::OpaqueTy,
3558 write!(w, "<pre class='rust opaque'>");
3559 render_attributes(w, it, false);
3560 write!(w, "type {}{}{where_clause} = impl {bounds};</pre>",
3561 it.name.as_ref().unwrap(),
3563 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3564 bounds = bounds(&t.bounds, false));
3566 document(w, cx, it);
3568 // Render any items associated directly to this alias, as otherwise they
3569 // won't be visible anywhere in the docs. It would be nice to also show
3570 // associated items from the aliased type (see discussion in #32077), but
3571 // we need #14072 to make sense of the generics.
3572 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3575 fn item_trait_alias(w: &mut Buffer, cx: &Context, it: &clean::Item,
3576 t: &clean::TraitAlias) {
3577 write!(w, "<pre class='rust trait-alias'>");
3578 render_attributes(w, it, false);
3579 write!(w, "trait {}{}{} = {};</pre>",
3580 it.name.as_ref().unwrap(),
3582 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3583 bounds(&t.bounds, true));
3585 document(w, cx, it);
3587 // Render any items associated directly to this alias, as otherwise they
3588 // won't be visible anywhere in the docs. It would be nice to also show
3589 // associated items from the aliased type (see discussion in #32077), but
3590 // we need #14072 to make sense of the generics.
3591 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3594 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef) {
3595 write!(w, "<pre class='rust typedef'>");
3596 render_attributes(w, it, false);
3597 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3598 it.name.as_ref().unwrap(),
3600 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3601 type_ = t.type_.print());
3603 document(w, cx, it);
3605 // Render any items associated directly to this alias, as otherwise they
3606 // won't be visible anywhere in the docs. It would be nice to also show
3607 // associated items from the aliased type (see discussion in #32077), but
3608 // we need #14072 to make sense of the generics.
3609 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3612 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item) {
3613 writeln!(w, "<pre class='rust foreigntype'>extern {{");
3614 render_attributes(w, it, false);
3617 " {}type {};\n}}</pre>",
3618 it.visibility.print_with_space(),
3619 it.name.as_ref().unwrap(),
3622 document(w, cx, it);
3624 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3627 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer) {
3628 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3630 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3631 || it.is_enum() || it.is_mod() || it.is_typedef() {
3632 write!(buffer, "<p class='location'>{}{}</p>",
3634 clean::StructItem(..) => "Struct ",
3635 clean::TraitItem(..) => "Trait ",
3636 clean::PrimitiveItem(..) => "Primitive Type ",
3637 clean::UnionItem(..) => "Union ",
3638 clean::EnumItem(..) => "Enum ",
3639 clean::TypedefItem(..) => "Type Definition ",
3640 clean::ForeignTypeItem => "Foreign Type ",
3641 clean::ModuleItem(..) => if it.is_crate() {
3648 it.name.as_ref().unwrap());
3652 if let Some(ref version) = cx.cache.crate_version {
3654 "<div class='block version'>\
3661 write!(buffer, "<div class=\"sidebar-elems\">");
3663 write!(buffer, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3664 it.name.as_ref().expect("crates always have a name"));
3667 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
3668 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
3669 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
3670 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
3671 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
3672 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
3673 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
3674 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
3678 // The sidebar is designed to display sibling functions, modules and
3679 // other miscellaneous information. since there are lots of sibling
3680 // items (and that causes quadratic growth in large modules),
3681 // we refactor common parts into a shared JavaScript file per module.
3682 // still, we don't move everything into JS because we want to preserve
3683 // as much HTML as possible in order to allow non-JS-enabled browsers
3684 // to navigate the documentation (though slightly inefficiently).
3686 write!(buffer, "<p class='location'>");
3687 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3689 write!(buffer, "::<wbr>");
3691 write!(buffer, "<a href='{}index.html'>{}</a>",
3692 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3695 write!(buffer, "</p>");
3697 // Sidebar refers to the enclosing module, not this module.
3698 let relpath = if it.is_mod() { "../" } else { "" };
3700 "<script>window.sidebarCurrent = {{\
3705 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3709 // There is no sidebar-items.js beyond the crate root path
3710 // FIXME maybe dynamic crate loading can be merged here
3712 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>",
3715 // Closes sidebar-elems div.
3716 write!(buffer, "</div>");
3719 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
3720 if used_links.insert(url.clone()) {
3724 while used_links.insert(format!("{}-{}", url, add)) == false {
3727 format!("{}-{}", url, add)
3733 used_links: &mut FxHashSet<String>,
3736 i.items.iter().filter_map(|item| {
3738 Some(ref name) if !name.is_empty() && item.is_method() => {
3739 if !for_deref || should_render_item(item, deref_mut) {
3740 Some(format!("<a href=\"#{}\">{}</a>",
3741 get_next_url(used_links, format!("method.{}", name)),
3749 }).collect::<Vec<_>>()
3752 // The point is to url encode any potential character from a type with genericity.
3753 fn small_url_encode(s: &str) -> String {
3754 s.replace("<", "%3C")
3755 .replace(">", "%3E")
3756 .replace(" ", "%20")
3757 .replace("?", "%3F")
3758 .replace("'", "%27")
3759 .replace("&", "%26")
3760 .replace(",", "%2C")
3761 .replace(":", "%3A")
3762 .replace(";", "%3B")
3763 .replace("[", "%5B")
3764 .replace("]", "%5D")
3765 .replace("\"", "%22")
3768 fn sidebar_assoc_items(it: &clean::Item) -> String {
3769 let mut out = String::new();
3771 if let Some(v) = c.impls.get(&it.def_id) {
3772 let mut used_links = FxHashSet::default();
3775 let used_links_bor = &mut used_links;
3776 let mut ret = v.iter()
3777 .filter(|i| i.inner_impl().trait_.is_none())
3778 .flat_map(move |i| get_methods(i.inner_impl(),
3780 used_links_bor, false))
3781 .collect::<Vec<_>>();
3782 // We want links' order to be reproducible so we don't use unstable sort.
3784 if !ret.is_empty() {
3785 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3786 </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
3790 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3791 if let Some(impl_) = v.iter()
3792 .filter(|i| i.inner_impl().trait_.is_some())
3793 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3794 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3796 clean::TypedefItem(ref t, true) => Some(&t.type_),
3800 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3801 c.primitive_locations.get(&prim).cloned()
3802 })).and_then(|did| c.impls.get(&did));
3803 if let Some(impls) = inner_impl {
3804 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3805 out.push_str(&format!("Methods from {}<Target={}>",
3807 "{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print()
3809 Escape(&format!("{:#}", target.print()))));
3810 out.push_str("</a>");
3811 let mut ret = impls.iter()
3812 .filter(|i| i.inner_impl().trait_.is_none())
3813 .flat_map(|i| get_methods(i.inner_impl(),
3817 .collect::<Vec<_>>();
3818 // We want links' order to be reproducible so we don't use unstable sort.
3820 if !ret.is_empty() {
3821 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
3827 let format_impls = |impls: Vec<&Impl>| {
3828 let mut links = FxHashSet::default();
3830 let mut ret = impls.iter()
3832 let is_negative_impl = is_negative_impl(i.inner_impl());
3833 if let Some(ref i) = i.inner_impl().trait_ {
3834 let i_display = format!("{:#}", i.print());
3835 let out = Escape(&i_display);
3836 let encoded = small_url_encode(&format!("{:#}", i.print()));
3837 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3839 if is_negative_impl { "!" } else { "" },
3841 if links.insert(generated.clone()) {
3850 .collect::<Vec<String>>();
3855 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
3857 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
3858 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
3860 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
3862 let concrete_format = format_impls(concrete);
3863 let synthetic_format = format_impls(synthetic);
3864 let blanket_format = format_impls(blanket_impl);
3866 if !concrete_format.is_empty() {
3867 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3868 Trait Implementations</a>");
3869 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
3872 if !synthetic_format.is_empty() {
3873 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
3874 Auto Trait Implementations</a>");
3875 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
3878 if !blanket_format.is_empty() {
3879 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
3880 Blanket Implementations</a>");
3881 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
3889 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
3890 let mut sidebar = String::new();
3891 let fields = get_struct_fields_name(&s.fields);
3893 if !fields.is_empty() {
3894 if let doctree::Plain = s.struct_type {
3895 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3896 <div class=\"sidebar-links\">{}</div>", fields));
3900 sidebar.push_str(&sidebar_assoc_items(it));
3902 if !sidebar.is_empty() {
3903 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
3907 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
3908 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
3911 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3913 clean::ItemEnum::ImplItem(ref i) => {
3914 if let Some(ref trait_) = i.trait_ {
3916 format!("{:#}", i.for_.print()),
3917 get_id_for_impl_on_foreign_type(&i.for_, trait_),
3927 fn is_negative_impl(i: &clean::Impl) -> bool {
3928 i.polarity == Some(clean::ImplPolarity::Negative)
3931 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
3932 let mut sidebar = String::new();
3938 Some(ref name) if m.is_associated_type() => {
3939 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3945 .collect::<String>();
3946 let consts = t.items
3950 Some(ref name) if m.is_associated_const() => {
3951 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3957 .collect::<String>();
3958 let mut required = t.items
3962 Some(ref name) if m.is_ty_method() => {
3963 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3969 .collect::<Vec<String>>();
3970 let mut provided = t.items
3974 Some(ref name) if m.is_method() => {
3975 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
3980 .collect::<Vec<String>>();
3982 if !types.is_empty() {
3983 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3984 Associated Types</a><div class=\"sidebar-links\">{}</div>",
3987 if !consts.is_empty() {
3988 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3989 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3992 if !required.is_empty() {
3994 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3995 Required Methods</a><div class=\"sidebar-links\">{}</div>",
3996 required.join("")));
3998 if !provided.is_empty() {
4000 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4001 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4002 provided.join("")));
4007 if let Some(implementors) = c.implementors.get(&it.def_id) {
4008 let mut res = implementors.iter()
4009 .filter(|i| i.inner_impl().for_.def_id()
4010 .map_or(false, |d| !c.paths.contains_key(&d)))
4012 match extract_for_impl_name(&i.impl_item) {
4013 Some((ref name, ref id)) => {
4014 Some(format!("<a href=\"#{}\">{}</a>",
4021 .collect::<Vec<String>>();
4022 if !res.is_empty() {
4024 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4025 Implementations on Foreign Types</a><div \
4026 class=\"sidebar-links\">{}</div>",
4031 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4033 sidebar.push_str("<a class=\"sidebar-title\" \
4034 href=\"#synthetic-implementors\">Auto Implementors</a>");
4037 sidebar.push_str(&sidebar_assoc_items(it));
4039 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4042 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4043 let sidebar = sidebar_assoc_items(it);
4045 if !sidebar.is_empty() {
4046 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4050 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4051 let sidebar = sidebar_assoc_items(it);
4053 if !sidebar.is_empty() {
4054 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4058 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4060 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4065 .filter_map(|f| match f.name {
4066 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4067 {name}</a>", name=name)),
4073 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4074 let mut sidebar = String::new();
4075 let fields = get_struct_fields_name(&u.fields);
4077 if !fields.is_empty() {
4078 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4079 <div class=\"sidebar-links\">{}</div>", fields));
4082 sidebar.push_str(&sidebar_assoc_items(it));
4084 if !sidebar.is_empty() {
4085 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4089 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4090 let mut sidebar = String::new();
4092 let variants = e.variants.iter()
4093 .filter_map(|v| match v.name {
4094 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4095 </a>", name = name)),
4098 .collect::<String>();
4099 if !variants.is_empty() {
4100 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4101 <div class=\"sidebar-links\">{}</div>", variants));
4104 sidebar.push_str(&sidebar_assoc_items(it));
4106 if !sidebar.is_empty() {
4107 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4111 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4113 ItemType::ExternCrate |
4114 ItemType::Import => ("reexports", "Re-exports"),
4115 ItemType::Module => ("modules", "Modules"),
4116 ItemType::Struct => ("structs", "Structs"),
4117 ItemType::Union => ("unions", "Unions"),
4118 ItemType::Enum => ("enums", "Enums"),
4119 ItemType::Function => ("functions", "Functions"),
4120 ItemType::Typedef => ("types", "Type Definitions"),
4121 ItemType::Static => ("statics", "Statics"),
4122 ItemType::Constant => ("constants", "Constants"),
4123 ItemType::Trait => ("traits", "Traits"),
4124 ItemType::Impl => ("impls", "Implementations"),
4125 ItemType::TyMethod => ("tymethods", "Type Methods"),
4126 ItemType::Method => ("methods", "Methods"),
4127 ItemType::StructField => ("fields", "Struct Fields"),
4128 ItemType::Variant => ("variants", "Variants"),
4129 ItemType::Macro => ("macros", "Macros"),
4130 ItemType::Primitive => ("primitives", "Primitive Types"),
4131 ItemType::AssocType => ("associated-types", "Associated Types"),
4132 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4133 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4134 ItemType::Keyword => ("keywords", "Keywords"),
4135 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4136 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4137 ItemType::ProcDerive => ("derives", "Derive Macros"),
4138 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4142 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4143 let mut sidebar = String::new();
4145 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4146 it.type_() == ItemType::Import) {
4147 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4149 name = "Re-exports"));
4152 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4153 // to print its headings
4154 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4155 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4156 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4157 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4158 ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType,
4159 ItemType::Keyword] {
4160 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4161 let (short, name) = item_ty_to_strs(&myty);
4162 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4168 if !sidebar.is_empty() {
4169 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4173 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4174 let sidebar = sidebar_assoc_items(it);
4175 if !sidebar.is_empty() {
4176 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4180 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4181 wrap_into_docblock(w, |w| {
4182 w.write_str(&highlight::render_with_highlighting(&t.source,
4190 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4191 let name = it.name.as_ref().expect("proc-macros always have names");
4193 MacroKind::Bang => {
4194 write!(w, "<pre class='rust macro'>");
4195 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4196 write!(w, "</pre>");
4198 MacroKind::Attr => {
4199 write!(w, "<pre class='rust attr'>");
4200 write!(w, "#[{}]", name);
4201 write!(w, "</pre>");
4203 MacroKind::Derive => {
4204 write!(w, "<pre class='rust derive'>");
4205 write!(w, "#[derive({})]", name);
4206 if !m.helpers.is_empty() {
4207 writeln!(w, "\n{{");
4208 writeln!(w, " // Attributes available to this derive:");
4209 for attr in &m.helpers {
4210 writeln!(w, " #[{}]", attr);
4214 write!(w, "</pre>");
4220 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4221 document(w, cx, it);
4222 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4225 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4229 crate const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4231 fn make_item_keywords(it: &clean::Item) -> String {
4232 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4235 /// Returns a list of all paths used in the type.
4236 /// This is used to help deduplicate imported impls
4237 /// for reexported types. If any of the contained
4238 /// types are re-exported, we don't use the corresponding
4239 /// entry from the js file, as inlining will have already
4240 /// picked up the impl
4241 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4242 let mut out = Vec::new();
4243 let mut visited = FxHashSet::default();
4244 let mut work = VecDeque::new();
4245 let cache = cache();
4247 work.push_back(first_ty);
4249 while let Some(ty) = work.pop_front() {
4250 if !visited.insert(ty.clone()) {
4255 clean::Type::ResolvedPath { did, .. } => {
4256 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4257 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4261 out.push(path.join("::"));
4267 clean::Type::Tuple(tys) => {
4268 work.extend(tys.into_iter());
4270 clean::Type::Slice(ty) => {
4271 work.push_back(*ty);
4273 clean::Type::Array(ty, _) => {
4274 work.push_back(*ty);
4276 clean::Type::RawPointer(_, ty) => {
4277 work.push_back(*ty);
4279 clean::Type::BorrowedRef { type_, .. } => {
4280 work.push_back(*type_);
4282 clean::Type::QPath { self_type, trait_, .. } => {
4283 work.push_back(*self_type);
4284 work.push_back(*trait_);
4292 crate fn cache() -> Arc<Cache> {
4293 CACHE_KEY.with(|c| c.borrow().clone())