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::ext::base::MacroKind;
49 use syntax::source_map::FileName;
50 use syntax::feature_gate::UnstableFeatures;
51 use syntax::symbol::{Symbol, sym};
52 use rustc::hir::def_id::DefId;
53 use rustc::middle::privacy::AccessLevels;
54 use rustc::middle::stability;
56 use rustc::util::nodemap::{FxHashMap, FxHashSet};
57 use rustc_data_structures::flock;
59 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
60 use crate::config::RenderOptions;
61 use crate::docfs::{DocFS, ErrorStorage, PathError};
63 use crate::html::escape::Escape;
64 use crate::html::format::{Buffer, PrintWithSpace, print_abi_with_space};
65 use crate::html::format::{print_generic_bounds, WhereClause, href, print_default_space};
66 use crate::html::format::{Function};
67 use crate::html::format::fmt_impl_for_trait_page;
68 use crate::html::item_type::ItemType;
69 use crate::html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
70 use crate::html::{highlight, layout, static_files};
71 use crate::html::sources;
81 crate use cache::ExternalLocation::{self, *};
83 /// A pair of name and its optional document.
84 pub type NameDoc = (String, Option<String>);
86 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
87 crate::html::format::display_fn(move |f| {
88 if !v.ends_with("/") && !v.is_empty() {
102 impl error::Error for Error {
103 fn description(&self) -> &str {
104 self.error.description()
108 impl std::fmt::Display for Error {
109 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
110 let file = self.file.display().to_string();
112 write!(f, "{}", self.error)
114 write!(f, "\"{}\": {}", self.file.display(), self.error)
119 impl PathError for Error {
120 fn new<P: AsRef<Path>>(e: io::Error, path: P) -> Error {
122 file: path.as_ref().to_path_buf(),
128 macro_rules! try_none {
129 ($e:expr, $file:expr) => ({
133 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
139 macro_rules! try_err {
140 ($e:expr, $file:expr) => ({
143 Err(e) => return Err(Error::new(e, $file)),
148 /// Major driving force in all rustdoc rendering. This contains information
149 /// about where in the tree-like hierarchy rendering is occurring and controls
150 /// how the current page is being rendered.
152 /// It is intended that this context is a lightweight object which can be fairly
153 /// easily cloned because it is cloned per work-job (about once per item in the
157 /// Current hierarchy of components leading down to what's currently being
159 pub current: Vec<String>,
160 /// The current destination folder of where HTML artifacts should be placed.
161 /// This changes as the context descends into the module hierarchy.
163 /// A flag, which when `true`, will render pages which redirect to the
164 /// real location of an item. This is used to allow external links to
165 /// publicly reused items to redirect to the right location.
166 pub render_redirect_pages: bool,
167 /// The map used to ensure all generated 'id=' attributes are unique.
168 id_map: Rc<RefCell<IdMap>>,
169 pub shared: Arc<SharedContext>,
170 pub cache: Arc<Cache>,
173 crate struct SharedContext {
174 /// The path to the crate root source minus the file name.
175 /// Used for simplifying paths to the highlighted source code files.
176 pub src_root: PathBuf,
177 /// This describes the layout of each page, and is not modified after
178 /// creation of the context (contains info like the favicon and added html).
179 pub layout: layout::Layout,
180 /// This flag indicates whether `[src]` links should be generated or not. If
181 /// the source files are present in the html rendering, then this will be
183 pub include_sources: bool,
184 /// The local file sources we've emitted and their respective url-paths.
185 pub local_sources: FxHashMap<PathBuf, String>,
186 /// Whether the collapsed pass ran
188 /// The base-URL of the issue tracker for when an item has been tagged with
190 pub issue_tracker_base_url: Option<String>,
191 /// The directories that have already been created in this doc run. Used to reduce the number
192 /// of spurious `create_dir_all` calls.
193 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
194 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
195 /// should be ordered alphabetically or in order of appearance (in the source code).
196 pub sort_modules_alphabetically: bool,
197 /// Additional themes to be added to the generated docs.
198 pub themes: Vec<PathBuf>,
199 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
201 pub resource_suffix: String,
202 /// Optional path string to be used to load static files on output pages. If not set, uses
203 /// combinations of `../` to reach the documentation root.
204 pub static_root_path: Option<String>,
205 /// Option disabled by default to generate files used by RLS and some other tools.
206 pub generate_redirect_pages: bool,
207 /// The fs handle we are working with.
209 /// The default edition used to parse doctests.
210 pub edition: Edition,
211 pub codes: ErrorCodes,
212 playground: Option<markdown::Playground>,
216 fn path(&self, filename: &str) -> PathBuf {
217 // We use splitn vs Path::extension here because we might get a filename
218 // like `style.min.css` and we want to process that into
219 // `style-suffix.min.css`. Path::extension would just return `css`
220 // which would result in `style.min-suffix.css` which isn't what we
222 let mut iter = filename.splitn(2, '.');
223 let base = iter.next().unwrap();
224 let ext = iter.next().unwrap();
225 let filename = format!(
228 self.shared.resource_suffix,
231 self.dst.join(&filename)
236 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
237 let mut dirs = self.created_dirs.borrow_mut();
238 if !dirs.contains(dst) {
239 try_err!(self.fs.create_dir_all(dst), dst);
240 dirs.insert(dst.to_path_buf());
246 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
247 /// `collapsed_doc_value` of the given item.
248 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
250 item.collapsed_doc_value().map(|s| s.into())
252 item.doc_value().map(|s| s.into())
257 /// Metadata about implementations for a type or trait.
258 #[derive(Clone, Debug)]
260 pub impl_item: clean::Item,
264 fn inner_impl(&self) -> &clean::Impl {
265 match self.impl_item.inner {
266 clean::ImplItem(ref impl_) => impl_,
267 _ => panic!("non-impl item found in impl")
271 fn trait_did(&self) -> Option<DefId> {
272 self.inner_impl().trait_.def_id()
276 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
277 /// Later on moved into `CACHE_KEY`.
279 pub struct RenderInfo {
280 pub inlined: FxHashSet<DefId>,
281 pub external_paths: crate::core::ExternalPaths,
282 pub exact_paths: FxHashMap<DefId, Vec<String>>,
283 pub access_levels: AccessLevels<DefId>,
284 pub deref_trait_did: Option<DefId>,
285 pub deref_mut_trait_did: Option<DefId>,
286 pub owned_box_did: Option<DefId>,
289 // Helper structs for rendering items/sidebars and carrying along contextual
292 /// Struct representing one entry in the JS search index. These are all emitted
293 /// by hand to a large JS file at the end of cache-creation.
300 parent: Option<DefId>,
301 parent_idx: Option<usize>,
302 search_type: Option<IndexItemFunctionType>,
305 impl ToJson for IndexItem {
306 fn to_json(&self) -> Json {
307 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
309 let mut data = Vec::with_capacity(6);
310 data.push((self.ty as usize).to_json());
311 data.push(self.name.to_json());
312 data.push(self.path.to_json());
313 data.push(self.desc.to_json());
314 data.push(self.parent_idx.to_json());
315 data.push(self.search_type.to_json());
321 /// A type used for the search index.
324 name: Option<String>,
325 generics: Option<Vec<String>>,
328 impl ToJson for Type {
329 fn to_json(&self) -> Json {
332 let mut data = Vec::with_capacity(2);
333 data.push(name.to_json());
334 if let Some(ref generics) = self.generics {
335 data.push(generics.to_json());
344 /// Full type of functions/methods in the search index.
346 struct IndexItemFunctionType {
348 output: Option<Vec<Type>>,
351 impl ToJson for IndexItemFunctionType {
352 fn to_json(&self) -> Json {
353 // If we couldn't figure out a type, just write `null`.
354 let mut iter = self.inputs.iter();
355 if match self.output {
356 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()),
357 None => iter.any(|ref i| i.name.is_none()),
361 let mut data = Vec::with_capacity(2);
362 data.push(self.inputs.to_json());
363 if let Some(ref output) = self.output {
364 if output.len() > 1 {
365 data.push(output.to_json());
367 data.push(output[0].to_json());
375 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
376 thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
378 pub fn initial_ids() -> Vec<String> {
390 "synthetic-implementors",
392 "synthetic-implementors-list",
396 ].iter().map(|id| (String::from(*id))).collect()
399 /// Generates the documentation for `crate` into the directory `dst`
400 pub fn run(mut krate: clean::Crate,
401 options: RenderOptions,
402 renderinfo: RenderInfo,
403 diag: &errors::Handler,
404 edition: Edition) -> Result<(), Error> {
405 // need to save a copy of the options for rendering the index page
406 let md_opts = options.clone();
412 sort_modules_alphabetically,
415 extern_html_root_urls,
418 generate_search_filter,
419 generate_redirect_pages,
423 let src_root = match krate.src {
424 FileName::Real(ref p) => match p.parent() {
425 Some(p) => p.to_path_buf(),
426 None => PathBuf::new(),
430 let mut errors = Arc::new(ErrorStorage::new());
431 // If user passed in `--playground-url` arg, we fill in crate name here
432 let mut playground = None;
433 if let Some(url) = playground_url {
434 playground = Some(markdown::Playground {
435 crate_name: Some(krate.name.clone()),
439 let mut layout = layout::Layout {
441 favicon: String::new(),
443 krate: krate.name.clone(),
444 css_file_extension: extension_css,
445 generate_search_filter,
447 let mut issue_tracker_base_url = None;
448 let mut include_sources = true;
450 // Crawl the crate attributes looking for attributes which control how we're
451 // going to emit HTML
452 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
453 for attr in attrs.lists(sym::doc) {
454 match (attr.name_or_empty(), attr.value_str()) {
455 (sym::html_favicon_url, Some(s)) => {
456 layout.favicon = s.to_string();
458 (sym::html_logo_url, Some(s)) => {
459 layout.logo = s.to_string();
461 (sym::html_playground_url, Some(s)) => {
462 playground = Some(markdown::Playground {
463 crate_name: Some(krate.name.clone()),
467 (sym::issue_tracker_base_url, Some(s)) => {
468 issue_tracker_base_url = Some(s.to_string());
470 (sym::html_no_source, None) if attr.is_word() => {
471 include_sources = false;
477 let mut scx = SharedContext {
478 collapsed: krate.collapsed,
481 local_sources: Default::default(),
482 issue_tracker_base_url,
484 created_dirs: Default::default(),
485 sort_modules_alphabetically,
489 generate_redirect_pages,
490 fs: DocFS::new(&errors),
492 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
497 scx.ensure_dir(&dst)?;
498 krate = sources::render(&dst, &mut scx, krate)?;
499 let (new_crate, index, cache) = Cache::from_krate(
501 &extern_html_root_urls,
506 let cache = Arc::new(cache);
507 let mut cx = Context {
510 render_redirect_pages: false,
511 id_map: Rc::new(RefCell::new(id_map)),
512 shared: Arc::new(scx),
513 cache: cache.clone(),
516 // Freeze the cache now that the index has been built. Put an Arc into TLS
517 // for future parallelization opportunities
518 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
519 CURRENT_DEPTH.with(|s| s.set(0));
521 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
522 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
523 write_shared(&cx, &krate, index, &md_opts, diag)?;
524 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
526 // And finally render the whole crate's documentation
527 let ret = cx.krate(krate);
528 let nb_errors = Arc::get_mut(&mut errors).map_or_else(|| 0, |errors| errors.write_errors(diag));
531 } else if nb_errors > 0 {
532 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
540 krate: &clean::Crate,
541 search_index: String,
542 options: &RenderOptions,
543 diag: &errors::Handler,
544 ) -> Result<(), Error> {
545 // Write out the shared files. Note that these are shared among all rustdoc
546 // docs placed in the output directory, so this needs to be a synchronized
547 // operation with respect to all other rustdocs running around.
548 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
550 // Add all the static files. These may already exist, but we just
551 // overwrite them anyway to make sure that they're fresh and up-to-date.
553 write_minify(&cx.shared.fs, cx.path("rustdoc.css"),
554 static_files::RUSTDOC_CSS,
555 options.enable_minification)?;
556 write_minify(&cx.shared.fs, cx.path("settings.css"),
557 static_files::SETTINGS_CSS,
558 options.enable_minification)?;
559 write_minify(&cx.shared.fs, cx.path("noscript.css"),
560 static_files::NOSCRIPT_CSS,
561 options.enable_minification)?;
563 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
564 // then we'll run over the "official" styles.
565 let mut themes: FxHashSet<String> = FxHashSet::default();
567 for entry in &cx.shared.themes {
568 let content = try_err!(fs::read(&entry), &entry);
569 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
570 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
571 cx.shared.fs.write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
572 themes.insert(theme.to_owned());
575 let write = |p, c| { cx.shared.fs.write(p, c) };
576 if (*cx.shared).layout.logo.is_empty() {
577 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
579 if (*cx.shared).layout.favicon.is_empty() {
580 write(cx.path("favicon.ico"), static_files::RUST_FAVICON)?;
582 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
583 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
584 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
585 write_minify(&cx.shared.fs,
586 cx.path("light.css"), static_files::themes::LIGHT, options.enable_minification)?;
587 themes.insert("light".to_owned());
588 write_minify(&cx.shared.fs,
589 cx.path("dark.css"), static_files::themes::DARK, options.enable_minification)?;
590 themes.insert("dark".to_owned());
592 let mut themes: Vec<&String> = themes.iter().collect();
594 // To avoid theme switch latencies as much as possible, we put everything theme related
595 // at the beginning of the html files into another js file.
596 let theme_js = format!(
597 r#"var themes = document.getElementById("theme-choices");
598 var themePicker = document.getElementById("theme-picker");
600 function showThemeButtonState() {{
601 themes.style.display = "block";
602 themePicker.style.borderBottomRightRadius = "0";
603 themePicker.style.borderBottomLeftRadius = "0";
606 function hideThemeButtonState() {{
607 themes.style.display = "none";
608 themePicker.style.borderBottomRightRadius = "3px";
609 themePicker.style.borderBottomLeftRadius = "3px";
612 function switchThemeButtonState() {{
613 if (themes.style.display === "block") {{
614 hideThemeButtonState();
616 showThemeButtonState();
620 function handleThemeButtonsBlur(e) {{
621 var active = document.activeElement;
622 var related = e.relatedTarget;
624 if (active.id !== "themePicker" &&
625 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
627 (related.id !== "themePicker" &&
628 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
629 hideThemeButtonState();
633 themePicker.onclick = switchThemeButtonState;
634 themePicker.onblur = handleThemeButtonsBlur;
635 [{}].forEach(function(item) {{
636 var but = document.createElement('button');
637 but.innerHTML = item;
638 but.onclick = function(el) {{
639 switchTheme(currentTheme, mainTheme, item, true);
641 but.onblur = handleThemeButtonsBlur;
642 themes.appendChild(but);
645 .map(|s| format!("\"{}\"", s))
646 .collect::<Vec<String>>()
648 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
652 write_minify(&cx.shared.fs, cx.path("main.js"),
653 static_files::MAIN_JS,
654 options.enable_minification)?;
655 write_minify(&cx.shared.fs, cx.path("settings.js"),
656 static_files::SETTINGS_JS,
657 options.enable_minification)?;
658 if cx.shared.include_sources {
661 cx.path("source-script.js"),
662 static_files::sidebar::SOURCE_SCRIPT,
663 options.enable_minification)?;
669 cx.path("storage.js"),
670 &format!("var resourcesSuffix = \"{}\";{}",
671 cx.shared.resource_suffix,
672 static_files::STORAGE_JS),
673 options.enable_minification)?;
676 if let Some(ref css) = cx.shared.layout.css_file_extension {
677 let out = cx.path("theme.css");
678 let buffer = try_err!(fs::read_to_string(css), css);
679 if !options.enable_minification {
680 cx.shared.fs.write(&out, &buffer)?;
682 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
685 write_minify(&cx.shared.fs, cx.path("normalize.css"),
686 static_files::NORMALIZE_CSS,
687 options.enable_minification)?;
688 write(cx.dst.join("FiraSans-Regular.woff"),
689 static_files::fira_sans::REGULAR)?;
690 write(cx.dst.join("FiraSans-Medium.woff"),
691 static_files::fira_sans::MEDIUM)?;
692 write(cx.dst.join("FiraSans-LICENSE.txt"),
693 static_files::fira_sans::LICENSE)?;
694 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
695 static_files::source_serif_pro::REGULAR)?;
696 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
697 static_files::source_serif_pro::BOLD)?;
698 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
699 static_files::source_serif_pro::ITALIC)?;
700 write(cx.dst.join("SourceSerifPro-LICENSE.md"),
701 static_files::source_serif_pro::LICENSE)?;
702 write(cx.dst.join("SourceCodePro-Regular.woff"),
703 static_files::source_code_pro::REGULAR)?;
704 write(cx.dst.join("SourceCodePro-Semibold.woff"),
705 static_files::source_code_pro::SEMIBOLD)?;
706 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
707 static_files::source_code_pro::LICENSE)?;
708 write(cx.dst.join("LICENSE-MIT.txt"),
709 static_files::LICENSE_MIT)?;
710 write(cx.dst.join("LICENSE-APACHE.txt"),
711 static_files::LICENSE_APACHE)?;
712 write(cx.dst.join("COPYRIGHT.txt"),
713 static_files::COPYRIGHT)?;
719 for_search_index: bool,
720 ) -> io::Result<(Vec<String>, Vec<String>, Vec<String>)> {
721 let mut ret = Vec::new();
722 let mut krates = Vec::new();
723 let mut variables = Vec::new();
726 for line in BufReader::new(File::open(path)?).lines() {
728 if for_search_index && line.starts_with("var R") {
729 variables.push(line.clone());
732 if !line.starts_with(key) {
735 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
738 ret.push(line.to_string());
739 krates.push(line[key.len() + 2..].split('"')
741 .map(|s| s.to_owned())
742 .unwrap_or_else(|| String::new()));
745 Ok((ret, krates, variables))
748 fn show_item(item: &IndexItem, krate: &str) -> String {
749 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
750 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
751 if let Some(p) = item.parent_idx {
752 format!(",'parent':{}", p)
758 let dst = cx.dst.join(&format!("aliases{}.js", cx.shared.resource_suffix));
760 let (mut all_aliases, _, _) = try_err!(collect(&dst, &krate.name, "ALIASES", false), &dst);
761 let mut output = String::with_capacity(100);
762 for (alias, items) in &cx.cache.aliases {
763 if items.is_empty() {
766 output.push_str(&format!("\"{}\":[{}],",
769 .map(|v| show_item(v, &krate.name))
773 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
775 let mut v = Buffer::html();
776 writeln!(&mut v, "var ALIASES = {{}};");
777 for aliases in &all_aliases {
778 writeln!(&mut v, "{}", aliases);
780 cx.shared.fs.write(&dst, v.into_inner().into_bytes())?;
783 use std::ffi::OsString;
788 children: FxHashMap<OsString, Hierarchy>,
789 elems: FxHashSet<OsString>,
793 fn new(elem: OsString) -> Hierarchy {
796 children: FxHashMap::default(),
797 elems: FxHashSet::default(),
801 fn to_json_string(&self) -> String {
802 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
803 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
804 let mut files = self.elems.iter()
805 .map(|s| format!("\"{}\"",
807 .expect("invalid osstring conversion")))
808 .collect::<Vec<_>>();
809 files.sort_unstable_by(|a, b| a.cmp(b));
810 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
811 let dirs = if subs.is_empty() {
814 format!(",\"dirs\":[{}]", subs)
816 let files = files.join(",");
817 let files = if files.is_empty() {
820 format!(",\"files\":[{}]", files)
822 format!("{{\"name\":\"{name}\"{dirs}{files}}}",
823 name=self.elem.to_str().expect("invalid osstring conversion"),
829 if cx.shared.include_sources {
830 let mut hierarchy = Hierarchy::new(OsString::new());
831 for source in cx.shared.local_sources.iter()
832 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
834 let mut h = &mut hierarchy;
835 let mut elems = source.components()
838 Component::Normal(s) => Some(s.to_owned()),
844 let cur_elem = elems.next().expect("empty file path");
845 if elems.peek().is_none() {
846 h.elems.insert(cur_elem);
849 let e = cur_elem.clone();
850 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
851 h = h.children.get_mut(&cur_elem).expect("not found child");
856 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
857 let (mut all_sources, _krates, _) = try_err!(collect(&dst, &krate.name, "sourcesIndex",
860 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
862 hierarchy.to_json_string()));
864 let v = format!("var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
865 all_sources.join("\n"));
866 cx.shared.fs.write(&dst, v.as_bytes())?;
869 // Update the search index
870 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
871 let (mut all_indexes, mut krates, variables) = try_err!(collect(&dst,
875 all_indexes.push(search_index);
877 // Sort the indexes by crate so the file will be generated identically even
878 // with rustdoc running in parallel.
881 let mut v = String::from("var N=null,E=\"\",T=\"t\",U=\"u\",searchIndex={};\n");
882 v.push_str(&minify_replacer(
883 &format!("{}\n{}", variables.join(""), all_indexes.join("\n")),
884 options.enable_minification));
885 v.push_str("initSearch(searchIndex);addSearchOptions(searchIndex);");
886 cx.shared.fs.write(&dst, &v)?;
888 if options.enable_index_page {
889 if let Some(index_page) = options.index_page.clone() {
890 let mut md_opts = options.clone();
891 md_opts.output = cx.dst.clone();
892 md_opts.external_html = (*cx.shared).layout.external_html.clone();
894 crate::markdown::render(index_page, md_opts, diag, cx.shared.edition);
896 let dst = cx.dst.join("index.html");
897 let page = layout::Page {
898 title: "Index of crates",
901 static_root_path: cx.shared.static_root_path.as_deref(),
902 description: "List of crates",
903 keywords: BASIC_KEYWORDS,
904 resource_suffix: &cx.shared.resource_suffix,
906 static_extra_scripts: &[],
908 krates.push(krate.name.clone());
912 let content = format!(
914 <span class='in-band'>List of all crates</span>\
915 </h1><ul class='mod'>{}</ul>",
919 format!("<li><a href=\"{}index.html\">{}</li>",
920 ensure_trailing_slash(s), s)
922 .collect::<String>());
923 let v = layout::render(&cx.shared.layout,
926 cx.shared.fs.write(&dst, v.as_bytes())?;
930 // Update the list of all implementors for traits
931 let dst = cx.dst.join("implementors");
932 for (&did, imps) in &cx.cache.implementors {
933 // Private modules can leak through to this phase of rustdoc, which
934 // could contain implementations for otherwise private types. In some
935 // rare cases we could find an implementation for an item which wasn't
936 // indexed, so we just skip this step in that case.
938 // FIXME: this is a vague explanation for why this can't be a `get`, in
939 // theory it should be...
940 let &(ref remote_path, remote_item_type) = match cx.cache.paths.get(&did) {
942 None => match cx.cache.external_paths.get(&did) {
948 let mut have_impls = false;
949 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
951 // If the trait and implementation are in the same crate, then
952 // there's no need to emit information about it (there's inlining
953 // going on). If they're in different crates then the crate defining
954 // the trait will be interested in our implementation.
955 if imp.impl_item.def_id.krate == did.krate { continue }
956 // If the implementation is from another crate then that crate
958 if !imp.impl_item.def_id.is_local() { continue }
960 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
961 as_json(&imp.inner_impl().print().to_string()),
962 imp.inner_impl().synthetic,
963 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
965 implementors.push_str("];");
967 // Only create a js file if we have impls to add to it. If the trait is
968 // documented locally though we always create the file to avoid dead
970 if !have_impls && !cx.cache.paths.contains_key(&did) {
974 let mut mydst = dst.clone();
975 for part in &remote_path[..remote_path.len() - 1] {
978 cx.shared.ensure_dir(&mydst)?;
979 mydst.push(&format!("{}.{}.js",
981 remote_path[remote_path.len() - 1]));
983 let (mut all_implementors, _, _) = try_err!(collect(&mydst, &krate.name, "implementors",
986 all_implementors.push(implementors);
987 // Sort the implementors by crate so the file will be generated
988 // identically even with rustdoc running in parallel.
989 all_implementors.sort();
991 let mut v = String::from("(function() {var implementors = {};\n");
992 for implementor in &all_implementors {
993 writeln!(v, "{}", *implementor).unwrap();
996 if (window.register_implementors) {
997 window.register_implementors(implementors);
999 window.pending_implementors = implementors;
1003 cx.shared.fs.write(&mydst, &v)?;
1008 fn write_minify(fs:&DocFS, dst: PathBuf, contents: &str, enable_minification: bool
1009 ) -> Result<(), Error> {
1010 if enable_minification {
1011 if dst.extension() == Some(&OsStr::new("css")) {
1012 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1013 fs.write(dst, res.as_bytes())
1015 fs.write(dst, minifier::js::minify(contents).as_bytes())
1018 fs.write(dst, contents.as_bytes())
1024 enable_minification: bool,
1026 use minifier::js::{simple_minify, Keyword, ReservedChar, Token, Tokens};
1028 if enable_minification {
1029 let tokens: Tokens<'_> = simple_minify(contents)
1031 .filter(|(f, next)| {
1032 // We keep backlines.
1033 minifier::js::clean_token_except(f, next, &|c: &Token<'_>| {
1034 c.get_char() != Some(ReservedChar::Backline)
1038 minifier::js::replace_token_with(f, &|t: &Token<'_>| {
1040 Token::Keyword(Keyword::Null) => Some(Token::Other("N")),
1041 Token::String(s) => {
1042 let s = &s[1..s.len() -1]; // The quotes are included
1044 Some(Token::Other("E"))
1045 } else if s == "t" {
1046 Some(Token::Other("T"))
1047 } else if s == "u" {
1048 Some(Token::Other("U"))
1057 .collect::<Vec<_>>()
1059 let o = tokens.apply(|f| {
1060 // We add a backline after the newly created variables.
1061 minifier::js::aggregate_strings_into_array_with_separation_filter(
1064 Token::Char(ReservedChar::Backline),
1065 // This closure prevents crates' names from being aggregated.
1067 // The point here is to check if the string is preceded by '[' and
1068 // "searchIndex". If so, it means this is a crate name and that it
1069 // shouldn't be aggregated.
1072 !tokens[pos - 1].eq_char(ReservedChar::OpenBracket) ||
1073 tokens[pos - 2].get_other() != Some("searchIndex")
1080 format!("{}\n", contents)
1084 #[derive(Debug, Eq, PartialEq, Hash)]
1091 fn new(mut url: String, name: String) -> ItemEntry {
1092 while url.starts_with('/') {
1103 crate fn print(&self) -> impl fmt::Display + '_ {
1104 crate::html::format::display_fn(move |f| {
1105 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1110 impl PartialOrd for ItemEntry {
1111 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1112 Some(self.cmp(other))
1116 impl Ord for ItemEntry {
1117 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1118 self.name.cmp(&other.name)
1124 structs: FxHashSet<ItemEntry>,
1125 enums: FxHashSet<ItemEntry>,
1126 unions: FxHashSet<ItemEntry>,
1127 primitives: FxHashSet<ItemEntry>,
1128 traits: FxHashSet<ItemEntry>,
1129 macros: FxHashSet<ItemEntry>,
1130 functions: FxHashSet<ItemEntry>,
1131 typedefs: FxHashSet<ItemEntry>,
1132 opaque_tys: FxHashSet<ItemEntry>,
1133 statics: FxHashSet<ItemEntry>,
1134 constants: FxHashSet<ItemEntry>,
1135 keywords: FxHashSet<ItemEntry>,
1136 attributes: FxHashSet<ItemEntry>,
1137 derives: FxHashSet<ItemEntry>,
1138 trait_aliases: FxHashSet<ItemEntry>,
1142 fn new() -> AllTypes {
1143 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1145 structs: new_set(100),
1146 enums: new_set(100),
1147 unions: new_set(100),
1148 primitives: new_set(26),
1149 traits: new_set(100),
1150 macros: new_set(100),
1151 functions: new_set(100),
1152 typedefs: new_set(100),
1153 opaque_tys: new_set(100),
1154 statics: new_set(100),
1155 constants: new_set(100),
1156 keywords: new_set(100),
1157 attributes: new_set(100),
1158 derives: new_set(100),
1159 trait_aliases: new_set(100),
1163 fn append(&mut self, item_name: String, item_type: &ItemType) {
1164 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1165 if let Some(name) = url.pop() {
1166 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1168 let name = url.join("::");
1170 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1171 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1172 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1173 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1174 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1175 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1176 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1177 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1178 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1179 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1180 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1181 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1182 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1183 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1190 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1192 let mut e: Vec<&ItemEntry> = e.iter().collect();
1194 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1198 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>());
1203 fn print(self, f: &mut Buffer) {
1206 <span class='out-of-band'>\
1207 <span id='render-detail'>\
1208 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1209 [<span class='inner'>−</span>]\
1213 <span class='in-band'>List of all items</span>\
1215 print_entries(f, &self.structs, "Structs", "structs");
1216 print_entries(f, &self.enums, "Enums", "enums");
1217 print_entries(f, &self.unions, "Unions", "unions");
1218 print_entries(f, &self.primitives, "Primitives", "primitives");
1219 print_entries(f, &self.traits, "Traits", "traits");
1220 print_entries(f, &self.macros, "Macros", "macros");
1221 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1222 print_entries(f, &self.derives, "Derive Macros", "derives");
1223 print_entries(f, &self.functions, "Functions", "functions");
1224 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1225 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1226 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1227 print_entries(f, &self.statics, "Statics", "statics");
1228 print_entries(f, &self.constants, "Constants", "constants")
1232 fn settings(root_path: &str, suffix: &str) -> String {
1233 // (id, explanation, default value)
1235 ("item-declarations", "Auto-hide item declarations.", true),
1236 ("item-attributes", "Auto-hide item attributes.", true),
1237 ("trait-implementations", "Auto-hide trait implementations documentation",
1239 ("method-docs", "Auto-hide item methods' documentation", false),
1240 ("go-to-only-result", "Directly go to item in search if there is only one result",
1242 ("line-numbers", "Show line numbers on code examples", false),
1246 <span class='in-band'>Rustdoc settings</span>\
1248 <div class='settings'>{}</div>\
1249 <script src='{}settings{}.js'></script>",
1251 .map(|(id, text, enabled)| {
1252 format!("<div class='setting-line'>\
1253 <label class='toggle'>\
1254 <input type='checkbox' id='{}' {}>\
1255 <span class='slider'></span>\
1258 </div>", id, if *enabled { " checked" } else { "" }, text)
1260 .collect::<String>(),
1266 fn derive_id(&self, id: String) -> String {
1267 let mut map = self.id_map.borrow_mut();
1271 /// String representation of how to get back to the root path of the 'doc/'
1272 /// folder in terms of a relative URL.
1273 fn root_path(&self) -> String {
1274 "../".repeat(self.current.len())
1277 /// Main method for rendering a crate.
1279 /// This currently isn't parallelized, but it'd be pretty easy to add
1280 /// parallelization to this function.
1281 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1282 let mut item = match krate.module.take() {
1284 None => return Ok(()),
1286 let final_file = self.dst.join(&krate.name)
1288 let settings_file = self.dst.join("settings.html");
1290 let crate_name = krate.name.clone();
1291 item.name = Some(krate.name);
1293 let mut all = AllTypes::new();
1296 // Render the crate documentation
1297 let mut work = vec![(self.clone(), item)];
1299 while let Some((mut cx, item)) = work.pop() {
1300 cx.item(item, &mut all, |cx, item| {
1301 work.push((cx.clone(), item))
1306 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1307 if !root_path.ends_with('/') {
1308 root_path.push('/');
1310 let mut page = layout::Page {
1311 title: "List of all items in this crate",
1314 static_root_path: self.shared.static_root_path.as_deref(),
1315 description: "List of all items in this crate",
1316 keywords: BASIC_KEYWORDS,
1317 resource_suffix: &self.shared.resource_suffix,
1319 static_extra_scripts: &[],
1321 let sidebar = if let Some(ref version) = self.cache.crate_version {
1322 format!("<p class='location'>Crate {}</p>\
1323 <div class='block version'>\
1326 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1327 crate_name, version)
1331 let v = layout::render(&self.shared.layout,
1332 &page, sidebar, |buf: &mut Buffer| all.print(buf),
1333 &self.shared.themes);
1334 self.shared.fs.write(&final_file, v.as_bytes())?;
1336 // Generating settings page.
1337 page.title = "Rustdoc settings";
1338 page.description = "Settings of Rustdoc";
1339 page.root_path = "./";
1341 let mut themes = self.shared.themes.clone();
1342 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1343 themes.push(PathBuf::from("settings.css"));
1344 let v = layout::render(
1345 &self.shared.layout,
1346 &page, sidebar, settings(
1347 self.shared.static_root_path.as_deref().unwrap_or("./"),
1348 &self.shared.resource_suffix
1351 self.shared.fs.write(&settings_file, v.as_bytes())?;
1356 fn render_item(&self,
1358 pushname: bool) -> String {
1359 // A little unfortunate that this is done like this, but it sure
1360 // does make formatting *a lot* nicer.
1361 CURRENT_DEPTH.with(|slot| {
1362 slot.set(self.current.len());
1365 let mut title = if it.is_primitive() || it.is_keyword() {
1366 // No need to include the namespace for primitive types and keywords
1369 self.current.join("::")
1372 if !title.is_empty() {
1373 title.push_str("::");
1375 title.push_str(it.name.as_ref().unwrap());
1377 title.push_str(" - Rust");
1378 let tyname = it.type_();
1379 let desc = if it.is_crate() {
1380 format!("API documentation for the Rust `{}` crate.",
1381 self.shared.layout.krate)
1383 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1384 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1386 let keywords = make_item_keywords(it);
1387 let page = layout::Page {
1388 css_class: tyname.as_str(),
1389 root_path: &self.root_path(),
1390 static_root_path: self.shared.static_root_path.as_deref(),
1393 keywords: &keywords,
1394 resource_suffix: &self.shared.resource_suffix,
1396 static_extra_scripts: &[],
1400 self.id_map.borrow_mut().reset();
1401 self.id_map.borrow_mut().populate(initial_ids());
1404 if !self.render_redirect_pages {
1405 layout::render(&self.shared.layout, &page,
1406 |buf: &mut _| print_sidebar(self, it, buf),
1407 |buf: &mut _| print_item(self, it, buf),
1408 &self.shared.themes)
1410 let mut url = self.root_path();
1411 if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) {
1412 for name in &names[..names.len() - 1] {
1416 url.push_str(&item_path(ty, names.last().unwrap()));
1417 layout::redirect(&url)
1424 /// Non-parallelized version of rendering an item. This will take the input
1425 /// item, render its contents, and then invoke the specified closure with
1426 /// all sub-items which need to be rendered.
1428 /// The rendering driver uses this closure to queue up more work.
1429 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
1430 where F: FnMut(&mut Context, clean::Item),
1432 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
1433 // if they contain impls for public types. These modules can also
1434 // contain items such as publicly re-exported structures.
1436 // External crates will provide links to these structures, so
1437 // these modules are recursed into, but not rendered normally
1438 // (a flag on the context).
1439 if !self.render_redirect_pages {
1440 self.render_redirect_pages = item.is_stripped();
1444 // modules are special because they add a namespace. We also need to
1445 // recurse into the items of the module as well.
1446 let name = item.name.as_ref().unwrap().to_string();
1447 let scx = &self.shared;
1448 if name.is_empty() {
1449 panic!("Unexpected empty destination: {:?}", self.current);
1451 let prev = self.dst.clone();
1452 self.dst.push(&name);
1453 self.current.push(name);
1455 info!("Recursing into {}", self.dst.display());
1457 let buf = self.render_item(&item, false);
1458 // buf will be empty if the module is stripped and there is no redirect for it
1459 if !buf.is_empty() {
1460 self.shared.ensure_dir(&self.dst)?;
1461 let joint_dst = self.dst.join("index.html");
1462 scx.fs.write(&joint_dst, buf.as_bytes())?;
1465 let m = match item.inner {
1466 clean::StrippedItem(box clean::ModuleItem(m)) |
1467 clean::ModuleItem(m) => m,
1471 // Render sidebar-items.js used throughout this module.
1472 if !self.render_redirect_pages {
1473 let items = self.build_sidebar_items(&m);
1474 let js_dst = self.dst.join("sidebar-items.js");
1475 let v = format!("initSidebarItems({});", as_json(&items));
1476 scx.fs.write(&js_dst, &v)?;
1479 for item in m.items {
1483 info!("Recursed; leaving {}", self.dst.display());
1485 // Go back to where we were at
1487 self.current.pop().unwrap();
1488 } else if item.name.is_some() {
1489 let buf = self.render_item(&item, true);
1490 // buf will be empty if the item is stripped and there is no redirect for it
1491 if !buf.is_empty() {
1492 let name = item.name.as_ref().unwrap();
1493 let item_type = item.type_();
1494 let file_name = &item_path(item_type, name);
1495 self.shared.ensure_dir(&self.dst)?;
1496 let joint_dst = self.dst.join(file_name);
1497 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
1499 if !self.render_redirect_pages {
1500 all.append(full_path(self, &item), &item_type);
1502 if self.shared.generate_redirect_pages {
1503 // Redirect from a sane URL using the namespace to Rustdoc's
1504 // URL for the page.
1505 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1506 let redir_dst = self.dst.join(redir_name);
1507 let v = layout::redirect(file_name);
1508 self.shared.fs.write(&redir_dst, v.as_bytes())?;
1510 // If the item is a macro, redirect from the old macro URL (with !)
1511 // to the new one (without).
1512 if item_type == ItemType::Macro {
1513 let redir_name = format!("{}.{}!.html", item_type, name);
1514 let redir_dst = self.dst.join(redir_name);
1515 let v = layout::redirect(file_name);
1516 self.shared.fs.write(&redir_dst, v.as_bytes())?;
1523 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1524 // BTreeMap instead of HashMap to get a sorted output
1525 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1526 for item in &m.items {
1527 if item.is_stripped() { continue }
1529 let short = item.type_();
1530 let myname = match item.name {
1532 Some(ref s) => s.to_string(),
1534 let short = short.to_string();
1535 map.entry(short).or_default()
1536 .push((myname, Some(plain_summary_line(item.doc_value()))));
1539 if self.shared.sort_modules_alphabetically {
1540 for (_, items) in &mut map {
1549 /// Generates a url appropriate for an `href` attribute back to the source of
1552 /// The url generated, when clicked, will redirect the browser back to the
1553 /// original source code.
1555 /// If `None` is returned, then a source link couldn't be generated. This
1556 /// may happen, for example, with externally inlined items where the source
1557 /// of their crate documentation isn't known.
1558 fn src_href(&self, item: &clean::Item) -> Option<String> {
1559 let mut root = self.root_path();
1561 let mut path = String::new();
1563 // We can safely ignore macros from other libraries
1564 let file = match item.source.filename {
1565 FileName::Real(ref path) => path,
1569 let (krate, path) = if item.def_id.is_local() {
1570 if let Some(path) = self.shared.local_sources.get(file) {
1571 (&self.shared.layout.krate, path)
1576 let (krate, src_root) = match *self.cache.extern_locations.get(&item.def_id.krate)? {
1577 (ref name, ref src, Local) => (name, src),
1578 (ref name, ref src, Remote(ref s)) => {
1579 root = s.to_string();
1582 (_, _, Unknown) => return None,
1585 sources::clean_path(&src_root, file, false, |component| {
1586 path.push_str(&component.to_string_lossy());
1589 let mut fname = file.file_name().expect("source has no filename")
1591 fname.push(".html");
1592 path.push_str(&fname.to_string_lossy());
1596 let lines = if item.source.loline == item.source.hiline {
1597 item.source.loline.to_string()
1599 format!("{}-{}", item.source.loline, item.source.hiline)
1601 Some(format!("{root}src/{krate}/{path}#{lines}",
1602 root = Escape(&root),
1609 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1610 where F: FnOnce(&mut Buffer)
1612 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1617 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer) {
1618 debug_assert!(!item.is_stripped());
1619 // Write the breadcrumb trail header for the top
1620 write!(buf, "<h1 class='fqn'><span class='out-of-band'>");
1621 if let Some(version) = item.stable_since() {
1622 write!(buf, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1626 "<span id='render-detail'>\
1627 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1628 title=\"collapse all docs\">\
1629 [<span class='inner'>−</span>]\
1635 // When this item is part of a `pub use` in a downstream crate, the
1636 // [src] link in the downstream documentation will actually come back to
1637 // this page, and this link will be auto-clicked. The `id` attribute is
1638 // used to find the link to auto-click.
1639 if cx.shared.include_sources && !item.is_primitive() {
1640 if let Some(l) = cx.src_href(item) {
1641 write!(buf, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1642 l, "goto source code");
1646 write!(buf, "</span>"); // out-of-band
1647 write!(buf, "<span class='in-band'>");
1648 let name = match item.inner {
1649 clean::ModuleItem(ref m) => if m.is_crate {
1654 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1655 clean::TraitItem(..) => "Trait ",
1656 clean::StructItem(..) => "Struct ",
1657 clean::UnionItem(..) => "Union ",
1658 clean::EnumItem(..) => "Enum ",
1659 clean::TypedefItem(..) => "Type Definition ",
1660 clean::MacroItem(..) => "Macro ",
1661 clean::ProcMacroItem(ref mac) => match mac.kind {
1662 MacroKind::Bang => "Macro ",
1663 MacroKind::Attr => "Attribute Macro ",
1664 MacroKind::Derive => "Derive Macro ",
1666 clean::PrimitiveItem(..) => "Primitive Type ",
1667 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1668 clean::ConstantItem(..) => "Constant ",
1669 clean::ForeignTypeItem => "Foreign Type ",
1670 clean::KeywordItem(..) => "Keyword ",
1671 clean::OpaqueTyItem(..) => "Opaque Type ",
1672 clean::TraitAliasItem(..) => "Trait Alias ",
1674 // We don't generate pages for any other type.
1678 buf.write_str(name);
1679 if !item.is_primitive() && !item.is_keyword() {
1680 let cur = &cx.current;
1681 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1682 for (i, component) in cur.iter().enumerate().take(amt) {
1683 write!(buf, "<a href='{}index.html'>{}</a>::<wbr>",
1684 "../".repeat(cur.len() - i - 1),
1688 write!(buf, "<a class=\"{}\" href=''>{}</a>",
1689 item.type_(), item.name.as_ref().unwrap());
1691 write!(buf, "</span></h1>"); // in-band
1694 clean::ModuleItem(ref m) =>
1695 item_module(buf, cx, item, &m.items),
1696 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1697 item_function(buf, cx, item, f),
1698 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
1699 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
1700 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
1701 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
1702 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t),
1703 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1704 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1705 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
1706 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1707 item_static(buf, cx, item, i),
1708 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1709 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
1710 clean::KeywordItem(_) => item_keyword(buf, cx, item),
1711 clean::OpaqueTyItem(ref e, _) => item_opaque_ty(buf, cx, item, e),
1712 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
1714 // We don't generate pages for any other type.
1720 fn item_path(ty: ItemType, name: &str) -> String {
1722 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1723 _ => format!("{}.{}.html", ty, name),
1727 fn full_path(cx: &Context, item: &clean::Item) -> String {
1728 let mut s = cx.current.join("::");
1730 s.push_str(item.name.as_ref().unwrap());
1735 fn plain_summary_line(s: Option<&str>) -> String {
1736 let s = s.unwrap_or("");
1737 // This essentially gets the first paragraph of text in one line.
1738 let mut line = s.lines()
1739 .skip_while(|line| line.chars().all(|c| c.is_whitespace()))
1740 .take_while(|line| line.chars().any(|c| !c.is_whitespace()))
1741 .fold(String::new(), |mut acc, line| {
1746 // remove final whitespace
1748 markdown::plain_summary_line(&line[..])
1751 fn shorten(s: String) -> String {
1752 if s.chars().count() > 60 {
1754 let mut ret = s.split_whitespace()
1756 // + 1 for the added character after the word.
1757 len += p.chars().count() + 1;
1760 .collect::<Vec<_>>()
1769 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item) {
1770 if let Some(ref name) = item.name {
1771 info!("Documenting {}", name);
1773 document_stability(w, cx, item, false);
1774 document_full(w, item, cx, "", false);
1777 /// Render md_text as markdown.
1782 links: Vec<(String, String)>,
1786 let mut ids = cx.id_map.borrow_mut();
1787 write!(w, "<div class='docblock{}'>{}{}</div>",
1788 if is_hidden { " hidden" } else { "" },
1790 Markdown(md_text, &links, &mut ids,
1791 cx.shared.codes, cx.shared.edition, &cx.shared.playground).to_string())
1798 link: AssocItemLink<'_>,
1802 if let Some(s) = item.doc_value() {
1803 let markdown = if s.contains('\n') {
1804 format!("{} [Read more]({})",
1805 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1807 plain_summary_line(Some(s))
1809 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden);
1810 } else if !prefix.is_empty() {
1811 write!(w, "<div class='docblock{}'>{}</div>",
1812 if is_hidden { " hidden" } else { "" },
1817 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1818 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1819 debug!("Doc block: =====\n{}\n=====", s);
1820 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1821 } else if !prefix.is_empty() {
1822 write!(w, "<div class='docblock{}'>{}</div>",
1823 if is_hidden { " hidden" } else { "" },
1828 fn document_stability(w: &mut Buffer, cx: &Context, item: &clean::Item, is_hidden: bool) {
1829 let stabilities = short_stability(item, cx);
1830 if !stabilities.is_empty() {
1831 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" });
1832 for stability in stabilities {
1833 write!(w, "{}", stability);
1835 write!(w, "</div>");
1839 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1840 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1843 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1844 if item.is_non_exhaustive() {
1845 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
1846 if item.is_struct() {
1848 } else if item.is_enum() {
1850 } else if item.is_variant() {
1857 if item.is_struct() {
1858 write!(w, "Non-exhaustive structs could have additional fields added in future. \
1859 Therefore, non-exhaustive structs cannot be constructed in external crates \
1860 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1861 matched against without a wildcard <code>..</code>; and \
1862 struct update syntax will not work.");
1863 } else if item.is_enum() {
1864 write!(w, "Non-exhaustive enums could have additional variants added in future. \
1865 Therefore, when matching against variants of non-exhaustive enums, an \
1866 extra wildcard arm must be added to account for any future variants.");
1867 } else if item.is_variant() {
1868 write!(w, "Non-exhaustive enum variants could have additional fields added in future. \
1869 Therefore, non-exhaustive enum variants cannot be constructed in external \
1870 crates and cannot be matched against.");
1872 write!(w, "This type will require a wildcard arm in any match statements or \
1876 write!(w, "</div>");
1880 fn name_key(name: &str) -> (&str, u64, usize) {
1881 let end = name.bytes()
1882 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
1884 // find number at end
1885 let split = name[0..end].bytes()
1886 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
1888 // count leading zeroes
1890 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1892 // sort leading zeroes last
1893 let num_zeroes = after_zeroes - split;
1895 match name[split..end].parse() {
1896 Ok(n) => (&name[..split], n, num_zeroes),
1897 Err(_) => (name, 0, num_zeroes),
1901 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
1902 document(w, cx, item);
1904 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1906 // the order of item types in the listing
1907 fn reorder(ty: ItemType) -> u8 {
1909 ItemType::ExternCrate => 0,
1910 ItemType::Import => 1,
1911 ItemType::Primitive => 2,
1912 ItemType::Module => 3,
1913 ItemType::Macro => 4,
1914 ItemType::Struct => 5,
1915 ItemType::Enum => 6,
1916 ItemType::Constant => 7,
1917 ItemType::Static => 8,
1918 ItemType::Trait => 9,
1919 ItemType::Function => 10,
1920 ItemType::Typedef => 12,
1921 ItemType::Union => 13,
1926 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1927 let ty1 = i1.type_();
1928 let ty2 = i2.type_();
1930 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1932 let s1 = i1.stability.as_ref().map(|s| s.level);
1933 let s2 = i2.stability.as_ref().map(|s| s.level);
1935 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1936 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1939 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1940 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1941 name_key(lhs).cmp(&name_key(rhs))
1944 if cx.shared.sort_modules_alphabetically {
1945 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1947 // This call is to remove re-export duplicates in cases such as:
1952 // pub trait Double { fn foo(); }
1956 // pub use foo::bar::*;
1960 // `Double` will appear twice in the generated docs.
1962 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1963 // can be identical even if the elements are different (mostly in imports).
1964 // So in case this is an import, we keep everything by adding a "unique id"
1965 // (which is the position in the vector).
1966 indices.dedup_by_key(|i| (items[*i].def_id,
1967 if items[*i].name.as_ref().is_some() {
1968 Some(full_path(cx, &items[*i]))
1973 if items[*i].is_import() {
1979 debug!("{:?}", indices);
1980 let mut curty = None;
1981 for &idx in &indices {
1982 let myitem = &items[idx];
1983 if myitem.is_stripped() {
1987 let myty = Some(myitem.type_());
1988 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1989 // Put `extern crate` and `use` re-exports in the same section.
1991 } else if myty != curty {
1992 if curty.is_some() {
1993 write!(w, "</table>");
1996 let (short, name) = item_ty_to_strs(&myty.unwrap());
1997 write!(w, "<h2 id='{id}' class='section-header'>\
1998 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1999 id = cx.derive_id(short.to_owned()), name = name);
2002 match myitem.inner {
2003 clean::ExternCrateItem(ref name, ref src) => {
2004 use crate::html::format::anchor;
2008 write!(w, "<tr><td><code>{}extern crate {} as {};",
2009 myitem.visibility.print_with_space(),
2010 anchor(myitem.def_id, src),
2014 write!(w, "<tr><td><code>{}extern crate {};",
2015 myitem.visibility.print_with_space(),
2016 anchor(myitem.def_id, name))
2019 write!(w, "</code></td></tr>");
2022 clean::ImportItem(ref import) => {
2023 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2024 myitem.visibility.print_with_space(), import.print());
2028 if myitem.name.is_none() { continue }
2030 let unsafety_flag = match myitem.inner {
2031 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2032 if func.header.unsafety == hir::Unsafety::Unsafe => {
2033 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2038 let stab = myitem.stability_class();
2039 let add = if stab.is_some() {
2045 let doc_value = myitem.doc_value().unwrap_or("");
2047 <tr class='{stab}{add}module-item'>\
2048 <td><a class=\"{class}\" href=\"{href}\" \
2049 title='{title}'>{name}</a>{unsafety_flag}</td>\
2050 <td class='docblock-short'>{stab_tags}{docs}</td>\
2052 name = *myitem.name.as_ref().unwrap(),
2053 stab_tags = stability_tags(myitem),
2054 docs = MarkdownSummaryLine(doc_value, &myitem.links()).to_string(),
2055 class = myitem.type_(),
2057 stab = stab.unwrap_or_else(|| String::new()),
2058 unsafety_flag = unsafety_flag,
2059 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2060 title = [full_path(cx, myitem), myitem.type_().to_string()]
2062 .filter_map(|s| if !s.is_empty() {
2067 .collect::<Vec<_>>()
2074 if curty.is_some() {
2075 write!(w, "</table>");
2079 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2081 fn stability_tags(item: &clean::Item) -> String {
2082 let mut tags = String::new();
2084 fn tag_html(class: &str, contents: &str) -> String {
2085 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2088 // The trailing space after each tag is to space it properly against the rest of the docs.
2089 if item.deprecation().is_some() {
2090 let mut message = "Deprecated";
2091 if let Some(ref stab) = item.stability {
2092 if let Some(ref depr) = stab.deprecation {
2093 if let Some(ref since) = depr.since {
2094 if !stability::deprecation_in_effect(&since) {
2095 message = "Deprecation planned";
2100 tags += &tag_html("deprecated", message);
2103 if let Some(stab) = item
2106 .filter(|s| s.level == stability::Unstable)
2108 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2109 tags += &tag_html("internal", "Internal");
2111 tags += &tag_html("unstable", "Experimental");
2115 if let Some(ref cfg) = item.attrs.cfg {
2116 tags += &tag_html("portability", &cfg.render_short_html());
2122 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2124 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2125 let mut stability = vec![];
2126 let error_codes = cx.shared.codes;
2128 if let Some(Deprecation { note, since }) = &item.deprecation() {
2129 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2130 // but only display the future-deprecation messages for #[rustc_deprecated].
2131 let mut message = if let Some(since) = since {
2132 format!("Deprecated since {}", Escape(since))
2134 String::from("Deprecated")
2136 if let Some(ref stab) = item.stability {
2137 if let Some(ref depr) = stab.deprecation {
2138 if let Some(ref since) = depr.since {
2139 if !stability::deprecation_in_effect(&since) {
2140 message = format!("Deprecating in {}", Escape(&since));
2146 if let Some(note) = note {
2147 let mut ids = cx.id_map.borrow_mut();
2148 let html = MarkdownHtml(
2149 ¬e, &mut ids, error_codes, cx.shared.edition, &cx.shared.playground);
2150 message.push_str(&format!(": {}", html.to_string()));
2152 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2155 if let Some(stab) = item
2158 .filter(|stab| stab.level == stability::Unstable)
2160 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2162 let mut message = if is_rustc_private {
2163 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2165 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2169 if let Some(feature) = stab.feature.as_ref() {
2170 let mut feature = format!("<code>{}</code>", Escape(&feature));
2171 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2172 feature.push_str(&format!(
2173 " <a href=\"{url}{issue}\">#{issue}</a>",
2179 message.push_str(&format!(" ({})", feature));
2182 if let Some(unstable_reason) = &stab.unstable_reason {
2183 // Provide a more informative message than the compiler help.
2184 let unstable_reason = if is_rustc_private {
2185 "This crate is being loaded from the sysroot, a permanently unstable location \
2186 for private compiler dependencies. It is not intended for general use. Prefer \
2187 using a public version of this crate from \
2188 [crates.io](https://crates.io) via [`Cargo.toml`]\
2189 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2194 let mut ids = cx.id_map.borrow_mut();
2196 "<details><summary>{}</summary>{}</details>",
2203 &cx.shared.playground,
2208 let class = if is_rustc_private {
2213 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2216 if let Some(ref cfg) = item.attrs.cfg {
2217 stability.push(format!(
2218 "<div class='stab portability'>{}</div>",
2219 cfg.render_long_html()
2226 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2227 write!(w, "<pre class='rust const'>");
2228 render_attributes(w, it, false);
2229 write!(w, "{vis}const \
2230 {name}: {typ}</pre>",
2231 vis = it.visibility.print_with_space(),
2232 name = it.name.as_ref().unwrap(),
2233 typ = c.type_.print());
2237 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2238 write!(w, "<pre class='rust static'>");
2239 render_attributes(w, it, false);
2240 write!(w, "{vis}static {mutability}\
2241 {name}: {typ}</pre>",
2242 vis = it.visibility.print_with_space(),
2243 mutability = s.mutability.print_with_space(),
2244 name = it.name.as_ref().unwrap(),
2245 typ = s.type_.print());
2249 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2250 let header_len = format!(
2251 "{}{}{}{}{:#}fn {}{:#}",
2252 it.visibility.print_with_space(),
2253 f.header.constness.print_with_space(),
2254 f.header.unsafety.print_with_space(),
2255 f.header.asyncness.print_with_space(),
2256 print_abi_with_space(f.header.abi),
2257 it.name.as_ref().unwrap(),
2260 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it));
2261 render_attributes(w, it, false);
2263 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2264 {name}{generics}{decl}{where_clause}</pre>",
2265 vis = it.visibility.print_with_space(),
2266 constness = f.header.constness.print_with_space(),
2267 unsafety = f.header.unsafety.print_with_space(),
2268 asyncness = f.header.asyncness.print_with_space(),
2269 abi = print_abi_with_space(f.header.abi),
2270 name = it.name.as_ref().unwrap(),
2271 generics = f.generics.print(),
2272 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2277 asyncness: f.header.asyncness,
2282 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut Buffer,
2283 implementor_dups: &FxHashMap<&str, (DefId, bool)>) {
2284 // If there's already another implementor that has the same abbridged name, use the
2285 // full path, for example in `std::iter::ExactSizeIterator`
2286 let use_absolute = match implementor.inner_impl().for_ {
2287 clean::ResolvedPath { ref path, is_generic: false, .. } |
2288 clean::BorrowedRef {
2289 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2291 } => implementor_dups[path.last_name()].1,
2294 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
2295 implementor.impl_item.stable_since(), false, Some(use_absolute), false, false);
2298 fn render_impls(cx: &Context, w: &mut Buffer,
2300 containing_item: &clean::Item) {
2302 let did = i.trait_did().unwrap();
2303 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2304 render_impl(w, cx, i, assoc_link,
2305 RenderMode::Normal, containing_item.stable_since(), true, None, false, true);
2309 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2310 let mut bounds = String::new();
2311 if !t_bounds.is_empty() {
2313 bounds.push_str(": ");
2315 for (i, p) in t_bounds.iter().enumerate() {
2317 bounds.push_str(" + ");
2319 bounds.push_str(&p.print().to_string());
2325 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2326 let lhs = format!("{}", lhs.inner_impl().print());
2327 let rhs = format!("{}", rhs.inner_impl().print());
2329 // lhs and rhs are formatted as HTML, which may be unnecessary
2330 name_key(&lhs).cmp(&name_key(&rhs))
2339 let bounds = bounds(&t.bounds, false);
2340 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2341 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2342 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2343 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2345 // Output the trait definition
2346 wrap_into_docblock(w, |w| {
2347 write!(w, "<pre class='rust trait'>");
2348 render_attributes(w, it, true);
2349 write!(w, "{}{}{}trait {}{}{}",
2350 it.visibility.print_with_space(),
2351 t.unsafety.print_with_space(),
2352 if t.is_auto { "auto " } else { "" },
2353 it.name.as_ref().unwrap(),
2357 if !t.generics.where_predicates.is_empty() {
2358 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2363 if t.items.is_empty() {
2366 // FIXME: we should be using a derived_id for the Anchors here
2369 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2372 if !types.is_empty() && !consts.is_empty() {
2376 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2379 if !consts.is_empty() && !required.is_empty() {
2382 for (pos, m) in required.iter().enumerate() {
2383 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2386 if pos < required.len() - 1 {
2387 write!(w, "<div class='item-spacer'></div>");
2390 if !required.is_empty() && !provided.is_empty() {
2393 for (pos, m) in provided.iter().enumerate() {
2394 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2396 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2397 write!(w, ",\n {{ ... }}\n");
2400 write!(w, " {{ ... }}\n");
2403 if pos < provided.len() - 1 {
2404 write!(w, "<div class='item-spacer'></div>");
2412 // Trait documentation
2413 document(w, cx, it);
2415 fn write_small_section_header(
2419 extra_content: &str,
2422 <h2 id='{0}' class='small-section-header'>\
2423 {1}<a href='#{0}' class='anchor'></a>\
2424 </h2>{2}", id, title, extra_content)
2427 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2428 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
2431 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item) {
2432 let name = m.name.as_ref().unwrap();
2433 let item_type = m.type_();
2434 let id = cx.derive_id(format!("{}.{}", item_type, name));
2435 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
2436 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
2437 extra = render_spotlight_traits(m),
2440 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2441 write!(w, "</code>");
2442 render_stability_since(w, m, t);
2447 if !types.is_empty() {
2448 write_small_section_header(w, "associated-types", "Associated Types",
2449 "<div class='methods'>");
2451 trait_item(w, cx, *t, it);
2453 write_loading_content(w, "</div>");
2456 if !consts.is_empty() {
2457 write_small_section_header(w, "associated-const", "Associated Constants",
2458 "<div class='methods'>");
2460 trait_item(w, cx, *t, it);
2462 write_loading_content(w, "</div>");
2465 // Output the documentation for each function individually
2466 if !required.is_empty() {
2467 write_small_section_header(w, "required-methods", "Required methods",
2468 "<div class='methods'>");
2469 for m in &required {
2470 trait_item(w, cx, *m, it);
2472 write_loading_content(w, "</div>");
2474 if !provided.is_empty() {
2475 write_small_section_header(w, "provided-methods", "Provided methods",
2476 "<div class='methods'>");
2477 for m in &provided {
2478 trait_item(w, cx, *m, it);
2480 write_loading_content(w, "</div>");
2483 // If there are methods directly on this trait object, render them here.
2484 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All);
2486 let mut synthetic_types = Vec::new();
2488 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2489 // The DefId is for the first Type found with that name. The bool is
2490 // if any Types with the same name but different DefId have been found.
2491 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2492 for implementor in implementors {
2493 match implementor.inner_impl().for_ {
2494 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2495 clean::BorrowedRef {
2496 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2499 let &mut (prev_did, ref mut has_duplicates) =
2500 implementor_dups.entry(path.last_name()).or_insert((did, false));
2501 if prev_did != did {
2502 *has_duplicates = true;
2509 let (local, foreign) = implementors.iter()
2510 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2511 .map_or(true, |d| cx.cache.paths.contains_key(&d)));
2514 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
2515 .partition(|i| i.inner_impl().synthetic);
2517 synthetic.sort_by(compare_impl);
2518 concrete.sort_by(compare_impl);
2520 if !foreign.is_empty() {
2521 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2523 for implementor in foreign {
2524 let assoc_link = AssocItemLink::GotoSource(
2525 implementor.impl_item.def_id,
2526 &implementor.inner_impl().provided_trait_methods
2528 render_impl(w, cx, &implementor, assoc_link,
2529 RenderMode::Normal, implementor.impl_item.stable_since(), false,
2532 write_loading_content(w, "");
2535 write_small_section_header(w, "implementors", "Implementors",
2536 "<div class='item-list' id='implementors-list'>");
2537 for implementor in concrete {
2538 render_implementor(cx, implementor, w, &implementor_dups);
2540 write_loading_content(w, "</div>");
2543 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
2544 "<div class='item-list' id='synthetic-implementors-list'>");
2545 for implementor in synthetic {
2546 synthetic_types.extend(
2547 collect_paths_for_type(implementor.inner_impl().for_.clone())
2549 render_implementor(cx, implementor, w, &implementor_dups);
2551 write_loading_content(w, "</div>");
2554 // even without any implementations to write in, we still want the heading and list, so the
2555 // implementors javascript file pulled in below has somewhere to write the impls into
2556 write_small_section_header(w, "implementors", "Implementors",
2557 "<div class='item-list' id='implementors-list'>");
2558 write_loading_content(w, "</div>");
2561 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
2562 "<div class='item-list' id='synthetic-implementors-list'>");
2563 write_loading_content(w, "</div>");
2566 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2567 as_json(&synthetic_types));
2569 write!(w, r#"<script type="text/javascript" async
2570 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2572 root_path = vec![".."; cx.current.len()].join("/"),
2573 path = if it.def_id.is_local() {
2574 cx.current.join("/")
2576 let (ref path, _) = cx.cache.external_paths[&it.def_id];
2577 path[..path.len() - 1].join("/")
2580 name = *it.name.as_ref().unwrap());
2583 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2584 use crate::html::item_type::ItemType::*;
2586 let name = it.name.as_ref().unwrap();
2587 let ty = match it.type_() {
2588 Typedef | AssocType => AssocType,
2592 let anchor = format!("#{}.{}", ty, name);
2594 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2595 AssocItemLink::Anchor(None) => anchor,
2596 AssocItemLink::GotoSource(did, _) => {
2597 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2602 fn assoc_const(w: &mut Buffer,
2605 _default: Option<&String>,
2606 link: AssocItemLink<'_>,
2608 write!(w, "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2610 it.visibility.print_with_space(),
2611 naive_assoc_href(it, link),
2612 it.name.as_ref().unwrap(),
2616 fn assoc_type(w: &mut Buffer, it: &clean::Item,
2617 bounds: &[clean::GenericBound],
2618 default: Option<&clean::Type>,
2619 link: AssocItemLink<'_>,
2621 write!(w, "{}type <a href='{}' class=\"type\">{}</a>",
2623 naive_assoc_href(it, link),
2624 it.name.as_ref().unwrap());
2625 if !bounds.is_empty() {
2626 write!(w, ": {}", print_generic_bounds(bounds))
2628 if let Some(default) = default {
2629 write!(w, " = {}", default.print())
2633 fn render_stability_since_raw(w: &mut Buffer, ver: Option<&str>, containing_ver: Option<&str>) {
2634 if let Some(v) = ver {
2635 if containing_ver != ver && v.len() > 0 {
2636 write!(w, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", v)
2641 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2642 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2645 fn render_assoc_item(w: &mut Buffer,
2647 link: AssocItemLink<'_>,
2649 fn method(w: &mut Buffer,
2651 header: hir::FnHeader,
2652 g: &clean::Generics,
2654 link: AssocItemLink<'_>,
2656 let name = meth.name.as_ref().unwrap();
2657 let anchor = format!("#{}.{}", meth.type_(), name);
2658 let href = match link {
2659 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2660 AssocItemLink::Anchor(None) => anchor,
2661 AssocItemLink::GotoSource(did, provided_methods) => {
2662 // We're creating a link from an impl-item to the corresponding
2663 // trait-item and need to map the anchored type accordingly.
2664 let ty = if provided_methods.contains(name) {
2670 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2673 let mut header_len = format!(
2674 "{}{}{}{}{}{:#}fn {}{:#}",
2675 meth.visibility.print_with_space(),
2676 header.constness.print_with_space(),
2677 header.unsafety.print_with_space(),
2678 header.asyncness.print_with_space(),
2679 print_default_space(meth.is_default()),
2680 print_abi_with_space(header.abi),
2684 let (indent, end_newline) = if parent == ItemType::Trait {
2690 render_attributes(w, meth, false);
2691 write!(w, "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2692 {generics}{decl}{where_clause}",
2693 if parent == ItemType::Trait { " " } else { "" },
2694 meth.visibility.print_with_space(),
2695 header.constness.print_with_space(),
2696 header.unsafety.print_with_space(),
2697 header.asyncness.print_with_space(),
2698 print_default_space(meth.is_default()),
2699 print_abi_with_space(header.abi),
2702 generics = g.print(),
2707 asyncness: header.asyncness,
2709 where_clause = WhereClause {
2716 clean::StrippedItem(..) => {},
2717 clean::TyMethodItem(ref m) => {
2718 method(w, item, m.header, &m.generics, &m.decl, link, parent)
2720 clean::MethodItem(ref m) => {
2721 method(w, item, m.header, &m.generics, &m.decl, link, parent)
2723 clean::AssocConstItem(ref ty, ref default) => {
2724 assoc_const(w, item, ty, default.as_ref(), link,
2725 if parent == ItemType::Trait { " " } else { "" })
2727 clean::AssocTypeItem(ref bounds, ref default) => {
2728 assoc_type(w, item, bounds, default.as_ref(), link,
2729 if parent == ItemType::Trait { " " } else { "" })
2731 _ => panic!("render_assoc_item called on non-associated-item")
2735 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct) {
2736 wrap_into_docblock(w, |w| {
2737 write!(w, "<pre class='rust struct'>");
2738 render_attributes(w, it, true);
2749 document(w, cx, it);
2750 let mut fields = s.fields.iter().filter_map(|f| {
2752 clean::StructFieldItem(ref ty) => Some((f, ty)),
2756 if let doctree::Plain = s.struct_type {
2757 if fields.peek().is_some() {
2758 write!(w, "<h2 id='fields' class='fields small-section-header'>
2759 Fields{}<a href='#fields' class='anchor'></a></h2>",
2760 document_non_exhaustive_header(it));
2761 document_non_exhaustive(w, it);
2762 for (field, ty) in fields {
2763 let id = cx.derive_id(format!("{}.{}",
2764 ItemType::StructField,
2765 field.name.as_ref().unwrap()));
2766 let ns_id = cx.derive_id(format!("{}.{}",
2767 field.name.as_ref().unwrap(),
2768 ItemType::StructField.name_space()));
2769 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
2770 <a href=\"#{id}\" class=\"anchor field\"></a>\
2771 <code id=\"{ns_id}\">{name}: {ty}</code>\
2773 item_type = ItemType::StructField,
2776 name = field.name.as_ref().unwrap(),
2778 document(w, cx, field);
2782 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2785 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union) {
2786 wrap_into_docblock(w, |w| {
2787 write!(w, "<pre class='rust union'>");
2788 render_attributes(w, it, true);
2798 document(w, cx, it);
2799 let mut fields = s.fields.iter().filter_map(|f| {
2801 clean::StructFieldItem(ref ty) => Some((f, ty)),
2805 if fields.peek().is_some() {
2806 write!(w, "<h2 id='fields' class='fields small-section-header'>
2807 Fields<a href='#fields' class='anchor'></a></h2>");
2808 for (field, ty) in fields {
2809 let name = field.name.as_ref().expect("union field name");
2810 let id = format!("{}.{}", ItemType::StructField, name);
2811 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
2812 <a href=\"#{id}\" class=\"anchor field\"></a>\
2813 <code>{name}: {ty}</code>\
2817 shortty = ItemType::StructField,
2819 if let Some(stability_class) = field.stability_class() {
2820 write!(w, "<span class='stab {stab}'></span>",
2821 stab = stability_class);
2823 document(w, cx, field);
2826 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2829 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum) {
2830 wrap_into_docblock(w, |w| {
2831 write!(w, "<pre class='rust enum'>");
2832 render_attributes(w, it, true);
2833 write!(w, "{}enum {}{}{}",
2834 it.visibility.print_with_space(),
2835 it.name.as_ref().unwrap(),
2837 WhereClause { gens: &e.generics, indent: 0, end_newline: true });
2838 if e.variants.is_empty() && !e.variants_stripped {
2842 for v in &e.variants {
2844 let name = v.name.as_ref().unwrap();
2846 clean::VariantItem(ref var) => {
2848 clean::VariantKind::CLike => write!(w, "{}", name),
2849 clean::VariantKind::Tuple(ref tys) => {
2850 write!(w, "{}(", name);
2851 for (i, ty) in tys.iter().enumerate() {
2853 write!(w, ", ")
2855 write!(w, "{}", ty.print());
2859 clean::VariantKind::Struct(ref s) => {
2875 if e.variants_stripped {
2876 write!(w, " // some variants omitted\n");
2883 document(w, cx, it);
2884 if !e.variants.is_empty() {
2885 write!(w, "<h2 id='variants' class='variants small-section-header'>
2886 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
2887 document_non_exhaustive_header(it));
2888 document_non_exhaustive(w, it);
2889 for variant in &e.variants {
2890 let id = cx.derive_id(format!("{}.{}",
2892 variant.name.as_ref().unwrap()));
2893 let ns_id = cx.derive_id(format!("{}.{}",
2894 variant.name.as_ref().unwrap(),
2895 ItemType::Variant.name_space()));
2896 write!(w, "<div id=\"{id}\" class=\"variant small-section-header\">\
2897 <a href=\"#{id}\" class=\"anchor field\"></a>\
2898 <code id='{ns_id}'>{name}",
2901 name = variant.name.as_ref().unwrap());
2902 if let clean::VariantItem(ref var) = variant.inner {
2903 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2905 for (i, ty) in tys.iter().enumerate() {
2907 write!(w, ", ");
2909 write!(w, "{}", ty.print());
2914 write!(w, "</code></div>");
2915 document(w, cx, variant);
2916 document_non_exhaustive(w, variant);
2918 use crate::clean::{Variant, VariantKind};
2919 if let clean::VariantItem(Variant {
2920 kind: VariantKind::Struct(ref s)
2921 }) = variant.inner {
2922 let variant_id = cx.derive_id(format!("{}.{}.fields",
2924 variant.name.as_ref().unwrap()));
2925 write!(w, "<div class='autohide sub-variant' id='{id}'>",
2927 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
2928 name = variant.name.as_ref().unwrap());
2929 for field in &s.fields {
2930 use crate::clean::StructFieldItem;
2931 if let StructFieldItem(ref ty) = field.inner {
2932 let id = cx.derive_id(format!("variant.{}.field.{}",
2933 variant.name.as_ref().unwrap(),
2934 field.name.as_ref().unwrap()));
2935 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
2936 variant.name.as_ref().unwrap(),
2937 ItemType::Variant.name_space(),
2938 field.name.as_ref().unwrap(),
2939 ItemType::StructField.name_space()));
2940 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2941 <a href=\"#{id}\" class=\"anchor field\"></a>\
2942 <code id='{ns_id}'>{f}: {t}\
2946 f = field.name.as_ref().unwrap(),
2948 document(w, cx, field);
2951 write!(w, "</div></div>");
2953 render_stability_since(w, variant, it);
2956 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2959 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2960 let path = attr.path.to_string();
2964 } else if let Some(v) = attr.value_str() {
2965 Some(format!("{} = {:?}", path, v.as_str()))
2966 } else if let Some(values) = attr.meta_item_list() {
2967 let display: Vec<_> = values.iter().filter_map(|attr| {
2968 attr.meta_item().and_then(|mi| render_attribute(mi))
2971 if display.len() > 0 {
2972 Some(format!("{}({})", path, display.join(", ")))
2981 const ATTRIBUTE_WHITELIST: &'static [Symbol] = &[
2991 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
2992 // left padding. For example:
2994 // #[foo] <----- "top" attribute
2996 // #[bar] <---- not "top" attribute
2999 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3000 let mut attrs = String::new();
3002 for attr in &it.attrs.other_attrs {
3003 if !ATTRIBUTE_WHITELIST.contains(&attr.name_or_empty()) {
3006 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3007 attrs.push_str(&format!("#[{}]\n", s));
3010 if attrs.len() > 0 {
3011 write!(w, "<span class=\"docblock attributes{}\">{}</span>",
3012 if top { " top-attr" } else { "" }, &attrs);
3016 fn render_struct(w: &mut Buffer, it: &clean::Item,
3017 g: Option<&clean::Generics>,
3018 ty: doctree::StructType,
3019 fields: &[clean::Item],
3023 it.visibility.print_with_space(),
3024 if structhead {"struct "} else {""},
3025 it.name.as_ref().unwrap());
3026 if let Some(g) = g {
3027 write!(w, "{}", g.print())
3031 if let Some(g) = g {
3032 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3034 let mut has_visible_fields = false;
3036 for field in fields {
3037 if let clean::StructFieldItem(ref ty) = field.inner {
3038 write!(w, "\n{} {}{}: {},",
3040 field.visibility.print_with_space(),
3041 field.name.as_ref().unwrap(),
3043 has_visible_fields = true;
3047 if has_visible_fields {
3048 if it.has_stripped_fields().unwrap() {
3049 write!(w, "\n{} // some fields omitted", tab);
3051 write!(w, "\n{}", tab);
3052 } else if it.has_stripped_fields().unwrap() {
3053 // If there are no visible fields we can just display
3054 // `{ /* fields omitted */ }` to save space.
3055 write!(w, " /* fields omitted */ ");
3061 for (i, field) in fields.iter().enumerate() {
3066 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3069 clean::StructFieldItem(ref ty) => {
3070 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3076 if let Some(g) = g {
3077 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3082 // Needed for PhantomData.
3083 if let Some(g) = g {
3084 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3091 fn render_union(w: &mut Buffer, it: &clean::Item,
3092 g: Option<&clean::Generics>,
3093 fields: &[clean::Item],
3097 it.visibility.print_with_space(),
3098 if structhead {"union "} else {""},
3099 it.name.as_ref().unwrap());
3100 if let Some(g) = g {
3101 write!(w, "{}", g.print());
3102 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3105 write!(w, " {{\n{}", tab);
3106 for field in fields {
3107 if let clean::StructFieldItem(ref ty) = field.inner {
3108 write!(w, " {}{}: {},\n{}",
3109 field.visibility.print_with_space(),
3110 field.name.as_ref().unwrap(),
3116 if it.has_stripped_fields().unwrap() {
3117 write!(w, " // some fields omitted\n{}", tab);
3122 #[derive(Copy, Clone)]
3123 enum AssocItemLink<'a> {
3124 Anchor(Option<&'a str>),
3125 GotoSource(DefId, &'a FxHashSet<String>),
3128 impl<'a> AssocItemLink<'a> {
3129 fn anchor(&self, id: &'a String) -> Self {
3131 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3132 ref other => *other,
3137 enum AssocItemRender<'a> {
3139 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3142 #[derive(Copy, Clone, PartialEq)]
3145 ForDeref { mut_: bool },
3148 fn render_assoc_items(w: &mut Buffer,
3150 containing_item: &clean::Item,
3152 what: AssocItemRender<'_>) {
3154 let v = match c.impls.get(&it) {
3158 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3159 i.inner_impl().trait_.is_none()
3161 if !non_trait.is_empty() {
3162 let render_mode = match what {
3163 AssocItemRender::All => {
3165 <h2 id='methods' class='small-section-header'>\
3166 Methods<a href='#methods' class='anchor'></a>\
3171 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3173 <h2 id='deref-methods' class='small-section-header'>\
3174 Methods from {}<Target = {}>\
3175 <a href='#deref-methods' class='anchor'></a>\
3177 ", trait_.print(), type_.print());
3178 RenderMode::ForDeref { mut_: deref_mut_ }
3181 for i in &non_trait {
3182 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3183 containing_item.stable_since(), true, None, false, true);
3186 if let AssocItemRender::DerefFor { .. } = what {
3189 if !traits.is_empty() {
3190 let deref_impl = traits.iter().find(|t| {
3191 t.inner_impl().trait_.def_id() == c.deref_trait_did
3193 if let Some(impl_) = deref_impl {
3194 let has_deref_mut = traits.iter().find(|t| {
3195 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3197 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
3200 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3202 .partition(|t| t.inner_impl().synthetic);
3203 let (blanket_impl, concrete): (Vec<&&Impl>, _) = concrete
3205 .partition(|t| t.inner_impl().blanket_impl.is_some());
3207 let mut impls = Buffer::empty_from(&w);
3208 render_impls(cx, &mut impls, &concrete, containing_item);
3209 let impls = impls.into_inner();
3210 if !impls.is_empty() {
3212 <h2 id='implementations' class='small-section-header'>\
3213 Trait Implementations<a href='#implementations' class='anchor'></a>\
3215 <div id='implementations-list'>{}</div>", impls);
3218 if !synthetic.is_empty() {
3220 <h2 id='synthetic-implementations' class='small-section-header'>\
3221 Auto Trait Implementations\
3222 <a href='#synthetic-implementations' class='anchor'></a>\
3224 <div id='synthetic-implementations-list'>\
3226 render_impls(cx, w, &synthetic, containing_item);
3227 write!(w, "</div>");
3230 if !blanket_impl.is_empty() {
3232 <h2 id='blanket-implementations' class='small-section-header'>\
3233 Blanket Implementations\
3234 <a href='#blanket-implementations' class='anchor'></a>\
3236 <div id='blanket-implementations-list'>\
3238 render_impls(cx, w, &blanket_impl, containing_item);
3239 write!(w, "</div>");
3244 fn render_deref_methods(w: &mut Buffer, cx: &Context, impl_: &Impl,
3245 container_item: &clean::Item, deref_mut: bool) {
3246 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3247 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3249 clean::TypedefItem(ref t, true) => Some(&t.type_),
3252 }).next().expect("Expected associated type binding");
3253 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3254 deref_mut_: deref_mut };
3255 if let Some(did) = target.def_id() {
3256 render_assoc_items(w, cx, container_item, did, what)
3258 if let Some(prim) = target.primitive_type() {
3259 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
3260 render_assoc_items(w, cx, container_item, did, what);
3266 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3267 let self_type_opt = match item.inner {
3268 clean::MethodItem(ref method) => method.decl.self_type(),
3269 clean::TyMethodItem(ref method) => method.decl.self_type(),
3273 if let Some(self_ty) = self_type_opt {
3274 let (by_mut_ref, by_box, by_value) = match self_ty {
3275 SelfTy::SelfBorrowed(_, mutability) |
3276 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3277 (mutability == Mutability::Mutable, false, false)
3279 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3280 (false, Some(did) == cache().owned_box_did, false)
3282 SelfTy::SelfValue => (false, false, true),
3283 _ => (false, false, false),
3286 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3292 fn render_spotlight_traits(item: &clean::Item) -> String {
3294 clean::FunctionItem(clean::Function { ref decl, .. }) |
3295 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3296 clean::MethodItem(clean::Method { ref decl, .. }) |
3297 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3298 spotlight_decl(decl)
3304 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3305 let mut out = Buffer::html();
3306 let mut trait_ = String::new();
3308 if let Some(did) = decl.output.def_id() {
3310 if let Some(impls) = c.impls.get(&did) {
3312 let impl_ = i.inner_impl();
3313 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3316 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3317 <code class=\"content\">",
3318 impl_.for_.print()));
3319 trait_.push_str(&impl_.for_.print().to_string());
3322 //use the "where" class here to make it small
3324 &format!("<span class=\"where fmt-newline\">{}</span>", impl_.print()));
3325 let t_did = impl_.trait_.def_id().unwrap();
3326 for it in &impl_.items {
3327 if let clean::TypedefItem(ref tydef, _) = it.inner {
3328 out.push_str("<span class=\"where fmt-newline\"> ");
3329 assoc_type(&mut out, it, &[],
3331 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3333 out.push_str(";</span>");
3341 if !out.is_empty() {
3342 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3343 <span class='tooltiptext'>Important traits for {}</span></div>\
3344 <div class=\"content hidden\">",
3346 out.push_str("</code></div></div>");
3352 fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>,
3353 render_mode: RenderMode, outer_version: Option<&str>, show_def_docs: bool,
3354 use_absolute: Option<bool>, is_on_foreign_type: bool,
3355 show_default_items: bool) {
3356 if render_mode == RenderMode::Normal {
3357 let id = cx.derive_id(match i.inner_impl().trait_ {
3358 Some(ref t) => if is_on_foreign_type {
3359 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3361 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3363 None => "impl".to_string(),
3365 if let Some(use_absolute) = use_absolute {
3366 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id);
3367 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3369 for it in &i.inner_impl().items {
3370 if let clean::TypedefItem(ref tydef, _) = it.inner {
3371 write!(w, "<span class=\"where fmt-newline\"> ");
3372 assoc_type(w, it, &vec![], Some(&tydef.type_),
3373 AssocItemLink::Anchor(None),
3375 write!(w, ";</span>");
3379 write!(w, "</code>");
3381 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
3382 id, i.inner_impl().print()
3385 write!(w, "<a href='#{}' class='anchor'></a>", id);
3386 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3387 render_stability_since_raw(w, since, outer_version);
3388 if let Some(l) = cx.src_href(&i.impl_item) {
3389 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3390 l, "goto source code");
3393 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3394 let mut ids = cx.id_map.borrow_mut();
3395 write!(w, "<div class='docblock'>{}</div>",
3396 Markdown(&*dox, &i.impl_item.links(), &mut ids,
3397 cx.shared.codes, cx.shared.edition, &cx.shared.playground).to_string());
3401 fn doc_impl_item(w: &mut Buffer, cx: &Context, item: &clean::Item,
3402 link: AssocItemLink<'_>, render_mode: RenderMode,
3403 is_default_item: bool, outer_version: Option<&str>,
3404 trait_: Option<&clean::Trait>, show_def_docs: bool) {
3405 let item_type = item.type_();
3406 let name = item.name.as_ref().unwrap();
3408 let render_method_item = match render_mode {
3409 RenderMode::Normal => true,
3410 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3413 let (is_hidden, extra_class) = if (trait_.is_none() ||
3414 item.doc_value().is_some() ||
3415 item.inner.is_associated()) &&
3422 clean::MethodItem(clean::Method { ref decl, .. }) |
3423 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
3424 // Only render when the method is not static or we allow static methods
3425 if render_method_item {
3426 let id = cx.derive_id(format!("{}.{}", item_type, name));
3427 let ns_id = cx.derive_id(format!("{}.{}",
3428 name, item_type.name_space()));
3429 write!(w, "<h4 id='{}' class=\"{}{}\">",
3430 id, item_type, extra_class);
3431 write!(w, "{}", spotlight_decl(decl));
3432 write!(w, "<code id='{}'>", ns_id);
3433 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3434 write!(w, "</code>");
3435 render_stability_since_raw(w, item.stable_since(), outer_version);
3436 if let Some(l) = cx.src_href(item) {
3437 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3438 l, "goto source code");
3443 clean::TypedefItem(ref tydef, _) => {
3444 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3445 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3446 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3447 write!(w, "<code id='{}'>", ns_id);
3448 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3449 write!(w, "</code></h4>");
3451 clean::AssocConstItem(ref ty, ref default) => {
3452 let id = cx.derive_id(format!("{}.{}", item_type, name));
3453 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3454 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3455 write!(w, "<code id='{}'>", ns_id);
3456 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3457 write!(w, "</code>");
3458 render_stability_since_raw(w, item.stable_since(), outer_version);
3459 if let Some(l) = cx.src_href(item) {
3460 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3461 l, "goto source code");
3465 clean::AssocTypeItem(ref bounds, ref default) => {
3466 let id = cx.derive_id(format!("{}.{}", item_type, name));
3467 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3468 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3469 write!(w, "<code id='{}'>", ns_id);
3470 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3471 write!(w, "</code></h4>");
3473 clean::StrippedItem(..) => return,
3474 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3477 if render_method_item {
3478 if !is_default_item {
3479 if let Some(t) = trait_ {
3480 // The trait item may have been stripped so we might not
3481 // find any documentation or stability for it.
3482 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3483 // We need the stability of the item from the trait
3484 // because impls can't have a stability.
3485 document_stability(w, cx, it, is_hidden);
3486 if item.doc_value().is_some() {
3487 document_full(w, item, cx, "", is_hidden);
3488 } else if show_def_docs {
3489 // In case the item isn't documented,
3490 // provide short documentation from the trait.
3491 document_short(w, cx, it, link, "", is_hidden);
3495 document_stability(w, cx, item, is_hidden);
3497 document_full(w, item, cx, "", is_hidden);
3501 document_stability(w, cx, item, is_hidden);
3503 document_short(w, cx, item, link, "", is_hidden);
3509 let traits = &cx.cache.traits;
3510 let trait_ = i.trait_did().map(|did| &traits[&did]);
3512 write!(w, "<div class='impl-items'>");
3513 for trait_item in &i.inner_impl().items {
3514 doc_impl_item(w, cx, trait_item, link, render_mode,
3515 false, outer_version, trait_, show_def_docs);
3518 fn render_default_items(w: &mut Buffer,
3522 render_mode: RenderMode,
3523 outer_version: Option<&str>,
3524 show_def_docs: bool) {
3525 for trait_item in &t.items {
3526 let n = trait_item.name.clone();
3527 if i.items.iter().find(|m| m.name == n).is_some() {
3530 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3531 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3533 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3534 outer_version, None, show_def_docs);
3538 // If we've implemented a trait, then also emit documentation for all
3539 // default items which weren't overridden in the implementation block.
3540 // We don't emit documentation for default items if they appear in the
3541 // Implementations on Foreign Types or Implementors sections.
3542 if show_default_items {
3543 if let Some(t) = trait_ {
3544 render_default_items(w, cx, t, &i.inner_impl(),
3545 render_mode, outer_version, show_def_docs);
3548 write!(w, "</div>");
3555 t: &clean::OpaqueTy,
3557 write!(w, "<pre class='rust opaque'>");
3558 render_attributes(w, it, false);
3559 write!(w, "type {}{}{where_clause} = impl {bounds};</pre>",
3560 it.name.as_ref().unwrap(),
3562 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3563 bounds = bounds(&t.bounds, false));
3565 document(w, cx, it);
3567 // Render any items associated directly to this alias, as otherwise they
3568 // won't be visible anywhere in the docs. It would be nice to also show
3569 // associated items from the aliased type (see discussion in #32077), but
3570 // we need #14072 to make sense of the generics.
3571 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3574 fn item_trait_alias(w: &mut Buffer, cx: &Context, it: &clean::Item,
3575 t: &clean::TraitAlias) {
3576 write!(w, "<pre class='rust trait-alias'>");
3577 render_attributes(w, it, false);
3578 write!(w, "trait {}{}{} = {};</pre>",
3579 it.name.as_ref().unwrap(),
3581 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3582 bounds(&t.bounds, true));
3584 document(w, cx, it);
3586 // Render any items associated directly to this alias, as otherwise they
3587 // won't be visible anywhere in the docs. It would be nice to also show
3588 // associated items from the aliased type (see discussion in #32077), but
3589 // we need #14072 to make sense of the generics.
3590 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3593 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef) {
3594 write!(w, "<pre class='rust typedef'>");
3595 render_attributes(w, it, false);
3596 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3597 it.name.as_ref().unwrap(),
3599 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3600 type_ = t.type_.print());
3602 document(w, cx, it);
3604 // Render any items associated directly to this alias, as otherwise they
3605 // won't be visible anywhere in the docs. It would be nice to also show
3606 // associated items from the aliased type (see discussion in #32077), but
3607 // we need #14072 to make sense of the generics.
3608 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3611 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item) {
3612 writeln!(w, "<pre class='rust foreigntype'>extern {{");
3613 render_attributes(w, it, false);
3616 " {}type {};\n}}</pre>",
3617 it.visibility.print_with_space(),
3618 it.name.as_ref().unwrap(),
3621 document(w, cx, it);
3623 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3626 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer) {
3627 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3629 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3630 || it.is_enum() || it.is_mod() || it.is_typedef() {
3631 write!(buffer, "<p class='location'>{}{}</p>",
3633 clean::StructItem(..) => "Struct ",
3634 clean::TraitItem(..) => "Trait ",
3635 clean::PrimitiveItem(..) => "Primitive Type ",
3636 clean::UnionItem(..) => "Union ",
3637 clean::EnumItem(..) => "Enum ",
3638 clean::TypedefItem(..) => "Type Definition ",
3639 clean::ForeignTypeItem => "Foreign Type ",
3640 clean::ModuleItem(..) => if it.is_crate() {
3647 it.name.as_ref().unwrap());
3651 if let Some(ref version) = cx.cache.crate_version {
3653 "<div class='block version'>\
3660 write!(buffer, "<div class=\"sidebar-elems\">");
3662 write!(buffer, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3663 it.name.as_ref().expect("crates always have a name"));
3666 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
3667 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
3668 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
3669 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
3670 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
3671 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
3672 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
3673 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
3677 // The sidebar is designed to display sibling functions, modules and
3678 // other miscellaneous information. since there are lots of sibling
3679 // items (and that causes quadratic growth in large modules),
3680 // we refactor common parts into a shared JavaScript file per module.
3681 // still, we don't move everything into JS because we want to preserve
3682 // as much HTML as possible in order to allow non-JS-enabled browsers
3683 // to navigate the documentation (though slightly inefficiently).
3685 write!(buffer, "<p class='location'>");
3686 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3688 write!(buffer, "::<wbr>");
3690 write!(buffer, "<a href='{}index.html'>{}</a>",
3691 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3694 write!(buffer, "</p>");
3696 // Sidebar refers to the enclosing module, not this module.
3697 let relpath = if it.is_mod() { "../" } else { "" };
3699 "<script>window.sidebarCurrent = {{\
3704 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3708 // There is no sidebar-items.js beyond the crate root path
3709 // FIXME maybe dynamic crate loading can be merged here
3711 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>",
3714 // Closes sidebar-elems div.
3715 write!(buffer, "</div>");
3718 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
3719 if used_links.insert(url.clone()) {
3723 while used_links.insert(format!("{}-{}", url, add)) == false {
3726 format!("{}-{}", url, add)
3732 used_links: &mut FxHashSet<String>,
3735 i.items.iter().filter_map(|item| {
3737 Some(ref name) if !name.is_empty() && item.is_method() => {
3738 if !for_deref || should_render_item(item, deref_mut) {
3739 Some(format!("<a href=\"#{}\">{}</a>",
3740 get_next_url(used_links, format!("method.{}", name)),
3748 }).collect::<Vec<_>>()
3751 // The point is to url encode any potential character from a type with genericity.
3752 fn small_url_encode(s: &str) -> String {
3753 s.replace("<", "%3C")
3754 .replace(">", "%3E")
3755 .replace(" ", "%20")
3756 .replace("?", "%3F")
3757 .replace("'", "%27")
3758 .replace("&", "%26")
3759 .replace(",", "%2C")
3760 .replace(":", "%3A")
3761 .replace(";", "%3B")
3762 .replace("[", "%5B")
3763 .replace("]", "%5D")
3764 .replace("\"", "%22")
3767 fn sidebar_assoc_items(it: &clean::Item) -> String {
3768 let mut out = String::new();
3770 if let Some(v) = c.impls.get(&it.def_id) {
3771 let mut used_links = FxHashSet::default();
3774 let used_links_bor = &mut used_links;
3775 let mut ret = v.iter()
3776 .filter(|i| i.inner_impl().trait_.is_none())
3777 .flat_map(move |i| get_methods(i.inner_impl(),
3779 used_links_bor, false))
3780 .collect::<Vec<_>>();
3781 // We want links' order to be reproducible so we don't use unstable sort.
3783 if !ret.is_empty() {
3784 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3785 </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
3789 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3790 if let Some(impl_) = v.iter()
3791 .filter(|i| i.inner_impl().trait_.is_some())
3792 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3793 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3795 clean::TypedefItem(ref t, true) => Some(&t.type_),
3799 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3800 c.primitive_locations.get(&prim).cloned()
3801 })).and_then(|did| c.impls.get(&did));
3802 if let Some(impls) = inner_impl {
3803 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3804 out.push_str(&format!("Methods from {}<Target={}>",
3806 "{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print()
3808 Escape(&format!("{:#}", target.print()))));
3809 out.push_str("</a>");
3810 let mut ret = impls.iter()
3811 .filter(|i| i.inner_impl().trait_.is_none())
3812 .flat_map(|i| get_methods(i.inner_impl(),
3816 .collect::<Vec<_>>();
3817 // We want links' order to be reproducible so we don't use unstable sort.
3819 if !ret.is_empty() {
3820 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
3826 let format_impls = |impls: Vec<&Impl>| {
3827 let mut links = FxHashSet::default();
3829 let mut ret = impls.iter()
3831 let is_negative_impl = is_negative_impl(i.inner_impl());
3832 if let Some(ref i) = i.inner_impl().trait_ {
3833 let i_display = format!("{:#}", i.print());
3834 let out = Escape(&i_display);
3835 let encoded = small_url_encode(&format!("{:#}", i.print()));
3836 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3838 if is_negative_impl { "!" } else { "" },
3840 if links.insert(generated.clone()) {
3849 .collect::<Vec<String>>();
3854 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
3856 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
3857 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
3859 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
3861 let concrete_format = format_impls(concrete);
3862 let synthetic_format = format_impls(synthetic);
3863 let blanket_format = format_impls(blanket_impl);
3865 if !concrete_format.is_empty() {
3866 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3867 Trait Implementations</a>");
3868 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
3871 if !synthetic_format.is_empty() {
3872 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
3873 Auto Trait Implementations</a>");
3874 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
3877 if !blanket_format.is_empty() {
3878 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
3879 Blanket Implementations</a>");
3880 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
3888 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
3889 let mut sidebar = String::new();
3890 let fields = get_struct_fields_name(&s.fields);
3892 if !fields.is_empty() {
3893 if let doctree::Plain = s.struct_type {
3894 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3895 <div class=\"sidebar-links\">{}</div>", fields));
3899 sidebar.push_str(&sidebar_assoc_items(it));
3901 if !sidebar.is_empty() {
3902 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
3906 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
3907 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
3910 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3912 clean::ItemEnum::ImplItem(ref i) => {
3913 if let Some(ref trait_) = i.trait_ {
3915 format!("{:#}", i.for_.print()),
3916 get_id_for_impl_on_foreign_type(&i.for_, trait_),
3926 fn is_negative_impl(i: &clean::Impl) -> bool {
3927 i.polarity == Some(clean::ImplPolarity::Negative)
3930 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
3931 let mut sidebar = String::new();
3937 Some(ref name) if m.is_associated_type() => {
3938 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3944 .collect::<String>();
3945 let consts = t.items
3949 Some(ref name) if m.is_associated_const() => {
3950 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3956 .collect::<String>();
3957 let mut required = t.items
3961 Some(ref name) if m.is_ty_method() => {
3962 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3968 .collect::<Vec<String>>();
3969 let mut provided = t.items
3973 Some(ref name) if m.is_method() => {
3974 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
3979 .collect::<Vec<String>>();
3981 if !types.is_empty() {
3982 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3983 Associated Types</a><div class=\"sidebar-links\">{}</div>",
3986 if !consts.is_empty() {
3987 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3988 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3991 if !required.is_empty() {
3993 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3994 Required Methods</a><div class=\"sidebar-links\">{}</div>",
3995 required.join("")));
3997 if !provided.is_empty() {
3999 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4000 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4001 provided.join("")));
4006 if let Some(implementors) = c.implementors.get(&it.def_id) {
4007 let mut res = implementors.iter()
4008 .filter(|i| i.inner_impl().for_.def_id()
4009 .map_or(false, |d| !c.paths.contains_key(&d)))
4011 match extract_for_impl_name(&i.impl_item) {
4012 Some((ref name, ref id)) => {
4013 Some(format!("<a href=\"#{}\">{}</a>",
4020 .collect::<Vec<String>>();
4021 if !res.is_empty() {
4023 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4024 Implementations on Foreign Types</a><div \
4025 class=\"sidebar-links\">{}</div>",
4030 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4032 sidebar.push_str("<a class=\"sidebar-title\" \
4033 href=\"#synthetic-implementors\">Auto Implementors</a>");
4036 sidebar.push_str(&sidebar_assoc_items(it));
4038 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4041 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4042 let sidebar = sidebar_assoc_items(it);
4044 if !sidebar.is_empty() {
4045 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4049 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4050 let sidebar = sidebar_assoc_items(it);
4052 if !sidebar.is_empty() {
4053 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4057 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4059 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4064 .filter_map(|f| match f.name {
4065 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4066 {name}</a>", name=name)),
4072 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4073 let mut sidebar = String::new();
4074 let fields = get_struct_fields_name(&u.fields);
4076 if !fields.is_empty() {
4077 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4078 <div class=\"sidebar-links\">{}</div>", fields));
4081 sidebar.push_str(&sidebar_assoc_items(it));
4083 if !sidebar.is_empty() {
4084 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4088 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4089 let mut sidebar = String::new();
4091 let variants = e.variants.iter()
4092 .filter_map(|v| match v.name {
4093 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4094 </a>", name = name)),
4097 .collect::<String>();
4098 if !variants.is_empty() {
4099 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4100 <div class=\"sidebar-links\">{}</div>", variants));
4103 sidebar.push_str(&sidebar_assoc_items(it));
4105 if !sidebar.is_empty() {
4106 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4110 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4112 ItemType::ExternCrate |
4113 ItemType::Import => ("reexports", "Re-exports"),
4114 ItemType::Module => ("modules", "Modules"),
4115 ItemType::Struct => ("structs", "Structs"),
4116 ItemType::Union => ("unions", "Unions"),
4117 ItemType::Enum => ("enums", "Enums"),
4118 ItemType::Function => ("functions", "Functions"),
4119 ItemType::Typedef => ("types", "Type Definitions"),
4120 ItemType::Static => ("statics", "Statics"),
4121 ItemType::Constant => ("constants", "Constants"),
4122 ItemType::Trait => ("traits", "Traits"),
4123 ItemType::Impl => ("impls", "Implementations"),
4124 ItemType::TyMethod => ("tymethods", "Type Methods"),
4125 ItemType::Method => ("methods", "Methods"),
4126 ItemType::StructField => ("fields", "Struct Fields"),
4127 ItemType::Variant => ("variants", "Variants"),
4128 ItemType::Macro => ("macros", "Macros"),
4129 ItemType::Primitive => ("primitives", "Primitive Types"),
4130 ItemType::AssocType => ("associated-types", "Associated Types"),
4131 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4132 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4133 ItemType::Keyword => ("keywords", "Keywords"),
4134 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4135 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4136 ItemType::ProcDerive => ("derives", "Derive Macros"),
4137 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4141 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4142 let mut sidebar = String::new();
4144 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4145 it.type_() == ItemType::Import) {
4146 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4148 name = "Re-exports"));
4151 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4152 // to print its headings
4153 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4154 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4155 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4156 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4157 ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType,
4158 ItemType::Keyword] {
4159 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4160 let (short, name) = item_ty_to_strs(&myty);
4161 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4167 if !sidebar.is_empty() {
4168 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4172 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4173 let sidebar = sidebar_assoc_items(it);
4174 if !sidebar.is_empty() {
4175 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4179 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4180 wrap_into_docblock(w, |w| {
4181 w.write_str(&highlight::render_with_highlighting(&t.source,
4189 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4190 let name = it.name.as_ref().expect("proc-macros always have names");
4192 MacroKind::Bang => {
4193 write!(w, "<pre class='rust macro'>");
4194 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4195 write!(w, "</pre>");
4197 MacroKind::Attr => {
4198 write!(w, "<pre class='rust attr'>");
4199 write!(w, "#[{}]", name);
4200 write!(w, "</pre>");
4202 MacroKind::Derive => {
4203 write!(w, "<pre class='rust derive'>");
4204 write!(w, "#[derive({})]", name);
4205 if !m.helpers.is_empty() {
4206 writeln!(w, "\n{{");
4207 writeln!(w, " // Attributes available to this derive:");
4208 for attr in &m.helpers {
4209 writeln!(w, " #[{}]", attr);
4213 write!(w, "</pre>");
4219 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4220 document(w, cx, it);
4221 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4224 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4228 crate const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4230 fn make_item_keywords(it: &clean::Item) -> String {
4231 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4234 /// Returns a list of all paths used in the type.
4235 /// This is used to help deduplicate imported impls
4236 /// for reexported types. If any of the contained
4237 /// types are re-exported, we don't use the corresponding
4238 /// entry from the js file, as inlining will have already
4239 /// picked up the impl
4240 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4241 let mut out = Vec::new();
4242 let mut visited = FxHashSet::default();
4243 let mut work = VecDeque::new();
4244 let cache = cache();
4246 work.push_back(first_ty);
4248 while let Some(ty) = work.pop_front() {
4249 if !visited.insert(ty.clone()) {
4254 clean::Type::ResolvedPath { did, .. } => {
4255 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4256 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4260 out.push(path.join("::"));
4266 clean::Type::Tuple(tys) => {
4267 work.extend(tys.into_iter());
4269 clean::Type::Slice(ty) => {
4270 work.push_back(*ty);
4272 clean::Type::Array(ty, _) => {
4273 work.push_back(*ty);
4275 clean::Type::RawPointer(_, ty) => {
4276 work.push_back(*ty);
4278 clean::Type::BorrowedRef { type_, .. } => {
4279 work.push_back(*type_);
4281 clean::Type::QPath { self_type, trait_, .. } => {
4282 work.push_back(*self_type);
4283 work.push_back(*trait_);
4291 crate fn cache() -> Arc<Cache> {
4292 CACHE_KEY.with(|c| c.borrow().clone())