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, 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,
146 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
147 let mut dirs = self.created_dirs.borrow_mut();
148 if !dirs.contains(dst) {
149 fs::create_dir_all(dst)?;
150 dirs.insert(dst.to_path_buf());
158 /// Returns whether the `collapse-docs` pass was run on this crate.
159 pub fn was_collapsed(&self) -> bool {
160 self.passes.contains("collapse-docs")
163 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
164 /// `collapsed_doc_value` of the given item.
165 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
166 if self.was_collapsed() {
167 item.collapsed_doc_value().map(|s| s.into())
169 item.doc_value().map(|s| s.into())
174 /// Indicates where an external crate can be found.
175 pub enum ExternalLocation {
176 /// Remote URL root of the external crate
178 /// This external crate can be found in the local doc/ folder
180 /// The external crate could not be found.
184 /// Metadata about implementations for a type or trait.
185 #[derive(Clone, Debug)]
187 pub impl_item: clean::Item,
191 fn inner_impl(&self) -> &clean::Impl {
192 match self.impl_item.inner {
193 clean::ImplItem(ref impl_) => impl_,
194 _ => panic!("non-impl item found in impl")
198 fn trait_did(&self) -> Option<DefId> {
199 self.inner_impl().trait_.def_id()
206 pub error: io::Error,
209 impl error::Error for Error {
210 fn description(&self) -> &str {
211 self.error.description()
215 impl Display for Error {
216 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
217 write!(f, "\"{}\": {}", self.file.display(), self.error)
222 pub fn new(e: io::Error, file: &Path) -> Error {
224 file: file.to_path_buf(),
230 macro_rules! try_none {
231 ($e:expr, $file:expr) => ({
235 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
241 macro_rules! try_err {
242 ($e:expr, $file:expr) => ({
245 Err(e) => return Err(Error::new(e, $file)),
250 /// This cache is used to store information about the `clean::Crate` being
251 /// rendered in order to provide more useful documentation. This contains
252 /// information like all implementors of a trait, all traits a type implements,
253 /// documentation for all known traits, etc.
255 /// This structure purposefully does not implement `Clone` because it's intended
256 /// to be a fairly large and expensive structure to clone. Instead this adheres
257 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
258 /// rendering threads.
261 /// Mapping of typaram ids to the name of the type parameter. This is used
262 /// when pretty-printing a type (so pretty printing doesn't have to
263 /// painfully maintain a context like this)
264 pub typarams: FxHashMap<DefId, String>,
266 /// Maps a type id to all known implementations for that type. This is only
267 /// recognized for intra-crate `ResolvedPath` types, and is used to print
268 /// out extra documentation on the page of an enum/struct.
270 /// The values of the map are a list of implementations and documentation
271 /// found on that implementation.
272 pub impls: FxHashMap<DefId, Vec<Impl>>,
274 /// Maintains a mapping of local crate node ids to the fully qualified name
275 /// and "short type description" of that node. This is used when generating
276 /// URLs when a type is being linked to. External paths are not located in
277 /// this map because the `External` type itself has all the information
279 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
281 /// Similar to `paths`, but only holds external paths. This is only used for
282 /// generating explicit hyperlinks to other crates.
283 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
285 /// Maps local def ids of exported types to fully qualified paths.
286 /// Unlike 'paths', this mapping ignores any renames that occur
287 /// due to 'use' statements.
289 /// This map is used when writing out the special 'implementors'
290 /// javascript file. By using the exact path that the type
291 /// is declared with, we ensure that each path will be identical
292 /// to the path used if the corresponding type is inlined. By
293 /// doing this, we can detect duplicate impls on a trait page, and only display
294 /// the impl for the inlined type.
295 pub exact_paths: FxHashMap<DefId, Vec<String>>,
297 /// This map contains information about all known traits of this crate.
298 /// Implementations of a crate should inherit the documentation of the
299 /// parent trait if no extra documentation is specified, and default methods
300 /// should show up in documentation about trait implementations.
301 pub traits: FxHashMap<DefId, clean::Trait>,
303 /// When rendering traits, it's often useful to be able to list all
304 /// implementors of the trait, and this mapping is exactly, that: a mapping
305 /// of trait ids to the list of known implementors of the trait
306 pub implementors: FxHashMap<DefId, Vec<Impl>>,
308 /// Cache of where external crate documentation can be found.
309 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
311 /// Cache of where documentation for primitives can be found.
312 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
314 // Note that external items for which `doc(hidden)` applies to are shown as
315 // non-reachable while local items aren't. This is because we're reusing
316 // the access levels from crateanalysis.
317 pub access_levels: AccessLevels<DefId>,
319 /// The version of the crate being documented, if given from the `--crate-version` flag.
320 pub crate_version: Option<String>,
322 // Private fields only used when initially crawling a crate to build a cache
325 parent_stack: Vec<DefId>,
326 parent_is_trait_impl: bool,
327 search_index: Vec<IndexItem>,
329 deref_trait_did: Option<DefId>,
330 deref_mut_trait_did: Option<DefId>,
331 owned_box_did: Option<DefId>,
332 masked_crates: FxHashSet<CrateNum>,
334 // In rare case where a structure is defined in one module but implemented
335 // in another, if the implementing module is parsed before defining module,
336 // then the fully qualified name of the structure isn't presented in `paths`
337 // yet when its implementation methods are being indexed. Caches such methods
338 // and their parent id here and indexes them at the end of crate parsing.
339 orphan_impl_items: Vec<(DefId, clean::Item)>,
341 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
342 // even though the trait itself is not exported. This can happen if a trait
343 // was defined in function/expression scope, since the impl will be picked
344 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
345 // crawl. In order to prevent crashes when looking for spotlight traits or
346 // when gathering trait documentation on a type, hold impls here while
347 // folding and add them to the cache later on if we find the trait.
348 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
350 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
351 /// we need the alias element to have an array of items.
352 aliases: FxHashMap<String, Vec<IndexItem>>,
355 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
356 /// Later on moved into `CACHE_KEY`.
358 pub struct RenderInfo {
359 pub inlined: FxHashSet<DefId>,
360 pub external_paths: ::core::ExternalPaths,
361 pub external_typarams: FxHashMap<DefId, String>,
362 pub exact_paths: FxHashMap<DefId, Vec<String>>,
363 pub access_levels: AccessLevels<DefId>,
364 pub deref_trait_did: Option<DefId>,
365 pub deref_mut_trait_did: Option<DefId>,
366 pub owned_box_did: Option<DefId>,
369 /// Helper struct to render all source code to HTML pages
370 struct SourceCollector<'a> {
371 scx: &'a mut SharedContext,
373 /// Root destination to place all HTML output into
377 /// Wrapper struct to render the source code of a file. This will do things like
378 /// adding line numbers to the left-hand side.
379 struct Source<'a>(&'a str);
381 // Helper structs for rendering items/sidebars and carrying along contextual
384 #[derive(Copy, Clone)]
387 item: &'a clean::Item,
390 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
392 /// Struct representing one entry in the JS search index. These are all emitted
393 /// by hand to a large JS file at the end of cache-creation.
400 parent: Option<DefId>,
401 parent_idx: Option<usize>,
402 search_type: Option<IndexItemFunctionType>,
405 impl ToJson for IndexItem {
406 fn to_json(&self) -> Json {
407 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
409 let mut data = Vec::with_capacity(6);
410 data.push((self.ty as usize).to_json());
411 data.push(self.name.to_json());
412 data.push(self.path.to_json());
413 data.push(self.desc.to_json());
414 data.push(self.parent_idx.to_json());
415 data.push(self.search_type.to_json());
421 /// A type used for the search index.
424 name: Option<String>,
425 generics: Option<Vec<String>>,
428 impl ToJson for Type {
429 fn to_json(&self) -> Json {
432 let mut data = Vec::with_capacity(2);
433 data.push(name.to_json());
434 if let Some(ref generics) = self.generics {
435 data.push(generics.to_json());
444 /// Full type of functions/methods in the search index.
446 struct IndexItemFunctionType {
448 output: Option<Type>,
451 impl ToJson for IndexItemFunctionType {
452 fn to_json(&self) -> Json {
453 // If we couldn't figure out a type, just write `null`.
454 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
457 let mut data = Vec::with_capacity(2);
458 data.push(self.inputs.to_json());
459 if let Some(ref output) = self.output {
460 data.push(output.to_json());
467 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
468 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
470 pub fn initial_ids() -> Vec<String> {
482 "synthetic-implementors",
484 "synthetic-implementors-list",
488 ].into_iter().map(|id| (String::from(*id))).collect()
491 /// Generates the documentation for `crate` into the directory `dst`
492 pub fn run(mut krate: clean::Crate,
493 options: RenderOptions,
494 passes: FxHashSet<String>,
495 renderinfo: RenderInfo,
496 diag: &errors::Handler) -> Result<(), Error> {
497 // need to save a copy of the options for rendering the index page
498 let md_opts = options.clone();
504 sort_modules_alphabetically,
507 extern_html_root_urls,
512 let src_root = match krate.src {
513 FileName::Real(ref p) => match p.parent() {
514 Some(p) => p.to_path_buf(),
515 None => PathBuf::new(),
519 let mut scx = SharedContext {
522 include_sources: true,
523 local_sources: Default::default(),
524 issue_tracker_base_url: None,
525 layout: layout::Layout {
527 favicon: String::new(),
529 krate: krate.name.clone(),
531 css_file_extension: extension_css,
532 created_dirs: Default::default(),
533 sort_modules_alphabetically,
538 // If user passed in `--playground-url` arg, we fill in crate name here
539 if let Some(url) = playground_url {
540 markdown::PLAYGROUND.with(|slot| {
541 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
545 // Crawl the crate attributes looking for attributes which control how we're
546 // going to emit HTML
547 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
548 for attr in attrs.lists("doc") {
549 let name = attr.name().map(|s| s.as_str());
550 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
551 (Some("html_favicon_url"), Some(s)) => {
552 scx.layout.favicon = s.to_string();
554 (Some("html_logo_url"), Some(s)) => {
555 scx.layout.logo = s.to_string();
557 (Some("html_playground_url"), Some(s)) => {
558 markdown::PLAYGROUND.with(|slot| {
559 let name = krate.name.clone();
560 *slot.borrow_mut() = Some((Some(name), s.to_string()));
563 (Some("issue_tracker_base_url"), Some(s)) => {
564 scx.issue_tracker_base_url = Some(s.to_string());
566 (Some("html_no_source"), None) if attr.is_word() => {
567 scx.include_sources = false;
574 try_err!(fs::create_dir_all(&dst), &dst);
575 krate = render_sources(&dst, &mut scx, krate)?;
579 render_redirect_pages: false,
580 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
581 id_map: Rc::new(RefCell::new(id_map)),
582 shared: Arc::new(scx),
585 // Crawl the crate to build various caches used for the output
597 let external_paths = external_paths.into_iter()
598 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
601 let mut cache = Cache {
602 impls: Default::default(),
605 paths: Default::default(),
606 implementors: Default::default(),
608 parent_stack: Vec::new(),
609 search_index: Vec::new(),
610 parent_is_trait_impl: false,
611 extern_locations: Default::default(),
612 primitive_locations: Default::default(),
615 crate_version: krate.version.take(),
616 orphan_impl_items: Vec::new(),
617 orphan_trait_impls: Vec::new(),
618 traits: krate.external_traits.lock().replace(Default::default()),
622 masked_crates: mem::replace(&mut krate.masked_crates, Default::default()),
623 typarams: external_typarams,
624 aliases: Default::default(),
627 // Cache where all our extern crates are located
628 for &(n, ref e) in &krate.externs {
629 let src_root = match e.src {
630 FileName::Real(ref p) => match p.parent() {
631 Some(p) => p.to_path_buf(),
632 None => PathBuf::new(),
636 let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
637 cache.extern_locations.insert(n, (e.name.clone(), src_root,
638 extern_location(e, extern_url, &cx.dst)));
640 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
641 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
644 // Cache where all known primitives have their documentation located.
646 // Favor linking to as local extern as possible, so iterate all crates in
647 // reverse topological order.
648 for &(_, ref e) in krate.externs.iter().rev() {
649 for &(def_id, prim, _) in &e.primitives {
650 cache.primitive_locations.insert(prim, def_id);
653 for &(def_id, prim, _) in &krate.primitives {
654 cache.primitive_locations.insert(prim, def_id);
657 cache.stack.push(krate.name.clone());
658 krate = cache.fold_crate(krate);
660 for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
661 if cache.traits.contains_key(&trait_did) {
663 cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
668 // Build our search index
669 let index = build_index(&krate, &mut cache);
671 // Freeze the cache now that the index has been built. Put an Arc into TLS
672 // for future parallelization opportunities
673 let cache = Arc::new(cache);
674 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
675 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
677 write_shared(&cx, &krate, &*cache, index, &md_opts, diag)?;
679 // And finally render the whole crate's documentation
683 /// Build the search index from the collected metadata
684 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
685 let mut nodeid_to_pathid = FxHashMap::default();
686 let mut crate_items = Vec::with_capacity(cache.search_index.len());
687 let mut crate_paths = Vec::<Json>::new();
689 let Cache { ref mut search_index,
690 ref orphan_impl_items,
691 ref mut paths, .. } = *cache;
693 // Attach all orphan items to the type's definition if the type
694 // has since been learned.
695 for &(did, ref item) in orphan_impl_items {
696 if let Some(&(ref fqp, _)) = paths.get(&did) {
697 search_index.push(IndexItem {
699 name: item.name.clone().unwrap(),
700 path: fqp[..fqp.len() - 1].join("::"),
701 desc: plain_summary_line_short(item.doc_value()),
704 search_type: get_index_search_type(&item),
709 // Reduce `NodeId` in paths into smaller sequential numbers,
710 // and prune the paths that do not appear in the index.
711 let mut lastpath = String::new();
712 let mut lastpathid = 0usize;
714 for item in search_index {
715 item.parent_idx = item.parent.map(|nodeid| {
716 if nodeid_to_pathid.contains_key(&nodeid) {
717 *nodeid_to_pathid.get(&nodeid).unwrap()
719 let pathid = lastpathid;
720 nodeid_to_pathid.insert(nodeid, pathid);
723 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
724 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
729 // Omit the parent path if it is same to that of the prior item.
730 if lastpath == item.path {
733 lastpath = item.path.clone();
735 crate_items.push(item.to_json());
738 let crate_doc = krate.module.as_ref().map(|module| {
739 plain_summary_line_short(module.doc_value())
740 }).unwrap_or(String::new());
742 let mut crate_data = BTreeMap::new();
743 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
744 crate_data.insert("items".to_owned(), Json::Array(crate_items));
745 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
747 // Collect the index into a string
748 format!("searchIndex[{}] = {};",
749 as_json(&krate.name),
750 Json::Object(crate_data))
755 krate: &clean::Crate,
757 search_index: String,
758 options: &RenderOptions,
759 diag: &errors::Handler,
760 ) -> Result<(), Error> {
761 // Write out the shared files. Note that these are shared among all rustdoc
762 // docs placed in the output directory, so this needs to be a synchronized
763 // operation with respect to all other rustdocs running around.
764 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
766 // Add all the static files. These may already exist, but we just
767 // overwrite them anyway to make sure that they're fresh and up-to-date.
769 write_minify(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
770 static_files::RUSTDOC_CSS,
771 options.enable_minification)?;
772 write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
773 static_files::SETTINGS_CSS,
774 options.enable_minification)?;
775 write_minify(cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
776 static_files::NOSCRIPT_CSS,
777 options.enable_minification)?;
779 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
780 // then we'll run over the "official" styles.
781 let mut themes: FxHashSet<String> = FxHashSet::default();
783 for entry in &cx.shared.themes {
784 let content = try_err!(fs::read(&entry), &entry);
785 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
786 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
787 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
788 content.as_slice())?;
789 themes.insert(theme.to_owned());
792 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
793 static_files::BRUSH_SVG)?;
794 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
795 static_files::WHEEL_SVG)?;
796 write(cx.dst.join(&format!("down-arrow{}.svg", cx.shared.resource_suffix)),
797 static_files::DOWN_ARROW_SVG)?;
798 write_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
799 static_files::themes::LIGHT,
800 options.enable_minification)?;
801 themes.insert("light".to_owned());
802 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
803 static_files::themes::DARK,
804 options.enable_minification)?;
805 themes.insert("dark".to_owned());
807 let mut themes: Vec<&String> = themes.iter().collect();
809 // To avoid theme switch latencies as much as possible, we put everything theme related
810 // at the beginning of the html files into another js file.
811 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
813 r#"var themes = document.getElementById("theme-choices");
814 var themePicker = document.getElementById("theme-picker");
816 function switchThemeButtonState() {{
817 if (themes.style.display === "block") {{
818 themes.style.display = "none";
819 themePicker.style.borderBottomRightRadius = "3px";
820 themePicker.style.borderBottomLeftRadius = "3px";
822 themes.style.display = "block";
823 themePicker.style.borderBottomRightRadius = "0";
824 themePicker.style.borderBottomLeftRadius = "0";
828 function handleThemeButtonsBlur(e) {{
829 var active = document.activeElement;
830 var related = e.relatedTarget;
832 if (active.id !== "themePicker" &&
833 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
835 (related.id !== "themePicker" &&
836 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
837 switchThemeButtonState();
841 themePicker.onclick = switchThemeButtonState;
842 themePicker.onblur = handleThemeButtonsBlur;
843 [{}].forEach(function(item) {{
844 var but = document.createElement('button');
845 but.innerHTML = item;
846 but.onclick = function(el) {{
847 switchTheme(currentTheme, mainTheme, item);
849 but.onblur = handleThemeButtonsBlur;
850 themes.appendChild(but);
853 .map(|s| format!("\"{}\"", s))
854 .collect::<Vec<String>>()
855 .join(",")).as_bytes(),
858 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
859 static_files::MAIN_JS,
860 options.enable_minification)?;
861 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
862 static_files::SETTINGS_JS,
863 options.enable_minification)?;
864 if cx.shared.include_sources {
865 write_minify(cx.dst.join(&format!("source-script{}.js", cx.shared.resource_suffix)),
866 static_files::sidebar::SOURCE_SCRIPT,
867 options.enable_minification)?;
871 let mut data = static_files::STORAGE_JS.to_owned();
872 data.push_str(&format!("var resourcesSuffix = \"{}\";", cx.shared.resource_suffix));
873 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
875 options.enable_minification)?;
878 if let Some(ref css) = cx.shared.css_file_extension {
879 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
880 if !options.enable_minification {
881 try_err!(fs::copy(css, out), css);
883 let buffer = try_err!(fs::read_to_string(css), css);
884 write_minify(out, &buffer, options.enable_minification)?;
887 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
888 static_files::NORMALIZE_CSS,
889 options.enable_minification)?;
890 write(cx.dst.join("FiraSans-Regular.woff"),
891 static_files::fira_sans::REGULAR)?;
892 write(cx.dst.join("FiraSans-Medium.woff"),
893 static_files::fira_sans::MEDIUM)?;
894 write(cx.dst.join("FiraSans-LICENSE.txt"),
895 static_files::fira_sans::LICENSE)?;
896 write(cx.dst.join("Heuristica-Italic.woff"),
897 static_files::heuristica::ITALIC)?;
898 write(cx.dst.join("Heuristica-LICENSE.txt"),
899 static_files::heuristica::LICENSE)?;
900 write(cx.dst.join("SourceSerifPro-Regular.woff"),
901 static_files::source_serif_pro::REGULAR)?;
902 write(cx.dst.join("SourceSerifPro-Bold.woff"),
903 static_files::source_serif_pro::BOLD)?;
904 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
905 static_files::source_serif_pro::LICENSE)?;
906 write(cx.dst.join("SourceCodePro-Regular.woff"),
907 static_files::source_code_pro::REGULAR)?;
908 write(cx.dst.join("SourceCodePro-Semibold.woff"),
909 static_files::source_code_pro::SEMIBOLD)?;
910 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
911 static_files::source_code_pro::LICENSE)?;
912 write(cx.dst.join("LICENSE-MIT.txt"),
913 static_files::LICENSE_MIT)?;
914 write(cx.dst.join("LICENSE-APACHE.txt"),
915 static_files::LICENSE_APACHE)?;
916 write(cx.dst.join("COPYRIGHT.txt"),
917 static_files::COPYRIGHT)?;
919 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
920 let mut ret = Vec::new();
921 let mut krates = Vec::new();
923 for line in BufReader::new(File::open(path)?).lines() {
925 if !line.starts_with(key) {
928 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
931 ret.push(line.to_string());
932 krates.push(line[key.len() + 2..].split('"')
934 .map(|s| s.to_owned())
935 .unwrap_or_else(|| String::new()));
941 fn show_item(item: &IndexItem, krate: &str) -> String {
942 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
943 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
944 if let Some(p) = item.parent_idx {
945 format!(",'parent':{}", p)
951 let dst = cx.dst.join("aliases.js");
953 let (mut all_aliases, _) = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
954 let mut w = try_err!(File::create(&dst), &dst);
955 let mut output = String::with_capacity(100);
956 for (alias, items) in &cache.aliases {
957 if items.is_empty() {
960 output.push_str(&format!("\"{}\":[{}],",
963 .map(|v| show_item(v, &krate.name))
967 all_aliases.push(format!("ALIASES['{}'] = {{{}}};", krate.name, output));
969 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
970 for aliases in &all_aliases {
971 try_err!(writeln!(&mut w, "{}", aliases), &dst);
975 use std::ffi::OsString;
980 children: FxHashMap<OsString, Hierarchy>,
981 elems: FxHashSet<OsString>,
985 fn new(elem: OsString) -> Hierarchy {
988 children: FxHashMap::default(),
989 elems: FxHashSet::default(),
993 fn to_json_string(&self) -> String {
994 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
995 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
996 let mut files = self.elems.iter()
997 .map(|s| format!("\"{}\"",
999 .expect("invalid osstring conversion")))
1000 .collect::<Vec<_>>();
1001 files.sort_unstable_by(|a, b| a.cmp(b));
1002 // FIXME(imperio): we could avoid to generate "dirs" and "files" if they're empty.
1003 format!("{{\"name\":\"{name}\",\"dirs\":[{subs}],\"files\":[{files}]}}",
1004 name=self.elem.to_str().expect("invalid osstring conversion"),
1005 subs=subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(","),
1006 files=files.join(","))
1010 if cx.shared.include_sources {
1011 use std::path::Component;
1013 let mut hierarchy = Hierarchy::new(OsString::new());
1014 for source in cx.shared.local_sources.iter()
1015 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
1017 let mut h = &mut hierarchy;
1018 let mut elems = source.components()
1021 Component::Normal(s) => Some(s.to_owned()),
1027 let cur_elem = elems.next().expect("empty file path");
1028 if elems.peek().is_none() {
1029 h.elems.insert(cur_elem);
1032 let e = cur_elem.clone();
1033 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1034 h = h.children.get_mut(&cur_elem).expect("not found child");
1039 let dst = cx.dst.join("source-files.js");
1040 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1041 all_sources.push(format!("sourcesIndex['{}'] = {};",
1043 hierarchy.to_json_string()));
1045 let mut w = try_err!(File::create(&dst), &dst);
1046 try_err!(writeln!(&mut w,
1047 "var N = null;var sourcesIndex = {{}};\n{}",
1048 all_sources.join("\n")),
1052 // Update the search index
1053 let dst = cx.dst.join("search-index.js");
1054 let (mut all_indexes, mut krates) = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
1055 all_indexes.push(search_index);
1057 // Sort the indexes by crate so the file will be generated identically even
1058 // with rustdoc running in parallel.
1060 let mut w = try_err!(File::create(&dst), &dst);
1061 try_err!(writeln!(&mut w, "var N = null;var searchIndex = {{}};"), &dst);
1062 for index in &all_indexes {
1063 try_err!(write_minify_replacer(&mut w, &*index, options.enable_minification,
1064 &[(minifier::js::Keyword::Null, "N")]),
1067 try_err!(writeln!(&mut w, "initSearch(searchIndex);addSearchOptions(searchIndex);"), &dst);
1069 if options.enable_index_page {
1070 if let Some(index_page) = options.index_page.clone() {
1071 let mut md_opts = options.clone();
1072 md_opts.output = cx.dst.clone();
1073 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1075 ::markdown::render(index_page, md_opts, diag);
1077 let dst = cx.dst.join("index.html");
1078 let mut w = BufWriter::new(try_err!(File::create(&dst), &dst));
1079 let page = layout::Page {
1080 title: "Index of crates",
1083 description: "List of crates",
1084 keywords: BASIC_KEYWORDS,
1085 resource_suffix: &cx.shared.resource_suffix,
1087 krates.push(krate.name.clone());
1091 let content = format!(
1093 <span class='in-band'>List of all crates</span>\
1094 </h1><ul class='mod'>{}</ul>",
1098 format!("<li><a href=\"{}/index.html\">{}</li>", s, s)
1100 .collect::<String>());
1101 try_err!(layout::render(&mut w, &cx.shared.layout,
1102 &page, &(""), &content,
1103 cx.shared.css_file_extension.is_some(),
1104 &cx.shared.themes, &[]), &dst);
1105 try_err!(w.flush(), &dst);
1109 // Update the list of all implementors for traits
1110 let dst = cx.dst.join("implementors");
1111 for (&did, imps) in &cache.implementors {
1112 // Private modules can leak through to this phase of rustdoc, which
1113 // could contain implementations for otherwise private types. In some
1114 // rare cases we could find an implementation for an item which wasn't
1115 // indexed, so we just skip this step in that case.
1117 // FIXME: this is a vague explanation for why this can't be a `get`, in
1118 // theory it should be...
1119 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1121 None => match cache.external_paths.get(&did) {
1127 let mut have_impls = false;
1128 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1130 // If the trait and implementation are in the same crate, then
1131 // there's no need to emit information about it (there's inlining
1132 // going on). If they're in different crates then the crate defining
1133 // the trait will be interested in our implementation.
1134 if imp.impl_item.def_id.krate == did.krate { continue }
1135 // If the implementation is from another crate then that crate
1137 if !imp.impl_item.def_id.is_local() { continue }
1139 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1140 as_json(&imp.inner_impl().to_string()),
1141 imp.inner_impl().synthetic,
1142 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1144 implementors.push_str("];");
1146 // Only create a js file if we have impls to add to it. If the trait is
1147 // documented locally though we always create the file to avoid dead
1149 if !have_impls && !cache.paths.contains_key(&did) {
1153 let mut mydst = dst.clone();
1154 for part in &remote_path[..remote_path.len() - 1] {
1157 try_err!(fs::create_dir_all(&mydst), &mydst);
1158 mydst.push(&format!("{}.{}.js",
1159 remote_item_type.css_class(),
1160 remote_path[remote_path.len() - 1]));
1162 let (mut all_implementors, _) = try_err!(collect(&mydst, &krate.name, "implementors"),
1164 all_implementors.push(implementors);
1165 // Sort the implementors by crate so the file will be generated
1166 // identically even with rustdoc running in parallel.
1167 all_implementors.sort();
1169 let mut f = try_err!(File::create(&mydst), &mydst);
1170 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1171 for implementor in &all_implementors {
1172 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1174 try_err!(writeln!(&mut f, "{}", r"
1175 if (window.register_implementors) {
1176 window.register_implementors(implementors);
1178 window.pending_implementors = implementors;
1181 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1186 fn render_sources(dst: &Path, scx: &mut SharedContext,
1187 krate: clean::Crate) -> Result<clean::Crate, Error> {
1188 info!("emitting source files");
1189 let dst = dst.join("src").join(&krate.name);
1190 try_err!(fs::create_dir_all(&dst), &dst);
1191 let mut folder = SourceCollector {
1195 Ok(folder.fold_crate(krate))
1198 /// Writes the entire contents of a string to a destination, not attempting to
1199 /// catch any errors.
1200 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1201 Ok(try_err!(fs::write(&dst, contents), &dst))
1204 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1205 if enable_minification {
1206 if dst.extension() == Some(&OsStr::new("css")) {
1207 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1208 write(dst, res.as_bytes())
1210 write(dst, minifier::js::minify(contents).as_bytes())
1213 write(dst, contents.as_bytes())
1217 fn write_minify_replacer<W: Write>(dst: &mut W,
1219 enable_minification: bool,
1220 keywords_to_replace: &[(minifier::js::Keyword, &str)])
1222 if enable_minification {
1224 minifier::js::minify_and_replace_keywords(contents, keywords_to_replace))
1226 writeln!(dst, "{}", contents)
1230 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1231 /// things like ".." to components which preserve the "top down" hierarchy of a
1232 /// static HTML tree. Each component in the cleaned path will be passed as an
1233 /// argument to `f`. The very last component of the path (ie the file name) will
1234 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1235 // FIXME (#9639): The closure should deal with &[u8] instead of &str
1236 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
1237 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1240 // make it relative, if possible
1241 let p = p.strip_prefix(src_root).unwrap_or(p);
1243 let mut iter = p.components().peekable();
1245 while let Some(c) = iter.next() {
1246 if !keep_filename && iter.peek().is_none() {
1251 Component::ParentDir => f("up"),
1252 Component::Normal(c) => f(c.to_str().unwrap()),
1258 /// Attempts to find where an external crate is located, given that we're
1259 /// rendering in to the specified source destination.
1260 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1263 // See if there's documentation generated into the local directory
1264 let local_location = dst.join(&e.name);
1265 if local_location.is_dir() {
1269 if let Some(url) = extern_url {
1270 let mut url = url.to_string();
1271 if !url.ends_with("/") {
1277 // Failing that, see if there's an attribute specifying where to find this
1279 e.attrs.lists("doc")
1280 .filter(|a| a.check_name("html_root_url"))
1281 .filter_map(|a| a.value_str())
1283 let mut url = url.to_string();
1284 if !url.ends_with("/") {
1288 }).next().unwrap_or(Unknown) // Well, at least we tried.
1291 impl<'a> DocFolder for SourceCollector<'a> {
1292 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1293 // If we're including source files, and we haven't seen this file yet,
1294 // then we need to render it out to the filesystem.
1295 if self.scx.include_sources
1296 // skip all invalid or macro spans
1297 && item.source.filename.is_real()
1298 // skip non-local items
1299 && item.def_id.is_local() {
1301 // If it turns out that we couldn't read this file, then we probably
1302 // can't read any of the files (generating html output from json or
1303 // something like that), so just don't include sources for the
1304 // entire crate. The other option is maintaining this mapping on a
1305 // per-file basis, but that's probably not worth it...
1307 .include_sources = match self.emit_source(&item.source.filename) {
1310 println!("warning: source code was requested to be rendered, \
1311 but processing `{}` had an error: {}",
1312 item.source.filename, e);
1313 println!(" skipping rendering of source code");
1318 self.fold_item_recur(item)
1322 impl<'a> SourceCollector<'a> {
1323 /// Renders the given filename into its corresponding HTML source file.
1324 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1325 let p = match *filename {
1326 FileName::Real(ref file) => file,
1329 if self.scx.local_sources.contains_key(&**p) {
1330 // We've already emitted this source
1334 let contents = fs::read_to_string(&p)?;
1336 // Remove the utf-8 BOM if any
1337 let contents = if contents.starts_with("\u{feff}") {
1343 // Create the intermediate directories
1344 let mut cur = self.dst.clone();
1345 let mut root_path = String::from("../../");
1346 let mut href = String::new();
1347 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1348 cur.push(component);
1349 fs::create_dir_all(&cur).unwrap();
1350 root_path.push_str("../");
1351 href.push_str(component);
1354 let mut fname = p.file_name()
1355 .expect("source has no filename")
1357 fname.push(".html");
1359 href.push_str(&fname.to_string_lossy());
1361 let mut w = BufWriter::new(File::create(&cur)?);
1362 let title = format!("{} -- source", cur.file_name().unwrap()
1363 .to_string_lossy());
1364 let desc = format!("Source to the Rust file `{}`.", filename);
1365 let page = layout::Page {
1367 css_class: "source",
1368 root_path: &root_path,
1370 keywords: BASIC_KEYWORDS,
1371 resource_suffix: &self.scx.resource_suffix,
1373 layout::render(&mut w, &self.scx.layout,
1374 &page, &(""), &Source(contents),
1375 self.scx.css_file_extension.is_some(),
1376 &self.scx.themes, &["source-files",
1377 &format!("source-script{}", page.resource_suffix)])?;
1379 self.scx.local_sources.insert(p.clone(), href);
1384 impl DocFolder for Cache {
1385 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1386 if item.def_id.is_local() {
1387 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
1390 // If this is a stripped module,
1391 // we don't want it or its children in the search index.
1392 let orig_stripped_mod = match item.inner {
1393 clean::StrippedItem(box clean::ModuleItem(..)) => {
1394 mem::replace(&mut self.stripped_mod, true)
1396 _ => self.stripped_mod,
1399 // If the impl is from a masked crate or references something from a
1400 // masked crate then remove it completely.
1401 if let clean::ImplItem(ref i) = item.inner {
1402 if self.masked_crates.contains(&item.def_id.krate) ||
1403 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1404 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1409 // Register any generics to their corresponding string. This is used
1410 // when pretty-printing types.
1411 if let Some(generics) = item.inner.generics() {
1412 self.generics(generics);
1415 // Propagate a trait method's documentation to all implementors of the
1417 if let clean::TraitItem(ref t) = item.inner {
1418 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1421 // Collect all the implementors of traits.
1422 if let clean::ImplItem(ref i) = item.inner {
1423 if let Some(did) = i.trait_.def_id() {
1424 if i.blanket_impl.is_none() {
1425 self.implementors.entry(did).or_default().push(Impl {
1426 impl_item: item.clone(),
1432 // Index this method for searching later on.
1433 if let Some(ref s) = item.name {
1434 let (parent, is_inherent_impl_item) = match item.inner {
1435 clean::StrippedItem(..) => ((None, None), false),
1436 clean::AssociatedConstItem(..) |
1437 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1438 // skip associated items in trait impls
1439 ((None, None), false)
1441 clean::AssociatedTypeItem(..) |
1442 clean::TyMethodItem(..) |
1443 clean::StructFieldItem(..) |
1444 clean::VariantItem(..) => {
1445 ((Some(*self.parent_stack.last().unwrap()),
1446 Some(&self.stack[..self.stack.len() - 1])),
1449 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1450 if self.parent_stack.is_empty() {
1451 ((None, None), false)
1453 let last = self.parent_stack.last().unwrap();
1455 let path = match self.paths.get(&did) {
1456 // The current stack not necessarily has correlation
1457 // for where the type was defined. On the other
1458 // hand, `paths` always has the right
1459 // information if present.
1460 Some(&(ref fqp, ItemType::Trait)) |
1461 Some(&(ref fqp, ItemType::Struct)) |
1462 Some(&(ref fqp, ItemType::Union)) |
1463 Some(&(ref fqp, ItemType::Enum)) =>
1464 Some(&fqp[..fqp.len() - 1]),
1465 Some(..) => Some(&*self.stack),
1468 ((Some(*last), path), true)
1471 _ => ((None, Some(&*self.stack)), false)
1475 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1476 debug_assert!(!item.is_stripped());
1478 // A crate has a module at its root, containing all items,
1479 // which should not be indexed. The crate-item itself is
1480 // inserted later on when serializing the search-index.
1481 if item.def_id.index != CRATE_DEF_INDEX {
1482 self.search_index.push(IndexItem {
1484 name: s.to_string(),
1485 path: path.join("::"),
1486 desc: plain_summary_line_short(item.doc_value()),
1489 search_type: get_index_search_type(&item),
1493 (Some(parent), None) if is_inherent_impl_item => {
1494 // We have a parent, but we don't know where they're
1495 // defined yet. Wait for later to index this item.
1496 self.orphan_impl_items.push((parent, item.clone()));
1502 // Keep track of the fully qualified path for this item.
1503 let pushed = match item.name {
1504 Some(ref n) if !n.is_empty() => {
1505 self.stack.push(n.to_string());
1512 clean::StructItem(..) | clean::EnumItem(..) |
1513 clean::TypedefItem(..) | clean::TraitItem(..) |
1514 clean::FunctionItem(..) | clean::ModuleItem(..) |
1515 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1516 clean::ConstantItem(..) | clean::StaticItem(..) |
1517 clean::UnionItem(..) | clean::ForeignTypeItem |
1518 clean::MacroItem(..) | clean::ProcMacroItem(..)
1519 if !self.stripped_mod => {
1520 // Re-exported items mean that the same id can show up twice
1521 // in the rustdoc ast that we're looking at. We know,
1522 // however, that a re-exported item doesn't show up in the
1523 // `public_items` map, so we can skip inserting into the
1524 // paths map if there was already an entry present and we're
1525 // not a public item.
1526 if !self.paths.contains_key(&item.def_id) ||
1527 self.access_levels.is_public(item.def_id)
1529 self.paths.insert(item.def_id,
1530 (self.stack.clone(), item.type_()));
1532 self.add_aliases(&item);
1534 // Link variants to their parent enum because pages aren't emitted
1535 // for each variant.
1536 clean::VariantItem(..) if !self.stripped_mod => {
1537 let mut stack = self.stack.clone();
1539 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1542 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1543 self.add_aliases(&item);
1544 self.paths.insert(item.def_id, (self.stack.clone(),
1551 // Maintain the parent stack
1552 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1553 let parent_pushed = match item.inner {
1554 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1555 clean::StructItem(..) | clean::UnionItem(..) => {
1556 self.parent_stack.push(item.def_id);
1557 self.parent_is_trait_impl = false;
1560 clean::ImplItem(ref i) => {
1561 self.parent_is_trait_impl = i.trait_.is_some();
1563 clean::ResolvedPath{ did, .. } => {
1564 self.parent_stack.push(did);
1568 let prim_did = t.primitive_type().and_then(|t| {
1569 self.primitive_locations.get(&t).cloned()
1573 self.parent_stack.push(did);
1584 // Once we've recursively found all the generics, hoard off all the
1585 // implementations elsewhere.
1586 let ret = self.fold_item_recur(item).and_then(|item| {
1587 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1588 // Figure out the id of this impl. This may map to a
1589 // primitive rather than always to a struct/enum.
1590 // Note: matching twice to restrict the lifetime of the `i` borrow.
1591 let mut dids = FxHashSet::default();
1592 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1594 clean::ResolvedPath { did, .. } |
1595 clean::BorrowedRef {
1596 type_: box clean::ResolvedPath { did, .. }, ..
1601 let did = t.primitive_type().and_then(|t| {
1602 self.primitive_locations.get(&t).cloned()
1605 if let Some(did) = did {
1611 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1612 for bound in generics {
1613 if let Some(did) = bound.def_id() {
1621 let impl_item = Impl {
1624 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
1626 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
1629 let trait_did = impl_item.trait_did().unwrap();
1630 self.orphan_trait_impls.push((trait_did, dids, impl_item));
1638 if pushed { self.stack.pop().unwrap(); }
1639 if parent_pushed { self.parent_stack.pop().unwrap(); }
1640 self.stripped_mod = orig_stripped_mod;
1641 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1647 fn generics(&mut self, generics: &clean::Generics) {
1648 for param in &generics.params {
1650 clean::GenericParamDefKind::Lifetime => {}
1651 clean::GenericParamDefKind::Type { did, .. } => {
1652 self.typarams.insert(did, param.name.clone());
1658 fn add_aliases(&mut self, item: &clean::Item) {
1659 if item.def_id.index == CRATE_DEF_INDEX {
1662 if let Some(ref item_name) = item.name {
1663 let path = self.paths.get(&item.def_id)
1664 .map(|p| p.0[..p.0.len() - 1].join("::"))
1665 .unwrap_or("std".to_owned());
1666 for alias in item.attrs.lists("doc")
1667 .filter(|a| a.check_name("alias"))
1668 .filter_map(|a| a.value_str()
1669 .map(|s| s.to_string().replace("\"", "")))
1670 .filter(|v| !v.is_empty())
1671 .collect::<FxHashSet<_>>()
1673 self.aliases.entry(alias)
1674 .or_insert(Vec::with_capacity(1))
1677 name: item_name.to_string(),
1679 desc: plain_summary_line_short(item.doc_value()),
1682 search_type: get_index_search_type(&item),
1689 #[derive(Debug, Eq, PartialEq, Hash)]
1696 fn new(mut url: String, name: String) -> ItemEntry {
1697 while url.starts_with('/') {
1707 impl fmt::Display for ItemEntry {
1708 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1709 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1713 impl PartialOrd for ItemEntry {
1714 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1715 Some(self.cmp(other))
1719 impl Ord for ItemEntry {
1720 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1721 self.name.cmp(&other.name)
1727 structs: FxHashSet<ItemEntry>,
1728 enums: FxHashSet<ItemEntry>,
1729 unions: FxHashSet<ItemEntry>,
1730 primitives: FxHashSet<ItemEntry>,
1731 traits: FxHashSet<ItemEntry>,
1732 macros: FxHashSet<ItemEntry>,
1733 functions: FxHashSet<ItemEntry>,
1734 typedefs: FxHashSet<ItemEntry>,
1735 existentials: FxHashSet<ItemEntry>,
1736 statics: FxHashSet<ItemEntry>,
1737 constants: FxHashSet<ItemEntry>,
1738 keywords: FxHashSet<ItemEntry>,
1739 attributes: FxHashSet<ItemEntry>,
1740 derives: FxHashSet<ItemEntry>,
1744 fn new() -> AllTypes {
1745 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1747 structs: new_set(100),
1748 enums: new_set(100),
1749 unions: new_set(100),
1750 primitives: new_set(26),
1751 traits: new_set(100),
1752 macros: new_set(100),
1753 functions: new_set(100),
1754 typedefs: new_set(100),
1755 existentials: new_set(100),
1756 statics: new_set(100),
1757 constants: new_set(100),
1758 keywords: new_set(100),
1759 attributes: new_set(100),
1760 derives: new_set(100),
1764 fn append(&mut self, item_name: String, item_type: &ItemType) {
1765 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1766 if let Some(name) = url.pop() {
1767 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1769 let name = url.join("::");
1771 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1772 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1773 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1774 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1775 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1776 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1777 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1778 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1779 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1780 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1781 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1782 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1783 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1790 fn print_entries(f: &mut fmt::Formatter, e: &FxHashSet<ItemEntry>, title: &str,
1791 class: &str) -> fmt::Result {
1793 let mut e: Vec<&ItemEntry> = e.iter().collect();
1795 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1799 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1804 impl fmt::Display for AllTypes {
1805 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1808 <span class='out-of-band'>\
1809 <span id='render-detail'>\
1810 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1811 [<span class='inner'>−</span>]\
1815 <span class='in-band'>List of all items</span>\
1817 print_entries(f, &self.structs, "Structs", "structs")?;
1818 print_entries(f, &self.enums, "Enums", "enums")?;
1819 print_entries(f, &self.unions, "Unions", "unions")?;
1820 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1821 print_entries(f, &self.traits, "Traits", "traits")?;
1822 print_entries(f, &self.macros, "Macros", "macros")?;
1823 print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1824 print_entries(f, &self.derives, "Derive Macros", "derives")?;
1825 print_entries(f, &self.functions, "Functions", "functions")?;
1826 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1827 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1828 print_entries(f, &self.statics, "Statics", "statics")?;
1829 print_entries(f, &self.constants, "Constants", "constants")
1834 struct Settings<'a> {
1835 // (id, explanation, default value)
1836 settings: Vec<(&'static str, &'static str, bool)>,
1841 impl<'a> Settings<'a> {
1842 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1845 ("item-declarations", "Auto-hide item declarations.", true),
1846 ("item-attributes", "Auto-hide item attributes.", true),
1847 ("trait-implementations", "Auto-hide trait implementations documentation",
1849 ("method-docs", "Auto-hide item methods' documentation", false),
1850 ("go-to-only-result", "Directly go to item in search if there is only one result",
1852 ("line-numbers", "Show line numbers on code examples", false),
1860 impl<'a> fmt::Display for Settings<'a> {
1861 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1864 <span class='in-band'>Rustdoc settings</span>\
1866 <div class='settings'>{}</div>\
1867 <script src='{}settings{}.js'></script>",
1868 self.settings.iter()
1869 .map(|(id, text, enabled)| {
1870 format!("<div class='setting-line'>\
1871 <label class='toggle'>\
1872 <input type='checkbox' id='{}' {}>\
1873 <span class='slider'></span>\
1876 </div>", id, if *enabled { " checked" } else { "" }, text)
1878 .collect::<String>(),
1885 fn derive_id(&self, id: String) -> String {
1886 let mut map = self.id_map.borrow_mut();
1890 /// String representation of how to get back to the root path of the 'doc/'
1891 /// folder in terms of a relative URL.
1892 fn root_path(&self) -> String {
1893 "../".repeat(self.current.len())
1896 /// Recurse in the directory structure and change the "root path" to make
1897 /// sure it always points to the top (relatively).
1898 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1899 F: FnOnce(&mut Context) -> T,
1902 panic!("Unexpected empty destination: {:?}", self.current);
1904 let prev = self.dst.clone();
1906 self.current.push(s);
1908 info!("Recursing into {}", self.dst.display());
1912 info!("Recursed; leaving {}", self.dst.display());
1914 // Go back to where we were at
1916 self.current.pop().unwrap();
1921 /// Main method for rendering a crate.
1923 /// This currently isn't parallelized, but it'd be pretty easy to add
1924 /// parallelization to this function.
1925 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1926 let mut item = match krate.module.take() {
1928 None => return Ok(()),
1930 let final_file = self.dst.join(&krate.name)
1932 let settings_file = self.dst.join("settings.html");
1934 let crate_name = krate.name.clone();
1935 item.name = Some(krate.name);
1937 let mut all = AllTypes::new();
1940 // Render the crate documentation
1941 let mut work = vec![(self.clone(), item)];
1943 while let Some((mut cx, item)) = work.pop() {
1944 cx.item(item, &mut all, |cx, item| {
1945 work.push((cx.clone(), item))
1950 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
1951 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1952 if !root_path.ends_with('/') {
1953 root_path.push('/');
1955 let mut page = layout::Page {
1956 title: "List of all items in this crate",
1959 description: "List of all items in this crate",
1960 keywords: BASIC_KEYWORDS,
1961 resource_suffix: &self.shared.resource_suffix,
1963 let sidebar = if let Some(ref version) = cache().crate_version {
1964 format!("<p class='location'>Crate {}</p>\
1965 <div class='block version'>\
1968 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1969 crate_name, version)
1973 try_err!(layout::render(&mut w, &self.shared.layout,
1974 &page, &sidebar, &all,
1975 self.shared.css_file_extension.is_some(),
1976 &self.shared.themes, &[]),
1979 // Generating settings page.
1980 let settings = Settings::new("./", &self.shared.resource_suffix);
1981 page.title = "Rustdoc settings";
1982 page.description = "Settings of Rustdoc";
1983 page.root_path = "./";
1985 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
1986 let mut themes = self.shared.themes.clone();
1987 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1988 themes.push(PathBuf::from("settings.css"));
1989 let mut layout = self.shared.layout.clone();
1990 layout.krate = String::new();
1991 layout.logo = String::new();
1992 layout.favicon = String::new();
1993 try_err!(layout::render(&mut w, &layout,
1994 &page, &sidebar, &settings,
1995 self.shared.css_file_extension.is_some(),
2002 fn render_item(&self,
2003 writer: &mut dyn io::Write,
2007 // A little unfortunate that this is done like this, but it sure
2008 // does make formatting *a lot* nicer.
2009 CURRENT_LOCATION_KEY.with(|slot| {
2010 *slot.borrow_mut() = self.current.clone();
2013 let mut title = if it.is_primitive() || it.is_keyword() {
2014 // No need to include the namespace for primitive types and keywords
2017 self.current.join("::")
2020 if !title.is_empty() {
2021 title.push_str("::");
2023 title.push_str(it.name.as_ref().unwrap());
2025 title.push_str(" - Rust");
2026 let tyname = it.type_().css_class();
2027 let desc = if it.is_crate() {
2028 format!("API documentation for the Rust `{}` crate.",
2029 self.shared.layout.krate)
2031 format!("API documentation for the Rust `{}` {} in crate `{}`.",
2032 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2034 let keywords = make_item_keywords(it);
2035 let page = layout::Page {
2037 root_path: &self.root_path(),
2040 keywords: &keywords,
2041 resource_suffix: &self.shared.resource_suffix,
2045 self.id_map.borrow_mut().reset();
2046 self.id_map.borrow_mut().populate(initial_ids());
2049 if !self.render_redirect_pages {
2050 layout::render(writer, &self.shared.layout, &page,
2051 &Sidebar{ cx: self, item: it },
2052 &Item{ cx: self, item: it },
2053 self.shared.css_file_extension.is_some(),
2054 &self.shared.themes, &[])?;
2056 let mut url = self.root_path();
2057 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2058 for name in &names[..names.len() - 1] {
2062 url.push_str(&item_path(ty, names.last().unwrap()));
2063 layout::redirect(writer, &url)?;
2069 /// Non-parallelized version of rendering an item. This will take the input
2070 /// item, render its contents, and then invoke the specified closure with
2071 /// all sub-items which need to be rendered.
2073 /// The rendering driver uses this closure to queue up more work.
2074 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2075 where F: FnMut(&mut Context, clean::Item),
2077 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2078 // if they contain impls for public types. These modules can also
2079 // contain items such as publicly re-exported structures.
2081 // External crates will provide links to these structures, so
2082 // these modules are recursed into, but not rendered normally
2083 // (a flag on the context).
2084 if !self.render_redirect_pages {
2085 self.render_redirect_pages = item.is_stripped();
2089 // modules are special because they add a namespace. We also need to
2090 // recurse into the items of the module as well.
2091 let name = item.name.as_ref().unwrap().to_string();
2092 let mut item = Some(item);
2093 self.recurse(name, |this| {
2094 let item = item.take().unwrap();
2096 let mut buf = Vec::new();
2097 this.render_item(&mut buf, &item, false).unwrap();
2098 // buf will be empty if the module is stripped and there is no redirect for it
2099 if !buf.is_empty() {
2100 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
2101 let joint_dst = this.dst.join("index.html");
2102 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2105 let m = match item.inner {
2106 clean::StrippedItem(box clean::ModuleItem(m)) |
2107 clean::ModuleItem(m) => m,
2111 // Render sidebar-items.js used throughout this module.
2112 if !this.render_redirect_pages {
2113 let items = this.build_sidebar_items(&m);
2114 let js_dst = this.dst.join("sidebar-items.js");
2115 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
2116 try_err!(write!(&mut js_out, "initSidebarItems({});",
2117 as_json(&items)), &js_dst);
2120 for item in m.items {
2126 } else if item.name.is_some() {
2127 let mut buf = Vec::new();
2128 self.render_item(&mut buf, &item, true).unwrap();
2129 // buf will be empty if the item is stripped and there is no redirect for it
2130 if !buf.is_empty() {
2131 let name = item.name.as_ref().unwrap();
2132 let item_type = item.type_();
2133 let file_name = &item_path(item_type, name);
2134 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
2135 let joint_dst = self.dst.join(file_name);
2136 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2138 if !self.render_redirect_pages {
2139 all.append(full_path(self, &item), &item_type);
2141 // Redirect from a sane URL using the namespace to Rustdoc's
2142 // URL for the page.
2143 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2144 let redir_dst = self.dst.join(redir_name);
2145 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
2148 let mut redirect_out = BufWriter::new(redirect_out);
2149 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2152 // If the item is a macro, redirect from the old macro URL (with !)
2153 // to the new one (without).
2154 if item_type == ItemType::Macro {
2155 let redir_name = format!("{}.{}!.html", item_type, name);
2156 let redir_dst = self.dst.join(redir_name);
2157 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
2158 let mut redirect_out = BufWriter::new(redirect_out);
2159 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2166 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2167 // BTreeMap instead of HashMap to get a sorted output
2168 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2169 for item in &m.items {
2170 if item.is_stripped() { continue }
2172 let short = item.type_().css_class();
2173 let myname = match item.name {
2175 Some(ref s) => s.to_string(),
2177 let short = short.to_string();
2178 map.entry(short).or_default()
2179 .push((myname, Some(plain_summary_line(item.doc_value()))));
2182 if self.shared.sort_modules_alphabetically {
2183 for (_, items) in &mut map {
2192 /// Generate a url appropriate for an `href` attribute back to the source of
2195 /// The url generated, when clicked, will redirect the browser back to the
2196 /// original source code.
2198 /// If `None` is returned, then a source link couldn't be generated. This
2199 /// may happen, for example, with externally inlined items where the source
2200 /// of their crate documentation isn't known.
2201 fn src_href(&self) -> Option<String> {
2202 let mut root = self.cx.root_path();
2204 let cache = cache();
2205 let mut path = String::new();
2207 // We can safely ignore macros from other libraries
2208 let file = match self.item.source.filename {
2209 FileName::Real(ref path) => path,
2213 let (krate, path) = if self.item.def_id.is_local() {
2214 if let Some(path) = self.cx.shared.local_sources.get(file) {
2215 (&self.cx.shared.layout.krate, path)
2220 let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2221 (ref name, ref src, Local) => (name, src),
2222 (ref name, ref src, Remote(ref s)) => {
2223 root = s.to_string();
2226 (_, _, Unknown) => return None,
2229 clean_srcpath(&src_root, file, false, |component| {
2230 path.push_str(component);
2233 let mut fname = file.file_name().expect("source has no filename")
2235 fname.push(".html");
2236 path.push_str(&fname.to_string_lossy());
2240 let lines = if self.item.source.loline == self.item.source.hiline {
2241 self.item.source.loline.to_string()
2243 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2245 Some(format!("{root}src/{krate}/{path}#{lines}",
2246 root = Escape(&root),
2253 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2254 f: F) -> fmt::Result
2255 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2256 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2261 impl<'a> fmt::Display for Item<'a> {
2262 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2263 debug_assert!(!self.item.is_stripped());
2264 // Write the breadcrumb trail header for the top
2265 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2266 if let Some(version) = self.item.stable_since() {
2267 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2271 "<span id='render-detail'>\
2272 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2273 title=\"collapse all docs\">\
2274 [<span class='inner'>−</span>]\
2280 // When this item is part of a `pub use` in a downstream crate, the
2281 // [src] link in the downstream documentation will actually come back to
2282 // this page, and this link will be auto-clicked. The `id` attribute is
2283 // used to find the link to auto-click.
2284 if self.cx.shared.include_sources && !self.item.is_primitive() {
2285 if let Some(l) = self.src_href() {
2286 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2287 l, "goto source code")?;
2291 write!(fmt, "</span>")?; // out-of-band
2292 write!(fmt, "<span class='in-band'>")?;
2293 match self.item.inner {
2294 clean::ModuleItem(ref m) => if m.is_crate {
2295 write!(fmt, "Crate ")?;
2297 write!(fmt, "Module ")?;
2299 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2300 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2301 clean::StructItem(..) => write!(fmt, "Struct ")?,
2302 clean::UnionItem(..) => write!(fmt, "Union ")?,
2303 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2304 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2305 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2306 clean::ProcMacroItem(ref mac) => match mac.kind {
2307 MacroKind::Bang => write!(fmt, "Macro ")?,
2308 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2309 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2310 MacroKind::ProcMacroStub => unreachable!(),
2312 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2313 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2314 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2315 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2316 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2317 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2319 // We don't generate pages for any other type.
2323 if !self.item.is_primitive() && !self.item.is_keyword() {
2324 let cur = &self.cx.current;
2325 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2326 for (i, component) in cur.iter().enumerate().take(amt) {
2327 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2328 "../".repeat(cur.len() - i - 1),
2332 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2333 self.item.type_(), self.item.name.as_ref().unwrap())?;
2335 write!(fmt, "</span></h1>")?; // in-band
2337 match self.item.inner {
2338 clean::ModuleItem(ref m) =>
2339 item_module(fmt, self.cx, self.item, &m.items),
2340 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2341 item_function(fmt, self.cx, self.item, f),
2342 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2343 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2344 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2345 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2346 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2347 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2348 clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2349 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2350 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2351 item_static(fmt, self.cx, self.item, i),
2352 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2353 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2354 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2355 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2357 // We don't generate pages for any other type.
2364 fn item_path(ty: ItemType, name: &str) -> String {
2366 ItemType::Module => format!("{}/index.html", name),
2367 _ => format!("{}.{}.html", ty.css_class(), name),
2371 fn full_path(cx: &Context, item: &clean::Item) -> String {
2372 let mut s = cx.current.join("::");
2374 s.push_str(item.name.as_ref().unwrap());
2378 fn shorter<'a>(s: Option<&'a str>) -> String {
2380 Some(s) => s.lines()
2381 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2383 (*line).chars().any(|chr|{
2384 !chr.is_whitespace()
2386 }).collect::<Vec<_>>().join("\n"),
2387 None => String::new()
2392 fn plain_summary_line(s: Option<&str>) -> String {
2393 let line = shorter(s).replace("\n", " ");
2394 markdown::plain_summary_line_full(&line[..], false)
2398 fn plain_summary_line_short(s: Option<&str>) -> String {
2399 let line = shorter(s).replace("\n", " ");
2400 markdown::plain_summary_line_full(&line[..], true)
2403 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2404 if let Some(ref name) = item.name {
2405 info!("Documenting {}", name);
2407 document_stability(w, cx, item, false)?;
2408 document_full(w, item, cx, "", false)?;
2412 /// Render md_text as markdown.
2413 fn render_markdown(w: &mut fmt::Formatter,
2416 links: Vec<(String, String)>,
2420 let mut ids = cx.id_map.borrow_mut();
2421 write!(w, "<div class='docblock{}'>{}{}</div>",
2422 if is_hidden { " hidden" } else { "" },
2424 Markdown(md_text, &links, RefCell::new(&mut ids),
2428 fn document_short(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, link: AssocItemLink,
2429 prefix: &str, is_hidden: bool) -> fmt::Result {
2430 if let Some(s) = item.doc_value() {
2431 let markdown = if s.contains('\n') {
2432 format!("{} [Read more]({})",
2433 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2435 plain_summary_line(Some(s))
2437 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden)?;
2438 } else if !prefix.is_empty() {
2439 write!(w, "<div class='docblock{}'>{}</div>",
2440 if is_hidden { " hidden" } else { "" },
2446 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2447 cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2448 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2449 debug!("Doc block: =====\n{}\n=====", s);
2450 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2451 } else if !prefix.is_empty() {
2452 write!(w, "<div class='docblock{}'>{}</div>",
2453 if is_hidden { " hidden" } else { "" },
2459 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2460 is_hidden: bool) -> fmt::Result {
2461 let stabilities = short_stability(item, cx, true);
2462 if !stabilities.is_empty() {
2463 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2464 for stability in stabilities {
2465 write!(w, "{}", stability)?;
2467 write!(w, "</div>")?;
2472 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2473 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2476 fn document_non_exhaustive(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
2477 if item.is_non_exhaustive() {
2478 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2479 if item.is_struct() { "struct" } else if item.is_enum() { "enum" } else { "type" }
2482 if item.is_struct() {
2483 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2484 Therefore, non-exhaustive structs cannot be constructed in external crates \
2485 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2486 matched against without a wildcard <code>..</code>; and \
2487 struct update syntax will not work.")?;
2488 } else if item.is_enum() {
2489 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2490 Therefore, when matching against variants of non-exhaustive enums, an \
2491 extra wildcard arm must be added to account for any future variants.")?;
2493 write!(w, "This type will require a wildcard arm in any match statements or \
2497 write!(w, "</div>")?;
2503 fn name_key(name: &str) -> (&str, u64, usize) {
2504 let end = name.bytes()
2505 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2507 // find number at end
2508 let split = name[0..end].bytes()
2509 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2511 // count leading zeroes
2513 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2515 // sort leading zeroes last
2516 let num_zeroes = after_zeroes - split;
2518 match name[split..end].parse() {
2519 Ok(n) => (&name[..split], n, num_zeroes),
2520 Err(_) => (name, 0, num_zeroes),
2524 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2525 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2526 document(w, cx, item)?;
2528 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2530 // the order of item types in the listing
2531 fn reorder(ty: ItemType) -> u8 {
2533 ItemType::ExternCrate => 0,
2534 ItemType::Import => 1,
2535 ItemType::Primitive => 2,
2536 ItemType::Module => 3,
2537 ItemType::Macro => 4,
2538 ItemType::Struct => 5,
2539 ItemType::Enum => 6,
2540 ItemType::Constant => 7,
2541 ItemType::Static => 8,
2542 ItemType::Trait => 9,
2543 ItemType::Function => 10,
2544 ItemType::Typedef => 12,
2545 ItemType::Union => 13,
2550 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2551 let ty1 = i1.type_();
2552 let ty2 = i2.type_();
2554 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2556 let s1 = i1.stability.as_ref().map(|s| s.level);
2557 let s2 = i2.stability.as_ref().map(|s| s.level);
2559 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2560 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2563 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2564 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2565 name_key(lhs).cmp(&name_key(rhs))
2568 if cx.shared.sort_modules_alphabetically {
2569 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2571 // This call is to remove re-export duplicates in cases such as:
2576 // pub trait Double { fn foo(); }
2580 // pub use foo::bar::*;
2584 // `Double` will appear twice in the generated docs.
2586 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2587 // can be identical even if the elements are different (mostly in imports).
2588 // So in case this is an import, we keep everything by adding a "unique id"
2589 // (which is the position in the vector).
2590 indices.dedup_by_key(|i| (items[*i].def_id,
2591 if items[*i].name.as_ref().is_some() {
2592 Some(full_path(cx, &items[*i]))
2597 if items[*i].is_import() {
2603 debug!("{:?}", indices);
2604 let mut curty = None;
2605 for &idx in &indices {
2606 let myitem = &items[idx];
2607 if myitem.is_stripped() {
2611 let myty = Some(myitem.type_());
2612 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2613 // Put `extern crate` and `use` re-exports in the same section.
2615 } else if myty != curty {
2616 if curty.is_some() {
2617 write!(w, "</table>")?;
2620 let (short, name) = item_ty_to_strs(&myty.unwrap());
2621 write!(w, "<h2 id='{id}' class='section-header'>\
2622 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2623 id = cx.derive_id(short.to_owned()), name = name)?;
2626 match myitem.inner {
2627 clean::ExternCrateItem(ref name, ref src) => {
2628 use html::format::HRef;
2632 write!(w, "<tr><td><code>{}extern crate {} as {};",
2633 VisSpace(&myitem.visibility),
2634 HRef::new(myitem.def_id, src),
2638 write!(w, "<tr><td><code>{}extern crate {};",
2639 VisSpace(&myitem.visibility),
2640 HRef::new(myitem.def_id, name))?
2643 write!(w, "</code></td></tr>")?;
2646 clean::ImportItem(ref import) => {
2647 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2648 VisSpace(&myitem.visibility), *import)?;
2652 if myitem.name.is_none() { continue }
2654 let stabilities = short_stability(myitem, cx, false);
2656 let stab_docs = if !stabilities.is_empty() {
2658 .map(|s| format!("[{}]", s))
2659 .collect::<Vec<_>>()
2666 let unsafety_flag = match myitem.inner {
2667 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2668 if func.header.unsafety == hir::Unsafety::Unsafe => {
2669 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2674 let stab = myitem.stability_class();
2675 let add = if stab.is_some() {
2681 let doc_value = myitem.doc_value().unwrap_or("");
2683 <tr class='{stab}{add}module-item'>\
2684 <td><a class=\"{class}\" href=\"{href}\" \
2685 title='{title}'>{name}</a>{unsafety_flag}</td>\
2686 <td class='docblock-short'>{stab_docs}{docs}\
2689 name = *myitem.name.as_ref().unwrap(),
2690 stab_docs = stab_docs,
2691 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2692 class = myitem.type_(),
2694 stab = stab.unwrap_or_else(|| String::new()),
2695 unsafety_flag = unsafety_flag,
2696 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2697 title = [full_path(cx, myitem), myitem.type_().to_string()]
2699 .filter_map(|s| if !s.is_empty() {
2704 .collect::<Vec<_>>()
2711 if curty.is_some() {
2712 write!(w, "</table>")?;
2717 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2718 let mut stability = vec![];
2719 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2721 if let Some(stab) = item.stability.as_ref() {
2722 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2723 format!(": {}", stab.deprecated_reason)
2727 if !stab.deprecated_since.is_empty() {
2728 let since = if show_reason {
2729 format!(" since {}", Escape(&stab.deprecated_since))
2733 let mut ids = cx.id_map.borrow_mut();
2734 let html = MarkdownHtml(&deprecated_reason, RefCell::new(&mut ids), error_codes);
2735 let text = if stability::deprecation_in_effect(&stab.deprecated_since) {
2736 format!("Deprecated{}{}", since, html)
2738 format!("Deprecating in {}{}", Escape(&stab.deprecated_since), html)
2740 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2743 if stab.level == stability::Unstable {
2745 let unstable_extra = match (!stab.feature.is_empty(),
2746 &cx.shared.issue_tracker_base_url,
2748 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2749 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2750 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2751 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2752 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2755 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2758 if stab.unstable_reason.is_empty() {
2759 stability.push(format!("<div class='stab unstable'>\
2760 <span class=microscope>🔬</span> \
2761 This is a nightly-only experimental API. {}\
2765 let mut ids = cx.id_map.borrow_mut();
2766 let text = format!("<summary><span class=microscope>🔬</span> \
2767 This is a nightly-only experimental API. {}\
2771 &stab.unstable_reason,
2772 RefCell::new(&mut ids),
2774 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2778 stability.push("<div class='stab unstable'>Experimental</div>".to_string())
2781 } else if let Some(depr) = item.deprecation.as_ref() {
2782 let note = if show_reason && !depr.note.is_empty() {
2783 format!(": {}", depr.note)
2787 let since = if show_reason && !depr.since.is_empty() {
2788 format!(" since {}", Escape(&depr.since))
2793 let mut ids = cx.id_map.borrow_mut();
2794 let text = if stability::deprecation_in_effect(&depr.since) {
2795 format!("Deprecated{}{}",
2797 MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes))
2799 format!("Deprecating in {}{}",
2800 Escape(&depr.since),
2801 MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes))
2803 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2806 if let Some(ref cfg) = item.attrs.cfg {
2807 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2808 cfg.render_long_html()
2810 cfg.render_short_html()
2817 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2818 c: &clean::Constant) -> fmt::Result {
2819 write!(w, "<pre class='rust const'>")?;
2820 render_attributes(w, it)?;
2821 write!(w, "{vis}const \
2822 {name}: {typ}</pre>",
2823 vis = VisSpace(&it.visibility),
2824 name = it.name.as_ref().unwrap(),
2829 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2830 s: &clean::Static) -> fmt::Result {
2831 write!(w, "<pre class='rust static'>")?;
2832 render_attributes(w, it)?;
2833 write!(w, "{vis}static {mutability}\
2834 {name}: {typ}</pre>",
2835 vis = VisSpace(&it.visibility),
2836 mutability = MutableSpace(s.mutability),
2837 name = it.name.as_ref().unwrap(),
2842 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2843 f: &clean::Function) -> fmt::Result {
2844 let name_len = format!("{}{}{}{}{:#}fn {}{:#}",
2845 VisSpace(&it.visibility),
2846 ConstnessSpace(f.header.constness),
2847 UnsafetySpace(f.header.unsafety),
2848 AsyncSpace(f.header.asyncness),
2849 AbiSpace(f.header.abi),
2850 it.name.as_ref().unwrap(),
2852 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2853 render_attributes(w, it)?;
2855 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2856 {name}{generics}{decl}{where_clause}</pre>",
2857 vis = VisSpace(&it.visibility),
2858 constness = ConstnessSpace(f.header.constness),
2859 unsafety = UnsafetySpace(f.header.unsafety),
2860 asyncness = AsyncSpace(f.header.asyncness),
2861 abi = AbiSpace(f.header.abi),
2862 name = it.name.as_ref().unwrap(),
2863 generics = f.generics,
2864 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2873 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2874 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2875 // If there's already another implementor that has the same abbridged name, use the
2876 // full path, for example in `std::iter::ExactSizeIterator`
2877 let use_absolute = match implementor.inner_impl().for_ {
2878 clean::ResolvedPath { ref path, is_generic: false, .. } |
2879 clean::BorrowedRef {
2880 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2882 } => implementor_dups[path.last_name()].1,
2885 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
2886 implementor.impl_item.stable_since(), false, Some(use_absolute))?;
2890 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2892 containing_item: &clean::Item) -> fmt::Result {
2894 let did = i.trait_did().unwrap();
2895 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2896 render_impl(w, cx, i, assoc_link,
2897 RenderMode::Normal, containing_item.stable_since(), true, None)?;
2902 fn bounds(t_bounds: &[clean::GenericBound]) -> String {
2903 let mut bounds = String::new();
2904 let mut bounds_plain = String::new();
2905 if !t_bounds.is_empty() {
2906 if !bounds.is_empty() {
2908 bounds_plain.push(' ');
2910 bounds.push_str(": ");
2911 bounds_plain.push_str(": ");
2912 for (i, p) in t_bounds.iter().enumerate() {
2914 bounds.push_str(" + ");
2915 bounds_plain.push_str(" + ");
2917 bounds.push_str(&(*p).to_string());
2918 bounds_plain.push_str(&format!("{:#}", *p));
2924 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2925 let lhs = format!("{}", lhs.inner_impl());
2926 let rhs = format!("{}", rhs.inner_impl());
2928 // lhs and rhs are formatted as HTML, which may be unnecessary
2929 name_key(&lhs).cmp(&name_key(&rhs))
2933 w: &mut fmt::Formatter,
2938 let bounds = bounds(&t.bounds);
2939 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2940 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2941 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2942 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2944 // Output the trait definition
2945 wrap_into_docblock(w, |w| {
2946 write!(w, "<pre class='rust trait'>")?;
2947 render_attributes(w, it)?;
2948 write!(w, "{}{}{}trait {}{}{}",
2949 VisSpace(&it.visibility),
2950 UnsafetySpace(t.unsafety),
2951 if t.is_auto { "auto " } else { "" },
2952 it.name.as_ref().unwrap(),
2956 if !t.generics.where_predicates.is_empty() {
2957 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2962 if t.items.is_empty() {
2963 write!(w, "{{ }}")?;
2965 // FIXME: we should be using a derived_id for the Anchors here
2969 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2972 if !types.is_empty() && !consts.is_empty() {
2977 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2980 if !consts.is_empty() && !required.is_empty() {
2983 for (pos, m) in required.iter().enumerate() {
2985 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2988 if pos < required.len() - 1 {
2989 write!(w, "<div class='item-spacer'></div>")?;
2992 if !required.is_empty() && !provided.is_empty() {
2995 for (pos, m) in provided.iter().enumerate() {
2997 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2999 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3000 write!(w, ",\n {{ ... }}\n")?;
3003 write!(w, " {{ ... }}\n")?;
3006 if pos < provided.len() - 1 {
3007 write!(w, "<div class='item-spacer'></div>")?;
3015 // Trait documentation
3016 document(w, cx, it)?;
3018 fn write_small_section_header(
3019 w: &mut fmt::Formatter,
3022 extra_content: &str,
3025 <h2 id='{0}' class='small-section-header'>\
3026 {1}<a href='#{0}' class='anchor'></a>\
3027 </h2>{2}", id, title, extra_content)
3030 fn write_loading_content(w: &mut fmt::Formatter, extra_content: &str) -> fmt::Result {
3031 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3034 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
3036 let name = m.name.as_ref().unwrap();
3037 let item_type = m.type_();
3038 let id = cx.derive_id(format!("{}.{}", item_type, name));
3039 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3040 write!(w, "{extra}<h3 id='{id}' class='method'>\
3041 <span id='{ns_id}' class='invisible'><code>",
3042 extra = render_spotlight_traits(m)?,
3045 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3046 write!(w, "</code>")?;
3047 render_stability_since(w, m, t)?;
3048 write!(w, "</span></h3>")?;
3049 document(w, cx, m)?;
3053 if !types.is_empty() {
3054 write_small_section_header(w, "associated-types", "Associated Types",
3055 "<div class='methods'>")?;
3057 trait_item(w, cx, *t, it)?;
3059 write_loading_content(w, "</div>")?;
3062 if !consts.is_empty() {
3063 write_small_section_header(w, "associated-const", "Associated Constants",
3064 "<div class='methods'>")?;
3066 trait_item(w, cx, *t, it)?;
3068 write_loading_content(w, "</div>")?;
3071 // Output the documentation for each function individually
3072 if !required.is_empty() {
3073 write_small_section_header(w, "required-methods", "Required methods",
3074 "<div class='methods'>")?;
3075 for m in &required {
3076 trait_item(w, cx, *m, it)?;
3078 write_loading_content(w, "</div>")?;
3080 if !provided.is_empty() {
3081 write_small_section_header(w, "provided-methods", "Provided methods",
3082 "<div class='methods'>")?;
3083 for m in &provided {
3084 trait_item(w, cx, *m, it)?;
3086 write_loading_content(w, "</div>")?;
3089 // If there are methods directly on this trait object, render them here.
3090 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3092 let cache = cache();
3094 let mut synthetic_types = Vec::new();
3096 if let Some(implementors) = cache.implementors.get(&it.def_id) {
3097 // The DefId is for the first Type found with that name. The bool is
3098 // if any Types with the same name but different DefId have been found.
3099 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3100 for implementor in implementors {
3101 match implementor.inner_impl().for_ {
3102 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3103 clean::BorrowedRef {
3104 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3107 let &mut (prev_did, ref mut has_duplicates) =
3108 implementor_dups.entry(path.last_name()).or_insert((did, false));
3109 if prev_did != did {
3110 *has_duplicates = true;
3117 let (local, foreign) = implementors.iter()
3118 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3119 .map_or(true, |d| cache.paths.contains_key(&d)));
3122 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3123 .partition(|i| i.inner_impl().synthetic);
3125 synthetic.sort_by(compare_impl);
3126 concrete.sort_by(compare_impl);
3128 if !foreign.is_empty() {
3129 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3131 for implementor in foreign {
3132 let assoc_link = AssocItemLink::GotoSource(
3133 implementor.impl_item.def_id,
3134 &implementor.inner_impl().provided_trait_methods
3136 render_impl(w, cx, &implementor, assoc_link,
3137 RenderMode::Normal, implementor.impl_item.stable_since(), false,
3140 write_loading_content(w, "")?;
3143 write_small_section_header(w, "implementors", "Implementors",
3144 "<div class='item-list' id='implementors-list'>")?;
3145 for implementor in concrete {
3146 render_implementor(cx, implementor, w, &implementor_dups)?;
3148 write_loading_content(w, "</div>")?;
3151 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3152 "<div class='item-list' id='synthetic-implementors-list'>")?;
3153 for implementor in synthetic {
3154 synthetic_types.extend(
3155 collect_paths_for_type(implementor.inner_impl().for_.clone())
3157 render_implementor(cx, implementor, w, &implementor_dups)?;
3159 write_loading_content(w, "</div>")?;
3162 // even without any implementations to write in, we still want the heading and list, so the
3163 // implementors javascript file pulled in below has somewhere to write the impls into
3164 write_small_section_header(w, "implementors", "Implementors",
3165 "<div class='item-list' id='implementors-list'>")?;
3166 write_loading_content(w, "</div>")?;
3169 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3170 "<div class='item-list' id='synthetic-implementors-list'>")?;
3171 write_loading_content(w, "</div>")?;
3174 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3175 as_json(&synthetic_types))?;
3177 write!(w, r#"<script type="text/javascript" async
3178 src="{root_path}/implementors/{path}/{ty}.{name}.js">
3180 root_path = vec![".."; cx.current.len()].join("/"),
3181 path = if it.def_id.is_local() {
3182 cx.current.join("/")
3184 let (ref path, _) = cache.external_paths[&it.def_id];
3185 path[..path.len() - 1].join("/")
3187 ty = it.type_().css_class(),
3188 name = *it.name.as_ref().unwrap())?;
3192 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
3193 use html::item_type::ItemType::*;
3195 let name = it.name.as_ref().unwrap();
3196 let ty = match it.type_() {
3197 Typedef | AssociatedType => AssociatedType,
3201 let anchor = format!("#{}.{}", ty, name);
3203 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3204 AssocItemLink::Anchor(None) => anchor,
3205 AssocItemLink::GotoSource(did, _) => {
3206 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3211 fn assoc_const(w: &mut fmt::Formatter,
3214 _default: Option<&String>,
3215 link: AssocItemLink) -> fmt::Result {
3216 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3217 VisSpace(&it.visibility),
3218 naive_assoc_href(it, link),
3219 it.name.as_ref().unwrap(),
3224 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3225 bounds: &[clean::GenericBound],
3226 default: Option<&clean::Type>,
3227 link: AssocItemLink) -> fmt::Result {
3228 write!(w, "type <a href='{}' class=\"type\">{}</a>",
3229 naive_assoc_href(it, link),
3230 it.name.as_ref().unwrap())?;
3231 if !bounds.is_empty() {
3232 write!(w, ": {}", GenericBounds(bounds))?
3234 if let Some(default) = default {
3235 write!(w, " = {}", default)?;
3240 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
3241 ver: Option<&'a str>,
3242 containing_ver: Option<&'a str>) -> fmt::Result {
3243 if let Some(v) = ver {
3244 if containing_ver != ver && v.len() > 0 {
3245 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
3252 fn render_stability_since(w: &mut fmt::Formatter,
3254 containing_item: &clean::Item) -> fmt::Result {
3255 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3258 fn render_assoc_item(w: &mut fmt::Formatter,
3260 link: AssocItemLink,
3261 parent: ItemType) -> fmt::Result {
3262 fn method(w: &mut fmt::Formatter,
3264 header: hir::FnHeader,
3265 g: &clean::Generics,
3267 link: AssocItemLink,
3270 let name = meth.name.as_ref().unwrap();
3271 let anchor = format!("#{}.{}", meth.type_(), name);
3272 let href = match link {
3273 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3274 AssocItemLink::Anchor(None) => anchor,
3275 AssocItemLink::GotoSource(did, provided_methods) => {
3276 // We're creating a link from an impl-item to the corresponding
3277 // trait-item and need to map the anchored type accordingly.
3278 let ty = if provided_methods.contains(name) {
3284 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3287 let mut head_len = format!("{}{}{}{}{:#}fn {}{:#}",
3288 VisSpace(&meth.visibility),
3289 ConstnessSpace(header.constness),
3290 UnsafetySpace(header.unsafety),
3291 AsyncSpace(header.asyncness),
3292 AbiSpace(header.abi),
3295 let (indent, end_newline) = if parent == ItemType::Trait {
3301 render_attributes(w, meth)?;
3302 write!(w, "{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3303 {generics}{decl}{where_clause}",
3304 VisSpace(&meth.visibility),
3305 ConstnessSpace(header.constness),
3306 UnsafetySpace(header.unsafety),
3307 AsyncSpace(header.asyncness),
3308 AbiSpace(header.abi),
3317 where_clause = WhereClause {
3324 clean::StrippedItem(..) => Ok(()),
3325 clean::TyMethodItem(ref m) => {
3326 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3328 clean::MethodItem(ref m) => {
3329 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3331 clean::AssociatedConstItem(ref ty, ref default) => {
3332 assoc_const(w, item, ty, default.as_ref(), link)
3334 clean::AssociatedTypeItem(ref bounds, ref default) => {
3335 assoc_type(w, item, bounds, default.as_ref(), link)
3337 _ => panic!("render_assoc_item called on non-associated-item")
3341 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3342 s: &clean::Struct) -> fmt::Result {
3343 wrap_into_docblock(w, |w| {
3344 write!(w, "<pre class='rust struct'>")?;
3345 render_attributes(w, it)?;
3356 document(w, cx, it)?;
3357 let mut fields = s.fields.iter().filter_map(|f| {
3359 clean::StructFieldItem(ref ty) => Some((f, ty)),
3363 if let doctree::Plain = s.struct_type {
3364 if fields.peek().is_some() {
3365 write!(w, "<h2 id='fields' class='fields small-section-header'>
3366 Fields{}<a href='#fields' class='anchor'></a></h2>",
3367 document_non_exhaustive_header(it))?;
3368 document_non_exhaustive(w, it)?;
3369 for (field, ty) in fields {
3370 let id = cx.derive_id(format!("{}.{}",
3371 ItemType::StructField,
3372 field.name.as_ref().unwrap()));
3373 let ns_id = cx.derive_id(format!("{}.{}",
3374 field.name.as_ref().unwrap(),
3375 ItemType::StructField.name_space()));
3376 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
3377 <a href=\"#{id}\" class=\"anchor field\"></a>
3378 <span id=\"{ns_id}\" class='invisible'>
3379 <code>{name}: {ty}</code>
3381 item_type = ItemType::StructField,
3384 name = field.name.as_ref().unwrap(),
3386 if let Some(stability_class) = field.stability_class() {
3387 write!(w, "<span class='stab {stab}'></span>",
3388 stab = stability_class)?;
3390 document(w, cx, field)?;
3394 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3397 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3398 s: &clean::Union) -> fmt::Result {
3399 wrap_into_docblock(w, |w| {
3400 write!(w, "<pre class='rust union'>")?;
3401 render_attributes(w, it)?;
3411 document(w, cx, it)?;
3412 let mut fields = s.fields.iter().filter_map(|f| {
3414 clean::StructFieldItem(ref ty) => Some((f, ty)),
3418 if fields.peek().is_some() {
3419 write!(w, "<h2 id='fields' class='fields small-section-header'>
3420 Fields<a href='#fields' class='anchor'></a></h2>")?;
3421 for (field, ty) in fields {
3422 let name = field.name.as_ref().expect("union field name");
3423 let id = format!("{}.{}", ItemType::StructField, name);
3424 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3425 <a href=\"#{id}\" class=\"anchor field\"></a>\
3426 <span class='invisible'><code>{name}: {ty}</code></span>\
3430 shortty = ItemType::StructField,
3432 if let Some(stability_class) = field.stability_class() {
3433 write!(w, "<span class='stab {stab}'></span>",
3434 stab = stability_class)?;
3436 document(w, cx, field)?;
3439 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3442 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3443 e: &clean::Enum) -> fmt::Result {
3444 wrap_into_docblock(w, |w| {
3445 write!(w, "<pre class='rust enum'>")?;
3446 render_attributes(w, it)?;
3447 write!(w, "{}enum {}{}{}",
3448 VisSpace(&it.visibility),
3449 it.name.as_ref().unwrap(),
3451 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3452 if e.variants.is_empty() && !e.variants_stripped {
3453 write!(w, " {{}}")?;
3455 write!(w, " {{\n")?;
3456 for v in &e.variants {
3458 let name = v.name.as_ref().unwrap();
3460 clean::VariantItem(ref var) => {
3462 clean::VariantKind::CLike => write!(w, "{}", name)?,
3463 clean::VariantKind::Tuple(ref tys) => {
3464 write!(w, "{}(", name)?;
3465 for (i, ty) in tys.iter().enumerate() {
3467 write!(w, ", ")?
3469 write!(w, "{}", *ty)?;
3473 clean::VariantKind::Struct(ref s) => {
3489 if e.variants_stripped {
3490 write!(w, " // some variants omitted\n")?;
3497 document(w, cx, it)?;
3498 if !e.variants.is_empty() {
3499 write!(w, "<h2 id='variants' class='variants small-section-header'>
3500 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3501 document_non_exhaustive_header(it))?;
3502 document_non_exhaustive(w, it)?;
3503 for variant in &e.variants {
3504 let id = cx.derive_id(format!("{}.{}",
3506 variant.name.as_ref().unwrap()));
3507 let ns_id = cx.derive_id(format!("{}.{}",
3508 variant.name.as_ref().unwrap(),
3509 ItemType::Variant.name_space()));
3510 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3511 <a href=\"#{id}\" class=\"anchor field\"></a>\
3512 <span id='{ns_id}' class='invisible'><code>{name}",
3515 name = variant.name.as_ref().unwrap())?;
3516 if let clean::VariantItem(ref var) = variant.inner {
3517 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3519 for (i, ty) in tys.iter().enumerate() {
3521 write!(w, ", ")?;
3523 write!(w, "{}", *ty)?;
3528 write!(w, "</code></span></span>")?;
3529 document(w, cx, variant)?;
3531 use clean::{Variant, VariantKind};
3532 if let clean::VariantItem(Variant {
3533 kind: VariantKind::Struct(ref s)
3534 }) = variant.inner {
3535 let variant_id = cx.derive_id(format!("{}.{}.fields",
3537 variant.name.as_ref().unwrap()));
3538 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3540 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3541 name = variant.name.as_ref().unwrap())?;
3542 for field in &s.fields {
3543 use clean::StructFieldItem;
3544 if let StructFieldItem(ref ty) = field.inner {
3545 let id = cx.derive_id(format!("variant.{}.field.{}",
3546 variant.name.as_ref().unwrap(),
3547 field.name.as_ref().unwrap()));
3548 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3549 variant.name.as_ref().unwrap(),
3550 ItemType::Variant.name_space(),
3551 field.name.as_ref().unwrap(),
3552 ItemType::StructField.name_space()));
3553 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3554 <a href=\"#{id}\" class=\"anchor field\"></a>\
3555 <span id='{ns_id}' class='invisible'><code>{f}: {t}\
3556 </code></span></span>",
3559 f = field.name.as_ref().unwrap(),
3561 document(w, cx, field)?;
3564 write!(w, "</div></span>")?;
3566 render_stability_since(w, variant, it)?;
3569 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3573 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3574 let name = attr.name();
3577 Some(name.to_string())
3578 } else if let Some(v) = attr.value_str() {
3579 Some(format!("{} = {:?}", name, v.as_str()))
3580 } else if let Some(values) = attr.meta_item_list() {
3581 let display: Vec<_> = values.iter().filter_map(|attr| {
3582 attr.meta_item().and_then(|mi| render_attribute(mi))
3585 if display.len() > 0 {
3586 Some(format!("{}({})", name, display.join(", ")))
3595 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3602 "unsafe_destructor_blind_to_params",
3606 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3607 let mut attrs = String::new();
3609 for attr in &it.attrs.other_attrs {
3610 let name = attr.name();
3611 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3614 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3615 attrs.push_str(&format!("#[{}]\n", s));
3618 if attrs.len() > 0 {
3619 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3624 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3625 g: Option<&clean::Generics>,
3626 ty: doctree::StructType,
3627 fields: &[clean::Item],
3629 structhead: bool) -> fmt::Result {
3631 VisSpace(&it.visibility),
3632 if structhead {"struct "} else {""},
3633 it.name.as_ref().unwrap())?;
3634 if let Some(g) = g {
3639 if let Some(g) = g {
3640 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3642 let mut has_visible_fields = false;
3644 for field in fields {
3645 if let clean::StructFieldItem(ref ty) = field.inner {
3646 write!(w, "\n{} {}{}: {},",
3648 VisSpace(&field.visibility),
3649 field.name.as_ref().unwrap(),
3651 has_visible_fields = true;
3655 if has_visible_fields {
3656 if it.has_stripped_fields().unwrap() {
3657 write!(w, "\n{} // some fields omitted", tab)?;
3659 write!(w, "\n{}", tab)?;
3660 } else if it.has_stripped_fields().unwrap() {
3661 // If there are no visible fields we can just display
3662 // `{ /* fields omitted */ }` to save space.
3663 write!(w, " /* fields omitted */ ")?;
3669 for (i, field) in fields.iter().enumerate() {
3674 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3677 clean::StructFieldItem(ref ty) => {
3678 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3684 if let Some(g) = g {
3685 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3690 // Needed for PhantomData.
3691 if let Some(g) = g {
3692 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3700 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3701 g: Option<&clean::Generics>,
3702 fields: &[clean::Item],
3704 structhead: bool) -> fmt::Result {
3706 VisSpace(&it.visibility),
3707 if structhead {"union "} else {""},
3708 it.name.as_ref().unwrap())?;
3709 if let Some(g) = g {
3710 write!(w, "{}", g)?;
3711 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3714 write!(w, " {{\n{}", tab)?;
3715 for field in fields {
3716 if let clean::StructFieldItem(ref ty) = field.inner {
3717 write!(w, " {}{}: {},\n{}",
3718 VisSpace(&field.visibility),
3719 field.name.as_ref().unwrap(),
3725 if it.has_stripped_fields().unwrap() {
3726 write!(w, " // some fields omitted\n{}", tab)?;
3732 #[derive(Copy, Clone)]
3733 enum AssocItemLink<'a> {
3734 Anchor(Option<&'a str>),
3735 GotoSource(DefId, &'a FxHashSet<String>),
3738 impl<'a> AssocItemLink<'a> {
3739 fn anchor(&self, id: &'a String) -> Self {
3741 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3742 ref other => *other,
3747 enum AssocItemRender<'a> {
3749 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3752 #[derive(Copy, Clone, PartialEq)]
3755 ForDeref { mut_: bool },
3758 fn render_assoc_items(w: &mut fmt::Formatter,
3760 containing_item: &clean::Item,
3762 what: AssocItemRender) -> fmt::Result {
3764 let v = match c.impls.get(&it) {
3766 None => return Ok(()),
3768 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3769 i.inner_impl().trait_.is_none()
3771 if !non_trait.is_empty() {
3772 let render_mode = match what {
3773 AssocItemRender::All => {
3775 <h2 id='methods' class='small-section-header'>\
3776 Methods<a href='#methods' class='anchor'></a>\
3781 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3783 <h2 id='deref-methods' class='small-section-header'>\
3784 Methods from {}<Target = {}>\
3785 <a href='#deref-methods' class='anchor'></a>\
3788 RenderMode::ForDeref { mut_: deref_mut_ }
3791 for i in &non_trait {
3792 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3793 containing_item.stable_since(), true, None)?;
3796 if let AssocItemRender::DerefFor { .. } = what {
3799 if !traits.is_empty() {
3800 let deref_impl = traits.iter().find(|t| {
3801 t.inner_impl().trait_.def_id() == c.deref_trait_did
3803 if let Some(impl_) = deref_impl {
3804 let has_deref_mut = traits.iter().find(|t| {
3805 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3807 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3810 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3812 .partition(|t| t.inner_impl().synthetic);
3813 let (blanket_impl, concrete) = concrete
3815 .partition(|t| t.inner_impl().blanket_impl.is_some());
3817 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3819 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3820 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3821 render_impls(self.0, fmt, &self.1, self.2)
3825 let impls = RendererStruct(cx, concrete, containing_item).to_string();
3826 if !impls.is_empty() {
3828 <h2 id='implementations' class='small-section-header'>\
3829 Trait Implementations<a href='#implementations' class='anchor'></a>\
3831 <div id='implementations-list'>{}</div>", impls)?;
3834 if !synthetic.is_empty() {
3836 <h2 id='synthetic-implementations' class='small-section-header'>\
3837 Auto Trait Implementations\
3838 <a href='#synthetic-implementations' class='anchor'></a>\
3840 <div id='synthetic-implementations-list'>\
3842 render_impls(cx, w, &synthetic, containing_item)?;
3843 write!(w, "</div>")?;
3846 if !blanket_impl.is_empty() {
3848 <h2 id='blanket-implementations' class='small-section-header'>\
3849 Blanket Implementations\
3850 <a href='#blanket-implementations' class='anchor'></a>\
3852 <div id='blanket-implementations-list'>\
3854 render_impls(cx, w, &blanket_impl, containing_item)?;
3855 write!(w, "</div>")?;
3861 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3862 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3863 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3864 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3866 clean::TypedefItem(ref t, true) => Some(&t.type_),
3869 }).next().expect("Expected associated type binding");
3870 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3871 deref_mut_: deref_mut };
3872 if let Some(did) = target.def_id() {
3873 render_assoc_items(w, cx, container_item, did, what)
3875 if let Some(prim) = target.primitive_type() {
3876 if let Some(&did) = cache().primitive_locations.get(&prim) {
3877 render_assoc_items(w, cx, container_item, did, what)?;
3884 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3885 let self_type_opt = match item.inner {
3886 clean::MethodItem(ref method) => method.decl.self_type(),
3887 clean::TyMethodItem(ref method) => method.decl.self_type(),
3891 if let Some(self_ty) = self_type_opt {
3892 let (by_mut_ref, by_box, by_value) = match self_ty {
3893 SelfTy::SelfBorrowed(_, mutability) |
3894 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3895 (mutability == Mutability::Mutable, false, false)
3897 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3898 (false, Some(did) == cache().owned_box_did, false)
3900 SelfTy::SelfValue => (false, false, true),
3901 _ => (false, false, false),
3904 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3910 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3911 let mut out = String::new();
3914 clean::FunctionItem(clean::Function { ref decl, .. }) |
3915 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3916 clean::MethodItem(clean::Method { ref decl, .. }) |
3917 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3918 out = spotlight_decl(decl)?;
3926 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3927 let mut out = String::new();
3928 let mut trait_ = String::new();
3930 if let Some(did) = decl.output.def_id() {
3932 if let Some(impls) = c.impls.get(&did) {
3934 let impl_ = i.inner_impl();
3935 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3938 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3939 <code class=\"content\">",
3941 trait_.push_str(&impl_.for_.to_string());
3944 //use the "where" class here to make it small
3945 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3946 let t_did = impl_.trait_.def_id().unwrap();
3947 for it in &impl_.items {
3948 if let clean::TypedefItem(ref tydef, _) = it.inner {
3949 out.push_str("<span class=\"where fmt-newline\"> ");
3950 assoc_type(&mut out, it, &[],
3952 AssocItemLink::GotoSource(t_did, &FxHashSet::default()))?;
3953 out.push_str(";</span>");
3961 if !out.is_empty() {
3962 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3963 <span class='tooltiptext'>Important traits for {}</span></div>\
3964 <div class=\"content hidden\">",
3966 out.push_str("</code></div></div>");
3972 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3973 render_mode: RenderMode, outer_version: Option<&str>,
3974 show_def_docs: bool, use_absolute: Option<bool>) -> fmt::Result {
3975 if render_mode == RenderMode::Normal {
3976 let id = cx.derive_id(match i.inner_impl().trait_ {
3977 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3978 None => "impl".to_string(),
3980 if let Some(use_absolute) = use_absolute {
3981 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
3982 <tbody><tr><td><code>", id)?;
3983 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
3985 for it in &i.inner_impl().items {
3986 if let clean::TypedefItem(ref tydef, _) = it.inner {
3987 write!(w, "<span class=\"where fmt-newline\"> ")?;
3988 assoc_type(w, it, &vec![], Some(&tydef.type_),
3989 AssocItemLink::Anchor(None))?;
3990 write!(w, ";</span>")?;
3994 write!(w, "</code>")?;
3996 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
3997 <tbody><tr><td><code>{}</code>",
3998 id, i.inner_impl())?;
4000 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4001 write!(w, "</span></td><td><span class='out-of-band'>")?;
4002 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4003 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4004 write!(w, "<div class='ghost'></div>")?;
4005 render_stability_since_raw(w, since, outer_version)?;
4006 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4007 l, "goto source code")?;
4009 render_stability_since_raw(w, since, outer_version)?;
4011 write!(w, "</span></td></tr></tbody></table></h3>")?;
4012 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4013 let mut ids = cx.id_map.borrow_mut();
4014 write!(w, "<div class='docblock'>{}</div>",
4015 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids), cx.codes))?;
4019 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
4020 link: AssocItemLink, render_mode: RenderMode,
4021 is_default_item: bool, outer_version: Option<&str>,
4022 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4023 let item_type = item.type_();
4024 let name = item.name.as_ref().unwrap();
4026 let render_method_item: bool = match render_mode {
4027 RenderMode::Normal => true,
4028 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4031 let (is_hidden, extra_class) = if trait_.is_none() ||
4032 item.doc_value().is_some() ||
4033 item.inner.is_associated() {
4039 clean::MethodItem(clean::Method { ref decl, .. }) |
4040 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4041 // Only render when the method is not static or we allow static methods
4042 if render_method_item {
4043 let id = cx.derive_id(format!("{}.{}", item_type, name));
4044 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4045 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4046 write!(w, "{}", spotlight_decl(decl)?)?;
4047 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
4048 write!(w, "<table class='table-display'><tbody><tr><td><code>")?;
4049 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4050 write!(w, "</code>")?;
4051 if let Some(l) = (Item { cx, item }).src_href() {
4052 write!(w, "</span></td><td><span class='out-of-band'>")?;
4053 write!(w, "<div class='ghost'></div>")?;
4054 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4055 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4056 l, "goto source code")?;
4058 write!(w, "</td><td>")?;
4059 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4061 write!(w, "</td></tr></tbody></table></span></h4>")?;
4064 clean::TypedefItem(ref tydef, _) => {
4065 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name));
4066 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4067 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4068 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
4069 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
4070 write!(w, "</code></span></h4>\n")?;
4072 clean::AssociatedConstItem(ref ty, ref default) => {
4073 let id = cx.derive_id(format!("{}.{}", item_type, name));
4074 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4075 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4076 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
4077 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
4078 let src = if let Some(l) = (Item { cx, item }).src_href() {
4079 format!("<a class='srclink' href='{}' title='{}'>[src]</a>",
4080 l, "goto source code")
4084 write!(w, "</code>{}</span></h4>\n", src)?;
4086 clean::AssociatedTypeItem(ref bounds, ref default) => {
4087 let id = cx.derive_id(format!("{}.{}", item_type, name));
4088 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4089 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4090 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
4091 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
4092 write!(w, "</code></span></h4>\n")?;
4094 clean::StrippedItem(..) => return Ok(()),
4095 _ => panic!("can't make docs for trait item with name {:?}", item.name)
4098 if render_method_item || render_mode == RenderMode::Normal {
4099 if !is_default_item {
4100 if let Some(t) = trait_ {
4101 // The trait item may have been stripped so we might not
4102 // find any documentation or stability for it.
4103 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4104 // We need the stability of the item from the trait
4105 // because impls can't have a stability.
4106 document_stability(w, cx, it, is_hidden)?;
4107 if item.doc_value().is_some() {
4108 document_full(w, item, cx, "", is_hidden)?;
4109 } else if show_def_docs {
4110 // In case the item isn't documented,
4111 // provide short documentation from the trait.
4112 document_short(w, cx, it, link, "", is_hidden)?;
4116 document_stability(w, cx, item, is_hidden)?;
4118 document_full(w, item, cx, "", is_hidden)?;
4122 document_stability(w, cx, item, is_hidden)?;
4124 document_short(w, cx, item, link, "", is_hidden)?;
4131 let traits = &cache().traits;
4132 let trait_ = i.trait_did().map(|did| &traits[&did]);
4134 write!(w, "<div class='impl-items'>")?;
4135 for trait_item in &i.inner_impl().items {
4136 doc_impl_item(w, cx, trait_item, link, render_mode,
4137 false, outer_version, trait_, show_def_docs)?;
4140 fn render_default_items(w: &mut fmt::Formatter,
4144 render_mode: RenderMode,
4145 outer_version: Option<&str>,
4146 show_def_docs: bool) -> fmt::Result {
4147 for trait_item in &t.items {
4148 let n = trait_item.name.clone();
4149 if i.items.iter().find(|m| m.name == n).is_some() {
4152 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4153 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4155 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4156 outer_version, None, show_def_docs)?;
4161 // If we've implemented a trait, then also emit documentation for all
4162 // default items which weren't overridden in the implementation block.
4163 if let Some(t) = trait_ {
4164 render_default_items(w, cx, t, &i.inner_impl(),
4165 render_mode, outer_version, show_def_docs)?;
4167 write!(w, "</div>")?;
4172 fn item_existential(
4173 w: &mut fmt::Formatter,
4176 t: &clean::Existential,
4178 write!(w, "<pre class='rust existential'>")?;
4179 render_attributes(w, it)?;
4180 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4181 it.name.as_ref().unwrap(),
4183 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4184 bounds = bounds(&t.bounds))?;
4186 document(w, cx, it)?;
4188 // Render any items associated directly to this alias, as otherwise they
4189 // won't be visible anywhere in the docs. It would be nice to also show
4190 // associated items from the aliased type (see discussion in #32077), but
4191 // we need #14072 to make sense of the generics.
4192 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4195 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4196 t: &clean::Typedef) -> fmt::Result {
4197 write!(w, "<pre class='rust typedef'>")?;
4198 render_attributes(w, it)?;
4199 write!(w, "type {}{}{where_clause} = {type_};</pre>",
4200 it.name.as_ref().unwrap(),
4202 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4205 document(w, cx, it)?;
4207 // Render any items associated directly to this alias, as otherwise they
4208 // won't be visible anywhere in the docs. It would be nice to also show
4209 // associated items from the aliased type (see discussion in #32077), but
4210 // we need #14072 to make sense of the generics.
4211 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4214 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
4215 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4216 render_attributes(w, it)?;
4219 " {}type {};\n}}</pre>",
4220 VisSpace(&it.visibility),
4221 it.name.as_ref().unwrap(),
4224 document(w, cx, it)?;
4226 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4229 impl<'a> fmt::Display for Sidebar<'a> {
4230 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4233 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4235 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4236 || it.is_enum() || it.is_mod() || it.is_typedef() {
4237 write!(fmt, "<p class='location'>{}{}</p>",
4239 clean::StructItem(..) => "Struct ",
4240 clean::TraitItem(..) => "Trait ",
4241 clean::PrimitiveItem(..) => "Primitive Type ",
4242 clean::UnionItem(..) => "Union ",
4243 clean::EnumItem(..) => "Enum ",
4244 clean::TypedefItem(..) => "Type Definition ",
4245 clean::ForeignTypeItem => "Foreign Type ",
4246 clean::ModuleItem(..) => if it.is_crate() {
4253 it.name.as_ref().unwrap())?;
4257 if let Some(ref version) = cache().crate_version {
4259 "<div class='block version'>\
4266 write!(fmt, "<div class=\"sidebar-elems\">")?;
4268 write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4269 it.name.as_ref().expect("crates always have a name"))?;
4272 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4273 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4274 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4275 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4276 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4277 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4278 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4279 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4283 // The sidebar is designed to display sibling functions, modules and
4284 // other miscellaneous information. since there are lots of sibling
4285 // items (and that causes quadratic growth in large modules),
4286 // we refactor common parts into a shared JavaScript file per module.
4287 // still, we don't move everything into JS because we want to preserve
4288 // as much HTML as possible in order to allow non-JS-enabled browsers
4289 // to navigate the documentation (though slightly inefficiently).
4291 write!(fmt, "<p class='location'>")?;
4292 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4294 write!(fmt, "::<wbr>")?;
4296 write!(fmt, "<a href='{}index.html'>{}</a>",
4297 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4300 write!(fmt, "</p>")?;
4302 // Sidebar refers to the enclosing module, not this module.
4303 let relpath = if it.is_mod() { "../" } else { "" };
4305 "<script>window.sidebarCurrent = {{\
4310 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4311 ty = it.type_().css_class(),
4314 // There is no sidebar-items.js beyond the crate root path
4315 // FIXME maybe dynamic crate loading can be merged here
4317 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4320 // Closes sidebar-elems div.
4321 write!(fmt, "</div>")?;
4327 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4328 if used_links.insert(url.clone()) {
4332 while used_links.insert(format!("{}-{}", url, add)) == false {
4335 format!("{}-{}", url, add)
4341 used_links: &mut FxHashSet<String>,
4343 i.items.iter().filter_map(|item| {
4345 // Maybe check with clean::Visibility::Public as well?
4346 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4347 if !for_deref || should_render_item(item, false) {
4348 Some(format!("<a href=\"#{}\">{}</a>",
4349 get_next_url(used_links, format!("method.{}", name)),
4357 }).collect::<Vec<_>>()
4360 // The point is to url encode any potential character from a type with genericity.
4361 fn small_url_encode(s: &str) -> String {
4362 s.replace("<", "%3C")
4363 .replace(">", "%3E")
4364 .replace(" ", "%20")
4365 .replace("?", "%3F")
4366 .replace("'", "%27")
4367 .replace("&", "%26")
4368 .replace(",", "%2C")
4369 .replace(":", "%3A")
4370 .replace(";", "%3B")
4371 .replace("[", "%5B")
4372 .replace("]", "%5D")
4373 .replace("\"", "%22")
4376 fn sidebar_assoc_items(it: &clean::Item) -> String {
4377 let mut out = String::new();
4379 if let Some(v) = c.impls.get(&it.def_id) {
4380 let mut used_links = FxHashSet::default();
4383 let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4385 .filter(|i| i.inner_impl().trait_.is_none())
4386 .flat_map(move |i| get_methods(i.inner_impl(),
4388 &mut used_links_bor.borrow_mut()))
4389 .collect::<String>();
4390 if !ret.is_empty() {
4391 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4392 </a><div class=\"sidebar-links\">{}</div>", ret));
4396 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4397 if let Some(impl_) = v.iter()
4398 .filter(|i| i.inner_impl().trait_.is_some())
4399 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4400 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4402 clean::TypedefItem(ref t, true) => Some(&t.type_),
4406 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4407 c.primitive_locations.get(&prim).cloned()
4408 })).and_then(|did| c.impls.get(&did));
4409 if let Some(impls) = inner_impl {
4410 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4411 out.push_str(&format!("Methods from {}<Target={}>",
4412 Escape(&format!("{:#}",
4413 impl_.inner_impl().trait_.as_ref().unwrap())),
4414 Escape(&format!("{:#}", target))));
4415 out.push_str("</a>");
4416 let ret = impls.iter()
4417 .filter(|i| i.inner_impl().trait_.is_none())
4418 .flat_map(|i| get_methods(i.inner_impl(),
4421 .collect::<String>();
4422 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
4426 let format_impls = |impls: Vec<&Impl>| {
4427 let mut links = FxHashSet::default();
4431 let is_negative_impl = is_negative_impl(i.inner_impl());
4432 if let Some(ref i) = i.inner_impl().trait_ {
4433 let i_display = format!("{:#}", i);
4434 let out = Escape(&i_display);
4435 let encoded = small_url_encode(&format!("{:#}", i));
4436 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4438 if is_negative_impl { "!" } else { "" },
4440 if links.insert(generated.clone()) {
4449 .collect::<String>()
4452 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4454 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4455 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4457 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4459 let concrete_format = format_impls(concrete);
4460 let synthetic_format = format_impls(synthetic);
4461 let blanket_format = format_impls(blanket_impl);
4463 if !concrete_format.is_empty() {
4464 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4465 Trait Implementations</a>");
4466 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4469 if !synthetic_format.is_empty() {
4470 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4471 Auto Trait Implementations</a>");
4472 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4475 if !blanket_format.is_empty() {
4476 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4477 Blanket Implementations</a>");
4478 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4486 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4487 s: &clean::Struct) -> fmt::Result {
4488 let mut sidebar = String::new();
4489 let fields = get_struct_fields_name(&s.fields);
4491 if !fields.is_empty() {
4492 if let doctree::Plain = s.struct_type {
4493 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4494 <div class=\"sidebar-links\">{}</div>", fields));
4498 sidebar.push_str(&sidebar_assoc_items(it));
4500 if !sidebar.is_empty() {
4501 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4506 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4508 clean::ItemEnum::ImplItem(ref i) => {
4509 if let Some(ref trait_) = i.trait_ {
4510 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4519 fn is_negative_impl(i: &clean::Impl) -> bool {
4520 i.polarity == Some(clean::ImplPolarity::Negative)
4523 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4524 t: &clean::Trait) -> fmt::Result {
4525 let mut sidebar = String::new();
4531 Some(ref name) if m.is_associated_type() => {
4532 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4538 .collect::<String>();
4539 let consts = t.items
4543 Some(ref name) if m.is_associated_const() => {
4544 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4550 .collect::<String>();
4551 let required = t.items
4555 Some(ref name) if m.is_ty_method() => {
4556 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4562 .collect::<String>();
4563 let provided = t.items
4567 Some(ref name) if m.is_method() => {
4568 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
4573 .collect::<String>();
4575 if !types.is_empty() {
4576 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4577 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4580 if !consts.is_empty() {
4581 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4582 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4585 if !required.is_empty() {
4586 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4587 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4590 if !provided.is_empty() {
4591 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4592 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4598 if let Some(implementors) = c.implementors.get(&it.def_id) {
4599 let res = implementors.iter()
4600 .filter(|i| i.inner_impl().for_.def_id()
4601 .map_or(false, |d| !c.paths.contains_key(&d)))
4603 match extract_for_impl_name(&i.impl_item) {
4604 Some((ref name, ref url)) => {
4605 Some(format!("<a href=\"#impl-{}\">{}</a>",
4606 small_url_encode(url),
4612 .collect::<String>();
4613 if !res.is_empty() {
4614 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4615 Implementations on Foreign Types</a><div \
4616 class=\"sidebar-links\">{}</div>",
4621 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4623 sidebar.push_str("<a class=\"sidebar-title\" \
4624 href=\"#synthetic-implementors\">Auto Implementors</a>");
4627 sidebar.push_str(&sidebar_assoc_items(it));
4629 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4632 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4633 _p: &clean::PrimitiveType) -> fmt::Result {
4634 let sidebar = sidebar_assoc_items(it);
4636 if !sidebar.is_empty() {
4637 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4642 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4643 _t: &clean::Typedef) -> fmt::Result {
4644 let sidebar = sidebar_assoc_items(it);
4646 if !sidebar.is_empty() {
4647 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4652 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4654 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4659 .filter_map(|f| match f.name {
4660 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4661 {name}</a>", name=name)),
4667 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4668 u: &clean::Union) -> fmt::Result {
4669 let mut sidebar = String::new();
4670 let fields = get_struct_fields_name(&u.fields);
4672 if !fields.is_empty() {
4673 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4674 <div class=\"sidebar-links\">{}</div>", fields));
4677 sidebar.push_str(&sidebar_assoc_items(it));
4679 if !sidebar.is_empty() {
4680 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4685 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4686 e: &clean::Enum) -> fmt::Result {
4687 let mut sidebar = String::new();
4689 let variants = e.variants.iter()
4690 .filter_map(|v| match v.name {
4691 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4692 </a>", name = name)),
4695 .collect::<String>();
4696 if !variants.is_empty() {
4697 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4698 <div class=\"sidebar-links\">{}</div>", variants));
4701 sidebar.push_str(&sidebar_assoc_items(it));
4703 if !sidebar.is_empty() {
4704 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4709 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4711 ItemType::ExternCrate |
4712 ItemType::Import => ("reexports", "Re-exports"),
4713 ItemType::Module => ("modules", "Modules"),
4714 ItemType::Struct => ("structs", "Structs"),
4715 ItemType::Union => ("unions", "Unions"),
4716 ItemType::Enum => ("enums", "Enums"),
4717 ItemType::Function => ("functions", "Functions"),
4718 ItemType::Typedef => ("types", "Type Definitions"),
4719 ItemType::Static => ("statics", "Statics"),
4720 ItemType::Constant => ("constants", "Constants"),
4721 ItemType::Trait => ("traits", "Traits"),
4722 ItemType::Impl => ("impls", "Implementations"),
4723 ItemType::TyMethod => ("tymethods", "Type Methods"),
4724 ItemType::Method => ("methods", "Methods"),
4725 ItemType::StructField => ("fields", "Struct Fields"),
4726 ItemType::Variant => ("variants", "Variants"),
4727 ItemType::Macro => ("macros", "Macros"),
4728 ItemType::Primitive => ("primitives", "Primitive Types"),
4729 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4730 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4731 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4732 ItemType::Keyword => ("keywords", "Keywords"),
4733 ItemType::Existential => ("existentials", "Existentials"),
4734 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4735 ItemType::ProcDerive => ("derives", "Derive Macros"),
4739 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4740 items: &[clean::Item]) -> fmt::Result {
4741 let mut sidebar = String::new();
4743 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4744 it.type_() == ItemType::Import) {
4745 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4747 name = "Re-exports"));
4750 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4751 // to print its headings
4752 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4753 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4754 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4755 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4756 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4757 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4758 let (short, name) = item_ty_to_strs(&myty);
4759 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4765 if !sidebar.is_empty() {
4766 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4771 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4772 let sidebar = sidebar_assoc_items(it);
4773 if !sidebar.is_empty() {
4774 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4779 impl<'a> fmt::Display for Source<'a> {
4780 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4781 let Source(s) = *self;
4782 let lines = s.lines().count();
4784 let mut tmp = lines;
4789 write!(fmt, "<pre class=\"line-numbers\">")?;
4790 for i in 1..=lines {
4791 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4793 write!(fmt, "</pre>")?;
4795 highlight::render_with_highlighting(s, None, None, None))?;
4800 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4801 t: &clean::Macro) -> fmt::Result {
4802 wrap_into_docblock(w, |w| {
4803 w.write_str(&highlight::render_with_highlighting(&t.source,
4811 fn item_proc_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
4814 let name = it.name.as_ref().expect("proc-macros always have names");
4816 MacroKind::Bang => {
4817 write!(w, "<pre class='rust macro'>")?;
4818 write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
4819 write!(w, "</pre>")?;
4821 MacroKind::Attr => {
4822 write!(w, "<pre class='rust attr'>")?;
4823 write!(w, "#[{}]", name)?;
4824 write!(w, "</pre>")?;
4826 MacroKind::Derive => {
4827 write!(w, "<pre class='rust derive'>")?;
4828 write!(w, "#[derive({})]", name)?;
4829 if !m.helpers.is_empty() {
4830 writeln!(w, "\n{{")?;
4831 writeln!(w, " // Attributes available to this derive:")?;
4832 for attr in &m.helpers {
4833 writeln!(w, " #[{}]", attr)?;
4837 write!(w, "</pre>")?;
4844 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4846 _p: &clean::PrimitiveType) -> fmt::Result {
4847 document(w, cx, it)?;
4848 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4851 fn item_keyword(w: &mut fmt::Formatter, cx: &Context,
4853 _p: &str) -> fmt::Result {
4857 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4859 fn make_item_keywords(it: &clean::Item) -> String {
4860 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4863 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4864 let decl = match item.inner {
4865 clean::FunctionItem(ref f) => &f.decl,
4866 clean::MethodItem(ref m) => &m.decl,
4867 clean::TyMethodItem(ref m) => &m.decl,
4871 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4872 let output = match decl.output {
4873 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4877 Some(IndexItemFunctionType { inputs: inputs, output: output })
4880 fn get_index_type(clean_type: &clean::Type) -> Type {
4882 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4883 generics: get_generics(clean_type),
4888 /// Returns a list of all paths used in the type.
4889 /// This is used to help deduplicate imported impls
4890 /// for reexported types. If any of the contained
4891 /// types are re-exported, we don't use the corresponding
4892 /// entry from the js file, as inlining will have already
4893 /// picked up the impl
4894 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4895 let mut out = Vec::new();
4896 let mut visited = FxHashSet::default();
4897 let mut work = VecDeque::new();
4898 let cache = cache();
4900 work.push_back(first_ty);
4902 while let Some(ty) = work.pop_front() {
4903 if !visited.insert(ty.clone()) {
4908 clean::Type::ResolvedPath { did, .. } => {
4909 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4910 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4914 out.push(path.join("::"));
4920 clean::Type::Tuple(tys) => {
4921 work.extend(tys.into_iter());
4923 clean::Type::Slice(ty) => {
4924 work.push_back(*ty);
4926 clean::Type::Array(ty, _) => {
4927 work.push_back(*ty);
4929 clean::Type::Unique(ty) => {
4930 work.push_back(*ty);
4932 clean::Type::RawPointer(_, ty) => {
4933 work.push_back(*ty);
4935 clean::Type::BorrowedRef { type_, .. } => {
4936 work.push_back(*type_);
4938 clean::Type::QPath { self_type, trait_, .. } => {
4939 work.push_back(*self_type);
4940 work.push_back(*trait_);
4948 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4950 clean::ResolvedPath { ref path, .. } => {
4951 let segments = &path.segments;
4952 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4953 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4954 clean_type, accept_generic
4956 Some(path_segment.name.clone())
4958 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4959 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4960 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4961 // FIXME: add all from clean::Type.
4966 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4967 clean_type.generics()
4969 let r = types.iter()
4970 .filter_map(|t| get_index_type_name(t, false))
4971 .map(|s| s.to_ascii_lowercase())
4972 .collect::<Vec<_>>();
4981 pub fn cache() -> Arc<Cache> {
4982 CACHE_KEY.with(|c| c.borrow().clone())
4987 fn test_name_key() {
4988 assert_eq!(name_key("0"), ("", 0, 1));
4989 assert_eq!(name_key("123"), ("", 123, 0));
4990 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4991 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4992 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4993 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4994 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4995 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5000 fn test_name_sorting() {
5001 let names = ["Apple",
5003 "Fruit", "Fruit0", "Fruit00",
5004 "Fruit1", "Fruit01",
5005 "Fruit2", "Fruit02",
5010 let mut sorted = names.to_owned();
5011 sorted.sort_by_key(|&s| name_key(s));
5012 assert_eq!(names, sorted);