1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Rustdoc's HTML Rendering module
13 //! This modules contains the bulk of the logic necessary for rendering a
14 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
15 //! rendering process is largely driven by the `format!` syntax extension to
16 //! perform all I/O into files and streams.
18 //! The rendering process is largely driven by the `Context` and `Cache`
19 //! structures. The cache is pre-populated by crawling the crate in question,
20 //! and then it is shared among the various rendering threads. The cache is meant
21 //! to be a fairly large structure not implementing `Clone` (because it's shared
22 //! among threads). The context, however, should be a lightweight structure. This
23 //! is cloned per-thread and contains information about what is currently being
26 //! In order to speed up rendering (mostly because of markdown rendering), the
27 //! rendering process has been parallelized. This parallelization is only
28 //! exposed through the `crate` method on the context, and then also from the
29 //! fact that the shared cache is stored in TLS (and must be accessed as such).
31 //! In addition to rendering the crate itself, this module is also responsible
32 //! for creating the corresponding search index and source file renderings.
33 //! These threads are not parallelized (they haven't been a bottleneck yet), and
34 //! both occur before the crate is rendered.
36 pub use self::ExternalLocation::*;
39 use std::cell::RefCell;
40 use std::cmp::Ordering;
41 use std::collections::{BTreeMap, VecDeque};
42 use std::default::Default;
44 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
46 use std::fs::{self, File, OpenOptions};
47 use std::io::prelude::*;
48 use std::io::{self, BufWriter, BufReader};
50 use std::path::{PathBuf, Path, Component};
56 use serialize::json::{ToJson, Json, as_json};
58 use syntax::ext::base::MacroKind;
59 use syntax::source_map::FileName;
60 use syntax::feature_gate::UnstableFeatures;
61 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
62 use rustc::middle::privacy::AccessLevels;
63 use rustc::middle::stability;
65 use rustc::util::nodemap::{FxHashMap, FxHashSet};
66 use rustc_data_structures::flock;
68 use clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
69 use config::RenderOptions;
72 use html::escape::Escape;
73 use html::format::{AsyncSpace, ConstnessSpace};
74 use html::format::{GenericBounds, WhereClause, href, AbiSpace};
75 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
76 use html::format::fmt_impl_for_trait_page;
77 use html::item_type::ItemType;
78 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
79 use html::{highlight, layout, static_files};
83 /// A pair of name and its optional document.
84 pub type NameDoc = (String, Option<String>);
86 /// Major driving force in all rustdoc rendering. This contains information
87 /// about where in the tree-like hierarchy rendering is occurring and controls
88 /// how the current page is being rendered.
90 /// It is intended that this context is a lightweight object which can be fairly
91 /// easily cloned because it is cloned per work-job (about once per item in the
95 /// Current hierarchy of components leading down to what's currently being
97 pub current: Vec<String>,
98 /// The current destination folder of where HTML artifacts should be placed.
99 /// This changes as the context descends into the module hierarchy.
101 /// A flag, which when `true`, will render pages which redirect to the
102 /// real location of an item. This is used to allow external links to
103 /// publicly reused items to redirect to the right location.
104 pub render_redirect_pages: bool,
105 pub codes: ErrorCodes,
106 /// The map used to ensure all generated 'id=' attributes are unique.
107 id_map: Rc<RefCell<IdMap>>,
108 pub shared: Arc<SharedContext>,
111 struct SharedContext {
112 /// The path to the crate root source minus the file name.
113 /// Used for simplifying paths to the highlighted source code files.
114 pub src_root: PathBuf,
115 /// This describes the layout of each page, and is not modified after
116 /// creation of the context (contains info like the favicon and added html).
117 pub layout: layout::Layout,
118 /// This flag indicates whether `[src]` links should be generated or not. If
119 /// the source files are present in the html rendering, then this will be
121 pub include_sources: bool,
122 /// The local file sources we've emitted and their respective url-paths.
123 pub local_sources: FxHashMap<PathBuf, String>,
124 /// All the passes that were run on this crate.
125 pub passes: FxHashSet<String>,
126 /// The base-URL of the issue tracker for when an item has been tagged with
128 pub issue_tracker_base_url: Option<String>,
129 /// The given user css file which allow to customize the generated
130 /// documentation theme.
131 pub css_file_extension: Option<PathBuf>,
132 /// The directories that have already been created in this doc run. Used to reduce the number
133 /// of spurious `create_dir_all` calls.
134 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
135 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
136 /// should be ordered alphabetically or in order of appearance (in the source code).
137 pub sort_modules_alphabetically: bool,
138 /// Additional themes to be added to the generated docs.
139 pub themes: Vec<PathBuf>,
140 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
142 pub resource_suffix: String,
143 /// Optional path string to be used to load static files on output pages. If not set, uses
144 /// combinations of `../` to reach the documentation root.
145 pub static_root_path: Option<String>,
149 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
150 let mut dirs = self.created_dirs.borrow_mut();
151 if !dirs.contains(dst) {
152 fs::create_dir_all(dst)?;
153 dirs.insert(dst.to_path_buf());
161 /// Returns whether the `collapse-docs` pass was run on this crate.
162 pub fn was_collapsed(&self) -> bool {
163 self.passes.contains("collapse-docs")
166 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
167 /// `collapsed_doc_value` of the given item.
168 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
169 if self.was_collapsed() {
170 item.collapsed_doc_value().map(|s| s.into())
172 item.doc_value().map(|s| s.into())
177 /// Indicates where an external crate can be found.
178 pub enum ExternalLocation {
179 /// Remote URL root of the external crate
181 /// This external crate can be found in the local doc/ folder
183 /// The external crate could not be found.
187 /// Metadata about implementations for a type or trait.
188 #[derive(Clone, Debug)]
190 pub impl_item: clean::Item,
194 fn inner_impl(&self) -> &clean::Impl {
195 match self.impl_item.inner {
196 clean::ImplItem(ref impl_) => impl_,
197 _ => panic!("non-impl item found in impl")
201 fn trait_did(&self) -> Option<DefId> {
202 self.inner_impl().trait_.def_id()
209 pub error: io::Error,
212 impl error::Error for Error {
213 fn description(&self) -> &str {
214 self.error.description()
218 impl Display for Error {
219 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
220 write!(f, "\"{}\": {}", self.file.display(), self.error)
225 pub fn new(e: io::Error, file: &Path) -> Error {
227 file: file.to_path_buf(),
233 macro_rules! try_none {
234 ($e:expr, $file:expr) => ({
238 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
244 macro_rules! try_err {
245 ($e:expr, $file:expr) => ({
248 Err(e) => return Err(Error::new(e, $file)),
253 /// This cache is used to store information about the `clean::Crate` being
254 /// rendered in order to provide more useful documentation. This contains
255 /// information like all implementors of a trait, all traits a type implements,
256 /// documentation for all known traits, etc.
258 /// This structure purposefully does not implement `Clone` because it's intended
259 /// to be a fairly large and expensive structure to clone. Instead this adheres
260 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
261 /// rendering threads.
264 /// Mapping of typaram ids to the name of the type parameter. This is used
265 /// when pretty-printing a type (so pretty printing doesn't have to
266 /// painfully maintain a context like this)
267 pub typarams: FxHashMap<DefId, String>,
269 /// Maps a type id to all known implementations for that type. This is only
270 /// recognized for intra-crate `ResolvedPath` types, and is used to print
271 /// out extra documentation on the page of an enum/struct.
273 /// The values of the map are a list of implementations and documentation
274 /// found on that implementation.
275 pub impls: FxHashMap<DefId, Vec<Impl>>,
277 /// Maintains a mapping of local crate node ids to the fully qualified name
278 /// and "short type description" of that node. This is used when generating
279 /// URLs when a type is being linked to. External paths are not located in
280 /// this map because the `External` type itself has all the information
282 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
284 /// Similar to `paths`, but only holds external paths. This is only used for
285 /// generating explicit hyperlinks to other crates.
286 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
288 /// Maps local def ids of exported types to fully qualified paths.
289 /// Unlike 'paths', this mapping ignores any renames that occur
290 /// due to 'use' statements.
292 /// This map is used when writing out the special 'implementors'
293 /// javascript file. By using the exact path that the type
294 /// is declared with, we ensure that each path will be identical
295 /// to the path used if the corresponding type is inlined. By
296 /// doing this, we can detect duplicate impls on a trait page, and only display
297 /// the impl for the inlined type.
298 pub exact_paths: FxHashMap<DefId, Vec<String>>,
300 /// This map contains information about all known traits of this crate.
301 /// Implementations of a crate should inherit the documentation of the
302 /// parent trait if no extra documentation is specified, and default methods
303 /// should show up in documentation about trait implementations.
304 pub traits: FxHashMap<DefId, clean::Trait>,
306 /// When rendering traits, it's often useful to be able to list all
307 /// implementors of the trait, and this mapping is exactly, that: a mapping
308 /// of trait ids to the list of known implementors of the trait
309 pub implementors: FxHashMap<DefId, Vec<Impl>>,
311 /// Cache of where external crate documentation can be found.
312 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
314 /// Cache of where documentation for primitives can be found.
315 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
317 // Note that external items for which `doc(hidden)` applies to are shown as
318 // non-reachable while local items aren't. This is because we're reusing
319 // the access levels from crateanalysis.
320 pub access_levels: AccessLevels<DefId>,
322 /// The version of the crate being documented, if given from the `--crate-version` flag.
323 pub crate_version: Option<String>,
325 // Private fields only used when initially crawling a crate to build a cache
328 parent_stack: Vec<DefId>,
329 parent_is_trait_impl: bool,
330 search_index: Vec<IndexItem>,
332 deref_trait_did: Option<DefId>,
333 deref_mut_trait_did: Option<DefId>,
334 owned_box_did: Option<DefId>,
335 masked_crates: FxHashSet<CrateNum>,
337 // In rare case where a structure is defined in one module but implemented
338 // in another, if the implementing module is parsed before defining module,
339 // then the fully qualified name of the structure isn't presented in `paths`
340 // yet when its implementation methods are being indexed. Caches such methods
341 // and their parent id here and indexes them at the end of crate parsing.
342 orphan_impl_items: Vec<(DefId, clean::Item)>,
344 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
345 // even though the trait itself is not exported. This can happen if a trait
346 // was defined in function/expression scope, since the impl will be picked
347 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
348 // crawl. In order to prevent crashes when looking for spotlight traits or
349 // when gathering trait documentation on a type, hold impls here while
350 // folding and add them to the cache later on if we find the trait.
351 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
353 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
354 /// we need the alias element to have an array of items.
355 aliases: FxHashMap<String, Vec<IndexItem>>,
358 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
359 /// Later on moved into `CACHE_KEY`.
361 pub struct RenderInfo {
362 pub inlined: FxHashSet<DefId>,
363 pub external_paths: ::core::ExternalPaths,
364 pub external_typarams: FxHashMap<DefId, String>,
365 pub exact_paths: FxHashMap<DefId, Vec<String>>,
366 pub access_levels: AccessLevels<DefId>,
367 pub deref_trait_did: Option<DefId>,
368 pub deref_mut_trait_did: Option<DefId>,
369 pub owned_box_did: Option<DefId>,
372 /// Helper struct to render all source code to HTML pages
373 struct SourceCollector<'a> {
374 scx: &'a mut SharedContext,
376 /// Root destination to place all HTML output into
380 /// Wrapper struct to render the source code of a file. This will do things like
381 /// adding line numbers to the left-hand side.
382 struct Source<'a>(&'a str);
384 // Helper structs for rendering items/sidebars and carrying along contextual
387 #[derive(Copy, Clone)]
390 item: &'a clean::Item,
393 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
395 /// Struct representing one entry in the JS search index. These are all emitted
396 /// by hand to a large JS file at the end of cache-creation.
403 parent: Option<DefId>,
404 parent_idx: Option<usize>,
405 search_type: Option<IndexItemFunctionType>,
408 impl ToJson for IndexItem {
409 fn to_json(&self) -> Json {
410 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
412 let mut data = Vec::with_capacity(6);
413 data.push((self.ty as usize).to_json());
414 data.push(self.name.to_json());
415 data.push(self.path.to_json());
416 data.push(self.desc.to_json());
417 data.push(self.parent_idx.to_json());
418 data.push(self.search_type.to_json());
424 /// A type used for the search index.
427 name: Option<String>,
428 generics: Option<Vec<String>>,
431 impl ToJson for Type {
432 fn to_json(&self) -> Json {
435 let mut data = Vec::with_capacity(2);
436 data.push(name.to_json());
437 if let Some(ref generics) = self.generics {
438 data.push(generics.to_json());
447 /// Full type of functions/methods in the search index.
449 struct IndexItemFunctionType {
451 output: Option<Type>,
454 impl ToJson for IndexItemFunctionType {
455 fn to_json(&self) -> Json {
456 // If we couldn't figure out a type, just write `null`.
457 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
460 let mut data = Vec::with_capacity(2);
461 data.push(self.inputs.to_json());
462 if let Some(ref output) = self.output {
463 data.push(output.to_json());
470 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
471 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
473 pub fn initial_ids() -> Vec<String> {
485 "synthetic-implementors",
487 "synthetic-implementors-list",
491 ].into_iter().map(|id| (String::from(*id))).collect()
494 /// Generates the documentation for `crate` into the directory `dst`
495 pub fn run(mut krate: clean::Crate,
496 options: RenderOptions,
497 passes: FxHashSet<String>,
498 renderinfo: RenderInfo,
499 diag: &errors::Handler) -> Result<(), Error> {
500 // need to save a copy of the options for rendering the index page
501 let md_opts = options.clone();
507 sort_modules_alphabetically,
510 extern_html_root_urls,
516 let src_root = match krate.src {
517 FileName::Real(ref p) => match p.parent() {
518 Some(p) => p.to_path_buf(),
519 None => PathBuf::new(),
523 let mut scx = SharedContext {
526 include_sources: true,
527 local_sources: Default::default(),
528 issue_tracker_base_url: None,
529 layout: layout::Layout {
531 favicon: String::new(),
533 krate: krate.name.clone(),
535 css_file_extension: extension_css,
536 created_dirs: Default::default(),
537 sort_modules_alphabetically,
543 // If user passed in `--playground-url` arg, we fill in crate name here
544 if let Some(url) = playground_url {
545 markdown::PLAYGROUND.with(|slot| {
546 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
550 // Crawl the crate attributes looking for attributes which control how we're
551 // going to emit HTML
552 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
553 for attr in attrs.lists("doc") {
554 let name = attr.name().map(|s| s.as_str());
555 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
556 (Some("html_favicon_url"), Some(s)) => {
557 scx.layout.favicon = s.to_string();
559 (Some("html_logo_url"), Some(s)) => {
560 scx.layout.logo = s.to_string();
562 (Some("html_playground_url"), Some(s)) => {
563 markdown::PLAYGROUND.with(|slot| {
564 let name = krate.name.clone();
565 *slot.borrow_mut() = Some((Some(name), s.to_string()));
568 (Some("issue_tracker_base_url"), Some(s)) => {
569 scx.issue_tracker_base_url = Some(s.to_string());
571 (Some("html_no_source"), None) if attr.is_word() => {
572 scx.include_sources = false;
579 try_err!(fs::create_dir_all(&dst), &dst);
580 krate = render_sources(&dst, &mut scx, krate)?;
584 render_redirect_pages: false,
585 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
586 id_map: Rc::new(RefCell::new(id_map)),
587 shared: Arc::new(scx),
590 // Crawl the crate to build various caches used for the output
602 let external_paths = external_paths.into_iter()
603 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
606 let mut cache = Cache {
607 impls: Default::default(),
610 paths: Default::default(),
611 implementors: Default::default(),
613 parent_stack: Vec::new(),
614 search_index: Vec::new(),
615 parent_is_trait_impl: false,
616 extern_locations: Default::default(),
617 primitive_locations: Default::default(),
620 crate_version: krate.version.take(),
621 orphan_impl_items: Vec::new(),
622 orphan_trait_impls: Vec::new(),
623 traits: krate.external_traits.lock().replace(Default::default()),
627 masked_crates: mem::replace(&mut krate.masked_crates, Default::default()),
628 typarams: external_typarams,
629 aliases: Default::default(),
632 // Cache where all our extern crates are located
633 for &(n, ref e) in &krate.externs {
634 let src_root = match e.src {
635 FileName::Real(ref p) => match p.parent() {
636 Some(p) => p.to_path_buf(),
637 None => PathBuf::new(),
641 let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
642 cache.extern_locations.insert(n, (e.name.clone(), src_root,
643 extern_location(e, extern_url, &cx.dst)));
645 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
646 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
649 // Cache where all known primitives have their documentation located.
651 // Favor linking to as local extern as possible, so iterate all crates in
652 // reverse topological order.
653 for &(_, ref e) in krate.externs.iter().rev() {
654 for &(def_id, prim, _) in &e.primitives {
655 cache.primitive_locations.insert(prim, def_id);
658 for &(def_id, prim, _) in &krate.primitives {
659 cache.primitive_locations.insert(prim, def_id);
662 cache.stack.push(krate.name.clone());
663 krate = cache.fold_crate(krate);
665 for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
666 if cache.traits.contains_key(&trait_did) {
668 cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
673 // Build our search index
674 let index = build_index(&krate, &mut cache);
676 // Freeze the cache now that the index has been built. Put an Arc into TLS
677 // for future parallelization opportunities
678 let cache = Arc::new(cache);
679 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
680 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
682 write_shared(&cx, &krate, &*cache, index, &md_opts, diag)?;
684 // And finally render the whole crate's documentation
688 /// Build the search index from the collected metadata
689 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
690 let mut nodeid_to_pathid = FxHashMap::default();
691 let mut crate_items = Vec::with_capacity(cache.search_index.len());
692 let mut crate_paths = Vec::<Json>::new();
694 let Cache { ref mut search_index,
695 ref orphan_impl_items,
696 ref mut paths, .. } = *cache;
698 // Attach all orphan items to the type's definition if the type
699 // has since been learned.
700 for &(did, ref item) in orphan_impl_items {
701 if let Some(&(ref fqp, _)) = paths.get(&did) {
702 search_index.push(IndexItem {
704 name: item.name.clone().unwrap(),
705 path: fqp[..fqp.len() - 1].join("::"),
706 desc: plain_summary_line_short(item.doc_value()),
709 search_type: get_index_search_type(&item),
714 // Reduce `NodeId` in paths into smaller sequential numbers,
715 // and prune the paths that do not appear in the index.
716 let mut lastpath = String::new();
717 let mut lastpathid = 0usize;
719 for item in search_index {
720 item.parent_idx = item.parent.map(|nodeid| {
721 if nodeid_to_pathid.contains_key(&nodeid) {
722 *nodeid_to_pathid.get(&nodeid).unwrap()
724 let pathid = lastpathid;
725 nodeid_to_pathid.insert(nodeid, pathid);
728 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
729 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
734 // Omit the parent path if it is same to that of the prior item.
735 if lastpath == item.path {
738 lastpath = item.path.clone();
740 crate_items.push(item.to_json());
743 let crate_doc = krate.module.as_ref().map(|module| {
744 plain_summary_line_short(module.doc_value())
745 }).unwrap_or(String::new());
747 let mut crate_data = BTreeMap::new();
748 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
749 crate_data.insert("items".to_owned(), Json::Array(crate_items));
750 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
752 // Collect the index into a string
753 format!("searchIndex[{}] = {};",
754 as_json(&krate.name),
755 Json::Object(crate_data))
760 krate: &clean::Crate,
762 search_index: String,
763 options: &RenderOptions,
764 diag: &errors::Handler,
765 ) -> Result<(), Error> {
766 // Write out the shared files. Note that these are shared among all rustdoc
767 // docs placed in the output directory, so this needs to be a synchronized
768 // operation with respect to all other rustdocs running around.
769 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
771 // Add all the static files. These may already exist, but we just
772 // overwrite them anyway to make sure that they're fresh and up-to-date.
774 write_minify(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
775 static_files::RUSTDOC_CSS,
776 options.enable_minification)?;
777 write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
778 static_files::SETTINGS_CSS,
779 options.enable_minification)?;
780 write_minify(cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
781 static_files::NOSCRIPT_CSS,
782 options.enable_minification)?;
784 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
785 // then we'll run over the "official" styles.
786 let mut themes: FxHashSet<String> = FxHashSet::default();
788 for entry in &cx.shared.themes {
789 let content = try_err!(fs::read(&entry), &entry);
790 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
791 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
792 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
793 content.as_slice())?;
794 themes.insert(theme.to_owned());
797 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
798 static_files::BRUSH_SVG)?;
799 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
800 static_files::WHEEL_SVG)?;
801 write(cx.dst.join(&format!("down-arrow{}.svg", cx.shared.resource_suffix)),
802 static_files::DOWN_ARROW_SVG)?;
803 write_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
804 static_files::themes::LIGHT,
805 options.enable_minification)?;
806 themes.insert("light".to_owned());
807 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
808 static_files::themes::DARK,
809 options.enable_minification)?;
810 themes.insert("dark".to_owned());
812 let mut themes: Vec<&String> = themes.iter().collect();
814 // To avoid theme switch latencies as much as possible, we put everything theme related
815 // at the beginning of the html files into another js file.
816 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
818 r#"var themes = document.getElementById("theme-choices");
819 var themePicker = document.getElementById("theme-picker");
821 function switchThemeButtonState() {{
822 if (themes.style.display === "block") {{
823 themes.style.display = "none";
824 themePicker.style.borderBottomRightRadius = "3px";
825 themePicker.style.borderBottomLeftRadius = "3px";
827 themes.style.display = "block";
828 themePicker.style.borderBottomRightRadius = "0";
829 themePicker.style.borderBottomLeftRadius = "0";
833 function handleThemeButtonsBlur(e) {{
834 var active = document.activeElement;
835 var related = e.relatedTarget;
837 if (active.id !== "themePicker" &&
838 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
840 (related.id !== "themePicker" &&
841 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
842 switchThemeButtonState();
846 themePicker.onclick = switchThemeButtonState;
847 themePicker.onblur = handleThemeButtonsBlur;
848 [{}].forEach(function(item) {{
849 var but = document.createElement('button');
850 but.innerHTML = item;
851 but.onclick = function(el) {{
852 switchTheme(currentTheme, mainTheme, item);
854 but.onblur = handleThemeButtonsBlur;
855 themes.appendChild(but);
858 .map(|s| format!("\"{}\"", s))
859 .collect::<Vec<String>>()
860 .join(",")).as_bytes(),
863 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
864 static_files::MAIN_JS,
865 options.enable_minification)?;
866 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
867 static_files::SETTINGS_JS,
868 options.enable_minification)?;
869 if cx.shared.include_sources {
870 write_minify(cx.dst.join(&format!("source-script{}.js", cx.shared.resource_suffix)),
871 static_files::sidebar::SOURCE_SCRIPT,
872 options.enable_minification)?;
876 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
877 &format!("var resourcesSuffix = \"{}\";{}",
878 cx.shared.resource_suffix,
879 static_files::STORAGE_JS),
880 options.enable_minification)?;
883 if let Some(ref css) = cx.shared.css_file_extension {
884 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
885 if !options.enable_minification {
886 try_err!(fs::copy(css, out), css);
888 let buffer = try_err!(fs::read_to_string(css), css);
889 write_minify(out, &buffer, options.enable_minification)?;
892 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
893 static_files::NORMALIZE_CSS,
894 options.enable_minification)?;
895 write(cx.dst.join("FiraSans-Regular.woff"),
896 static_files::fira_sans::REGULAR)?;
897 write(cx.dst.join("FiraSans-Medium.woff"),
898 static_files::fira_sans::MEDIUM)?;
899 write(cx.dst.join("FiraSans-LICENSE.txt"),
900 static_files::fira_sans::LICENSE)?;
901 write(cx.dst.join("Heuristica-Italic.woff"),
902 static_files::heuristica::ITALIC)?;
903 write(cx.dst.join("Heuristica-LICENSE.txt"),
904 static_files::heuristica::LICENSE)?;
905 write(cx.dst.join("SourceSerifPro-Regular.woff"),
906 static_files::source_serif_pro::REGULAR)?;
907 write(cx.dst.join("SourceSerifPro-Bold.woff"),
908 static_files::source_serif_pro::BOLD)?;
909 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
910 static_files::source_serif_pro::LICENSE)?;
911 write(cx.dst.join("SourceCodePro-Regular.woff"),
912 static_files::source_code_pro::REGULAR)?;
913 write(cx.dst.join("SourceCodePro-Semibold.woff"),
914 static_files::source_code_pro::SEMIBOLD)?;
915 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
916 static_files::source_code_pro::LICENSE)?;
917 write(cx.dst.join("LICENSE-MIT.txt"),
918 static_files::LICENSE_MIT)?;
919 write(cx.dst.join("LICENSE-APACHE.txt"),
920 static_files::LICENSE_APACHE)?;
921 write(cx.dst.join("COPYRIGHT.txt"),
922 static_files::COPYRIGHT)?;
924 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
925 let mut ret = Vec::new();
926 let mut krates = Vec::new();
928 for line in BufReader::new(File::open(path)?).lines() {
930 if !line.starts_with(key) {
933 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
936 ret.push(line.to_string());
937 krates.push(line[key.len() + 2..].split('"')
939 .map(|s| s.to_owned())
940 .unwrap_or_else(|| String::new()));
946 fn show_item(item: &IndexItem, krate: &str) -> String {
947 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
948 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
949 if let Some(p) = item.parent_idx {
950 format!(",'parent':{}", p)
956 let dst = cx.dst.join("aliases.js");
958 let (mut all_aliases, _) = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
959 let mut w = try_err!(File::create(&dst), &dst);
960 let mut output = String::with_capacity(100);
961 for (alias, items) in &cache.aliases {
962 if items.is_empty() {
965 output.push_str(&format!("\"{}\":[{}],",
968 .map(|v| show_item(v, &krate.name))
972 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
974 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
975 for aliases in &all_aliases {
976 try_err!(writeln!(&mut w, "{}", aliases), &dst);
980 use std::ffi::OsString;
985 children: FxHashMap<OsString, Hierarchy>,
986 elems: FxHashSet<OsString>,
990 fn new(elem: OsString) -> Hierarchy {
993 children: FxHashMap::default(),
994 elems: FxHashSet::default(),
998 fn to_json_string(&self) -> String {
999 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
1000 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
1001 let mut files = self.elems.iter()
1002 .map(|s| format!("\"{}\"",
1004 .expect("invalid osstring conversion")))
1005 .collect::<Vec<_>>();
1006 files.sort_unstable_by(|a, b| a.cmp(b));
1007 // FIXME(imperio): we could avoid to generate "dirs" and "files" if they're empty.
1008 format!("{{\"name\":\"{name}\",\"dirs\":[{subs}],\"files\":[{files}]}}",
1009 name=self.elem.to_str().expect("invalid osstring conversion"),
1010 subs=subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(","),
1011 files=files.join(","))
1015 if cx.shared.include_sources {
1016 use std::path::Component;
1018 let mut hierarchy = Hierarchy::new(OsString::new());
1019 for source in cx.shared.local_sources.iter()
1020 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
1022 let mut h = &mut hierarchy;
1023 let mut elems = source.components()
1026 Component::Normal(s) => Some(s.to_owned()),
1032 let cur_elem = elems.next().expect("empty file path");
1033 if elems.peek().is_none() {
1034 h.elems.insert(cur_elem);
1037 let e = cur_elem.clone();
1038 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1039 h = h.children.get_mut(&cur_elem).expect("not found child");
1044 let dst = cx.dst.join("source-files.js");
1045 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1046 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
1048 hierarchy.to_json_string()));
1050 let mut w = try_err!(File::create(&dst), &dst);
1051 try_err!(writeln!(&mut w,
1052 "var N = null;var sourcesIndex = {{}};\n{}",
1053 all_sources.join("\n")),
1057 // Update the search index
1058 let dst = cx.dst.join("search-index.js");
1059 let (mut all_indexes, mut krates) = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
1060 all_indexes.push(search_index);
1062 // Sort the indexes by crate so the file will be generated identically even
1063 // with rustdoc running in parallel.
1065 let mut w = try_err!(File::create(&dst), &dst);
1066 try_err!(writeln!(&mut w, "var N = null;var searchIndex = {{}};"), &dst);
1067 for index in &all_indexes {
1068 try_err!(write_minify_replacer(&mut w, &*index, options.enable_minification,
1069 &[(minifier::js::Keyword::Null, "N")]),
1072 try_err!(writeln!(&mut w, "initSearch(searchIndex);addSearchOptions(searchIndex);"), &dst);
1074 if options.enable_index_page {
1075 if let Some(index_page) = options.index_page.clone() {
1076 let mut md_opts = options.clone();
1077 md_opts.output = cx.dst.clone();
1078 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1080 ::markdown::render(index_page, md_opts, diag);
1082 let dst = cx.dst.join("index.html");
1083 let mut w = BufWriter::new(try_err!(File::create(&dst), &dst));
1084 let page = layout::Page {
1085 title: "Index of crates",
1088 static_root_path: cx.shared.static_root_path.deref(),
1089 description: "List of crates",
1090 keywords: BASIC_KEYWORDS,
1091 resource_suffix: &cx.shared.resource_suffix,
1093 static_extra_scripts: &[],
1095 krates.push(krate.name.clone());
1099 let content = format!(
1101 <span class='in-band'>List of all crates</span>\
1102 </h1><ul class='mod'>{}</ul>",
1106 format!("<li><a href=\"{}/index.html\">{}</li>", s, s)
1108 .collect::<String>());
1109 try_err!(layout::render(&mut w, &cx.shared.layout,
1110 &page, &(""), &content,
1111 cx.shared.css_file_extension.is_some(),
1112 &cx.shared.themes), &dst);
1113 try_err!(w.flush(), &dst);
1117 // Update the list of all implementors for traits
1118 let dst = cx.dst.join("implementors");
1119 for (&did, imps) in &cache.implementors {
1120 // Private modules can leak through to this phase of rustdoc, which
1121 // could contain implementations for otherwise private types. In some
1122 // rare cases we could find an implementation for an item which wasn't
1123 // indexed, so we just skip this step in that case.
1125 // FIXME: this is a vague explanation for why this can't be a `get`, in
1126 // theory it should be...
1127 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1129 None => match cache.external_paths.get(&did) {
1135 let mut have_impls = false;
1136 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1138 // If the trait and implementation are in the same crate, then
1139 // there's no need to emit information about it (there's inlining
1140 // going on). If they're in different crates then the crate defining
1141 // the trait will be interested in our implementation.
1142 if imp.impl_item.def_id.krate == did.krate { continue }
1143 // If the implementation is from another crate then that crate
1145 if !imp.impl_item.def_id.is_local() { continue }
1147 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1148 as_json(&imp.inner_impl().to_string()),
1149 imp.inner_impl().synthetic,
1150 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1152 implementors.push_str("];");
1154 // Only create a js file if we have impls to add to it. If the trait is
1155 // documented locally though we always create the file to avoid dead
1157 if !have_impls && !cache.paths.contains_key(&did) {
1161 let mut mydst = dst.clone();
1162 for part in &remote_path[..remote_path.len() - 1] {
1165 try_err!(fs::create_dir_all(&mydst), &mydst);
1166 mydst.push(&format!("{}.{}.js",
1167 remote_item_type.css_class(),
1168 remote_path[remote_path.len() - 1]));
1170 let (mut all_implementors, _) = try_err!(collect(&mydst, &krate.name, "implementors"),
1172 all_implementors.push(implementors);
1173 // Sort the implementors by crate so the file will be generated
1174 // identically even with rustdoc running in parallel.
1175 all_implementors.sort();
1177 let mut f = try_err!(File::create(&mydst), &mydst);
1178 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1179 for implementor in &all_implementors {
1180 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1182 try_err!(writeln!(&mut f, "{}", r"
1183 if (window.register_implementors) {
1184 window.register_implementors(implementors);
1186 window.pending_implementors = implementors;
1189 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1194 fn render_sources(dst: &Path, scx: &mut SharedContext,
1195 krate: clean::Crate) -> Result<clean::Crate, Error> {
1196 info!("emitting source files");
1197 let dst = dst.join("src").join(&krate.name);
1198 try_err!(fs::create_dir_all(&dst), &dst);
1199 let mut folder = SourceCollector {
1203 Ok(folder.fold_crate(krate))
1206 /// Writes the entire contents of a string to a destination, not attempting to
1207 /// catch any errors.
1208 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1209 Ok(try_err!(fs::write(&dst, contents), &dst))
1212 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1213 if enable_minification {
1214 if dst.extension() == Some(&OsStr::new("css")) {
1215 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1216 write(dst, res.as_bytes())
1218 write(dst, minifier::js::minify(contents).as_bytes())
1221 write(dst, contents.as_bytes())
1225 fn write_minify_replacer<W: Write>(dst: &mut W,
1227 enable_minification: bool,
1228 keywords_to_replace: &[(minifier::js::Keyword, &str)])
1230 if enable_minification {
1232 minifier::js::minify_and_replace_keywords(contents, keywords_to_replace))
1234 writeln!(dst, "{}", contents)
1238 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1239 /// things like ".." to components which preserve the "top down" hierarchy of a
1240 /// static HTML tree. Each component in the cleaned path will be passed as an
1241 /// argument to `f`. The very last component of the path (ie the file name) will
1242 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1243 // FIXME (#9639): The closure should deal with &[u8] instead of &str
1244 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
1245 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1248 // make it relative, if possible
1249 let p = p.strip_prefix(src_root).unwrap_or(p);
1251 let mut iter = p.components().peekable();
1253 while let Some(c) = iter.next() {
1254 if !keep_filename && iter.peek().is_none() {
1259 Component::ParentDir => f("up"),
1260 Component::Normal(c) => f(c.to_str().unwrap()),
1266 /// Attempts to find where an external crate is located, given that we're
1267 /// rendering in to the specified source destination.
1268 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1271 // See if there's documentation generated into the local directory
1272 let local_location = dst.join(&e.name);
1273 if local_location.is_dir() {
1277 if let Some(url) = extern_url {
1278 let mut url = url.to_string();
1279 if !url.ends_with("/") {
1285 // Failing that, see if there's an attribute specifying where to find this
1287 e.attrs.lists("doc")
1288 .filter(|a| a.check_name("html_root_url"))
1289 .filter_map(|a| a.value_str())
1291 let mut url = url.to_string();
1292 if !url.ends_with("/") {
1296 }).next().unwrap_or(Unknown) // Well, at least we tried.
1299 impl<'a> DocFolder for SourceCollector<'a> {
1300 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1301 // If we're including source files, and we haven't seen this file yet,
1302 // then we need to render it out to the filesystem.
1303 if self.scx.include_sources
1304 // skip all invalid or macro spans
1305 && item.source.filename.is_real()
1306 // skip non-local items
1307 && item.def_id.is_local() {
1309 // If it turns out that we couldn't read this file, then we probably
1310 // can't read any of the files (generating html output from json or
1311 // something like that), so just don't include sources for the
1312 // entire crate. The other option is maintaining this mapping on a
1313 // per-file basis, but that's probably not worth it...
1315 .include_sources = match self.emit_source(&item.source.filename) {
1318 println!("warning: source code was requested to be rendered, \
1319 but processing `{}` had an error: {}",
1320 item.source.filename, e);
1321 println!(" skipping rendering of source code");
1326 self.fold_item_recur(item)
1330 impl<'a> SourceCollector<'a> {
1331 /// Renders the given filename into its corresponding HTML source file.
1332 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1333 let p = match *filename {
1334 FileName::Real(ref file) => file,
1337 if self.scx.local_sources.contains_key(&**p) {
1338 // We've already emitted this source
1342 let contents = fs::read_to_string(&p)?;
1344 // Remove the utf-8 BOM if any
1345 let contents = if contents.starts_with("\u{feff}") {
1351 // Create the intermediate directories
1352 let mut cur = self.dst.clone();
1353 let mut root_path = String::from("../../");
1354 let mut href = String::new();
1355 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1356 cur.push(component);
1357 fs::create_dir_all(&cur).unwrap();
1358 root_path.push_str("../");
1359 href.push_str(component);
1362 let mut fname = p.file_name()
1363 .expect("source has no filename")
1365 fname.push(".html");
1367 href.push_str(&fname.to_string_lossy());
1369 let mut w = BufWriter::new(File::create(&cur)?);
1370 let title = format!("{} -- source", cur.file_name().unwrap()
1371 .to_string_lossy());
1372 let desc = format!("Source to the Rust file `{}`.", filename);
1373 let page = layout::Page {
1375 css_class: "source",
1376 root_path: &root_path,
1377 static_root_path: self.scx.static_root_path.deref(),
1379 keywords: BASIC_KEYWORDS,
1380 resource_suffix: &self.scx.resource_suffix,
1381 extra_scripts: &["source-files"],
1382 static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
1384 layout::render(&mut w, &self.scx.layout,
1385 &page, &(""), &Source(contents),
1386 self.scx.css_file_extension.is_some(),
1389 self.scx.local_sources.insert(p.clone(), href);
1394 impl DocFolder for Cache {
1395 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1396 if item.def_id.is_local() {
1397 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
1400 // If this is a stripped module,
1401 // we don't want it or its children in the search index.
1402 let orig_stripped_mod = match item.inner {
1403 clean::StrippedItem(box clean::ModuleItem(..)) => {
1404 mem::replace(&mut self.stripped_mod, true)
1406 _ => self.stripped_mod,
1409 // If the impl is from a masked crate or references something from a
1410 // masked crate then remove it completely.
1411 if let clean::ImplItem(ref i) = item.inner {
1412 if self.masked_crates.contains(&item.def_id.krate) ||
1413 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1414 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1419 // Register any generics to their corresponding string. This is used
1420 // when pretty-printing types.
1421 if let Some(generics) = item.inner.generics() {
1422 self.generics(generics);
1425 // Propagate a trait method's documentation to all implementors of the
1427 if let clean::TraitItem(ref t) = item.inner {
1428 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1431 // Collect all the implementors of traits.
1432 if let clean::ImplItem(ref i) = item.inner {
1433 if let Some(did) = i.trait_.def_id() {
1434 if i.blanket_impl.is_none() {
1435 self.implementors.entry(did).or_default().push(Impl {
1436 impl_item: item.clone(),
1442 // Index this method for searching later on.
1443 if let Some(ref s) = item.name {
1444 let (parent, is_inherent_impl_item) = match item.inner {
1445 clean::StrippedItem(..) => ((None, None), false),
1446 clean::AssociatedConstItem(..) |
1447 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1448 // skip associated items in trait impls
1449 ((None, None), false)
1451 clean::AssociatedTypeItem(..) |
1452 clean::TyMethodItem(..) |
1453 clean::StructFieldItem(..) |
1454 clean::VariantItem(..) => {
1455 ((Some(*self.parent_stack.last().unwrap()),
1456 Some(&self.stack[..self.stack.len() - 1])),
1459 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1460 if self.parent_stack.is_empty() {
1461 ((None, None), false)
1463 let last = self.parent_stack.last().unwrap();
1465 let path = match self.paths.get(&did) {
1466 // The current stack not necessarily has correlation
1467 // for where the type was defined. On the other
1468 // hand, `paths` always has the right
1469 // information if present.
1470 Some(&(ref fqp, ItemType::Trait)) |
1471 Some(&(ref fqp, ItemType::Struct)) |
1472 Some(&(ref fqp, ItemType::Union)) |
1473 Some(&(ref fqp, ItemType::Enum)) =>
1474 Some(&fqp[..fqp.len() - 1]),
1475 Some(..) => Some(&*self.stack),
1478 ((Some(*last), path), true)
1481 _ => ((None, Some(&*self.stack)), false)
1485 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1486 debug_assert!(!item.is_stripped());
1488 // A crate has a module at its root, containing all items,
1489 // which should not be indexed. The crate-item itself is
1490 // inserted later on when serializing the search-index.
1491 if item.def_id.index != CRATE_DEF_INDEX {
1492 self.search_index.push(IndexItem {
1494 name: s.to_string(),
1495 path: path.join("::"),
1496 desc: plain_summary_line_short(item.doc_value()),
1499 search_type: get_index_search_type(&item),
1503 (Some(parent), None) if is_inherent_impl_item => {
1504 // We have a parent, but we don't know where they're
1505 // defined yet. Wait for later to index this item.
1506 self.orphan_impl_items.push((parent, item.clone()));
1512 // Keep track of the fully qualified path for this item.
1513 let pushed = match item.name {
1514 Some(ref n) if !n.is_empty() => {
1515 self.stack.push(n.to_string());
1522 clean::StructItem(..) | clean::EnumItem(..) |
1523 clean::TypedefItem(..) | clean::TraitItem(..) |
1524 clean::FunctionItem(..) | clean::ModuleItem(..) |
1525 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1526 clean::ConstantItem(..) | clean::StaticItem(..) |
1527 clean::UnionItem(..) | clean::ForeignTypeItem |
1528 clean::MacroItem(..) | clean::ProcMacroItem(..)
1529 if !self.stripped_mod => {
1530 // Re-exported items mean that the same id can show up twice
1531 // in the rustdoc ast that we're looking at. We know,
1532 // however, that a re-exported item doesn't show up in the
1533 // `public_items` map, so we can skip inserting into the
1534 // paths map if there was already an entry present and we're
1535 // not a public item.
1536 if !self.paths.contains_key(&item.def_id) ||
1537 self.access_levels.is_public(item.def_id)
1539 self.paths.insert(item.def_id,
1540 (self.stack.clone(), item.type_()));
1542 self.add_aliases(&item);
1544 // Link variants to their parent enum because pages aren't emitted
1545 // for each variant.
1546 clean::VariantItem(..) if !self.stripped_mod => {
1547 let mut stack = self.stack.clone();
1549 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1552 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1553 self.add_aliases(&item);
1554 self.paths.insert(item.def_id, (self.stack.clone(),
1561 // Maintain the parent stack
1562 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1563 let parent_pushed = match item.inner {
1564 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1565 clean::StructItem(..) | clean::UnionItem(..) => {
1566 self.parent_stack.push(item.def_id);
1567 self.parent_is_trait_impl = false;
1570 clean::ImplItem(ref i) => {
1571 self.parent_is_trait_impl = i.trait_.is_some();
1573 clean::ResolvedPath{ did, .. } => {
1574 self.parent_stack.push(did);
1578 let prim_did = t.primitive_type().and_then(|t| {
1579 self.primitive_locations.get(&t).cloned()
1583 self.parent_stack.push(did);
1594 // Once we've recursively found all the generics, hoard off all the
1595 // implementations elsewhere.
1596 let ret = self.fold_item_recur(item).and_then(|item| {
1597 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1598 // Figure out the id of this impl. This may map to a
1599 // primitive rather than always to a struct/enum.
1600 // Note: matching twice to restrict the lifetime of the `i` borrow.
1601 let mut dids = FxHashSet::default();
1602 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1604 clean::ResolvedPath { did, .. } |
1605 clean::BorrowedRef {
1606 type_: box clean::ResolvedPath { did, .. }, ..
1611 let did = t.primitive_type().and_then(|t| {
1612 self.primitive_locations.get(&t).cloned()
1615 if let Some(did) = did {
1621 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1622 for bound in generics {
1623 if let Some(did) = bound.def_id() {
1631 let impl_item = Impl {
1634 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
1636 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
1639 let trait_did = impl_item.trait_did().unwrap();
1640 self.orphan_trait_impls.push((trait_did, dids, impl_item));
1648 if pushed { self.stack.pop().unwrap(); }
1649 if parent_pushed { self.parent_stack.pop().unwrap(); }
1650 self.stripped_mod = orig_stripped_mod;
1651 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1657 fn generics(&mut self, generics: &clean::Generics) {
1658 for param in &generics.params {
1660 clean::GenericParamDefKind::Lifetime => {}
1661 clean::GenericParamDefKind::Type { did, .. } => {
1662 self.typarams.insert(did, param.name.clone());
1668 fn add_aliases(&mut self, item: &clean::Item) {
1669 if item.def_id.index == CRATE_DEF_INDEX {
1672 if let Some(ref item_name) = item.name {
1673 let path = self.paths.get(&item.def_id)
1674 .map(|p| p.0[..p.0.len() - 1].join("::"))
1675 .unwrap_or("std".to_owned());
1676 for alias in item.attrs.lists("doc")
1677 .filter(|a| a.check_name("alias"))
1678 .filter_map(|a| a.value_str()
1679 .map(|s| s.to_string().replace("\"", "")))
1680 .filter(|v| !v.is_empty())
1681 .collect::<FxHashSet<_>>()
1683 self.aliases.entry(alias)
1684 .or_insert(Vec::with_capacity(1))
1687 name: item_name.to_string(),
1689 desc: plain_summary_line_short(item.doc_value()),
1692 search_type: get_index_search_type(&item),
1699 #[derive(Debug, Eq, PartialEq, Hash)]
1706 fn new(mut url: String, name: String) -> ItemEntry {
1707 while url.starts_with('/') {
1717 impl fmt::Display for ItemEntry {
1718 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1719 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1723 impl PartialOrd for ItemEntry {
1724 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1725 Some(self.cmp(other))
1729 impl Ord for ItemEntry {
1730 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1731 self.name.cmp(&other.name)
1737 structs: FxHashSet<ItemEntry>,
1738 enums: FxHashSet<ItemEntry>,
1739 unions: FxHashSet<ItemEntry>,
1740 primitives: FxHashSet<ItemEntry>,
1741 traits: FxHashSet<ItemEntry>,
1742 macros: FxHashSet<ItemEntry>,
1743 functions: FxHashSet<ItemEntry>,
1744 typedefs: FxHashSet<ItemEntry>,
1745 existentials: FxHashSet<ItemEntry>,
1746 statics: FxHashSet<ItemEntry>,
1747 constants: FxHashSet<ItemEntry>,
1748 keywords: FxHashSet<ItemEntry>,
1749 attributes: FxHashSet<ItemEntry>,
1750 derives: FxHashSet<ItemEntry>,
1754 fn new() -> AllTypes {
1755 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1757 structs: new_set(100),
1758 enums: new_set(100),
1759 unions: new_set(100),
1760 primitives: new_set(26),
1761 traits: new_set(100),
1762 macros: new_set(100),
1763 functions: new_set(100),
1764 typedefs: new_set(100),
1765 existentials: new_set(100),
1766 statics: new_set(100),
1767 constants: new_set(100),
1768 keywords: new_set(100),
1769 attributes: new_set(100),
1770 derives: new_set(100),
1774 fn append(&mut self, item_name: String, item_type: &ItemType) {
1775 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1776 if let Some(name) = url.pop() {
1777 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1779 let name = url.join("::");
1781 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1782 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1783 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1784 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1785 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1786 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1787 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1788 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1789 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1790 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1791 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1792 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1793 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1800 fn print_entries(f: &mut fmt::Formatter, e: &FxHashSet<ItemEntry>, title: &str,
1801 class: &str) -> fmt::Result {
1803 let mut e: Vec<&ItemEntry> = e.iter().collect();
1805 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1809 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1814 impl fmt::Display for AllTypes {
1815 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1818 <span class='out-of-band'>\
1819 <span id='render-detail'>\
1820 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1821 [<span class='inner'>−</span>]\
1825 <span class='in-band'>List of all items</span>\
1827 print_entries(f, &self.structs, "Structs", "structs")?;
1828 print_entries(f, &self.enums, "Enums", "enums")?;
1829 print_entries(f, &self.unions, "Unions", "unions")?;
1830 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1831 print_entries(f, &self.traits, "Traits", "traits")?;
1832 print_entries(f, &self.macros, "Macros", "macros")?;
1833 print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1834 print_entries(f, &self.derives, "Derive Macros", "derives")?;
1835 print_entries(f, &self.functions, "Functions", "functions")?;
1836 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1837 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1838 print_entries(f, &self.statics, "Statics", "statics")?;
1839 print_entries(f, &self.constants, "Constants", "constants")
1844 struct Settings<'a> {
1845 // (id, explanation, default value)
1846 settings: Vec<(&'static str, &'static str, bool)>,
1851 impl<'a> Settings<'a> {
1852 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1855 ("item-declarations", "Auto-hide item declarations.", true),
1856 ("item-attributes", "Auto-hide item attributes.", true),
1857 ("trait-implementations", "Auto-hide trait implementations documentation",
1859 ("method-docs", "Auto-hide item methods' documentation", false),
1860 ("go-to-only-result", "Directly go to item in search if there is only one result",
1862 ("line-numbers", "Show line numbers on code examples", false),
1870 impl<'a> fmt::Display for Settings<'a> {
1871 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1874 <span class='in-band'>Rustdoc settings</span>\
1876 <div class='settings'>{}</div>\
1877 <script src='{}settings{}.js'></script>",
1878 self.settings.iter()
1879 .map(|(id, text, enabled)| {
1880 format!("<div class='setting-line'>\
1881 <label class='toggle'>\
1882 <input type='checkbox' id='{}' {}>\
1883 <span class='slider'></span>\
1886 </div>", id, if *enabled { " checked" } else { "" }, text)
1888 .collect::<String>(),
1895 fn derive_id(&self, id: String) -> String {
1896 let mut map = self.id_map.borrow_mut();
1900 /// String representation of how to get back to the root path of the 'doc/'
1901 /// folder in terms of a relative URL.
1902 fn root_path(&self) -> String {
1903 "../".repeat(self.current.len())
1906 /// Recurse in the directory structure and change the "root path" to make
1907 /// sure it always points to the top (relatively).
1908 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1909 F: FnOnce(&mut Context) -> T,
1912 panic!("Unexpected empty destination: {:?}", self.current);
1914 let prev = self.dst.clone();
1916 self.current.push(s);
1918 info!("Recursing into {}", self.dst.display());
1922 info!("Recursed; leaving {}", self.dst.display());
1924 // Go back to where we were at
1926 self.current.pop().unwrap();
1931 /// Main method for rendering a crate.
1933 /// This currently isn't parallelized, but it'd be pretty easy to add
1934 /// parallelization to this function.
1935 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1936 let mut item = match krate.module.take() {
1938 None => return Ok(()),
1940 let final_file = self.dst.join(&krate.name)
1942 let settings_file = self.dst.join("settings.html");
1944 let crate_name = krate.name.clone();
1945 item.name = Some(krate.name);
1947 let mut all = AllTypes::new();
1950 // Render the crate documentation
1951 let mut work = vec![(self.clone(), item)];
1953 while let Some((mut cx, item)) = work.pop() {
1954 cx.item(item, &mut all, |cx, item| {
1955 work.push((cx.clone(), item))
1960 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
1961 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1962 if !root_path.ends_with('/') {
1963 root_path.push('/');
1965 let mut page = layout::Page {
1966 title: "List of all items in this crate",
1969 static_root_path: self.shared.static_root_path.deref(),
1970 description: "List of all items in this crate",
1971 keywords: BASIC_KEYWORDS,
1972 resource_suffix: &self.shared.resource_suffix,
1974 static_extra_scripts: &[],
1976 let sidebar = if let Some(ref version) = cache().crate_version {
1977 format!("<p class='location'>Crate {}</p>\
1978 <div class='block version'>\
1981 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1982 crate_name, version)
1986 try_err!(layout::render(&mut w, &self.shared.layout,
1987 &page, &sidebar, &all,
1988 self.shared.css_file_extension.is_some(),
1989 &self.shared.themes),
1992 // Generating settings page.
1993 let settings = Settings::new("./", &self.shared.resource_suffix);
1994 page.title = "Rustdoc settings";
1995 page.description = "Settings of Rustdoc";
1996 page.root_path = "./";
1998 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
1999 let mut themes = self.shared.themes.clone();
2000 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
2001 themes.push(PathBuf::from("settings.css"));
2002 let mut layout = self.shared.layout.clone();
2003 layout.krate = String::new();
2004 layout.logo = String::new();
2005 layout.favicon = String::new();
2006 try_err!(layout::render(&mut w, &layout,
2007 &page, &sidebar, &settings,
2008 self.shared.css_file_extension.is_some(),
2015 fn render_item(&self,
2016 writer: &mut dyn io::Write,
2020 // A little unfortunate that this is done like this, but it sure
2021 // does make formatting *a lot* nicer.
2022 CURRENT_LOCATION_KEY.with(|slot| {
2023 *slot.borrow_mut() = self.current.clone();
2026 let mut title = if it.is_primitive() || it.is_keyword() {
2027 // No need to include the namespace for primitive types and keywords
2030 self.current.join("::")
2033 if !title.is_empty() {
2034 title.push_str("::");
2036 title.push_str(it.name.as_ref().unwrap());
2038 title.push_str(" - Rust");
2039 let tyname = it.type_().css_class();
2040 let desc = if it.is_crate() {
2041 format!("API documentation for the Rust `{}` crate.",
2042 self.shared.layout.krate)
2044 format!("API documentation for the Rust `{}` {} in crate `{}`.",
2045 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2047 let keywords = make_item_keywords(it);
2048 let page = layout::Page {
2050 root_path: &self.root_path(),
2051 static_root_path: self.shared.static_root_path.deref(),
2054 keywords: &keywords,
2055 resource_suffix: &self.shared.resource_suffix,
2057 static_extra_scripts: &[],
2061 self.id_map.borrow_mut().reset();
2062 self.id_map.borrow_mut().populate(initial_ids());
2065 if !self.render_redirect_pages {
2066 layout::render(writer, &self.shared.layout, &page,
2067 &Sidebar{ cx: self, item: it },
2068 &Item{ cx: self, item: it },
2069 self.shared.css_file_extension.is_some(),
2070 &self.shared.themes)?;
2072 let mut url = self.root_path();
2073 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2074 for name in &names[..names.len() - 1] {
2078 url.push_str(&item_path(ty, names.last().unwrap()));
2079 layout::redirect(writer, &url)?;
2085 /// Non-parallelized version of rendering an item. This will take the input
2086 /// item, render its contents, and then invoke the specified closure with
2087 /// all sub-items which need to be rendered.
2089 /// The rendering driver uses this closure to queue up more work.
2090 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2091 where F: FnMut(&mut Context, clean::Item),
2093 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2094 // if they contain impls for public types. These modules can also
2095 // contain items such as publicly re-exported structures.
2097 // External crates will provide links to these structures, so
2098 // these modules are recursed into, but not rendered normally
2099 // (a flag on the context).
2100 if !self.render_redirect_pages {
2101 self.render_redirect_pages = item.is_stripped();
2105 // modules are special because they add a namespace. We also need to
2106 // recurse into the items of the module as well.
2107 let name = item.name.as_ref().unwrap().to_string();
2108 let mut item = Some(item);
2109 self.recurse(name, |this| {
2110 let item = item.take().unwrap();
2112 let mut buf = Vec::new();
2113 this.render_item(&mut buf, &item, false).unwrap();
2114 // buf will be empty if the module is stripped and there is no redirect for it
2115 if !buf.is_empty() {
2116 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
2117 let joint_dst = this.dst.join("index.html");
2118 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2121 let m = match item.inner {
2122 clean::StrippedItem(box clean::ModuleItem(m)) |
2123 clean::ModuleItem(m) => m,
2127 // Render sidebar-items.js used throughout this module.
2128 if !this.render_redirect_pages {
2129 let items = this.build_sidebar_items(&m);
2130 let js_dst = this.dst.join("sidebar-items.js");
2131 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
2132 try_err!(write!(&mut js_out, "initSidebarItems({});",
2133 as_json(&items)), &js_dst);
2136 for item in m.items {
2142 } else if item.name.is_some() {
2143 let mut buf = Vec::new();
2144 self.render_item(&mut buf, &item, true).unwrap();
2145 // buf will be empty if the item is stripped and there is no redirect for it
2146 if !buf.is_empty() {
2147 let name = item.name.as_ref().unwrap();
2148 let item_type = item.type_();
2149 let file_name = &item_path(item_type, name);
2150 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
2151 let joint_dst = self.dst.join(file_name);
2152 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2154 if !self.render_redirect_pages {
2155 all.append(full_path(self, &item), &item_type);
2157 // Redirect from a sane URL using the namespace to Rustdoc's
2158 // URL for the page.
2159 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2160 let redir_dst = self.dst.join(redir_name);
2161 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
2164 let mut redirect_out = BufWriter::new(redirect_out);
2165 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2168 // If the item is a macro, redirect from the old macro URL (with !)
2169 // to the new one (without).
2170 if item_type == ItemType::Macro {
2171 let redir_name = format!("{}.{}!.html", item_type, name);
2172 let redir_dst = self.dst.join(redir_name);
2173 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
2174 let mut redirect_out = BufWriter::new(redirect_out);
2175 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2182 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2183 // BTreeMap instead of HashMap to get a sorted output
2184 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2185 for item in &m.items {
2186 if item.is_stripped() { continue }
2188 let short = item.type_().css_class();
2189 let myname = match item.name {
2191 Some(ref s) => s.to_string(),
2193 let short = short.to_string();
2194 map.entry(short).or_default()
2195 .push((myname, Some(plain_summary_line(item.doc_value()))));
2198 if self.shared.sort_modules_alphabetically {
2199 for (_, items) in &mut map {
2208 /// Generate a url appropriate for an `href` attribute back to the source of
2211 /// The url generated, when clicked, will redirect the browser back to the
2212 /// original source code.
2214 /// If `None` is returned, then a source link couldn't be generated. This
2215 /// may happen, for example, with externally inlined items where the source
2216 /// of their crate documentation isn't known.
2217 fn src_href(&self) -> Option<String> {
2218 let mut root = self.cx.root_path();
2220 let cache = cache();
2221 let mut path = String::new();
2223 // We can safely ignore macros from other libraries
2224 let file = match self.item.source.filename {
2225 FileName::Real(ref path) => path,
2229 let (krate, path) = if self.item.def_id.is_local() {
2230 if let Some(path) = self.cx.shared.local_sources.get(file) {
2231 (&self.cx.shared.layout.krate, path)
2236 let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2237 (ref name, ref src, Local) => (name, src),
2238 (ref name, ref src, Remote(ref s)) => {
2239 root = s.to_string();
2242 (_, _, Unknown) => return None,
2245 clean_srcpath(&src_root, file, false, |component| {
2246 path.push_str(component);
2249 let mut fname = file.file_name().expect("source has no filename")
2251 fname.push(".html");
2252 path.push_str(&fname.to_string_lossy());
2256 let lines = if self.item.source.loline == self.item.source.hiline {
2257 self.item.source.loline.to_string()
2259 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2261 Some(format!("{root}src/{krate}/{path}#{lines}",
2262 root = Escape(&root),
2269 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2270 f: F) -> fmt::Result
2271 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2272 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2277 impl<'a> fmt::Display for Item<'a> {
2278 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2279 debug_assert!(!self.item.is_stripped());
2280 // Write the breadcrumb trail header for the top
2281 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2282 if let Some(version) = self.item.stable_since() {
2283 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2287 "<span id='render-detail'>\
2288 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2289 title=\"collapse all docs\">\
2290 [<span class='inner'>−</span>]\
2296 // When this item is part of a `pub use` in a downstream crate, the
2297 // [src] link in the downstream documentation will actually come back to
2298 // this page, and this link will be auto-clicked. The `id` attribute is
2299 // used to find the link to auto-click.
2300 if self.cx.shared.include_sources && !self.item.is_primitive() {
2301 if let Some(l) = self.src_href() {
2302 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2303 l, "goto source code")?;
2307 write!(fmt, "</span>")?; // out-of-band
2308 write!(fmt, "<span class='in-band'>")?;
2309 match self.item.inner {
2310 clean::ModuleItem(ref m) => if m.is_crate {
2311 write!(fmt, "Crate ")?;
2313 write!(fmt, "Module ")?;
2315 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2316 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2317 clean::StructItem(..) => write!(fmt, "Struct ")?,
2318 clean::UnionItem(..) => write!(fmt, "Union ")?,
2319 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2320 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2321 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2322 clean::ProcMacroItem(ref mac) => match mac.kind {
2323 MacroKind::Bang => write!(fmt, "Macro ")?,
2324 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2325 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2326 MacroKind::ProcMacroStub => unreachable!(),
2328 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2329 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2330 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2331 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2332 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2333 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2335 // We don't generate pages for any other type.
2339 if !self.item.is_primitive() && !self.item.is_keyword() {
2340 let cur = &self.cx.current;
2341 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2342 for (i, component) in cur.iter().enumerate().take(amt) {
2343 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2344 "../".repeat(cur.len() - i - 1),
2348 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2349 self.item.type_(), self.item.name.as_ref().unwrap())?;
2351 write!(fmt, "</span></h1>")?; // in-band
2353 match self.item.inner {
2354 clean::ModuleItem(ref m) =>
2355 item_module(fmt, self.cx, self.item, &m.items),
2356 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2357 item_function(fmt, self.cx, self.item, f),
2358 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2359 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2360 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2361 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2362 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2363 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2364 clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2365 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2366 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2367 item_static(fmt, self.cx, self.item, i),
2368 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2369 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2370 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2371 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2373 // We don't generate pages for any other type.
2380 fn item_path(ty: ItemType, name: &str) -> String {
2382 ItemType::Module => format!("{}/index.html", name),
2383 _ => format!("{}.{}.html", ty.css_class(), name),
2387 fn full_path(cx: &Context, item: &clean::Item) -> String {
2388 let mut s = cx.current.join("::");
2390 s.push_str(item.name.as_ref().unwrap());
2394 fn shorter<'a>(s: Option<&'a str>) -> String {
2396 Some(s) => s.lines()
2397 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2399 (*line).chars().any(|chr|{
2400 !chr.is_whitespace()
2402 }).collect::<Vec<_>>().join("\n"),
2403 None => String::new()
2408 fn plain_summary_line(s: Option<&str>) -> String {
2409 let line = shorter(s).replace("\n", " ");
2410 markdown::plain_summary_line_full(&line[..], false)
2414 fn plain_summary_line_short(s: Option<&str>) -> String {
2415 let line = shorter(s).replace("\n", " ");
2416 markdown::plain_summary_line_full(&line[..], true)
2419 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2420 if let Some(ref name) = item.name {
2421 info!("Documenting {}", name);
2423 document_stability(w, cx, item, false)?;
2424 document_full(w, item, cx, "", false)?;
2428 /// Render md_text as markdown.
2429 fn render_markdown(w: &mut fmt::Formatter,
2432 links: Vec<(String, String)>,
2436 let mut ids = cx.id_map.borrow_mut();
2437 write!(w, "<div class='docblock{}'>{}{}</div>",
2438 if is_hidden { " hidden" } else { "" },
2440 Markdown(md_text, &links, RefCell::new(&mut ids),
2444 fn document_short(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, link: AssocItemLink,
2445 prefix: &str, is_hidden: bool) -> fmt::Result {
2446 if let Some(s) = item.doc_value() {
2447 let markdown = if s.contains('\n') {
2448 format!("{} [Read more]({})",
2449 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2451 plain_summary_line(Some(s))
2453 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden)?;
2454 } else if !prefix.is_empty() {
2455 write!(w, "<div class='docblock{}'>{}</div>",
2456 if is_hidden { " hidden" } else { "" },
2462 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2463 cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2464 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2465 debug!("Doc block: =====\n{}\n=====", s);
2466 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2467 } else if !prefix.is_empty() {
2468 write!(w, "<div class='docblock{}'>{}</div>",
2469 if is_hidden { " hidden" } else { "" },
2475 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2476 is_hidden: bool) -> fmt::Result {
2477 let stabilities = short_stability(item, cx);
2478 if !stabilities.is_empty() {
2479 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2480 for stability in stabilities {
2481 write!(w, "{}", stability)?;
2483 write!(w, "</div>")?;
2488 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2489 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2492 fn document_non_exhaustive(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
2493 if item.is_non_exhaustive() {
2494 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2495 if item.is_struct() { "struct" } else if item.is_enum() { "enum" } else { "type" }
2498 if item.is_struct() {
2499 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2500 Therefore, non-exhaustive structs cannot be constructed in external crates \
2501 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2502 matched against without a wildcard <code>..</code>; and \
2503 struct update syntax will not work.")?;
2504 } else if item.is_enum() {
2505 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2506 Therefore, when matching against variants of non-exhaustive enums, an \
2507 extra wildcard arm must be added to account for any future variants.")?;
2509 write!(w, "This type will require a wildcard arm in any match statements or \
2513 write!(w, "</div>")?;
2519 fn name_key(name: &str) -> (&str, u64, usize) {
2520 let end = name.bytes()
2521 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2523 // find number at end
2524 let split = name[0..end].bytes()
2525 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2527 // count leading zeroes
2529 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2531 // sort leading zeroes last
2532 let num_zeroes = after_zeroes - split;
2534 match name[split..end].parse() {
2535 Ok(n) => (&name[..split], n, num_zeroes),
2536 Err(_) => (name, 0, num_zeroes),
2540 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2541 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2542 document(w, cx, item)?;
2544 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2546 // the order of item types in the listing
2547 fn reorder(ty: ItemType) -> u8 {
2549 ItemType::ExternCrate => 0,
2550 ItemType::Import => 1,
2551 ItemType::Primitive => 2,
2552 ItemType::Module => 3,
2553 ItemType::Macro => 4,
2554 ItemType::Struct => 5,
2555 ItemType::Enum => 6,
2556 ItemType::Constant => 7,
2557 ItemType::Static => 8,
2558 ItemType::Trait => 9,
2559 ItemType::Function => 10,
2560 ItemType::Typedef => 12,
2561 ItemType::Union => 13,
2566 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2567 let ty1 = i1.type_();
2568 let ty2 = i2.type_();
2570 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2572 let s1 = i1.stability.as_ref().map(|s| s.level);
2573 let s2 = i2.stability.as_ref().map(|s| s.level);
2575 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2576 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2579 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2580 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2581 name_key(lhs).cmp(&name_key(rhs))
2584 if cx.shared.sort_modules_alphabetically {
2585 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2587 // This call is to remove re-export duplicates in cases such as:
2592 // pub trait Double { fn foo(); }
2596 // pub use foo::bar::*;
2600 // `Double` will appear twice in the generated docs.
2602 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2603 // can be identical even if the elements are different (mostly in imports).
2604 // So in case this is an import, we keep everything by adding a "unique id"
2605 // (which is the position in the vector).
2606 indices.dedup_by_key(|i| (items[*i].def_id,
2607 if items[*i].name.as_ref().is_some() {
2608 Some(full_path(cx, &items[*i]))
2613 if items[*i].is_import() {
2619 debug!("{:?}", indices);
2620 let mut curty = None;
2621 for &idx in &indices {
2622 let myitem = &items[idx];
2623 if myitem.is_stripped() {
2627 let myty = Some(myitem.type_());
2628 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2629 // Put `extern crate` and `use` re-exports in the same section.
2631 } else if myty != curty {
2632 if curty.is_some() {
2633 write!(w, "</table>")?;
2636 let (short, name) = item_ty_to_strs(&myty.unwrap());
2637 write!(w, "<h2 id='{id}' class='section-header'>\
2638 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2639 id = cx.derive_id(short.to_owned()), name = name)?;
2642 match myitem.inner {
2643 clean::ExternCrateItem(ref name, ref src) => {
2644 use html::format::HRef;
2648 write!(w, "<tr><td><code>{}extern crate {} as {};",
2649 VisSpace(&myitem.visibility),
2650 HRef::new(myitem.def_id, src),
2654 write!(w, "<tr><td><code>{}extern crate {};",
2655 VisSpace(&myitem.visibility),
2656 HRef::new(myitem.def_id, name))?
2659 write!(w, "</code></td></tr>")?;
2662 clean::ImportItem(ref import) => {
2663 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2664 VisSpace(&myitem.visibility), *import)?;
2668 if myitem.name.is_none() { continue }
2670 let unsafety_flag = match myitem.inner {
2671 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2672 if func.header.unsafety == hir::Unsafety::Unsafe => {
2673 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2678 let stab = myitem.stability_class();
2679 let add = if stab.is_some() {
2685 let doc_value = myitem.doc_value().unwrap_or("");
2687 <tr class='{stab}{add}module-item'>\
2688 <td><a class=\"{class}\" href=\"{href}\" \
2689 title='{title}'>{name}</a>{unsafety_flag}</td>\
2690 <td class='docblock-short'>{stab_tags}{docs}\
2693 name = *myitem.name.as_ref().unwrap(),
2694 stab_tags = stability_tags(myitem),
2695 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2696 class = myitem.type_(),
2698 stab = stab.unwrap_or_else(|| String::new()),
2699 unsafety_flag = unsafety_flag,
2700 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2701 title = [full_path(cx, myitem), myitem.type_().to_string()]
2703 .filter_map(|s| if !s.is_empty() {
2708 .collect::<Vec<_>>()
2715 if curty.is_some() {
2716 write!(w, "</table>")?;
2721 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2723 fn stability_tags(item: &clean::Item) -> String {
2724 let mut tags = String::new();
2726 // The trailing space after each tag is to space it properly against the rest of the docs.
2727 if item.deprecation().is_some() {
2728 tags.push_str("[<div class='stab deprecated'>Deprecated</div>] ");
2731 if let Some(stab) = item
2734 .filter(|s| s.level == stability::Unstable)
2736 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2737 tags.push_str("[<div class='stab internal'>Internal</div>] ");
2739 tags.push_str("[<div class='stab unstable'>Experimental</div>] ");
2743 if let Some(ref cfg) = item.attrs.cfg {
2744 tags.push_str(&format!(
2745 "[<div class='stab portability'>{}</div>] ",
2746 cfg.render_short_html()
2753 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2755 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2756 let mut stability = vec![];
2757 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2759 if let Some(Deprecation { since, note }) = &item.deprecation() {
2760 let mut message = if let Some(since) = since {
2761 if stability::deprecation_in_effect(since) {
2762 format!("Deprecated since {}", Escape(since))
2764 format!("Deprecating in {}", Escape(since))
2767 String::from("Deprecated")
2770 if let Some(note) = note {
2771 let mut ids = cx.id_map.borrow_mut();
2772 let html = MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes);
2773 message.push_str(&format!(": {}", html));
2775 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2778 if let Some(stab) = item
2781 .filter(|stab| stab.level == stability::Unstable)
2783 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2785 let mut message = if is_rustc_private {
2786 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2788 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2792 if let Some(feature) = stab.feature.as_ref() {
2793 let mut feature = format!("<code>{}</code>", Escape(&feature));
2794 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2795 feature.push_str(&format!(
2796 " <a href=\"{url}{issue}\">#{issue}</a>",
2802 message.push_str(&format!(" ({})", feature));
2805 if let Some(unstable_reason) = &stab.unstable_reason {
2806 // Provide a more informative message than the compiler help.
2807 let unstable_reason = if is_rustc_private {
2808 "This crate is being loaded from the sysroot, a permanently unstable location \
2809 for private compiler dependencies. It is not intended for general use. Prefer \
2810 using a public version of this crate from \
2811 [crates.io](https://crates.io) via [`Cargo.toml`]\
2812 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2817 let mut ids = cx.id_map.borrow_mut();
2819 "<details><summary>{}</summary>{}</details>",
2821 MarkdownHtml(&unstable_reason, RefCell::new(&mut ids), error_codes)
2825 let class = if is_rustc_private {
2830 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2833 if let Some(ref cfg) = item.attrs.cfg {
2834 stability.push(format!(
2835 "<div class='stab portability'>{}</div>",
2836 cfg.render_long_html()
2843 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2844 c: &clean::Constant) -> fmt::Result {
2845 write!(w, "<pre class='rust const'>")?;
2846 render_attributes(w, it)?;
2847 write!(w, "{vis}const \
2848 {name}: {typ}</pre>",
2849 vis = VisSpace(&it.visibility),
2850 name = it.name.as_ref().unwrap(),
2855 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2856 s: &clean::Static) -> fmt::Result {
2857 write!(w, "<pre class='rust static'>")?;
2858 render_attributes(w, it)?;
2859 write!(w, "{vis}static {mutability}\
2860 {name}: {typ}</pre>",
2861 vis = VisSpace(&it.visibility),
2862 mutability = MutableSpace(s.mutability),
2863 name = it.name.as_ref().unwrap(),
2868 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2869 f: &clean::Function) -> fmt::Result {
2870 let name_len = format!("{}{}{}{}{:#}fn {}{:#}",
2871 VisSpace(&it.visibility),
2872 ConstnessSpace(f.header.constness),
2873 UnsafetySpace(f.header.unsafety),
2874 AsyncSpace(f.header.asyncness),
2875 AbiSpace(f.header.abi),
2876 it.name.as_ref().unwrap(),
2878 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2879 render_attributes(w, it)?;
2881 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2882 {name}{generics}{decl}{where_clause}</pre>",
2883 vis = VisSpace(&it.visibility),
2884 constness = ConstnessSpace(f.header.constness),
2885 unsafety = UnsafetySpace(f.header.unsafety),
2886 asyncness = AsyncSpace(f.header.asyncness),
2887 abi = AbiSpace(f.header.abi),
2888 name = it.name.as_ref().unwrap(),
2889 generics = f.generics,
2890 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2899 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2900 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2901 // If there's already another implementor that has the same abbridged name, use the
2902 // full path, for example in `std::iter::ExactSizeIterator`
2903 let use_absolute = match implementor.inner_impl().for_ {
2904 clean::ResolvedPath { ref path, is_generic: false, .. } |
2905 clean::BorrowedRef {
2906 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2908 } => implementor_dups[path.last_name()].1,
2911 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
2912 implementor.impl_item.stable_since(), false, Some(use_absolute))?;
2916 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2918 containing_item: &clean::Item) -> fmt::Result {
2920 let did = i.trait_did().unwrap();
2921 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2922 render_impl(w, cx, i, assoc_link,
2923 RenderMode::Normal, containing_item.stable_since(), true, None)?;
2928 fn bounds(t_bounds: &[clean::GenericBound]) -> String {
2929 let mut bounds = String::new();
2930 let mut bounds_plain = String::new();
2931 if !t_bounds.is_empty() {
2932 if !bounds.is_empty() {
2934 bounds_plain.push(' ');
2936 bounds.push_str(": ");
2937 bounds_plain.push_str(": ");
2938 for (i, p) in t_bounds.iter().enumerate() {
2940 bounds.push_str(" + ");
2941 bounds_plain.push_str(" + ");
2943 bounds.push_str(&(*p).to_string());
2944 bounds_plain.push_str(&format!("{:#}", *p));
2950 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2951 let lhs = format!("{}", lhs.inner_impl());
2952 let rhs = format!("{}", rhs.inner_impl());
2954 // lhs and rhs are formatted as HTML, which may be unnecessary
2955 name_key(&lhs).cmp(&name_key(&rhs))
2959 w: &mut fmt::Formatter,
2964 let bounds = bounds(&t.bounds);
2965 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2966 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2967 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2968 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2970 // Output the trait definition
2971 wrap_into_docblock(w, |w| {
2972 write!(w, "<pre class='rust trait'>")?;
2973 render_attributes(w, it)?;
2974 write!(w, "{}{}{}trait {}{}{}",
2975 VisSpace(&it.visibility),
2976 UnsafetySpace(t.unsafety),
2977 if t.is_auto { "auto " } else { "" },
2978 it.name.as_ref().unwrap(),
2982 if !t.generics.where_predicates.is_empty() {
2983 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2988 if t.items.is_empty() {
2989 write!(w, "{{ }}")?;
2991 // FIXME: we should be using a derived_id for the Anchors here
2995 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2998 if !types.is_empty() && !consts.is_empty() {
3003 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3006 if !consts.is_empty() && !required.is_empty() {
3009 for (pos, m) in required.iter().enumerate() {
3011 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3014 if pos < required.len() - 1 {
3015 write!(w, "<div class='item-spacer'></div>")?;
3018 if !required.is_empty() && !provided.is_empty() {
3021 for (pos, m) in provided.iter().enumerate() {
3023 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3025 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3026 write!(w, ",\n {{ ... }}\n")?;
3029 write!(w, " {{ ... }}\n")?;
3032 if pos < provided.len() - 1 {
3033 write!(w, "<div class='item-spacer'></div>")?;
3041 // Trait documentation
3042 document(w, cx, it)?;
3044 fn write_small_section_header(
3045 w: &mut fmt::Formatter,
3048 extra_content: &str,
3051 <h2 id='{0}' class='small-section-header'>\
3052 {1}<a href='#{0}' class='anchor'></a>\
3053 </h2>{2}", id, title, extra_content)
3056 fn write_loading_content(w: &mut fmt::Formatter, extra_content: &str) -> fmt::Result {
3057 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3060 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
3062 let name = m.name.as_ref().unwrap();
3063 let item_type = m.type_();
3064 let id = cx.derive_id(format!("{}.{}", item_type, name));
3065 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3066 write!(w, "{extra}<h3 id='{id}' class='method'><code id='{ns_id}'>",
3067 extra = render_spotlight_traits(m)?,
3070 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3071 write!(w, "</code>")?;
3072 render_stability_since(w, m, t)?;
3073 write!(w, "</h3>")?;
3074 document(w, cx, m)?;
3078 if !types.is_empty() {
3079 write_small_section_header(w, "associated-types", "Associated Types",
3080 "<div class='methods'>")?;
3082 trait_item(w, cx, *t, it)?;
3084 write_loading_content(w, "</div>")?;
3087 if !consts.is_empty() {
3088 write_small_section_header(w, "associated-const", "Associated Constants",
3089 "<div class='methods'>")?;
3091 trait_item(w, cx, *t, it)?;
3093 write_loading_content(w, "</div>")?;
3096 // Output the documentation for each function individually
3097 if !required.is_empty() {
3098 write_small_section_header(w, "required-methods", "Required methods",
3099 "<div class='methods'>")?;
3100 for m in &required {
3101 trait_item(w, cx, *m, it)?;
3103 write_loading_content(w, "</div>")?;
3105 if !provided.is_empty() {
3106 write_small_section_header(w, "provided-methods", "Provided methods",
3107 "<div class='methods'>")?;
3108 for m in &provided {
3109 trait_item(w, cx, *m, it)?;
3111 write_loading_content(w, "</div>")?;
3114 // If there are methods directly on this trait object, render them here.
3115 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3117 let cache = cache();
3119 let mut synthetic_types = Vec::new();
3121 if let Some(implementors) = cache.implementors.get(&it.def_id) {
3122 // The DefId is for the first Type found with that name. The bool is
3123 // if any Types with the same name but different DefId have been found.
3124 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3125 for implementor in implementors {
3126 match implementor.inner_impl().for_ {
3127 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3128 clean::BorrowedRef {
3129 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3132 let &mut (prev_did, ref mut has_duplicates) =
3133 implementor_dups.entry(path.last_name()).or_insert((did, false));
3134 if prev_did != did {
3135 *has_duplicates = true;
3142 let (local, foreign) = implementors.iter()
3143 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3144 .map_or(true, |d| cache.paths.contains_key(&d)));
3147 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3148 .partition(|i| i.inner_impl().synthetic);
3150 synthetic.sort_by(compare_impl);
3151 concrete.sort_by(compare_impl);
3153 if !foreign.is_empty() {
3154 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3156 for implementor in foreign {
3157 let assoc_link = AssocItemLink::GotoSource(
3158 implementor.impl_item.def_id,
3159 &implementor.inner_impl().provided_trait_methods
3161 render_impl(w, cx, &implementor, assoc_link,
3162 RenderMode::Normal, implementor.impl_item.stable_since(), false,
3165 write_loading_content(w, "")?;
3168 write_small_section_header(w, "implementors", "Implementors",
3169 "<div class='item-list' id='implementors-list'>")?;
3170 for implementor in concrete {
3171 render_implementor(cx, implementor, w, &implementor_dups)?;
3173 write_loading_content(w, "</div>")?;
3176 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3177 "<div class='item-list' id='synthetic-implementors-list'>")?;
3178 for implementor in synthetic {
3179 synthetic_types.extend(
3180 collect_paths_for_type(implementor.inner_impl().for_.clone())
3182 render_implementor(cx, implementor, w, &implementor_dups)?;
3184 write_loading_content(w, "</div>")?;
3187 // even without any implementations to write in, we still want the heading and list, so the
3188 // implementors javascript file pulled in below has somewhere to write the impls into
3189 write_small_section_header(w, "implementors", "Implementors",
3190 "<div class='item-list' id='implementors-list'>")?;
3191 write_loading_content(w, "</div>")?;
3194 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3195 "<div class='item-list' id='synthetic-implementors-list'>")?;
3196 write_loading_content(w, "</div>")?;
3199 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3200 as_json(&synthetic_types))?;
3202 write!(w, r#"<script type="text/javascript" async
3203 src="{root_path}/implementors/{path}/{ty}.{name}.js">
3205 root_path = vec![".."; cx.current.len()].join("/"),
3206 path = if it.def_id.is_local() {
3207 cx.current.join("/")
3209 let (ref path, _) = cache.external_paths[&it.def_id];
3210 path[..path.len() - 1].join("/")
3212 ty = it.type_().css_class(),
3213 name = *it.name.as_ref().unwrap())?;
3217 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
3218 use html::item_type::ItemType::*;
3220 let name = it.name.as_ref().unwrap();
3221 let ty = match it.type_() {
3222 Typedef | AssociatedType => AssociatedType,
3226 let anchor = format!("#{}.{}", ty, name);
3228 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3229 AssocItemLink::Anchor(None) => anchor,
3230 AssocItemLink::GotoSource(did, _) => {
3231 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3236 fn assoc_const(w: &mut fmt::Formatter,
3239 _default: Option<&String>,
3240 link: AssocItemLink) -> fmt::Result {
3241 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3242 VisSpace(&it.visibility),
3243 naive_assoc_href(it, link),
3244 it.name.as_ref().unwrap(),
3249 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3250 bounds: &[clean::GenericBound],
3251 default: Option<&clean::Type>,
3252 link: AssocItemLink) -> fmt::Result {
3253 write!(w, "type <a href='{}' class=\"type\">{}</a>",
3254 naive_assoc_href(it, link),
3255 it.name.as_ref().unwrap())?;
3256 if !bounds.is_empty() {
3257 write!(w, ": {}", GenericBounds(bounds))?
3259 if let Some(default) = default {
3260 write!(w, " = {}", default)?;
3265 fn render_stability_since_raw<'a, T: fmt::Write>(
3267 ver: Option<&'a str>,
3268 containing_ver: Option<&'a str>,
3270 if let Some(v) = ver {
3271 if containing_ver != ver && v.len() > 0 {
3272 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>", v)?
3278 fn render_stability_since(w: &mut fmt::Formatter,
3280 containing_item: &clean::Item) -> fmt::Result {
3281 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3284 fn render_assoc_item(w: &mut fmt::Formatter,
3286 link: AssocItemLink,
3287 parent: ItemType) -> fmt::Result {
3288 fn method(w: &mut fmt::Formatter,
3290 header: hir::FnHeader,
3291 g: &clean::Generics,
3293 link: AssocItemLink,
3296 let name = meth.name.as_ref().unwrap();
3297 let anchor = format!("#{}.{}", meth.type_(), name);
3298 let href = match link {
3299 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3300 AssocItemLink::Anchor(None) => anchor,
3301 AssocItemLink::GotoSource(did, provided_methods) => {
3302 // We're creating a link from an impl-item to the corresponding
3303 // trait-item and need to map the anchored type accordingly.
3304 let ty = if provided_methods.contains(name) {
3310 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3313 let mut head_len = format!("{}{}{}{}{:#}fn {}{:#}",
3314 VisSpace(&meth.visibility),
3315 ConstnessSpace(header.constness),
3316 UnsafetySpace(header.unsafety),
3317 AsyncSpace(header.asyncness),
3318 AbiSpace(header.abi),
3321 let (indent, end_newline) = if parent == ItemType::Trait {
3327 render_attributes(w, meth)?;
3328 write!(w, "{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3329 {generics}{decl}{where_clause}",
3330 VisSpace(&meth.visibility),
3331 ConstnessSpace(header.constness),
3332 UnsafetySpace(header.unsafety),
3333 AsyncSpace(header.asyncness),
3334 AbiSpace(header.abi),
3343 where_clause = WhereClause {
3350 clean::StrippedItem(..) => Ok(()),
3351 clean::TyMethodItem(ref m) => {
3352 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3354 clean::MethodItem(ref m) => {
3355 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3357 clean::AssociatedConstItem(ref ty, ref default) => {
3358 assoc_const(w, item, ty, default.as_ref(), link)
3360 clean::AssociatedTypeItem(ref bounds, ref default) => {
3361 assoc_type(w, item, bounds, default.as_ref(), link)
3363 _ => panic!("render_assoc_item called on non-associated-item")
3367 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3368 s: &clean::Struct) -> fmt::Result {
3369 wrap_into_docblock(w, |w| {
3370 write!(w, "<pre class='rust struct'>")?;
3371 render_attributes(w, it)?;
3382 document(w, cx, it)?;
3383 let mut fields = s.fields.iter().filter_map(|f| {
3385 clean::StructFieldItem(ref ty) => Some((f, ty)),
3389 if let doctree::Plain = s.struct_type {
3390 if fields.peek().is_some() {
3391 write!(w, "<h2 id='fields' class='fields small-section-header'>
3392 Fields{}<a href='#fields' class='anchor'></a></h2>",
3393 document_non_exhaustive_header(it))?;
3394 document_non_exhaustive(w, it)?;
3395 for (field, ty) in fields {
3396 let id = cx.derive_id(format!("{}.{}",
3397 ItemType::StructField,
3398 field.name.as_ref().unwrap()));
3399 let ns_id = cx.derive_id(format!("{}.{}",
3400 field.name.as_ref().unwrap(),
3401 ItemType::StructField.name_space()));
3402 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3403 <a href=\"#{id}\" class=\"anchor field\"></a>\
3404 <code id=\"{ns_id}\">{name}: {ty}</code>\
3406 item_type = ItemType::StructField,
3409 name = field.name.as_ref().unwrap(),
3411 if let Some(stability_class) = field.stability_class() {
3412 write!(w, "<span class='stab {stab}'></span>",
3413 stab = stability_class)?;
3415 document(w, cx, field)?;
3419 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3422 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3423 s: &clean::Union) -> fmt::Result {
3424 wrap_into_docblock(w, |w| {
3425 write!(w, "<pre class='rust union'>")?;
3426 render_attributes(w, it)?;
3436 document(w, cx, it)?;
3437 let mut fields = s.fields.iter().filter_map(|f| {
3439 clean::StructFieldItem(ref ty) => Some((f, ty)),
3443 if fields.peek().is_some() {
3444 write!(w, "<h2 id='fields' class='fields small-section-header'>
3445 Fields<a href='#fields' class='anchor'></a></h2>")?;
3446 for (field, ty) in fields {
3447 let name = field.name.as_ref().expect("union field name");
3448 let id = format!("{}.{}", ItemType::StructField, name);
3449 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3450 <a href=\"#{id}\" class=\"anchor field\"></a>\
3451 <span class='invisible'><code>{name}: {ty}</code></span>\
3455 shortty = ItemType::StructField,
3457 if let Some(stability_class) = field.stability_class() {
3458 write!(w, "<span class='stab {stab}'></span>",
3459 stab = stability_class)?;
3461 document(w, cx, field)?;
3464 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3467 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3468 e: &clean::Enum) -> fmt::Result {
3469 wrap_into_docblock(w, |w| {
3470 write!(w, "<pre class='rust enum'>")?;
3471 render_attributes(w, it)?;
3472 write!(w, "{}enum {}{}{}",
3473 VisSpace(&it.visibility),
3474 it.name.as_ref().unwrap(),
3476 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3477 if e.variants.is_empty() && !e.variants_stripped {
3478 write!(w, " {{}}")?;
3480 write!(w, " {{\n")?;
3481 for v in &e.variants {
3483 let name = v.name.as_ref().unwrap();
3485 clean::VariantItem(ref var) => {
3487 clean::VariantKind::CLike => write!(w, "{}", name)?,
3488 clean::VariantKind::Tuple(ref tys) => {
3489 write!(w, "{}(", name)?;
3490 for (i, ty) in tys.iter().enumerate() {
3492 write!(w, ", ")?
3494 write!(w, "{}", *ty)?;
3498 clean::VariantKind::Struct(ref s) => {
3514 if e.variants_stripped {
3515 write!(w, " // some variants omitted\n")?;
3522 document(w, cx, it)?;
3523 if !e.variants.is_empty() {
3524 write!(w, "<h2 id='variants' class='variants small-section-header'>
3525 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3526 document_non_exhaustive_header(it))?;
3527 document_non_exhaustive(w, it)?;
3528 for variant in &e.variants {
3529 let id = cx.derive_id(format!("{}.{}",
3531 variant.name.as_ref().unwrap()));
3532 let ns_id = cx.derive_id(format!("{}.{}",
3533 variant.name.as_ref().unwrap(),
3534 ItemType::Variant.name_space()));
3535 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3536 <a href=\"#{id}\" class=\"anchor field\"></a>\
3537 <code id='{ns_id}'>{name}",
3540 name = variant.name.as_ref().unwrap())?;
3541 if let clean::VariantItem(ref var) = variant.inner {
3542 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3544 for (i, ty) in tys.iter().enumerate() {
3546 write!(w, ", ")?;
3548 write!(w, "{}", *ty)?;
3553 write!(w, "</code></span>")?;
3554 document(w, cx, variant)?;
3556 use clean::{Variant, VariantKind};
3557 if let clean::VariantItem(Variant {
3558 kind: VariantKind::Struct(ref s)
3559 }) = variant.inner {
3560 let variant_id = cx.derive_id(format!("{}.{}.fields",
3562 variant.name.as_ref().unwrap()));
3563 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3565 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3566 name = variant.name.as_ref().unwrap())?;
3567 for field in &s.fields {
3568 use clean::StructFieldItem;
3569 if let StructFieldItem(ref ty) = field.inner {
3570 let id = cx.derive_id(format!("variant.{}.field.{}",
3571 variant.name.as_ref().unwrap(),
3572 field.name.as_ref().unwrap()));
3573 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3574 variant.name.as_ref().unwrap(),
3575 ItemType::Variant.name_space(),
3576 field.name.as_ref().unwrap(),
3577 ItemType::StructField.name_space()));
3578 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3579 <a href=\"#{id}\" class=\"anchor field\"></a>\
3580 <code id='{ns_id}'>{f}: {t}\
3584 f = field.name.as_ref().unwrap(),
3586 document(w, cx, field)?;
3589 write!(w, "</div></span>")?;
3591 render_stability_since(w, variant, it)?;
3594 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3598 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3599 let name = attr.name();
3602 Some(name.to_string())
3603 } else if let Some(v) = attr.value_str() {
3604 Some(format!("{} = {:?}", name, v.as_str()))
3605 } else if let Some(values) = attr.meta_item_list() {
3606 let display: Vec<_> = values.iter().filter_map(|attr| {
3607 attr.meta_item().and_then(|mi| render_attribute(mi))
3610 if display.len() > 0 {
3611 Some(format!("{}({})", name, display.join(", ")))
3620 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3627 "unsafe_destructor_blind_to_params",
3631 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3632 let mut attrs = String::new();
3634 for attr in &it.attrs.other_attrs {
3635 let name = attr.name();
3636 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3639 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3640 attrs.push_str(&format!("#[{}]\n", s));
3643 if attrs.len() > 0 {
3644 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3649 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3650 g: Option<&clean::Generics>,
3651 ty: doctree::StructType,
3652 fields: &[clean::Item],
3654 structhead: bool) -> fmt::Result {
3656 VisSpace(&it.visibility),
3657 if structhead {"struct "} else {""},
3658 it.name.as_ref().unwrap())?;
3659 if let Some(g) = g {
3664 if let Some(g) = g {
3665 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3667 let mut has_visible_fields = false;
3669 for field in fields {
3670 if let clean::StructFieldItem(ref ty) = field.inner {
3671 write!(w, "\n{} {}{}: {},",
3673 VisSpace(&field.visibility),
3674 field.name.as_ref().unwrap(),
3676 has_visible_fields = true;
3680 if has_visible_fields {
3681 if it.has_stripped_fields().unwrap() {
3682 write!(w, "\n{} // some fields omitted", tab)?;
3684 write!(w, "\n{}", tab)?;
3685 } else if it.has_stripped_fields().unwrap() {
3686 // If there are no visible fields we can just display
3687 // `{ /* fields omitted */ }` to save space.
3688 write!(w, " /* fields omitted */ ")?;
3694 for (i, field) in fields.iter().enumerate() {
3699 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3702 clean::StructFieldItem(ref ty) => {
3703 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3709 if let Some(g) = g {
3710 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3715 // Needed for PhantomData.
3716 if let Some(g) = g {
3717 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3725 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3726 g: Option<&clean::Generics>,
3727 fields: &[clean::Item],
3729 structhead: bool) -> fmt::Result {
3731 VisSpace(&it.visibility),
3732 if structhead {"union "} else {""},
3733 it.name.as_ref().unwrap())?;
3734 if let Some(g) = g {
3735 write!(w, "{}", g)?;
3736 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3739 write!(w, " {{\n{}", tab)?;
3740 for field in fields {
3741 if let clean::StructFieldItem(ref ty) = field.inner {
3742 write!(w, " {}{}: {},\n{}",
3743 VisSpace(&field.visibility),
3744 field.name.as_ref().unwrap(),
3750 if it.has_stripped_fields().unwrap() {
3751 write!(w, " // some fields omitted\n{}", tab)?;
3757 #[derive(Copy, Clone)]
3758 enum AssocItemLink<'a> {
3759 Anchor(Option<&'a str>),
3760 GotoSource(DefId, &'a FxHashSet<String>),
3763 impl<'a> AssocItemLink<'a> {
3764 fn anchor(&self, id: &'a String) -> Self {
3766 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3767 ref other => *other,
3772 enum AssocItemRender<'a> {
3774 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3777 #[derive(Copy, Clone, PartialEq)]
3780 ForDeref { mut_: bool },
3783 fn render_assoc_items(w: &mut fmt::Formatter,
3785 containing_item: &clean::Item,
3787 what: AssocItemRender) -> fmt::Result {
3789 let v = match c.impls.get(&it) {
3791 None => return Ok(()),
3793 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3794 i.inner_impl().trait_.is_none()
3796 if !non_trait.is_empty() {
3797 let render_mode = match what {
3798 AssocItemRender::All => {
3800 <h2 id='methods' class='small-section-header'>\
3801 Methods<a href='#methods' class='anchor'></a>\
3806 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3808 <h2 id='deref-methods' class='small-section-header'>\
3809 Methods from {}<Target = {}>\
3810 <a href='#deref-methods' class='anchor'></a>\
3813 RenderMode::ForDeref { mut_: deref_mut_ }
3816 for i in &non_trait {
3817 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3818 containing_item.stable_since(), true, None)?;
3821 if let AssocItemRender::DerefFor { .. } = what {
3824 if !traits.is_empty() {
3825 let deref_impl = traits.iter().find(|t| {
3826 t.inner_impl().trait_.def_id() == c.deref_trait_did
3828 if let Some(impl_) = deref_impl {
3829 let has_deref_mut = traits.iter().find(|t| {
3830 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3832 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3835 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3837 .partition(|t| t.inner_impl().synthetic);
3838 let (blanket_impl, concrete) = concrete
3840 .partition(|t| t.inner_impl().blanket_impl.is_some());
3842 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3844 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3845 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3846 render_impls(self.0, fmt, &self.1, self.2)
3850 let impls = RendererStruct(cx, concrete, containing_item).to_string();
3851 if !impls.is_empty() {
3853 <h2 id='implementations' class='small-section-header'>\
3854 Trait Implementations<a href='#implementations' class='anchor'></a>\
3856 <div id='implementations-list'>{}</div>", impls)?;
3859 if !synthetic.is_empty() {
3861 <h2 id='synthetic-implementations' class='small-section-header'>\
3862 Auto Trait Implementations\
3863 <a href='#synthetic-implementations' class='anchor'></a>\
3865 <div id='synthetic-implementations-list'>\
3867 render_impls(cx, w, &synthetic, containing_item)?;
3868 write!(w, "</div>")?;
3871 if !blanket_impl.is_empty() {
3873 <h2 id='blanket-implementations' class='small-section-header'>\
3874 Blanket Implementations\
3875 <a href='#blanket-implementations' class='anchor'></a>\
3877 <div id='blanket-implementations-list'>\
3879 render_impls(cx, w, &blanket_impl, containing_item)?;
3880 write!(w, "</div>")?;
3886 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3887 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3888 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3889 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3891 clean::TypedefItem(ref t, true) => Some(&t.type_),
3894 }).next().expect("Expected associated type binding");
3895 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3896 deref_mut_: deref_mut };
3897 if let Some(did) = target.def_id() {
3898 render_assoc_items(w, cx, container_item, did, what)
3900 if let Some(prim) = target.primitive_type() {
3901 if let Some(&did) = cache().primitive_locations.get(&prim) {
3902 render_assoc_items(w, cx, container_item, did, what)?;
3909 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3910 let self_type_opt = match item.inner {
3911 clean::MethodItem(ref method) => method.decl.self_type(),
3912 clean::TyMethodItem(ref method) => method.decl.self_type(),
3916 if let Some(self_ty) = self_type_opt {
3917 let (by_mut_ref, by_box, by_value) = match self_ty {
3918 SelfTy::SelfBorrowed(_, mutability) |
3919 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3920 (mutability == Mutability::Mutable, false, false)
3922 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3923 (false, Some(did) == cache().owned_box_did, false)
3925 SelfTy::SelfValue => (false, false, true),
3926 _ => (false, false, false),
3929 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3935 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3936 let mut out = String::new();
3939 clean::FunctionItem(clean::Function { ref decl, .. }) |
3940 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3941 clean::MethodItem(clean::Method { ref decl, .. }) |
3942 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3943 out = spotlight_decl(decl)?;
3951 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3952 let mut out = String::new();
3953 let mut trait_ = String::new();
3955 if let Some(did) = decl.output.def_id() {
3957 if let Some(impls) = c.impls.get(&did) {
3959 let impl_ = i.inner_impl();
3960 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3963 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3964 <code class=\"content\">",
3966 trait_.push_str(&impl_.for_.to_string());
3969 //use the "where" class here to make it small
3970 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3971 let t_did = impl_.trait_.def_id().unwrap();
3972 for it in &impl_.items {
3973 if let clean::TypedefItem(ref tydef, _) = it.inner {
3974 out.push_str("<span class=\"where fmt-newline\"> ");
3975 assoc_type(&mut out, it, &[],
3977 AssocItemLink::GotoSource(t_did, &FxHashSet::default()))?;
3978 out.push_str(";</span>");
3986 if !out.is_empty() {
3987 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3988 <span class='tooltiptext'>Important traits for {}</span></div>\
3989 <div class=\"content hidden\">",
3991 out.push_str("</code></div></div>");
3997 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3998 render_mode: RenderMode, outer_version: Option<&str>,
3999 show_def_docs: bool, use_absolute: Option<bool>) -> fmt::Result {
4000 if render_mode == RenderMode::Normal {
4001 let id = cx.derive_id(match i.inner_impl().trait_ {
4002 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
4003 None => "impl".to_string(),
4005 if let Some(use_absolute) = use_absolute {
4006 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
4007 <tbody><tr><td><code>", id)?;
4008 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
4010 for it in &i.inner_impl().items {
4011 if let clean::TypedefItem(ref tydef, _) = it.inner {
4012 write!(w, "<span class=\"where fmt-newline\"> ")?;
4013 assoc_type(w, it, &vec![], Some(&tydef.type_),
4014 AssocItemLink::Anchor(None))?;
4015 write!(w, ";</span>")?;
4019 write!(w, "</code>")?;
4021 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
4022 <tbody><tr><td><code>{}</code>",
4023 id, i.inner_impl())?;
4025 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4026 write!(w, "</td><td><span class='out-of-band'>")?;
4027 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4028 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4029 write!(w, "<div class='ghost'></div>")?;
4030 render_stability_since_raw(w, since, outer_version)?;
4031 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4032 l, "goto source code")?;
4034 render_stability_since_raw(w, since, outer_version)?;
4036 write!(w, "</span></td></tr></tbody></table></span></h3>")?;
4037 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4038 let mut ids = cx.id_map.borrow_mut();
4039 write!(w, "<div class='docblock'>{}</div>",
4040 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids), cx.codes))?;
4044 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
4045 link: AssocItemLink, render_mode: RenderMode,
4046 is_default_item: bool, outer_version: Option<&str>,
4047 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4048 let item_type = item.type_();
4049 let name = item.name.as_ref().unwrap();
4051 let render_method_item: bool = match render_mode {
4052 RenderMode::Normal => true,
4053 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4056 let (is_hidden, extra_class) = if trait_.is_none() ||
4057 item.doc_value().is_some() ||
4058 item.inner.is_associated() {
4064 clean::MethodItem(clean::Method { ref decl, .. }) |
4065 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4066 // Only render when the method is not static or we allow static methods
4067 if render_method_item {
4068 let id = cx.derive_id(format!("{}.{}", item_type, name));
4069 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4070 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4071 write!(w, "{}", spotlight_decl(decl)?)?;
4072 write!(w, "<table id='{}' class='table-display'><tbody><tr><td><code>", ns_id)?;
4073 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4074 write!(w, "</code>")?;
4075 if let Some(l) = (Item { cx, item }).src_href() {
4076 write!(w, "</td><td><span class='out-of-band'>")?;
4077 write!(w, "<div class='ghost'></div>")?;
4078 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4079 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a></span>",
4080 l, "goto source code")?;
4082 write!(w, "</td><td>")?;
4083 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4085 write!(w, "</td></tr></tbody></table></h4>")?;
4088 clean::TypedefItem(ref tydef, _) => {
4089 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name));
4090 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4091 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4092 write!(w, "<code id='{}'>", ns_id)?;
4093 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
4094 write!(w, "</code></h4>")?;
4096 clean::AssociatedConstItem(ref ty, ref default) => {
4097 let mut version = String::new();
4099 render_stability_since_raw(&mut version, item.stable_since(), outer_version)?;
4101 let id = cx.derive_id(format!("{}.{}", item_type, name));
4102 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4103 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4104 if !version.is_empty() {
4105 write!(w, "<table id='{}' class='table-display'><tbody><tr><td><code>", ns_id)?;
4107 write!(w, "<code id='{}'>", ns_id)?;
4109 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
4110 if !version.is_empty() {
4111 write!(w, "</code>")?;
4113 let src = if let Some(l) = (Item { cx, item }).src_href() {
4114 if !version.is_empty() {
4115 write!(w, "</td><td><span class='out-of-band'>")?;
4116 write!(w, "<div class='ghost'></div>{}", version)?;
4118 format!("<a class='srclink' href='{}' title='{}'>[src]</a>",
4119 l, "goto source code")
4121 if !version.is_empty() {
4122 write!(w, "</td><td>{}", version)?;
4126 if version.is_empty() {
4127 write!(w, "</code>{}</h4>", src)?;
4129 write!(w, "{}</span></td></tr></tbody></table></h4>", src)?;
4132 clean::AssociatedTypeItem(ref bounds, ref default) => {
4133 let id = cx.derive_id(format!("{}.{}", item_type, name));
4134 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4135 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4136 write!(w, "<code id='{}'>", ns_id)?;
4137 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
4138 write!(w, "</code></h4>")?;
4140 clean::StrippedItem(..) => return Ok(()),
4141 _ => panic!("can't make docs for trait item with name {:?}", item.name)
4144 if render_method_item || render_mode == RenderMode::Normal {
4145 if !is_default_item {
4146 if let Some(t) = trait_ {
4147 // The trait item may have been stripped so we might not
4148 // find any documentation or stability for it.
4149 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4150 // We need the stability of the item from the trait
4151 // because impls can't have a stability.
4152 document_stability(w, cx, it, is_hidden)?;
4153 if item.doc_value().is_some() {
4154 document_full(w, item, cx, "", is_hidden)?;
4155 } else if show_def_docs {
4156 // In case the item isn't documented,
4157 // provide short documentation from the trait.
4158 document_short(w, cx, it, link, "", is_hidden)?;
4162 document_stability(w, cx, item, is_hidden)?;
4164 document_full(w, item, cx, "", is_hidden)?;
4168 document_stability(w, cx, item, is_hidden)?;
4170 document_short(w, cx, item, link, "", is_hidden)?;
4177 let traits = &cache().traits;
4178 let trait_ = i.trait_did().map(|did| &traits[&did]);
4180 write!(w, "<div class='impl-items'>")?;
4181 for trait_item in &i.inner_impl().items {
4182 doc_impl_item(w, cx, trait_item, link, render_mode,
4183 false, outer_version, trait_, show_def_docs)?;
4186 fn render_default_items(w: &mut fmt::Formatter,
4190 render_mode: RenderMode,
4191 outer_version: Option<&str>,
4192 show_def_docs: bool) -> fmt::Result {
4193 for trait_item in &t.items {
4194 let n = trait_item.name.clone();
4195 if i.items.iter().find(|m| m.name == n).is_some() {
4198 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4199 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4201 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4202 outer_version, None, show_def_docs)?;
4207 // If we've implemented a trait, then also emit documentation for all
4208 // default items which weren't overridden in the implementation block.
4209 if let Some(t) = trait_ {
4210 render_default_items(w, cx, t, &i.inner_impl(),
4211 render_mode, outer_version, show_def_docs)?;
4213 write!(w, "</div>")?;
4218 fn item_existential(
4219 w: &mut fmt::Formatter,
4222 t: &clean::Existential,
4224 write!(w, "<pre class='rust existential'>")?;
4225 render_attributes(w, it)?;
4226 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4227 it.name.as_ref().unwrap(),
4229 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4230 bounds = bounds(&t.bounds))?;
4232 document(w, cx, it)?;
4234 // Render any items associated directly to this alias, as otherwise they
4235 // won't be visible anywhere in the docs. It would be nice to also show
4236 // associated items from the aliased type (see discussion in #32077), but
4237 // we need #14072 to make sense of the generics.
4238 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4241 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4242 t: &clean::Typedef) -> fmt::Result {
4243 write!(w, "<pre class='rust typedef'>")?;
4244 render_attributes(w, it)?;
4245 write!(w, "type {}{}{where_clause} = {type_};</pre>",
4246 it.name.as_ref().unwrap(),
4248 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4251 document(w, cx, it)?;
4253 // Render any items associated directly to this alias, as otherwise they
4254 // won't be visible anywhere in the docs. It would be nice to also show
4255 // associated items from the aliased type (see discussion in #32077), but
4256 // we need #14072 to make sense of the generics.
4257 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4260 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
4261 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4262 render_attributes(w, it)?;
4265 " {}type {};\n}}</pre>",
4266 VisSpace(&it.visibility),
4267 it.name.as_ref().unwrap(),
4270 document(w, cx, it)?;
4272 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4275 impl<'a> fmt::Display for Sidebar<'a> {
4276 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4279 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4281 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4282 || it.is_enum() || it.is_mod() || it.is_typedef() {
4283 write!(fmt, "<p class='location'>{}{}</p>",
4285 clean::StructItem(..) => "Struct ",
4286 clean::TraitItem(..) => "Trait ",
4287 clean::PrimitiveItem(..) => "Primitive Type ",
4288 clean::UnionItem(..) => "Union ",
4289 clean::EnumItem(..) => "Enum ",
4290 clean::TypedefItem(..) => "Type Definition ",
4291 clean::ForeignTypeItem => "Foreign Type ",
4292 clean::ModuleItem(..) => if it.is_crate() {
4299 it.name.as_ref().unwrap())?;
4303 if let Some(ref version) = cache().crate_version {
4305 "<div class='block version'>\
4312 write!(fmt, "<div class=\"sidebar-elems\">")?;
4314 write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4315 it.name.as_ref().expect("crates always have a name"))?;
4318 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4319 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4320 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4321 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4322 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4323 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4324 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4325 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4329 // The sidebar is designed to display sibling functions, modules and
4330 // other miscellaneous information. since there are lots of sibling
4331 // items (and that causes quadratic growth in large modules),
4332 // we refactor common parts into a shared JavaScript file per module.
4333 // still, we don't move everything into JS because we want to preserve
4334 // as much HTML as possible in order to allow non-JS-enabled browsers
4335 // to navigate the documentation (though slightly inefficiently).
4337 write!(fmt, "<p class='location'>")?;
4338 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4340 write!(fmt, "::<wbr>")?;
4342 write!(fmt, "<a href='{}index.html'>{}</a>",
4343 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4346 write!(fmt, "</p>")?;
4348 // Sidebar refers to the enclosing module, not this module.
4349 let relpath = if it.is_mod() { "../" } else { "" };
4351 "<script>window.sidebarCurrent = {{\
4356 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4357 ty = it.type_().css_class(),
4360 // There is no sidebar-items.js beyond the crate root path
4361 // FIXME maybe dynamic crate loading can be merged here
4363 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4366 // Closes sidebar-elems div.
4367 write!(fmt, "</div>")?;
4373 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4374 if used_links.insert(url.clone()) {
4378 while used_links.insert(format!("{}-{}", url, add)) == false {
4381 format!("{}-{}", url, add)
4387 used_links: &mut FxHashSet<String>,
4389 i.items.iter().filter_map(|item| {
4391 // Maybe check with clean::Visibility::Public as well?
4392 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4393 if !for_deref || should_render_item(item, false) {
4394 Some(format!("<a href=\"#{}\">{}</a>",
4395 get_next_url(used_links, format!("method.{}", name)),
4403 }).collect::<Vec<_>>()
4406 // The point is to url encode any potential character from a type with genericity.
4407 fn small_url_encode(s: &str) -> String {
4408 s.replace("<", "%3C")
4409 .replace(">", "%3E")
4410 .replace(" ", "%20")
4411 .replace("?", "%3F")
4412 .replace("'", "%27")
4413 .replace("&", "%26")
4414 .replace(",", "%2C")
4415 .replace(":", "%3A")
4416 .replace(";", "%3B")
4417 .replace("[", "%5B")
4418 .replace("]", "%5D")
4419 .replace("\"", "%22")
4422 fn sidebar_assoc_items(it: &clean::Item) -> String {
4423 let mut out = String::new();
4425 if let Some(v) = c.impls.get(&it.def_id) {
4426 let mut used_links = FxHashSet::default();
4429 let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4431 .filter(|i| i.inner_impl().trait_.is_none())
4432 .flat_map(move |i| get_methods(i.inner_impl(),
4434 &mut used_links_bor.borrow_mut()))
4435 .collect::<String>();
4436 if !ret.is_empty() {
4437 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4438 </a><div class=\"sidebar-links\">{}</div>", ret));
4442 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4443 if let Some(impl_) = v.iter()
4444 .filter(|i| i.inner_impl().trait_.is_some())
4445 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4446 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4448 clean::TypedefItem(ref t, true) => Some(&t.type_),
4452 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4453 c.primitive_locations.get(&prim).cloned()
4454 })).and_then(|did| c.impls.get(&did));
4455 if let Some(impls) = inner_impl {
4456 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4457 out.push_str(&format!("Methods from {}<Target={}>",
4458 Escape(&format!("{:#}",
4459 impl_.inner_impl().trait_.as_ref().unwrap())),
4460 Escape(&format!("{:#}", target))));
4461 out.push_str("</a>");
4462 let ret = impls.iter()
4463 .filter(|i| i.inner_impl().trait_.is_none())
4464 .flat_map(|i| get_methods(i.inner_impl(),
4467 .collect::<String>();
4468 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
4472 let format_impls = |impls: Vec<&Impl>| {
4473 let mut links = FxHashSet::default();
4477 let is_negative_impl = is_negative_impl(i.inner_impl());
4478 if let Some(ref i) = i.inner_impl().trait_ {
4479 let i_display = format!("{:#}", i);
4480 let out = Escape(&i_display);
4481 let encoded = small_url_encode(&format!("{:#}", i));
4482 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4484 if is_negative_impl { "!" } else { "" },
4486 if links.insert(generated.clone()) {
4495 .collect::<String>()
4498 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4500 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4501 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4503 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4505 let concrete_format = format_impls(concrete);
4506 let synthetic_format = format_impls(synthetic);
4507 let blanket_format = format_impls(blanket_impl);
4509 if !concrete_format.is_empty() {
4510 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4511 Trait Implementations</a>");
4512 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4515 if !synthetic_format.is_empty() {
4516 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4517 Auto Trait Implementations</a>");
4518 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4521 if !blanket_format.is_empty() {
4522 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4523 Blanket Implementations</a>");
4524 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4532 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4533 s: &clean::Struct) -> fmt::Result {
4534 let mut sidebar = String::new();
4535 let fields = get_struct_fields_name(&s.fields);
4537 if !fields.is_empty() {
4538 if let doctree::Plain = s.struct_type {
4539 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4540 <div class=\"sidebar-links\">{}</div>", fields));
4544 sidebar.push_str(&sidebar_assoc_items(it));
4546 if !sidebar.is_empty() {
4547 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4552 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4554 clean::ItemEnum::ImplItem(ref i) => {
4555 if let Some(ref trait_) = i.trait_ {
4556 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4565 fn is_negative_impl(i: &clean::Impl) -> bool {
4566 i.polarity == Some(clean::ImplPolarity::Negative)
4569 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4570 t: &clean::Trait) -> fmt::Result {
4571 let mut sidebar = String::new();
4577 Some(ref name) if m.is_associated_type() => {
4578 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4584 .collect::<String>();
4585 let consts = t.items
4589 Some(ref name) if m.is_associated_const() => {
4590 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4596 .collect::<String>();
4597 let required = t.items
4601 Some(ref name) if m.is_ty_method() => {
4602 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4608 .collect::<String>();
4609 let provided = t.items
4613 Some(ref name) if m.is_method() => {
4614 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
4619 .collect::<String>();
4621 if !types.is_empty() {
4622 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4623 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4626 if !consts.is_empty() {
4627 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4628 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4631 if !required.is_empty() {
4632 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4633 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4636 if !provided.is_empty() {
4637 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4638 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4644 if let Some(implementors) = c.implementors.get(&it.def_id) {
4645 let res = implementors.iter()
4646 .filter(|i| i.inner_impl().for_.def_id()
4647 .map_or(false, |d| !c.paths.contains_key(&d)))
4649 match extract_for_impl_name(&i.impl_item) {
4650 Some((ref name, ref url)) => {
4651 Some(format!("<a href=\"#impl-{}\">{}</a>",
4652 small_url_encode(url),
4658 .collect::<String>();
4659 if !res.is_empty() {
4660 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4661 Implementations on Foreign Types</a><div \
4662 class=\"sidebar-links\">{}</div>",
4667 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4669 sidebar.push_str("<a class=\"sidebar-title\" \
4670 href=\"#synthetic-implementors\">Auto Implementors</a>");
4673 sidebar.push_str(&sidebar_assoc_items(it));
4675 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4678 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4679 _p: &clean::PrimitiveType) -> fmt::Result {
4680 let sidebar = sidebar_assoc_items(it);
4682 if !sidebar.is_empty() {
4683 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4688 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4689 _t: &clean::Typedef) -> fmt::Result {
4690 let sidebar = sidebar_assoc_items(it);
4692 if !sidebar.is_empty() {
4693 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4698 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4700 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4705 .filter_map(|f| match f.name {
4706 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4707 {name}</a>", name=name)),
4713 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4714 u: &clean::Union) -> fmt::Result {
4715 let mut sidebar = String::new();
4716 let fields = get_struct_fields_name(&u.fields);
4718 if !fields.is_empty() {
4719 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4720 <div class=\"sidebar-links\">{}</div>", fields));
4723 sidebar.push_str(&sidebar_assoc_items(it));
4725 if !sidebar.is_empty() {
4726 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4731 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4732 e: &clean::Enum) -> fmt::Result {
4733 let mut sidebar = String::new();
4735 let variants = e.variants.iter()
4736 .filter_map(|v| match v.name {
4737 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4738 </a>", name = name)),
4741 .collect::<String>();
4742 if !variants.is_empty() {
4743 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4744 <div class=\"sidebar-links\">{}</div>", variants));
4747 sidebar.push_str(&sidebar_assoc_items(it));
4749 if !sidebar.is_empty() {
4750 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4755 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4757 ItemType::ExternCrate |
4758 ItemType::Import => ("reexports", "Re-exports"),
4759 ItemType::Module => ("modules", "Modules"),
4760 ItemType::Struct => ("structs", "Structs"),
4761 ItemType::Union => ("unions", "Unions"),
4762 ItemType::Enum => ("enums", "Enums"),
4763 ItemType::Function => ("functions", "Functions"),
4764 ItemType::Typedef => ("types", "Type Definitions"),
4765 ItemType::Static => ("statics", "Statics"),
4766 ItemType::Constant => ("constants", "Constants"),
4767 ItemType::Trait => ("traits", "Traits"),
4768 ItemType::Impl => ("impls", "Implementations"),
4769 ItemType::TyMethod => ("tymethods", "Type Methods"),
4770 ItemType::Method => ("methods", "Methods"),
4771 ItemType::StructField => ("fields", "Struct Fields"),
4772 ItemType::Variant => ("variants", "Variants"),
4773 ItemType::Macro => ("macros", "Macros"),
4774 ItemType::Primitive => ("primitives", "Primitive Types"),
4775 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4776 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4777 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4778 ItemType::Keyword => ("keywords", "Keywords"),
4779 ItemType::Existential => ("existentials", "Existentials"),
4780 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4781 ItemType::ProcDerive => ("derives", "Derive Macros"),
4785 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4786 items: &[clean::Item]) -> fmt::Result {
4787 let mut sidebar = String::new();
4789 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4790 it.type_() == ItemType::Import) {
4791 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4793 name = "Re-exports"));
4796 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4797 // to print its headings
4798 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4799 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4800 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4801 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4802 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4803 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4804 let (short, name) = item_ty_to_strs(&myty);
4805 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4811 if !sidebar.is_empty() {
4812 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4817 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4818 let sidebar = sidebar_assoc_items(it);
4819 if !sidebar.is_empty() {
4820 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4825 impl<'a> fmt::Display for Source<'a> {
4826 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4827 let Source(s) = *self;
4828 let lines = s.lines().count();
4830 let mut tmp = lines;
4835 write!(fmt, "<pre class=\"line-numbers\">")?;
4836 for i in 1..=lines {
4837 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4839 write!(fmt, "</pre>")?;
4841 highlight::render_with_highlighting(s, None, None, None))?;
4846 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4847 t: &clean::Macro) -> fmt::Result {
4848 wrap_into_docblock(w, |w| {
4849 w.write_str(&highlight::render_with_highlighting(&t.source,
4857 fn item_proc_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
4860 let name = it.name.as_ref().expect("proc-macros always have names");
4862 MacroKind::Bang => {
4863 write!(w, "<pre class='rust macro'>")?;
4864 write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
4865 write!(w, "</pre>")?;
4867 MacroKind::Attr => {
4868 write!(w, "<pre class='rust attr'>")?;
4869 write!(w, "#[{}]", name)?;
4870 write!(w, "</pre>")?;
4872 MacroKind::Derive => {
4873 write!(w, "<pre class='rust derive'>")?;
4874 write!(w, "#[derive({})]", name)?;
4875 if !m.helpers.is_empty() {
4876 writeln!(w, "\n{{")?;
4877 writeln!(w, " // Attributes available to this derive:")?;
4878 for attr in &m.helpers {
4879 writeln!(w, " #[{}]", attr)?;
4883 write!(w, "</pre>")?;
4890 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4892 _p: &clean::PrimitiveType) -> fmt::Result {
4893 document(w, cx, it)?;
4894 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4897 fn item_keyword(w: &mut fmt::Formatter, cx: &Context,
4899 _p: &str) -> fmt::Result {
4903 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4905 fn make_item_keywords(it: &clean::Item) -> String {
4906 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4909 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4910 let decl = match item.inner {
4911 clean::FunctionItem(ref f) => &f.decl,
4912 clean::MethodItem(ref m) => &m.decl,
4913 clean::TyMethodItem(ref m) => &m.decl,
4917 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4918 let output = match decl.output {
4919 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4923 Some(IndexItemFunctionType { inputs: inputs, output: output })
4926 fn get_index_type(clean_type: &clean::Type) -> Type {
4928 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4929 generics: get_generics(clean_type),
4934 /// Returns a list of all paths used in the type.
4935 /// This is used to help deduplicate imported impls
4936 /// for reexported types. If any of the contained
4937 /// types are re-exported, we don't use the corresponding
4938 /// entry from the js file, as inlining will have already
4939 /// picked up the impl
4940 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4941 let mut out = Vec::new();
4942 let mut visited = FxHashSet::default();
4943 let mut work = VecDeque::new();
4944 let cache = cache();
4946 work.push_back(first_ty);
4948 while let Some(ty) = work.pop_front() {
4949 if !visited.insert(ty.clone()) {
4954 clean::Type::ResolvedPath { did, .. } => {
4955 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4956 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4960 out.push(path.join("::"));
4966 clean::Type::Tuple(tys) => {
4967 work.extend(tys.into_iter());
4969 clean::Type::Slice(ty) => {
4970 work.push_back(*ty);
4972 clean::Type::Array(ty, _) => {
4973 work.push_back(*ty);
4975 clean::Type::Unique(ty) => {
4976 work.push_back(*ty);
4978 clean::Type::RawPointer(_, ty) => {
4979 work.push_back(*ty);
4981 clean::Type::BorrowedRef { type_, .. } => {
4982 work.push_back(*type_);
4984 clean::Type::QPath { self_type, trait_, .. } => {
4985 work.push_back(*self_type);
4986 work.push_back(*trait_);
4994 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4996 clean::ResolvedPath { ref path, .. } => {
4997 let segments = &path.segments;
4998 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4999 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
5000 clean_type, accept_generic
5002 Some(path_segment.name.clone())
5004 clean::Generic(ref s) if accept_generic => Some(s.clone()),
5005 clean::Primitive(ref p) => Some(format!("{:?}", p)),
5006 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
5007 // FIXME: add all from clean::Type.
5012 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
5013 clean_type.generics()
5015 let r = types.iter()
5016 .filter_map(|t| get_index_type_name(t, false))
5017 .map(|s| s.to_ascii_lowercase())
5018 .collect::<Vec<_>>();
5027 pub fn cache() -> Arc<Cache> {
5028 CACHE_KEY.with(|c| c.borrow().clone())
5033 fn test_name_key() {
5034 assert_eq!(name_key("0"), ("", 0, 1));
5035 assert_eq!(name_key("123"), ("", 123, 0));
5036 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
5037 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
5038 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
5039 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
5040 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
5041 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5046 fn test_name_sorting() {
5047 let names = ["Apple",
5049 "Fruit", "Fruit0", "Fruit00",
5050 "Fruit1", "Fruit01",
5051 "Fruit2", "Fruit02",
5056 let mut sorted = names.to_owned();
5057 sorted.sort_by_key(|&s| name_key(s));
5058 assert_eq!(names, sorted);