1 //! Rustdoc's HTML Rendering module
3 //! This modules contains the bulk of the logic necessary for rendering a
4 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
5 //! rendering process is largely driven by the `format!` syntax extension to
6 //! perform all I/O into files and streams.
8 //! The rendering process is largely driven by the `Context` and `Cache`
9 //! structures. The cache is pre-populated by crawling the crate in question,
10 //! and then it is shared among the various rendering threads. The cache is meant
11 //! to be a fairly large structure not implementing `Clone` (because it's shared
12 //! among threads). The context, however, should be a lightweight structure. This
13 //! is cloned per-thread and contains information about what is currently being
16 //! In order to speed up rendering (mostly because of markdown rendering), the
17 //! rendering process has been parallelized. This parallelization is only
18 //! exposed through the `crate` method on the context, and then also from the
19 //! fact that the shared cache is stored in TLS (and must be accessed as such).
21 //! In addition to rendering the crate itself, this module is also responsible
22 //! for creating the corresponding search index and source file renderings.
23 //! These threads are not parallelized (they haven't been a bottleneck yet), and
24 //! both occur before the crate is rendered.
26 pub use self::ExternalLocation::*;
29 use std::cell::RefCell;
30 use std::cmp::Ordering;
31 use std::collections::{BTreeMap, VecDeque};
32 use std::default::Default;
34 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
36 use std::fs::{self, File, OpenOptions};
37 use std::io::prelude::*;
38 use std::io::{self, BufWriter, BufReader};
40 use std::path::{PathBuf, Path, Component};
46 use serialize::json::{ToJson, Json, as_json};
48 use syntax::ext::base::MacroKind;
49 use syntax::source_map::FileName;
50 use syntax::feature_gate::UnstableFeatures;
51 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
52 use rustc::middle::privacy::AccessLevels;
53 use rustc::middle::stability;
55 use rustc::util::nodemap::{FxHashMap, FxHashSet};
56 use rustc_data_structures::flock;
58 use clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
59 use config::RenderOptions;
62 use html::escape::Escape;
63 use html::format::{AsyncSpace, ConstnessSpace};
64 use html::format::{GenericBounds, WhereClause, href, AbiSpace};
65 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
66 use html::format::fmt_impl_for_trait_page;
67 use html::item_type::ItemType;
68 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
69 use html::{highlight, layout, static_files};
73 /// A pair of name and its optional document.
74 pub type NameDoc = (String, Option<String>);
76 /// Major driving force in all rustdoc rendering. This contains information
77 /// about where in the tree-like hierarchy rendering is occurring and controls
78 /// how the current page is being rendered.
80 /// It is intended that this context is a lightweight object which can be fairly
81 /// easily cloned because it is cloned per work-job (about once per item in the
85 /// Current hierarchy of components leading down to what's currently being
87 pub current: Vec<String>,
88 /// The current destination folder of where HTML artifacts should be placed.
89 /// This changes as the context descends into the module hierarchy.
91 /// A flag, which when `true`, will render pages which redirect to the
92 /// real location of an item. This is used to allow external links to
93 /// publicly reused items to redirect to the right location.
94 pub render_redirect_pages: bool,
95 pub codes: ErrorCodes,
96 /// The map used to ensure all generated 'id=' attributes are unique.
97 id_map: Rc<RefCell<IdMap>>,
98 pub shared: Arc<SharedContext>,
101 struct SharedContext {
102 /// The path to the crate root source minus the file name.
103 /// Used for simplifying paths to the highlighted source code files.
104 pub src_root: PathBuf,
105 /// This describes the layout of each page, and is not modified after
106 /// creation of the context (contains info like the favicon and added html).
107 pub layout: layout::Layout,
108 /// This flag indicates whether `[src]` links should be generated or not. If
109 /// the source files are present in the html rendering, then this will be
111 pub include_sources: bool,
112 /// The local file sources we've emitted and their respective url-paths.
113 pub local_sources: FxHashMap<PathBuf, String>,
114 /// All the passes that were run on this crate.
115 pub passes: FxHashSet<String>,
116 /// The base-URL of the issue tracker for when an item has been tagged with
118 pub issue_tracker_base_url: Option<String>,
119 /// The given user css file which allow to customize the generated
120 /// documentation theme.
121 pub css_file_extension: Option<PathBuf>,
122 /// The directories that have already been created in this doc run. Used to reduce the number
123 /// of spurious `create_dir_all` calls.
124 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
125 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
126 /// should be ordered alphabetically or in order of appearance (in the source code).
127 pub sort_modules_alphabetically: bool,
128 /// Additional themes to be added to the generated docs.
129 pub themes: Vec<PathBuf>,
130 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
132 pub resource_suffix: String,
133 /// Optional path string to be used to load static files on output pages. If not set, uses
134 /// combinations of `../` to reach the documentation root.
135 pub static_root_path: Option<String>,
136 /// If false, the `select` element to have search filtering by crates on rendered docs
137 /// won't be generated.
138 pub generate_search_filter: bool,
142 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
143 let mut dirs = self.created_dirs.borrow_mut();
144 if !dirs.contains(dst) {
145 fs::create_dir_all(dst)?;
146 dirs.insert(dst.to_path_buf());
154 /// Returns whether the `collapse-docs` pass was run on this crate.
155 pub fn was_collapsed(&self) -> bool {
156 self.passes.contains("collapse-docs")
159 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
160 /// `collapsed_doc_value` of the given item.
161 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
162 if self.was_collapsed() {
163 item.collapsed_doc_value().map(|s| s.into())
165 item.doc_value().map(|s| s.into())
170 /// Indicates where an external crate can be found.
171 pub enum ExternalLocation {
172 /// Remote URL root of the external crate
174 /// This external crate can be found in the local doc/ folder
176 /// The external crate could not be found.
180 /// Metadata about implementations for a type or trait.
181 #[derive(Clone, Debug)]
183 pub impl_item: clean::Item,
187 fn inner_impl(&self) -> &clean::Impl {
188 match self.impl_item.inner {
189 clean::ImplItem(ref impl_) => impl_,
190 _ => panic!("non-impl item found in impl")
194 fn trait_did(&self) -> Option<DefId> {
195 self.inner_impl().trait_.def_id()
202 pub error: io::Error,
205 impl error::Error for Error {
206 fn description(&self) -> &str {
207 self.error.description()
211 impl Display for Error {
212 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
213 write!(f, "\"{}\": {}", self.file.display(), self.error)
218 pub fn new(e: io::Error, file: &Path) -> Error {
220 file: file.to_path_buf(),
226 macro_rules! try_none {
227 ($e:expr, $file:expr) => ({
231 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
237 macro_rules! try_err {
238 ($e:expr, $file:expr) => ({
241 Err(e) => return Err(Error::new(e, $file)),
246 /// This cache is used to store information about the `clean::Crate` being
247 /// rendered in order to provide more useful documentation. This contains
248 /// information like all implementors of a trait, all traits a type implements,
249 /// documentation for all known traits, etc.
251 /// This structure purposefully does not implement `Clone` because it's intended
252 /// to be a fairly large and expensive structure to clone. Instead this adheres
253 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
254 /// rendering threads.
257 /// Mapping of typaram ids to the name of the type parameter. This is used
258 /// when pretty-printing a type (so pretty printing doesn't have to
259 /// painfully maintain a context like this)
260 pub typarams: FxHashMap<DefId, String>,
262 /// Maps a type id to all known implementations for that type. This is only
263 /// recognized for intra-crate `ResolvedPath` types, and is used to print
264 /// out extra documentation on the page of an enum/struct.
266 /// The values of the map are a list of implementations and documentation
267 /// found on that implementation.
268 pub impls: FxHashMap<DefId, Vec<Impl>>,
270 /// Maintains a mapping of local crate node ids to the fully qualified name
271 /// and "short type description" of that node. This is used when generating
272 /// URLs when a type is being linked to. External paths are not located in
273 /// this map because the `External` type itself has all the information
275 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
277 /// Similar to `paths`, but only holds external paths. This is only used for
278 /// generating explicit hyperlinks to other crates.
279 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
281 /// Maps local def ids of exported types to fully qualified paths.
282 /// Unlike 'paths', this mapping ignores any renames that occur
283 /// due to 'use' statements.
285 /// This map is used when writing out the special 'implementors'
286 /// javascript file. By using the exact path that the type
287 /// is declared with, we ensure that each path will be identical
288 /// to the path used if the corresponding type is inlined. By
289 /// doing this, we can detect duplicate impls on a trait page, and only display
290 /// the impl for the inlined type.
291 pub exact_paths: FxHashMap<DefId, Vec<String>>,
293 /// This map contains information about all known traits of this crate.
294 /// Implementations of a crate should inherit the documentation of the
295 /// parent trait if no extra documentation is specified, and default methods
296 /// should show up in documentation about trait implementations.
297 pub traits: FxHashMap<DefId, clean::Trait>,
299 /// When rendering traits, it's often useful to be able to list all
300 /// implementors of the trait, and this mapping is exactly, that: a mapping
301 /// of trait ids to the list of known implementors of the trait
302 pub implementors: FxHashMap<DefId, Vec<Impl>>,
304 /// Cache of where external crate documentation can be found.
305 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
307 /// Cache of where documentation for primitives can be found.
308 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
310 // Note that external items for which `doc(hidden)` applies to are shown as
311 // non-reachable while local items aren't. This is because we're reusing
312 // the access levels from the privacy check pass.
313 pub access_levels: AccessLevels<DefId>,
315 /// The version of the crate being documented, if given from the `--crate-version` flag.
316 pub crate_version: Option<String>,
318 // Private fields only used when initially crawling a crate to build a cache
321 parent_stack: Vec<DefId>,
322 parent_is_trait_impl: bool,
323 search_index: Vec<IndexItem>,
325 deref_trait_did: Option<DefId>,
326 deref_mut_trait_did: Option<DefId>,
327 owned_box_did: Option<DefId>,
328 masked_crates: FxHashSet<CrateNum>,
330 // In rare case where a structure is defined in one module but implemented
331 // in another, if the implementing module is parsed before defining module,
332 // then the fully qualified name of the structure isn't presented in `paths`
333 // yet when its implementation methods are being indexed. Caches such methods
334 // and their parent id here and indexes them at the end of crate parsing.
335 orphan_impl_items: Vec<(DefId, clean::Item)>,
337 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
338 // even though the trait itself is not exported. This can happen if a trait
339 // was defined in function/expression scope, since the impl will be picked
340 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
341 // crawl. In order to prevent crashes when looking for spotlight traits or
342 // when gathering trait documentation on a type, hold impls here while
343 // folding and add them to the cache later on if we find the trait.
344 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
346 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
347 /// we need the alias element to have an array of items.
348 aliases: FxHashMap<String, Vec<IndexItem>>,
351 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
352 /// Later on moved into `CACHE_KEY`.
354 pub struct RenderInfo {
355 pub inlined: FxHashSet<DefId>,
356 pub external_paths: ::core::ExternalPaths,
357 pub external_typarams: FxHashMap<DefId, String>,
358 pub exact_paths: FxHashMap<DefId, Vec<String>>,
359 pub access_levels: AccessLevels<DefId>,
360 pub deref_trait_did: Option<DefId>,
361 pub deref_mut_trait_did: Option<DefId>,
362 pub owned_box_did: Option<DefId>,
365 /// Helper struct to render all source code to HTML pages
366 struct SourceCollector<'a> {
367 scx: &'a mut SharedContext,
369 /// Root destination to place all HTML output into
373 /// Wrapper struct to render the source code of a file. This will do things like
374 /// adding line numbers to the left-hand side.
375 struct Source<'a>(&'a str);
377 // Helper structs for rendering items/sidebars and carrying along contextual
380 #[derive(Copy, Clone)]
383 item: &'a clean::Item,
386 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
388 /// Struct representing one entry in the JS search index. These are all emitted
389 /// by hand to a large JS file at the end of cache-creation.
396 parent: Option<DefId>,
397 parent_idx: Option<usize>,
398 search_type: Option<IndexItemFunctionType>,
401 impl ToJson for IndexItem {
402 fn to_json(&self) -> Json {
403 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
405 let mut data = Vec::with_capacity(6);
406 data.push((self.ty as usize).to_json());
407 data.push(self.name.to_json());
408 data.push(self.path.to_json());
409 data.push(self.desc.to_json());
410 data.push(self.parent_idx.to_json());
411 data.push(self.search_type.to_json());
417 /// A type used for the search index.
420 name: Option<String>,
421 generics: Option<Vec<String>>,
424 impl ToJson for Type {
425 fn to_json(&self) -> Json {
428 let mut data = Vec::with_capacity(2);
429 data.push(name.to_json());
430 if let Some(ref generics) = self.generics {
431 data.push(generics.to_json());
440 /// Full type of functions/methods in the search index.
442 struct IndexItemFunctionType {
444 output: Option<Type>,
447 impl ToJson for IndexItemFunctionType {
448 fn to_json(&self) -> Json {
449 // If we couldn't figure out a type, just write `null`.
450 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
453 let mut data = Vec::with_capacity(2);
454 data.push(self.inputs.to_json());
455 if let Some(ref output) = self.output {
456 data.push(output.to_json());
463 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
464 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
466 pub fn initial_ids() -> Vec<String> {
478 "synthetic-implementors",
480 "synthetic-implementors-list",
484 ].into_iter().map(|id| (String::from(*id))).collect()
487 /// Generates the documentation for `crate` into the directory `dst`
488 pub fn run(mut krate: clean::Crate,
489 options: RenderOptions,
490 passes: FxHashSet<String>,
491 renderinfo: RenderInfo,
492 diag: &errors::Handler) -> Result<(), Error> {
493 // need to save a copy of the options for rendering the index page
494 let md_opts = options.clone();
500 sort_modules_alphabetically,
503 extern_html_root_urls,
506 generate_search_filter,
510 let src_root = match krate.src {
511 FileName::Real(ref p) => match p.parent() {
512 Some(p) => p.to_path_buf(),
513 None => PathBuf::new(),
517 let mut scx = SharedContext {
520 include_sources: true,
521 local_sources: Default::default(),
522 issue_tracker_base_url: None,
523 layout: layout::Layout {
525 favicon: String::new(),
527 krate: krate.name.clone(),
529 css_file_extension: extension_css,
530 created_dirs: Default::default(),
531 sort_modules_alphabetically,
535 generate_search_filter,
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("i".to_owned(), Json::Array(crate_items));
745 crate_data.insert("p".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 if (*cx.shared).layout.logo.is_empty() {
793 write(cx.dst.join(&format!("rust-logo{}.png", cx.shared.resource_suffix)),
794 static_files::RUST_LOGO)?;
796 if (*cx.shared).layout.favicon.is_empty() {
797 write(cx.dst.join(&format!("favicon{}.ico", cx.shared.resource_suffix)),
798 static_files::RUST_FAVICON)?;
800 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
801 static_files::BRUSH_SVG)?;
802 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
803 static_files::WHEEL_SVG)?;
804 write(cx.dst.join(&format!("down-arrow{}.svg", cx.shared.resource_suffix)),
805 static_files::DOWN_ARROW_SVG)?;
806 write_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
807 static_files::themes::LIGHT,
808 options.enable_minification)?;
809 themes.insert("light".to_owned());
810 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
811 static_files::themes::DARK,
812 options.enable_minification)?;
813 themes.insert("dark".to_owned());
815 let mut themes: Vec<&String> = themes.iter().collect();
817 // To avoid theme switch latencies as much as possible, we put everything theme related
818 // at the beginning of the html files into another js file.
819 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
821 r#"var themes = document.getElementById("theme-choices");
822 var themePicker = document.getElementById("theme-picker");
824 function switchThemeButtonState() {{
825 if (themes.style.display === "block") {{
826 themes.style.display = "none";
827 themePicker.style.borderBottomRightRadius = "3px";
828 themePicker.style.borderBottomLeftRadius = "3px";
830 themes.style.display = "block";
831 themePicker.style.borderBottomRightRadius = "0";
832 themePicker.style.borderBottomLeftRadius = "0";
836 function handleThemeButtonsBlur(e) {{
837 var active = document.activeElement;
838 var related = e.relatedTarget;
840 if (active.id !== "themePicker" &&
841 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
843 (related.id !== "themePicker" &&
844 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
845 switchThemeButtonState();
849 themePicker.onclick = switchThemeButtonState;
850 themePicker.onblur = handleThemeButtonsBlur;
851 [{}].forEach(function(item) {{
852 var but = document.createElement('button');
853 but.innerHTML = item;
854 but.onclick = function(el) {{
855 switchTheme(currentTheme, mainTheme, item);
857 but.onblur = handleThemeButtonsBlur;
858 themes.appendChild(but);
861 .map(|s| format!("\"{}\"", s))
862 .collect::<Vec<String>>()
863 .join(",")).as_bytes(),
866 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
867 static_files::MAIN_JS,
868 options.enable_minification)?;
869 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
870 static_files::SETTINGS_JS,
871 options.enable_minification)?;
872 if cx.shared.include_sources {
873 write_minify(cx.dst.join(&format!("source-script{}.js", cx.shared.resource_suffix)),
874 static_files::sidebar::SOURCE_SCRIPT,
875 options.enable_minification)?;
879 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
880 &format!("var resourcesSuffix = \"{}\";{}",
881 cx.shared.resource_suffix,
882 static_files::STORAGE_JS),
883 options.enable_minification)?;
886 if let Some(ref css) = cx.shared.css_file_extension {
887 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
888 if !options.enable_minification {
889 try_err!(fs::copy(css, out), css);
891 let buffer = try_err!(fs::read_to_string(css), css);
892 write_minify(out, &buffer, options.enable_minification)?;
895 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
896 static_files::NORMALIZE_CSS,
897 options.enable_minification)?;
898 write(cx.dst.join("FiraSans-Regular.woff"),
899 static_files::fira_sans::REGULAR)?;
900 write(cx.dst.join("FiraSans-Medium.woff"),
901 static_files::fira_sans::MEDIUM)?;
902 write(cx.dst.join("FiraSans-LICENSE.txt"),
903 static_files::fira_sans::LICENSE)?;
904 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
905 static_files::source_serif_pro::REGULAR)?;
906 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
907 static_files::source_serif_pro::BOLD)?;
908 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
909 static_files::source_serif_pro::ITALIC)?;
910 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
911 static_files::source_serif_pro::LICENSE)?;
912 write(cx.dst.join("SourceCodePro-Regular.woff"),
913 static_files::source_code_pro::REGULAR)?;
914 write(cx.dst.join("SourceCodePro-Semibold.woff"),
915 static_files::source_code_pro::SEMIBOLD)?;
916 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
917 static_files::source_code_pro::LICENSE)?;
918 write(cx.dst.join("LICENSE-MIT.txt"),
919 static_files::LICENSE_MIT)?;
920 write(cx.dst.join("LICENSE-APACHE.txt"),
921 static_files::LICENSE_APACHE)?;
922 write(cx.dst.join("COPYRIGHT.txt"),
923 static_files::COPYRIGHT)?;
929 for_search_index: bool,
930 ) -> io::Result<(Vec<String>, Vec<String>, Vec<String>)> {
933 let mut ret = Vec::new();
934 let mut krates = Vec::new();
935 let mut variables = Vec::new();
937 let mut krate = krate.to_owned();
940 for line in BufReader::new(File::open(path)?).lines() {
942 if for_search_index && line.starts_with("var R") {
943 variables.push(line.clone());
944 // We need to check if the crate name has been put into a variable as well.
945 let tokens = js::simple_minify(&line).apply(js::clean_tokens);
947 while pos < tokens.len() {
948 if let Some((var_pos, Some(value_pos))) =
949 js::get_variable_name_and_value_positions(&tokens, pos) {
950 if let Some(s) = tokens.0[value_pos].get_string() {
951 if &s[1..s.len() - 1] == krate {
952 if let Some(var) = tokens[var_pos].get_other() {
953 krate = var.to_owned();
963 if !line.starts_with(key) {
966 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
969 ret.push(line.to_string());
970 krates.push(line[key.len() + 2..].split('"')
972 .map(|s| s.to_owned())
973 .unwrap_or_else(|| String::new()));
976 Ok((ret, krates, variables))
979 fn show_item(item: &IndexItem, krate: &str) -> String {
980 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
981 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
982 if let Some(p) = item.parent_idx {
983 format!(",'parent':{}", p)
989 let dst = cx.dst.join("aliases.js");
991 let (mut all_aliases, _, _) = try_err!(collect(&dst, &krate.name, "ALIASES", false), &dst);
992 let mut w = try_err!(File::create(&dst), &dst);
993 let mut output = String::with_capacity(100);
994 for (alias, items) in &cache.aliases {
995 if items.is_empty() {
998 output.push_str(&format!("\"{}\":[{}],",
1001 .map(|v| show_item(v, &krate.name))
1002 .collect::<Vec<_>>()
1005 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
1007 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
1008 for aliases in &all_aliases {
1009 try_err!(writeln!(&mut w, "{}", aliases), &dst);
1013 use std::ffi::OsString;
1018 children: FxHashMap<OsString, Hierarchy>,
1019 elems: FxHashSet<OsString>,
1023 fn new(elem: OsString) -> Hierarchy {
1026 children: FxHashMap::default(),
1027 elems: FxHashSet::default(),
1031 fn to_json_string(&self) -> String {
1032 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
1033 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
1034 let mut files = self.elems.iter()
1035 .map(|s| format!("\"{}\"",
1037 .expect("invalid osstring conversion")))
1038 .collect::<Vec<_>>();
1039 files.sort_unstable_by(|a, b| a.cmp(b));
1040 // FIXME(imperio): we could avoid to generate "dirs" and "files" if they're empty.
1041 format!("{{\"name\":\"{name}\",\"dirs\":[{subs}],\"files\":[{files}]}}",
1042 name=self.elem.to_str().expect("invalid osstring conversion"),
1043 subs=subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(","),
1044 files=files.join(","))
1048 if cx.shared.include_sources {
1049 use std::path::Component;
1051 let mut hierarchy = Hierarchy::new(OsString::new());
1052 for source in cx.shared.local_sources.iter()
1053 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
1055 let mut h = &mut hierarchy;
1056 let mut elems = source.components()
1059 Component::Normal(s) => Some(s.to_owned()),
1065 let cur_elem = elems.next().expect("empty file path");
1066 if elems.peek().is_none() {
1067 h.elems.insert(cur_elem);
1070 let e = cur_elem.clone();
1071 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1072 h = h.children.get_mut(&cur_elem).expect("not found child");
1077 let dst = cx.dst.join("source-files.js");
1078 let (mut all_sources, _krates, _) = try_err!(collect(&dst, &krate.name, "sourcesIndex",
1081 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
1083 hierarchy.to_json_string()));
1085 let mut w = try_err!(File::create(&dst), &dst);
1086 try_err!(writeln!(&mut w,
1087 "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();",
1088 all_sources.join("\n")),
1092 // Update the search index
1093 let dst = cx.dst.join("search-index.js");
1094 let (mut all_indexes, mut krates, variables) = try_err!(collect(&dst,
1098 all_indexes.push(search_index);
1100 // Sort the indexes by crate so the file will be generated identically even
1101 // with rustdoc running in parallel.
1103 let mut w = try_err!(File::create(&dst), &dst);
1104 try_err!(writeln!(&mut w, "var N=null,E=\"\",T=\"t\",U=\"u\",searchIndex={{}};"), &dst);
1105 try_err!(write_minify_replacer(&mut w,
1106 &format!("{}\n{}", variables.join(""), all_indexes.join("\n")),
1107 options.enable_minification),
1109 try_err!(write!(&mut w, "initSearch(searchIndex);addSearchOptions(searchIndex);"), &dst);
1111 if options.enable_index_page {
1112 if let Some(index_page) = options.index_page.clone() {
1113 let mut md_opts = options.clone();
1114 md_opts.output = cx.dst.clone();
1115 md_opts.external_html = (*cx.shared).layout.external_html.clone();
1117 ::markdown::render(index_page, md_opts, diag);
1119 let dst = cx.dst.join("index.html");
1120 let mut w = BufWriter::new(try_err!(File::create(&dst), &dst));
1121 let page = layout::Page {
1122 title: "Index of crates",
1125 static_root_path: cx.shared.static_root_path.deref(),
1126 description: "List of crates",
1127 keywords: BASIC_KEYWORDS,
1128 resource_suffix: &cx.shared.resource_suffix,
1130 static_extra_scripts: &[],
1132 krates.push(krate.name.clone());
1136 let content = format!(
1138 <span class='in-band'>List of all crates</span>\
1139 </h1><ul class='mod'>{}</ul>",
1143 format!("<li><a href=\"{}/index.html\">{}</li>", s, s)
1145 .collect::<String>());
1146 try_err!(layout::render(&mut w, &cx.shared.layout,
1147 &page, &(""), &content,
1148 cx.shared.css_file_extension.is_some(),
1150 cx.shared.generate_search_filter), &dst);
1151 try_err!(w.flush(), &dst);
1155 // Update the list of all implementors for traits
1156 let dst = cx.dst.join("implementors");
1157 for (&did, imps) in &cache.implementors {
1158 // Private modules can leak through to this phase of rustdoc, which
1159 // could contain implementations for otherwise private types. In some
1160 // rare cases we could find an implementation for an item which wasn't
1161 // indexed, so we just skip this step in that case.
1163 // FIXME: this is a vague explanation for why this can't be a `get`, in
1164 // theory it should be...
1165 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1167 None => match cache.external_paths.get(&did) {
1173 let mut have_impls = false;
1174 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
1176 // If the trait and implementation are in the same crate, then
1177 // there's no need to emit information about it (there's inlining
1178 // going on). If they're in different crates then the crate defining
1179 // the trait will be interested in our implementation.
1180 if imp.impl_item.def_id.krate == did.krate { continue }
1181 // If the implementation is from another crate then that crate
1183 if !imp.impl_item.def_id.is_local() { continue }
1185 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1186 as_json(&imp.inner_impl().to_string()),
1187 imp.inner_impl().synthetic,
1188 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1190 implementors.push_str("];");
1192 // Only create a js file if we have impls to add to it. If the trait is
1193 // documented locally though we always create the file to avoid dead
1195 if !have_impls && !cache.paths.contains_key(&did) {
1199 let mut mydst = dst.clone();
1200 for part in &remote_path[..remote_path.len() - 1] {
1203 try_err!(fs::create_dir_all(&mydst), &mydst);
1204 mydst.push(&format!("{}.{}.js",
1205 remote_item_type.css_class(),
1206 remote_path[remote_path.len() - 1]));
1208 let (mut all_implementors, _, _) = try_err!(collect(&mydst, &krate.name, "implementors",
1211 all_implementors.push(implementors);
1212 // Sort the implementors by crate so the file will be generated
1213 // identically even with rustdoc running in parallel.
1214 all_implementors.sort();
1216 let mut f = try_err!(File::create(&mydst), &mydst);
1217 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1218 for implementor in &all_implementors {
1219 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1221 try_err!(writeln!(&mut f, "{}", r"
1222 if (window.register_implementors) {
1223 window.register_implementors(implementors);
1225 window.pending_implementors = implementors;
1228 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1233 fn render_sources(dst: &Path, scx: &mut SharedContext,
1234 krate: clean::Crate) -> Result<clean::Crate, Error> {
1235 info!("emitting source files");
1236 let dst = dst.join("src").join(&krate.name);
1237 try_err!(fs::create_dir_all(&dst), &dst);
1238 let mut folder = SourceCollector {
1242 Ok(folder.fold_crate(krate))
1245 /// Writes the entire contents of a string to a destination, not attempting to
1246 /// catch any errors.
1247 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1248 Ok(try_err!(fs::write(&dst, contents), &dst))
1251 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1252 if enable_minification {
1253 if dst.extension() == Some(&OsStr::new("css")) {
1254 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1255 write(dst, res.as_bytes())
1257 write(dst, minifier::js::minify(contents).as_bytes())
1260 write(dst, contents.as_bytes())
1264 fn write_minify_replacer<W: Write>(
1267 enable_minification: bool,
1268 ) -> io::Result<()> {
1269 use minifier::js::{Keyword, ReservedChar, Token};
1271 if enable_minification {
1273 minifier::js::simple_minify(contents)
1275 // We keep backlines.
1276 minifier::js::clean_tokens_except(f, |c| {
1277 c.get_char() != Some(ReservedChar::Backline)
1281 minifier::js::replace_token_with(f, |t| {
1283 Token::Keyword(Keyword::Null) => Some(Token::Other("N")),
1284 Token::String(s) => {
1285 let s = &s[1..s.len() -1]; // The quotes are included
1287 Some(Token::Other("E"))
1288 } else if s == "t" {
1289 Some(Token::Other("T"))
1290 } else if s == "u" {
1291 Some(Token::Other("U"))
1301 // We add a backline after the newly created variables.
1302 minifier::js::aggregate_strings_into_array_with_separation(
1305 Token::Char(ReservedChar::Backline),
1310 writeln!(dst, "{}", contents)
1314 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1315 /// things like ".." to components which preserve the "top down" hierarchy of a
1316 /// static HTML tree. Each component in the cleaned path will be passed as an
1317 /// argument to `f`. The very last component of the path (ie the file name) will
1318 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1319 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1322 // make it relative, if possible
1323 let p = p.strip_prefix(src_root).unwrap_or(p);
1325 let mut iter = p.components().peekable();
1327 while let Some(c) = iter.next() {
1328 if !keep_filename && iter.peek().is_none() {
1333 Component::ParentDir => f("up".as_ref()),
1334 Component::Normal(c) => f(c),
1340 /// Attempts to find where an external crate is located, given that we're
1341 /// rendering in to the specified source destination.
1342 fn extern_location(e: &clean::ExternalCrate, extern_url: Option<&str>, dst: &Path)
1345 // See if there's documentation generated into the local directory
1346 let local_location = dst.join(&e.name);
1347 if local_location.is_dir() {
1351 if let Some(url) = extern_url {
1352 let mut url = url.to_string();
1353 if !url.ends_with("/") {
1359 // Failing that, see if there's an attribute specifying where to find this
1361 e.attrs.lists("doc")
1362 .filter(|a| a.check_name("html_root_url"))
1363 .filter_map(|a| a.value_str())
1365 let mut url = url.to_string();
1366 if !url.ends_with("/") {
1370 }).next().unwrap_or(Unknown) // Well, at least we tried.
1373 impl<'a> DocFolder for SourceCollector<'a> {
1374 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1375 // If we're including source files, and we haven't seen this file yet,
1376 // then we need to render it out to the filesystem.
1377 if self.scx.include_sources
1378 // skip all invalid or macro spans
1379 && item.source.filename.is_real()
1380 // skip non-local items
1381 && item.def_id.is_local() {
1383 // If it turns out that we couldn't read this file, then we probably
1384 // can't read any of the files (generating html output from json or
1385 // something like that), so just don't include sources for the
1386 // entire crate. The other option is maintaining this mapping on a
1387 // per-file basis, but that's probably not worth it...
1389 .include_sources = match self.emit_source(&item.source.filename) {
1392 println!("warning: source code was requested to be rendered, \
1393 but processing `{}` had an error: {}",
1394 item.source.filename, e);
1395 println!(" skipping rendering of source code");
1400 self.fold_item_recur(item)
1404 impl<'a> SourceCollector<'a> {
1405 /// Renders the given filename into its corresponding HTML source file.
1406 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1407 let p = match *filename {
1408 FileName::Real(ref file) => file,
1411 if self.scx.local_sources.contains_key(&**p) {
1412 // We've already emitted this source
1416 let contents = fs::read_to_string(&p)?;
1418 // Remove the utf-8 BOM if any
1419 let contents = if contents.starts_with("\u{feff}") {
1425 // Create the intermediate directories
1426 let mut cur = self.dst.clone();
1427 let mut root_path = String::from("../../");
1428 let mut href = String::new();
1429 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1430 cur.push(component);
1431 fs::create_dir_all(&cur).unwrap();
1432 root_path.push_str("../");
1433 href.push_str(&component.to_string_lossy());
1436 let mut fname = p.file_name()
1437 .expect("source has no filename")
1439 fname.push(".html");
1441 href.push_str(&fname.to_string_lossy());
1443 let mut w = BufWriter::new(File::create(&cur)?);
1444 let title = format!("{} -- source", cur.file_name().unwrap()
1445 .to_string_lossy());
1446 let desc = format!("Source to the Rust file `{}`.", filename);
1447 let page = layout::Page {
1449 css_class: "source",
1450 root_path: &root_path,
1451 static_root_path: self.scx.static_root_path.deref(),
1453 keywords: BASIC_KEYWORDS,
1454 resource_suffix: &self.scx.resource_suffix,
1455 extra_scripts: &["source-files"],
1456 static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
1458 layout::render(&mut w, &self.scx.layout,
1459 &page, &(""), &Source(contents),
1460 self.scx.css_file_extension.is_some(),
1462 self.scx.generate_search_filter)?;
1464 self.scx.local_sources.insert(p.clone(), href);
1469 impl DocFolder for Cache {
1470 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1471 if item.def_id.is_local() {
1472 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
1475 // If this is a stripped module,
1476 // we don't want it or its children in the search index.
1477 let orig_stripped_mod = match item.inner {
1478 clean::StrippedItem(box clean::ModuleItem(..)) => {
1479 mem::replace(&mut self.stripped_mod, true)
1481 _ => self.stripped_mod,
1484 // If the impl is from a masked crate or references something from a
1485 // masked crate then remove it completely.
1486 if let clean::ImplItem(ref i) = item.inner {
1487 if self.masked_crates.contains(&item.def_id.krate) ||
1488 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1489 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1494 // Register any generics to their corresponding string. This is used
1495 // when pretty-printing types.
1496 if let Some(generics) = item.inner.generics() {
1497 self.generics(generics);
1500 // Propagate a trait method's documentation to all implementors of the
1502 if let clean::TraitItem(ref t) = item.inner {
1503 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1506 // Collect all the implementors of traits.
1507 if let clean::ImplItem(ref i) = item.inner {
1508 if let Some(did) = i.trait_.def_id() {
1509 if i.blanket_impl.is_none() {
1510 self.implementors.entry(did).or_default().push(Impl {
1511 impl_item: item.clone(),
1517 // Index this method for searching later on.
1518 if let Some(ref s) = item.name {
1519 let (parent, is_inherent_impl_item) = match item.inner {
1520 clean::StrippedItem(..) => ((None, None), false),
1521 clean::AssociatedConstItem(..) |
1522 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1523 // skip associated items in trait impls
1524 ((None, None), false)
1526 clean::AssociatedTypeItem(..) |
1527 clean::TyMethodItem(..) |
1528 clean::StructFieldItem(..) |
1529 clean::VariantItem(..) => {
1530 ((Some(*self.parent_stack.last().unwrap()),
1531 Some(&self.stack[..self.stack.len() - 1])),
1534 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1535 if self.parent_stack.is_empty() {
1536 ((None, None), false)
1538 let last = self.parent_stack.last().unwrap();
1540 let path = match self.paths.get(&did) {
1541 // The current stack not necessarily has correlation
1542 // for where the type was defined. On the other
1543 // hand, `paths` always has the right
1544 // information if present.
1545 Some(&(ref fqp, ItemType::Trait)) |
1546 Some(&(ref fqp, ItemType::Struct)) |
1547 Some(&(ref fqp, ItemType::Union)) |
1548 Some(&(ref fqp, ItemType::Enum)) =>
1549 Some(&fqp[..fqp.len() - 1]),
1550 Some(..) => Some(&*self.stack),
1553 ((Some(*last), path), true)
1556 _ => ((None, Some(&*self.stack)), false)
1560 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1561 debug_assert!(!item.is_stripped());
1563 // A crate has a module at its root, containing all items,
1564 // which should not be indexed. The crate-item itself is
1565 // inserted later on when serializing the search-index.
1566 if item.def_id.index != CRATE_DEF_INDEX {
1567 self.search_index.push(IndexItem {
1569 name: s.to_string(),
1570 path: path.join("::"),
1571 desc: plain_summary_line_short(item.doc_value()),
1574 search_type: get_index_search_type(&item),
1578 (Some(parent), None) if is_inherent_impl_item => {
1579 // We have a parent, but we don't know where they're
1580 // defined yet. Wait for later to index this item.
1581 self.orphan_impl_items.push((parent, item.clone()));
1587 // Keep track of the fully qualified path for this item.
1588 let pushed = match item.name {
1589 Some(ref n) if !n.is_empty() => {
1590 self.stack.push(n.to_string());
1597 clean::StructItem(..) | clean::EnumItem(..) |
1598 clean::TypedefItem(..) | clean::TraitItem(..) |
1599 clean::FunctionItem(..) | clean::ModuleItem(..) |
1600 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1601 clean::ConstantItem(..) | clean::StaticItem(..) |
1602 clean::UnionItem(..) | clean::ForeignTypeItem |
1603 clean::MacroItem(..) | clean::ProcMacroItem(..)
1604 if !self.stripped_mod => {
1605 // Re-exported items mean that the same id can show up twice
1606 // in the rustdoc ast that we're looking at. We know,
1607 // however, that a re-exported item doesn't show up in the
1608 // `public_items` map, so we can skip inserting into the
1609 // paths map if there was already an entry present and we're
1610 // not a public item.
1611 if !self.paths.contains_key(&item.def_id) ||
1612 self.access_levels.is_public(item.def_id)
1614 self.paths.insert(item.def_id,
1615 (self.stack.clone(), item.type_()));
1617 self.add_aliases(&item);
1619 // Link variants to their parent enum because pages aren't emitted
1620 // for each variant.
1621 clean::VariantItem(..) if !self.stripped_mod => {
1622 let mut stack = self.stack.clone();
1624 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1627 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1628 self.add_aliases(&item);
1629 self.paths.insert(item.def_id, (self.stack.clone(),
1636 // Maintain the parent stack
1637 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1638 let parent_pushed = match item.inner {
1639 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1640 clean::StructItem(..) | clean::UnionItem(..) => {
1641 self.parent_stack.push(item.def_id);
1642 self.parent_is_trait_impl = false;
1645 clean::ImplItem(ref i) => {
1646 self.parent_is_trait_impl = i.trait_.is_some();
1648 clean::ResolvedPath{ did, .. } => {
1649 self.parent_stack.push(did);
1653 let prim_did = t.primitive_type().and_then(|t| {
1654 self.primitive_locations.get(&t).cloned()
1658 self.parent_stack.push(did);
1669 // Once we've recursively found all the generics, hoard off all the
1670 // implementations elsewhere.
1671 let ret = self.fold_item_recur(item).and_then(|item| {
1672 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1673 // Figure out the id of this impl. This may map to a
1674 // primitive rather than always to a struct/enum.
1675 // Note: matching twice to restrict the lifetime of the `i` borrow.
1676 let mut dids = FxHashSet::default();
1677 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1679 clean::ResolvedPath { did, .. } |
1680 clean::BorrowedRef {
1681 type_: box clean::ResolvedPath { did, .. }, ..
1686 let did = t.primitive_type().and_then(|t| {
1687 self.primitive_locations.get(&t).cloned()
1690 if let Some(did) = did {
1696 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1697 for bound in generics {
1698 if let Some(did) = bound.def_id() {
1706 let impl_item = Impl {
1709 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
1711 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
1714 let trait_did = impl_item.trait_did().unwrap();
1715 self.orphan_trait_impls.push((trait_did, dids, impl_item));
1723 if pushed { self.stack.pop().unwrap(); }
1724 if parent_pushed { self.parent_stack.pop().unwrap(); }
1725 self.stripped_mod = orig_stripped_mod;
1726 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1732 fn generics(&mut self, generics: &clean::Generics) {
1733 for param in &generics.params {
1735 clean::GenericParamDefKind::Lifetime => {}
1736 clean::GenericParamDefKind::Type { did, .. } => {
1737 self.typarams.insert(did, param.name.clone());
1743 fn add_aliases(&mut self, item: &clean::Item) {
1744 if item.def_id.index == CRATE_DEF_INDEX {
1747 if let Some(ref item_name) = item.name {
1748 let path = self.paths.get(&item.def_id)
1749 .map(|p| p.0[..p.0.len() - 1].join("::"))
1750 .unwrap_or("std".to_owned());
1751 for alias in item.attrs.lists("doc")
1752 .filter(|a| a.check_name("alias"))
1753 .filter_map(|a| a.value_str()
1754 .map(|s| s.to_string().replace("\"", "")))
1755 .filter(|v| !v.is_empty())
1756 .collect::<FxHashSet<_>>()
1758 self.aliases.entry(alias)
1759 .or_insert(Vec::with_capacity(1))
1762 name: item_name.to_string(),
1764 desc: plain_summary_line_short(item.doc_value()),
1767 search_type: get_index_search_type(&item),
1774 #[derive(Debug, Eq, PartialEq, Hash)]
1781 fn new(mut url: String, name: String) -> ItemEntry {
1782 while url.starts_with('/') {
1792 impl fmt::Display for ItemEntry {
1793 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1794 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1798 impl PartialOrd for ItemEntry {
1799 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1800 Some(self.cmp(other))
1804 impl Ord for ItemEntry {
1805 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1806 self.name.cmp(&other.name)
1812 structs: FxHashSet<ItemEntry>,
1813 enums: FxHashSet<ItemEntry>,
1814 unions: FxHashSet<ItemEntry>,
1815 primitives: FxHashSet<ItemEntry>,
1816 traits: FxHashSet<ItemEntry>,
1817 macros: FxHashSet<ItemEntry>,
1818 functions: FxHashSet<ItemEntry>,
1819 typedefs: FxHashSet<ItemEntry>,
1820 existentials: FxHashSet<ItemEntry>,
1821 statics: FxHashSet<ItemEntry>,
1822 constants: FxHashSet<ItemEntry>,
1823 keywords: FxHashSet<ItemEntry>,
1824 attributes: FxHashSet<ItemEntry>,
1825 derives: FxHashSet<ItemEntry>,
1829 fn new() -> AllTypes {
1830 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1832 structs: new_set(100),
1833 enums: new_set(100),
1834 unions: new_set(100),
1835 primitives: new_set(26),
1836 traits: new_set(100),
1837 macros: new_set(100),
1838 functions: new_set(100),
1839 typedefs: new_set(100),
1840 existentials: new_set(100),
1841 statics: new_set(100),
1842 constants: new_set(100),
1843 keywords: new_set(100),
1844 attributes: new_set(100),
1845 derives: new_set(100),
1849 fn append(&mut self, item_name: String, item_type: &ItemType) {
1850 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1851 if let Some(name) = url.pop() {
1852 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1854 let name = url.join("::");
1856 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1857 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1858 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1859 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1860 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1861 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1862 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1863 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1864 ItemType::Existential => self.existentials.insert(ItemEntry::new(new_url, name)),
1865 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1866 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1867 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1868 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1875 fn print_entries(f: &mut fmt::Formatter, e: &FxHashSet<ItemEntry>, title: &str,
1876 class: &str) -> fmt::Result {
1878 let mut e: Vec<&ItemEntry> = e.iter().collect();
1880 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1884 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1889 impl fmt::Display for AllTypes {
1890 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1893 <span class='out-of-band'>\
1894 <span id='render-detail'>\
1895 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1896 [<span class='inner'>−</span>]\
1900 <span class='in-band'>List of all items</span>\
1902 print_entries(f, &self.structs, "Structs", "structs")?;
1903 print_entries(f, &self.enums, "Enums", "enums")?;
1904 print_entries(f, &self.unions, "Unions", "unions")?;
1905 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1906 print_entries(f, &self.traits, "Traits", "traits")?;
1907 print_entries(f, &self.macros, "Macros", "macros")?;
1908 print_entries(f, &self.attributes, "Attribute Macros", "attributes")?;
1909 print_entries(f, &self.derives, "Derive Macros", "derives")?;
1910 print_entries(f, &self.functions, "Functions", "functions")?;
1911 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1912 print_entries(f, &self.existentials, "Existentials", "existentials")?;
1913 print_entries(f, &self.statics, "Statics", "statics")?;
1914 print_entries(f, &self.constants, "Constants", "constants")
1919 struct Settings<'a> {
1920 // (id, explanation, default value)
1921 settings: Vec<(&'static str, &'static str, bool)>,
1926 impl<'a> Settings<'a> {
1927 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1930 ("item-declarations", "Auto-hide item declarations.", true),
1931 ("item-attributes", "Auto-hide item attributes.", true),
1932 ("trait-implementations", "Auto-hide trait implementations documentation",
1934 ("method-docs", "Auto-hide item methods' documentation", false),
1935 ("go-to-only-result", "Directly go to item in search if there is only one result",
1937 ("line-numbers", "Show line numbers on code examples", false),
1945 impl<'a> fmt::Display for Settings<'a> {
1946 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1949 <span class='in-band'>Rustdoc settings</span>\
1951 <div class='settings'>{}</div>\
1952 <script src='{}settings{}.js'></script>",
1953 self.settings.iter()
1954 .map(|(id, text, enabled)| {
1955 format!("<div class='setting-line'>\
1956 <label class='toggle'>\
1957 <input type='checkbox' id='{}' {}>\
1958 <span class='slider'></span>\
1961 </div>", id, if *enabled { " checked" } else { "" }, text)
1963 .collect::<String>(),
1970 fn derive_id(&self, id: String) -> String {
1971 let mut map = self.id_map.borrow_mut();
1975 /// String representation of how to get back to the root path of the 'doc/'
1976 /// folder in terms of a relative URL.
1977 fn root_path(&self) -> String {
1978 "../".repeat(self.current.len())
1981 /// Recurse in the directory structure and change the "root path" to make
1982 /// sure it always points to the top (relatively).
1983 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1984 F: FnOnce(&mut Context) -> T,
1987 panic!("Unexpected empty destination: {:?}", self.current);
1989 let prev = self.dst.clone();
1991 self.current.push(s);
1993 info!("Recursing into {}", self.dst.display());
1997 info!("Recursed; leaving {}", self.dst.display());
1999 // Go back to where we were at
2001 self.current.pop().unwrap();
2006 /// Main method for rendering a crate.
2008 /// This currently isn't parallelized, but it'd be pretty easy to add
2009 /// parallelization to this function.
2010 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
2011 let mut item = match krate.module.take() {
2013 None => return Ok(()),
2015 let final_file = self.dst.join(&krate.name)
2017 let settings_file = self.dst.join("settings.html");
2019 let crate_name = krate.name.clone();
2020 item.name = Some(krate.name);
2022 let mut all = AllTypes::new();
2025 // Render the crate documentation
2026 let mut work = vec![(self.clone(), item)];
2028 while let Some((mut cx, item)) = work.pop() {
2029 cx.item(item, &mut all, |cx, item| {
2030 work.push((cx.clone(), item))
2035 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
2036 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
2037 if !root_path.ends_with('/') {
2038 root_path.push('/');
2040 let mut page = layout::Page {
2041 title: "List of all items in this crate",
2044 static_root_path: self.shared.static_root_path.deref(),
2045 description: "List of all items in this crate",
2046 keywords: BASIC_KEYWORDS,
2047 resource_suffix: &self.shared.resource_suffix,
2049 static_extra_scripts: &[],
2051 let sidebar = if let Some(ref version) = cache().crate_version {
2052 format!("<p class='location'>Crate {}</p>\
2053 <div class='block version'>\
2056 <a id='all-types' href='index.html'><p>Back to index</p></a>",
2057 crate_name, version)
2061 try_err!(layout::render(&mut w, &self.shared.layout,
2062 &page, &sidebar, &all,
2063 self.shared.css_file_extension.is_some(),
2064 &self.shared.themes,
2065 self.shared.generate_search_filter),
2068 // Generating settings page.
2069 let settings = Settings::new("./", &self.shared.resource_suffix);
2070 page.title = "Rustdoc settings";
2071 page.description = "Settings of Rustdoc";
2072 page.root_path = "./";
2074 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
2075 let mut themes = self.shared.themes.clone();
2076 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
2077 themes.push(PathBuf::from("settings.css"));
2078 let mut layout = self.shared.layout.clone();
2079 layout.krate = String::new();
2080 try_err!(layout::render(&mut w, &layout,
2081 &page, &sidebar, &settings,
2082 self.shared.css_file_extension.is_some(),
2084 self.shared.generate_search_filter),
2090 fn render_item(&self,
2091 writer: &mut dyn io::Write,
2095 // A little unfortunate that this is done like this, but it sure
2096 // does make formatting *a lot* nicer.
2097 CURRENT_LOCATION_KEY.with(|slot| {
2098 *slot.borrow_mut() = self.current.clone();
2101 let mut title = if it.is_primitive() || it.is_keyword() {
2102 // No need to include the namespace for primitive types and keywords
2105 self.current.join("::")
2108 if !title.is_empty() {
2109 title.push_str("::");
2111 title.push_str(it.name.as_ref().unwrap());
2113 title.push_str(" - Rust");
2114 let tyname = it.type_().css_class();
2115 let desc = if it.is_crate() {
2116 format!("API documentation for the Rust `{}` crate.",
2117 self.shared.layout.krate)
2119 format!("API documentation for the Rust `{}` {} in crate `{}`.",
2120 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
2122 let keywords = make_item_keywords(it);
2123 let page = layout::Page {
2125 root_path: &self.root_path(),
2126 static_root_path: self.shared.static_root_path.deref(),
2129 keywords: &keywords,
2130 resource_suffix: &self.shared.resource_suffix,
2132 static_extra_scripts: &[],
2136 self.id_map.borrow_mut().reset();
2137 self.id_map.borrow_mut().populate(initial_ids());
2140 if !self.render_redirect_pages {
2141 layout::render(writer, &self.shared.layout, &page,
2142 &Sidebar{ cx: self, item: it },
2143 &Item{ cx: self, item: it },
2144 self.shared.css_file_extension.is_some(),
2145 &self.shared.themes,
2146 self.shared.generate_search_filter)?;
2148 let mut url = self.root_path();
2149 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
2150 for name in &names[..names.len() - 1] {
2154 url.push_str(&item_path(ty, names.last().unwrap()));
2155 layout::redirect(writer, &url)?;
2161 /// Non-parallelized version of rendering an item. This will take the input
2162 /// item, render its contents, and then invoke the specified closure with
2163 /// all sub-items which need to be rendered.
2165 /// The rendering driver uses this closure to queue up more work.
2166 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
2167 where F: FnMut(&mut Context, clean::Item),
2169 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
2170 // if they contain impls for public types. These modules can also
2171 // contain items such as publicly re-exported structures.
2173 // External crates will provide links to these structures, so
2174 // these modules are recursed into, but not rendered normally
2175 // (a flag on the context).
2176 if !self.render_redirect_pages {
2177 self.render_redirect_pages = item.is_stripped();
2181 // modules are special because they add a namespace. We also need to
2182 // recurse into the items of the module as well.
2183 let name = item.name.as_ref().unwrap().to_string();
2184 let mut item = Some(item);
2185 self.recurse(name, |this| {
2186 let item = item.take().unwrap();
2188 let mut buf = Vec::new();
2189 this.render_item(&mut buf, &item, false).unwrap();
2190 // buf will be empty if the module is stripped and there is no redirect for it
2191 if !buf.is_empty() {
2192 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
2193 let joint_dst = this.dst.join("index.html");
2194 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2197 let m = match item.inner {
2198 clean::StrippedItem(box clean::ModuleItem(m)) |
2199 clean::ModuleItem(m) => m,
2203 // Render sidebar-items.js used throughout this module.
2204 if !this.render_redirect_pages {
2205 let items = this.build_sidebar_items(&m);
2206 let js_dst = this.dst.join("sidebar-items.js");
2207 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
2208 try_err!(write!(&mut js_out, "initSidebarItems({});",
2209 as_json(&items)), &js_dst);
2212 for item in m.items {
2218 } else if item.name.is_some() {
2219 let mut buf = Vec::new();
2220 self.render_item(&mut buf, &item, true).unwrap();
2221 // buf will be empty if the item is stripped and there is no redirect for it
2222 if !buf.is_empty() {
2223 let name = item.name.as_ref().unwrap();
2224 let item_type = item.type_();
2225 let file_name = &item_path(item_type, name);
2226 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
2227 let joint_dst = self.dst.join(file_name);
2228 try_err!(fs::write(&joint_dst, buf), &joint_dst);
2230 if !self.render_redirect_pages {
2231 all.append(full_path(self, &item), &item_type);
2233 // Redirect from a sane URL using the namespace to Rustdoc's
2234 // URL for the page.
2235 let redir_name = format!("{}.{}.html", name, item_type.name_space());
2236 let redir_dst = self.dst.join(redir_name);
2237 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
2240 let mut redirect_out = BufWriter::new(redirect_out);
2241 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2244 // If the item is a macro, redirect from the old macro URL (with !)
2245 // to the new one (without).
2246 if item_type == ItemType::Macro {
2247 let redir_name = format!("{}.{}!.html", item_type, name);
2248 let redir_dst = self.dst.join(redir_name);
2249 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
2250 let mut redirect_out = BufWriter::new(redirect_out);
2251 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
2258 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
2259 // BTreeMap instead of HashMap to get a sorted output
2260 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
2261 for item in &m.items {
2262 if item.is_stripped() { continue }
2264 let short = item.type_().css_class();
2265 let myname = match item.name {
2267 Some(ref s) => s.to_string(),
2269 let short = short.to_string();
2270 map.entry(short).or_default()
2271 .push((myname, Some(plain_summary_line(item.doc_value()))));
2274 if self.shared.sort_modules_alphabetically {
2275 for (_, items) in &mut map {
2284 /// Generate a url appropriate for an `href` attribute back to the source of
2287 /// The url generated, when clicked, will redirect the browser back to the
2288 /// original source code.
2290 /// If `None` is returned, then a source link couldn't be generated. This
2291 /// may happen, for example, with externally inlined items where the source
2292 /// of their crate documentation isn't known.
2293 fn src_href(&self) -> Option<String> {
2294 let mut root = self.cx.root_path();
2296 let cache = cache();
2297 let mut path = String::new();
2299 // We can safely ignore macros from other libraries
2300 let file = match self.item.source.filename {
2301 FileName::Real(ref path) => path,
2305 let (krate, path) = if self.item.def_id.is_local() {
2306 if let Some(path) = self.cx.shared.local_sources.get(file) {
2307 (&self.cx.shared.layout.krate, path)
2312 let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? {
2313 (ref name, ref src, Local) => (name, src),
2314 (ref name, ref src, Remote(ref s)) => {
2315 root = s.to_string();
2318 (_, _, Unknown) => return None,
2321 clean_srcpath(&src_root, file, false, |component| {
2322 path.push_str(&component.to_string_lossy());
2325 let mut fname = file.file_name().expect("source has no filename")
2327 fname.push(".html");
2328 path.push_str(&fname.to_string_lossy());
2332 let lines = if self.item.source.loline == self.item.source.hiline {
2333 self.item.source.loline.to_string()
2335 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2337 Some(format!("{root}src/{krate}/{path}#{lines}",
2338 root = Escape(&root),
2345 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2346 f: F) -> fmt::Result
2347 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2348 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">")?;
2353 impl<'a> fmt::Display for Item<'a> {
2354 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2355 debug_assert!(!self.item.is_stripped());
2356 // Write the breadcrumb trail header for the top
2357 write!(fmt, "<h1 class='fqn'><span class='out-of-band'>")?;
2358 if let Some(version) = self.item.stable_since() {
2359 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2363 "<span id='render-detail'>\
2364 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2365 title=\"collapse all docs\">\
2366 [<span class='inner'>−</span>]\
2372 // When this item is part of a `pub use` in a downstream crate, the
2373 // [src] link in the downstream documentation will actually come back to
2374 // this page, and this link will be auto-clicked. The `id` attribute is
2375 // used to find the link to auto-click.
2376 if self.cx.shared.include_sources && !self.item.is_primitive() {
2377 if let Some(l) = self.src_href() {
2378 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2379 l, "goto source code")?;
2383 write!(fmt, "</span>")?; // out-of-band
2384 write!(fmt, "<span class='in-band'>")?;
2385 match self.item.inner {
2386 clean::ModuleItem(ref m) => if m.is_crate {
2387 write!(fmt, "Crate ")?;
2389 write!(fmt, "Module ")?;
2391 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2392 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2393 clean::StructItem(..) => write!(fmt, "Struct ")?,
2394 clean::UnionItem(..) => write!(fmt, "Union ")?,
2395 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2396 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2397 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2398 clean::ProcMacroItem(ref mac) => match mac.kind {
2399 MacroKind::Bang => write!(fmt, "Macro ")?,
2400 MacroKind::Attr => write!(fmt, "Attribute Macro ")?,
2401 MacroKind::Derive => write!(fmt, "Derive Macro ")?,
2402 MacroKind::ProcMacroStub => unreachable!(),
2404 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2405 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2406 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2407 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2408 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2409 clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2411 // We don't generate pages for any other type.
2415 if !self.item.is_primitive() && !self.item.is_keyword() {
2416 let cur = &self.cx.current;
2417 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2418 for (i, component) in cur.iter().enumerate().take(amt) {
2419 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2420 "../".repeat(cur.len() - i - 1),
2424 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2425 self.item.type_(), self.item.name.as_ref().unwrap())?;
2427 write!(fmt, "</span></h1>")?; // in-band
2429 match self.item.inner {
2430 clean::ModuleItem(ref m) =>
2431 item_module(fmt, self.cx, self.item, &m.items),
2432 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2433 item_function(fmt, self.cx, self.item, f),
2434 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2435 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2436 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2437 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2438 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2439 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2440 clean::ProcMacroItem(ref m) => item_proc_macro(fmt, self.cx, self.item, m),
2441 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2442 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2443 item_static(fmt, self.cx, self.item, i),
2444 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2445 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2446 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2447 clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2449 // We don't generate pages for any other type.
2456 fn item_path(ty: ItemType, name: &str) -> String {
2458 ItemType::Module => format!("{}/index.html", name),
2459 _ => format!("{}.{}.html", ty.css_class(), name),
2463 fn full_path(cx: &Context, item: &clean::Item) -> String {
2464 let mut s = cx.current.join("::");
2466 s.push_str(item.name.as_ref().unwrap());
2470 fn shorter<'a>(s: Option<&'a str>) -> String {
2472 Some(s) => s.lines()
2473 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2475 (*line).chars().any(|chr|{
2476 !chr.is_whitespace()
2478 }).collect::<Vec<_>>().join("\n"),
2479 None => String::new()
2484 fn plain_summary_line(s: Option<&str>) -> String {
2485 let line = shorter(s).replace("\n", " ");
2486 markdown::plain_summary_line_full(&line[..], false)
2490 fn plain_summary_line_short(s: Option<&str>) -> String {
2491 let line = shorter(s).replace("\n", " ");
2492 markdown::plain_summary_line_full(&line[..], true)
2495 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2496 if let Some(ref name) = item.name {
2497 info!("Documenting {}", name);
2499 document_stability(w, cx, item, false)?;
2500 document_full(w, item, cx, "", false)?;
2504 /// Render md_text as markdown.
2505 fn render_markdown(w: &mut fmt::Formatter,
2508 links: Vec<(String, String)>,
2512 let mut ids = cx.id_map.borrow_mut();
2513 write!(w, "<div class='docblock{}'>{}{}</div>",
2514 if is_hidden { " hidden" } else { "" },
2516 Markdown(md_text, &links, RefCell::new(&mut ids),
2520 fn document_short(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, link: AssocItemLink,
2521 prefix: &str, is_hidden: bool) -> fmt::Result {
2522 if let Some(s) = item.doc_value() {
2523 let markdown = if s.contains('\n') {
2524 format!("{} [Read more]({})",
2525 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2527 plain_summary_line(Some(s))
2529 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden)?;
2530 } else if !prefix.is_empty() {
2531 write!(w, "<div class='docblock{}'>{}</div>",
2532 if is_hidden { " hidden" } else { "" },
2538 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2539 cx: &Context, prefix: &str, is_hidden: bool) -> fmt::Result {
2540 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2541 debug!("Doc block: =====\n{}\n=====", s);
2542 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden)?;
2543 } else if !prefix.is_empty() {
2544 write!(w, "<div class='docblock{}'>{}</div>",
2545 if is_hidden { " hidden" } else { "" },
2551 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2552 is_hidden: bool) -> fmt::Result {
2553 let stabilities = short_stability(item, cx);
2554 if !stabilities.is_empty() {
2555 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" })?;
2556 for stability in stabilities {
2557 write!(w, "{}", stability)?;
2559 write!(w, "</div>")?;
2564 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2565 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2568 fn document_non_exhaustive(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
2569 if item.is_non_exhaustive() {
2570 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
2571 if item.is_struct() { "struct" } else if item.is_enum() { "enum" } else { "type" }
2574 if item.is_struct() {
2575 write!(w, "Non-exhaustive structs could have additional fields added in future. \
2576 Therefore, non-exhaustive structs cannot be constructed in external crates \
2577 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
2578 matched against without a wildcard <code>..</code>; and \
2579 struct update syntax will not work.")?;
2580 } else if item.is_enum() {
2581 write!(w, "Non-exhaustive enums could have additional variants added in future. \
2582 Therefore, when matching against variants of non-exhaustive enums, an \
2583 extra wildcard arm must be added to account for any future variants.")?;
2585 write!(w, "This type will require a wildcard arm in any match statements or \
2589 write!(w, "</div>")?;
2595 fn name_key(name: &str) -> (&str, u64, usize) {
2596 let end = name.bytes()
2597 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
2599 // find number at end
2600 let split = name[0..end].bytes()
2601 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
2603 // count leading zeroes
2605 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2607 // sort leading zeroes last
2608 let num_zeroes = after_zeroes - split;
2610 match name[split..end].parse() {
2611 Ok(n) => (&name[..split], n, num_zeroes),
2612 Err(_) => (name, 0, num_zeroes),
2616 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2617 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2618 document(w, cx, item)?;
2620 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2622 // the order of item types in the listing
2623 fn reorder(ty: ItemType) -> u8 {
2625 ItemType::ExternCrate => 0,
2626 ItemType::Import => 1,
2627 ItemType::Primitive => 2,
2628 ItemType::Module => 3,
2629 ItemType::Macro => 4,
2630 ItemType::Struct => 5,
2631 ItemType::Enum => 6,
2632 ItemType::Constant => 7,
2633 ItemType::Static => 8,
2634 ItemType::Trait => 9,
2635 ItemType::Function => 10,
2636 ItemType::Typedef => 12,
2637 ItemType::Union => 13,
2642 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2643 let ty1 = i1.type_();
2644 let ty2 = i2.type_();
2646 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2648 let s1 = i1.stability.as_ref().map(|s| s.level);
2649 let s2 = i2.stability.as_ref().map(|s| s.level);
2651 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2652 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2655 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2656 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2657 name_key(lhs).cmp(&name_key(rhs))
2660 if cx.shared.sort_modules_alphabetically {
2661 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2663 // This call is to remove re-export duplicates in cases such as:
2668 // pub trait Double { fn foo(); }
2672 // pub use foo::bar::*;
2676 // `Double` will appear twice in the generated docs.
2678 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2679 // can be identical even if the elements are different (mostly in imports).
2680 // So in case this is an import, we keep everything by adding a "unique id"
2681 // (which is the position in the vector).
2682 indices.dedup_by_key(|i| (items[*i].def_id,
2683 if items[*i].name.as_ref().is_some() {
2684 Some(full_path(cx, &items[*i]))
2689 if items[*i].is_import() {
2695 debug!("{:?}", indices);
2696 let mut curty = None;
2697 for &idx in &indices {
2698 let myitem = &items[idx];
2699 if myitem.is_stripped() {
2703 let myty = Some(myitem.type_());
2704 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2705 // Put `extern crate` and `use` re-exports in the same section.
2707 } else if myty != curty {
2708 if curty.is_some() {
2709 write!(w, "</table>")?;
2712 let (short, name) = item_ty_to_strs(&myty.unwrap());
2713 write!(w, "<h2 id='{id}' class='section-header'>\
2714 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2715 id = cx.derive_id(short.to_owned()), name = name)?;
2718 match myitem.inner {
2719 clean::ExternCrateItem(ref name, ref src) => {
2720 use html::format::HRef;
2724 write!(w, "<tr><td><code>{}extern crate {} as {};",
2725 VisSpace(&myitem.visibility),
2726 HRef::new(myitem.def_id, src),
2730 write!(w, "<tr><td><code>{}extern crate {};",
2731 VisSpace(&myitem.visibility),
2732 HRef::new(myitem.def_id, name))?
2735 write!(w, "</code></td></tr>")?;
2738 clean::ImportItem(ref import) => {
2739 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2740 VisSpace(&myitem.visibility), *import)?;
2744 if myitem.name.is_none() { continue }
2746 let unsafety_flag = match myitem.inner {
2747 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2748 if func.header.unsafety == hir::Unsafety::Unsafe => {
2749 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
2754 let stab = myitem.stability_class();
2755 let add = if stab.is_some() {
2761 let doc_value = myitem.doc_value().unwrap_or("");
2763 <tr class='{stab}{add}module-item'>\
2764 <td><a class=\"{class}\" href=\"{href}\" \
2765 title='{title}'>{name}</a>{unsafety_flag}</td>\
2766 <td class='docblock-short'>{stab_tags}{docs}\
2769 name = *myitem.name.as_ref().unwrap(),
2770 stab_tags = stability_tags(myitem),
2771 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2772 class = myitem.type_(),
2774 stab = stab.unwrap_or_else(|| String::new()),
2775 unsafety_flag = unsafety_flag,
2776 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2777 title = [full_path(cx, myitem), myitem.type_().to_string()]
2779 .filter_map(|s| if !s.is_empty() {
2784 .collect::<Vec<_>>()
2791 if curty.is_some() {
2792 write!(w, "</table>")?;
2797 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2799 fn stability_tags(item: &clean::Item) -> String {
2800 let mut tags = String::new();
2802 // The trailing space after each tag is to space it properly against the rest of the docs.
2803 if item.deprecation().is_some() {
2804 tags.push_str("[<div class='stab deprecated'>Deprecated</div>] ");
2807 if let Some(stab) = item
2810 .filter(|s| s.level == stability::Unstable)
2812 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
2813 tags.push_str("[<div class='stab internal'>Internal</div>] ");
2815 tags.push_str("[<div class='stab unstable'>Experimental</div>] ");
2819 if let Some(ref cfg) = item.attrs.cfg {
2820 tags.push_str(&format!(
2821 "[<div class='stab portability'>{}</div>] ",
2822 cfg.render_short_html()
2829 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2831 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2832 let mut stability = vec![];
2833 let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
2835 if let Some(Deprecation { since, note }) = &item.deprecation() {
2836 let mut message = if let Some(since) = since {
2837 if stability::deprecation_in_effect(since) {
2838 format!("Deprecated since {}", Escape(since))
2840 format!("Deprecating in {}", Escape(since))
2843 String::from("Deprecated")
2846 if let Some(note) = note {
2847 let mut ids = cx.id_map.borrow_mut();
2848 let html = MarkdownHtml(¬e, RefCell::new(&mut ids), error_codes);
2849 message.push_str(&format!(": {}", html));
2851 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2854 if let Some(stab) = item
2857 .filter(|stab| stab.level == stability::Unstable)
2859 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2861 let mut message = if is_rustc_private {
2862 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2864 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2868 if let Some(feature) = stab.feature.as_ref() {
2869 let mut feature = format!("<code>{}</code>", Escape(&feature));
2870 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2871 feature.push_str(&format!(
2872 " <a href=\"{url}{issue}\">#{issue}</a>",
2878 message.push_str(&format!(" ({})", feature));
2881 if let Some(unstable_reason) = &stab.unstable_reason {
2882 // Provide a more informative message than the compiler help.
2883 let unstable_reason = if is_rustc_private {
2884 "This crate is being loaded from the sysroot, a permanently unstable location \
2885 for private compiler dependencies. It is not intended for general use. Prefer \
2886 using a public version of this crate from \
2887 [crates.io](https://crates.io) via [`Cargo.toml`]\
2888 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
2893 let mut ids = cx.id_map.borrow_mut();
2895 "<details><summary>{}</summary>{}</details>",
2897 MarkdownHtml(&unstable_reason, RefCell::new(&mut ids), error_codes)
2901 let class = if is_rustc_private {
2906 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
2909 if let Some(ref cfg) = item.attrs.cfg {
2910 stability.push(format!(
2911 "<div class='stab portability'>{}</div>",
2912 cfg.render_long_html()
2919 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2920 c: &clean::Constant) -> fmt::Result {
2921 write!(w, "<pre class='rust const'>")?;
2922 render_attributes(w, it)?;
2923 write!(w, "{vis}const \
2924 {name}: {typ}</pre>",
2925 vis = VisSpace(&it.visibility),
2926 name = it.name.as_ref().unwrap(),
2931 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2932 s: &clean::Static) -> fmt::Result {
2933 write!(w, "<pre class='rust static'>")?;
2934 render_attributes(w, it)?;
2935 write!(w, "{vis}static {mutability}\
2936 {name}: {typ}</pre>",
2937 vis = VisSpace(&it.visibility),
2938 mutability = MutableSpace(s.mutability),
2939 name = it.name.as_ref().unwrap(),
2944 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2945 f: &clean::Function) -> fmt::Result {
2946 let name_len = format!("{}{}{}{}{:#}fn {}{:#}",
2947 VisSpace(&it.visibility),
2948 ConstnessSpace(f.header.constness),
2949 UnsafetySpace(f.header.unsafety),
2950 AsyncSpace(f.header.asyncness),
2951 AbiSpace(f.header.abi),
2952 it.name.as_ref().unwrap(),
2954 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2955 render_attributes(w, it)?;
2957 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2958 {name}{generics}{decl}{where_clause}</pre>",
2959 vis = VisSpace(&it.visibility),
2960 constness = ConstnessSpace(f.header.constness),
2961 unsafety = UnsafetySpace(f.header.unsafety),
2962 asyncness = AsyncSpace(f.header.asyncness),
2963 abi = AbiSpace(f.header.abi),
2964 name = it.name.as_ref().unwrap(),
2965 generics = f.generics,
2966 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2975 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2976 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2977 // If there's already another implementor that has the same abbridged name, use the
2978 // full path, for example in `std::iter::ExactSizeIterator`
2979 let use_absolute = match implementor.inner_impl().for_ {
2980 clean::ResolvedPath { ref path, is_generic: false, .. } |
2981 clean::BorrowedRef {
2982 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2984 } => implementor_dups[path.last_name()].1,
2987 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
2988 implementor.impl_item.stable_since(), false, Some(use_absolute))?;
2992 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2994 containing_item: &clean::Item) -> fmt::Result {
2996 let did = i.trait_did().unwrap();
2997 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2998 render_impl(w, cx, i, assoc_link,
2999 RenderMode::Normal, containing_item.stable_since(), true, None)?;
3004 fn bounds(t_bounds: &[clean::GenericBound]) -> String {
3005 let mut bounds = String::new();
3006 let mut bounds_plain = String::new();
3007 if !t_bounds.is_empty() {
3008 if !bounds.is_empty() {
3010 bounds_plain.push(' ');
3012 bounds.push_str(": ");
3013 bounds_plain.push_str(": ");
3014 for (i, p) in t_bounds.iter().enumerate() {
3016 bounds.push_str(" + ");
3017 bounds_plain.push_str(" + ");
3019 bounds.push_str(&(*p).to_string());
3020 bounds_plain.push_str(&format!("{:#}", *p));
3026 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
3027 let lhs = format!("{}", lhs.inner_impl());
3028 let rhs = format!("{}", rhs.inner_impl());
3030 // lhs and rhs are formatted as HTML, which may be unnecessary
3031 name_key(&lhs).cmp(&name_key(&rhs))
3035 w: &mut fmt::Formatter,
3040 let bounds = bounds(&t.bounds);
3041 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
3042 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
3043 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
3044 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
3046 // Output the trait definition
3047 wrap_into_docblock(w, |w| {
3048 write!(w, "<pre class='rust trait'>")?;
3049 render_attributes(w, it)?;
3050 write!(w, "{}{}{}trait {}{}{}",
3051 VisSpace(&it.visibility),
3052 UnsafetySpace(t.unsafety),
3053 if t.is_auto { "auto " } else { "" },
3054 it.name.as_ref().unwrap(),
3058 if !t.generics.where_predicates.is_empty() {
3059 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
3064 if t.items.is_empty() {
3065 write!(w, "{{ }}")?;
3067 // FIXME: we should be using a derived_id for the Anchors here
3071 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3074 if !types.is_empty() && !consts.is_empty() {
3079 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
3082 if !consts.is_empty() && !required.is_empty() {
3085 for (pos, m) in required.iter().enumerate() {
3087 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3090 if pos < required.len() - 1 {
3091 write!(w, "<div class='item-spacer'></div>")?;
3094 if !required.is_empty() && !provided.is_empty() {
3097 for (pos, m) in provided.iter().enumerate() {
3099 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
3101 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
3102 write!(w, ",\n {{ ... }}\n")?;
3105 write!(w, " {{ ... }}\n")?;
3108 if pos < provided.len() - 1 {
3109 write!(w, "<div class='item-spacer'></div>")?;
3117 // Trait documentation
3118 document(w, cx, it)?;
3120 fn write_small_section_header(
3121 w: &mut fmt::Formatter,
3124 extra_content: &str,
3127 <h2 id='{0}' class='small-section-header'>\
3128 {1}<a href='#{0}' class='anchor'></a>\
3129 </h2>{2}", id, title, extra_content)
3132 fn write_loading_content(w: &mut fmt::Formatter, extra_content: &str) -> fmt::Result {
3133 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
3136 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
3138 let name = m.name.as_ref().unwrap();
3139 let item_type = m.type_();
3140 let id = cx.derive_id(format!("{}.{}", item_type, name));
3141 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
3142 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
3143 extra = render_spotlight_traits(m)?,
3146 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
3147 write!(w, "</code>")?;
3148 render_stability_since(w, m, t)?;
3149 write!(w, "</h3>")?;
3150 document(w, cx, m)?;
3154 if !types.is_empty() {
3155 write_small_section_header(w, "associated-types", "Associated Types",
3156 "<div class='methods'>")?;
3158 trait_item(w, cx, *t, it)?;
3160 write_loading_content(w, "</div>")?;
3163 if !consts.is_empty() {
3164 write_small_section_header(w, "associated-const", "Associated Constants",
3165 "<div class='methods'>")?;
3167 trait_item(w, cx, *t, it)?;
3169 write_loading_content(w, "</div>")?;
3172 // Output the documentation for each function individually
3173 if !required.is_empty() {
3174 write_small_section_header(w, "required-methods", "Required methods",
3175 "<div class='methods'>")?;
3176 for m in &required {
3177 trait_item(w, cx, *m, it)?;
3179 write_loading_content(w, "</div>")?;
3181 if !provided.is_empty() {
3182 write_small_section_header(w, "provided-methods", "Provided methods",
3183 "<div class='methods'>")?;
3184 for m in &provided {
3185 trait_item(w, cx, *m, it)?;
3187 write_loading_content(w, "</div>")?;
3190 // If there are methods directly on this trait object, render them here.
3191 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3193 let cache = cache();
3195 let mut synthetic_types = Vec::new();
3197 if let Some(implementors) = cache.implementors.get(&it.def_id) {
3198 // The DefId is for the first Type found with that name. The bool is
3199 // if any Types with the same name but different DefId have been found.
3200 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
3201 for implementor in implementors {
3202 match implementor.inner_impl().for_ {
3203 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
3204 clean::BorrowedRef {
3205 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
3208 let &mut (prev_did, ref mut has_duplicates) =
3209 implementor_dups.entry(path.last_name()).or_insert((did, false));
3210 if prev_did != did {
3211 *has_duplicates = true;
3218 let (local, foreign) = implementors.iter()
3219 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
3220 .map_or(true, |d| cache.paths.contains_key(&d)));
3223 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
3224 .partition(|i| i.inner_impl().synthetic);
3226 synthetic.sort_by(compare_impl);
3227 concrete.sort_by(compare_impl);
3229 if !foreign.is_empty() {
3230 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
3232 for implementor in foreign {
3233 let assoc_link = AssocItemLink::GotoSource(
3234 implementor.impl_item.def_id,
3235 &implementor.inner_impl().provided_trait_methods
3237 render_impl(w, cx, &implementor, assoc_link,
3238 RenderMode::Normal, implementor.impl_item.stable_since(), false,
3241 write_loading_content(w, "")?;
3244 write_small_section_header(w, "implementors", "Implementors",
3245 "<div class='item-list' id='implementors-list'>")?;
3246 for implementor in concrete {
3247 render_implementor(cx, implementor, w, &implementor_dups)?;
3249 write_loading_content(w, "</div>")?;
3252 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3253 "<div class='item-list' id='synthetic-implementors-list'>")?;
3254 for implementor in synthetic {
3255 synthetic_types.extend(
3256 collect_paths_for_type(implementor.inner_impl().for_.clone())
3258 render_implementor(cx, implementor, w, &implementor_dups)?;
3260 write_loading_content(w, "</div>")?;
3263 // even without any implementations to write in, we still want the heading and list, so the
3264 // implementors javascript file pulled in below has somewhere to write the impls into
3265 write_small_section_header(w, "implementors", "Implementors",
3266 "<div class='item-list' id='implementors-list'>")?;
3267 write_loading_content(w, "</div>")?;
3270 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
3271 "<div class='item-list' id='synthetic-implementors-list'>")?;
3272 write_loading_content(w, "</div>")?;
3275 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
3276 as_json(&synthetic_types))?;
3278 write!(w, r#"<script type="text/javascript" async
3279 src="{root_path}/implementors/{path}/{ty}.{name}.js">
3281 root_path = vec![".."; cx.current.len()].join("/"),
3282 path = if it.def_id.is_local() {
3283 cx.current.join("/")
3285 let (ref path, _) = cache.external_paths[&it.def_id];
3286 path[..path.len() - 1].join("/")
3288 ty = it.type_().css_class(),
3289 name = *it.name.as_ref().unwrap())?;
3293 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
3294 use html::item_type::ItemType::*;
3296 let name = it.name.as_ref().unwrap();
3297 let ty = match it.type_() {
3298 Typedef | AssociatedType => AssociatedType,
3302 let anchor = format!("#{}.{}", ty, name);
3304 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3305 AssocItemLink::Anchor(None) => anchor,
3306 AssocItemLink::GotoSource(did, _) => {
3307 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
3312 fn assoc_const(w: &mut fmt::Formatter,
3315 _default: Option<&String>,
3316 link: AssocItemLink) -> fmt::Result {
3317 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
3318 VisSpace(&it.visibility),
3319 naive_assoc_href(it, link),
3320 it.name.as_ref().unwrap(),
3325 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
3326 bounds: &[clean::GenericBound],
3327 default: Option<&clean::Type>,
3328 link: AssocItemLink) -> fmt::Result {
3329 write!(w, "type <a href='{}' class=\"type\">{}</a>",
3330 naive_assoc_href(it, link),
3331 it.name.as_ref().unwrap())?;
3332 if !bounds.is_empty() {
3333 write!(w, ": {}", GenericBounds(bounds))?
3335 if let Some(default) = default {
3336 write!(w, " = {}", default)?;
3341 fn render_stability_since_raw<'a, T: fmt::Write>(
3343 ver: Option<&'a str>,
3344 containing_ver: Option<&'a str>,
3346 if let Some(v) = ver {
3347 if containing_ver != ver && v.len() > 0 {
3348 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>", v)?
3354 fn render_stability_since(w: &mut fmt::Formatter,
3356 containing_item: &clean::Item) -> fmt::Result {
3357 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3360 fn render_assoc_item(w: &mut fmt::Formatter,
3362 link: AssocItemLink,
3363 parent: ItemType) -> fmt::Result {
3364 fn method(w: &mut fmt::Formatter,
3366 header: hir::FnHeader,
3367 g: &clean::Generics,
3369 link: AssocItemLink,
3372 let name = meth.name.as_ref().unwrap();
3373 let anchor = format!("#{}.{}", meth.type_(), name);
3374 let href = match link {
3375 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3376 AssocItemLink::Anchor(None) => anchor,
3377 AssocItemLink::GotoSource(did, provided_methods) => {
3378 // We're creating a link from an impl-item to the corresponding
3379 // trait-item and need to map the anchored type accordingly.
3380 let ty = if provided_methods.contains(name) {
3386 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3389 let mut head_len = format!("{}{}{}{}{:#}fn {}{:#}",
3390 VisSpace(&meth.visibility),
3391 ConstnessSpace(header.constness),
3392 UnsafetySpace(header.unsafety),
3393 AsyncSpace(header.asyncness),
3394 AbiSpace(header.abi),
3397 let (indent, end_newline) = if parent == ItemType::Trait {
3403 render_attributes(w, meth)?;
3404 write!(w, "{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3405 {generics}{decl}{where_clause}",
3406 VisSpace(&meth.visibility),
3407 ConstnessSpace(header.constness),
3408 UnsafetySpace(header.unsafety),
3409 AsyncSpace(header.asyncness),
3410 AbiSpace(header.abi),
3419 where_clause = WhereClause {
3426 clean::StrippedItem(..) => Ok(()),
3427 clean::TyMethodItem(ref m) => {
3428 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3430 clean::MethodItem(ref m) => {
3431 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3433 clean::AssociatedConstItem(ref ty, ref default) => {
3434 assoc_const(w, item, ty, default.as_ref(), link)
3436 clean::AssociatedTypeItem(ref bounds, ref default) => {
3437 assoc_type(w, item, bounds, default.as_ref(), link)
3439 _ => panic!("render_assoc_item called on non-associated-item")
3443 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3444 s: &clean::Struct) -> fmt::Result {
3445 wrap_into_docblock(w, |w| {
3446 write!(w, "<pre class='rust struct'>")?;
3447 render_attributes(w, it)?;
3458 document(w, cx, it)?;
3459 let mut fields = s.fields.iter().filter_map(|f| {
3461 clean::StructFieldItem(ref ty) => Some((f, ty)),
3465 if let doctree::Plain = s.struct_type {
3466 if fields.peek().is_some() {
3467 write!(w, "<h2 id='fields' class='fields small-section-header'>
3468 Fields{}<a href='#fields' class='anchor'></a></h2>",
3469 document_non_exhaustive_header(it))?;
3470 document_non_exhaustive(w, it)?;
3471 for (field, ty) in fields {
3472 let id = cx.derive_id(format!("{}.{}",
3473 ItemType::StructField,
3474 field.name.as_ref().unwrap()));
3475 let ns_id = cx.derive_id(format!("{}.{}",
3476 field.name.as_ref().unwrap(),
3477 ItemType::StructField.name_space()));
3478 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
3479 <a href=\"#{id}\" class=\"anchor field\"></a>\
3480 <code id=\"{ns_id}\">{name}: {ty}</code>\
3482 item_type = ItemType::StructField,
3485 name = field.name.as_ref().unwrap(),
3487 if let Some(stability_class) = field.stability_class() {
3488 write!(w, "<span class='stab {stab}'></span>",
3489 stab = stability_class)?;
3491 document(w, cx, field)?;
3495 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3498 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3499 s: &clean::Union) -> fmt::Result {
3500 wrap_into_docblock(w, |w| {
3501 write!(w, "<pre class='rust union'>")?;
3502 render_attributes(w, it)?;
3512 document(w, cx, it)?;
3513 let mut fields = s.fields.iter().filter_map(|f| {
3515 clean::StructFieldItem(ref ty) => Some((f, ty)),
3519 if fields.peek().is_some() {
3520 write!(w, "<h2 id='fields' class='fields small-section-header'>
3521 Fields<a href='#fields' class='anchor'></a></h2>")?;
3522 for (field, ty) in fields {
3523 let name = field.name.as_ref().expect("union field name");
3524 let id = format!("{}.{}", ItemType::StructField, name);
3525 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3526 <a href=\"#{id}\" class=\"anchor field\"></a>\
3527 <code>{name}: {ty}</code>\
3531 shortty = ItemType::StructField,
3533 if let Some(stability_class) = field.stability_class() {
3534 write!(w, "<span class='stab {stab}'></span>",
3535 stab = stability_class)?;
3537 document(w, cx, field)?;
3540 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3543 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3544 e: &clean::Enum) -> fmt::Result {
3545 wrap_into_docblock(w, |w| {
3546 write!(w, "<pre class='rust enum'>")?;
3547 render_attributes(w, it)?;
3548 write!(w, "{}enum {}{}{}",
3549 VisSpace(&it.visibility),
3550 it.name.as_ref().unwrap(),
3552 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3553 if e.variants.is_empty() && !e.variants_stripped {
3554 write!(w, " {{}}")?;
3556 write!(w, " {{\n")?;
3557 for v in &e.variants {
3559 let name = v.name.as_ref().unwrap();
3561 clean::VariantItem(ref var) => {
3563 clean::VariantKind::CLike => write!(w, "{}", name)?,
3564 clean::VariantKind::Tuple(ref tys) => {
3565 write!(w, "{}(", name)?;
3566 for (i, ty) in tys.iter().enumerate() {
3568 write!(w, ", ")?
3570 write!(w, "{}", *ty)?;
3574 clean::VariantKind::Struct(ref s) => {
3590 if e.variants_stripped {
3591 write!(w, " // some variants omitted\n")?;
3598 document(w, cx, it)?;
3599 if !e.variants.is_empty() {
3600 write!(w, "<h2 id='variants' class='variants small-section-header'>
3601 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3602 document_non_exhaustive_header(it))?;
3603 document_non_exhaustive(w, it)?;
3604 for variant in &e.variants {
3605 let id = cx.derive_id(format!("{}.{}",
3607 variant.name.as_ref().unwrap()));
3608 let ns_id = cx.derive_id(format!("{}.{}",
3609 variant.name.as_ref().unwrap(),
3610 ItemType::Variant.name_space()));
3611 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3612 <a href=\"#{id}\" class=\"anchor field\"></a>\
3613 <code id='{ns_id}'>{name}",
3616 name = variant.name.as_ref().unwrap())?;
3617 if let clean::VariantItem(ref var) = variant.inner {
3618 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3620 for (i, ty) in tys.iter().enumerate() {
3622 write!(w, ", ")?;
3624 write!(w, "{}", *ty)?;
3629 write!(w, "</code></span>")?;
3630 document(w, cx, variant)?;
3632 use clean::{Variant, VariantKind};
3633 if let clean::VariantItem(Variant {
3634 kind: VariantKind::Struct(ref s)
3635 }) = variant.inner {
3636 let variant_id = cx.derive_id(format!("{}.{}.fields",
3638 variant.name.as_ref().unwrap()));
3639 write!(w, "<span class='autohide sub-variant' id='{id}'>",
3641 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
3642 name = variant.name.as_ref().unwrap())?;
3643 for field in &s.fields {
3644 use clean::StructFieldItem;
3645 if let StructFieldItem(ref ty) = field.inner {
3646 let id = cx.derive_id(format!("variant.{}.field.{}",
3647 variant.name.as_ref().unwrap(),
3648 field.name.as_ref().unwrap()));
3649 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
3650 variant.name.as_ref().unwrap(),
3651 ItemType::Variant.name_space(),
3652 field.name.as_ref().unwrap(),
3653 ItemType::StructField.name_space()));
3654 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3655 <a href=\"#{id}\" class=\"anchor field\"></a>\
3656 <code id='{ns_id}'>{f}: {t}\
3660 f = field.name.as_ref().unwrap(),
3662 document(w, cx, field)?;
3665 write!(w, "</div></span>")?;
3667 render_stability_since(w, variant, it)?;
3670 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3674 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3675 let name = attr.name();
3678 Some(name.to_string())
3679 } else if let Some(v) = attr.value_str() {
3680 Some(format!("{} = {:?}", name, v.as_str()))
3681 } else if let Some(values) = attr.meta_item_list() {
3682 let display: Vec<_> = values.iter().filter_map(|attr| {
3683 attr.meta_item().and_then(|mi| render_attribute(mi))
3686 if display.len() > 0 {
3687 Some(format!("{}({})", name, display.join(", ")))
3696 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3703 "unsafe_destructor_blind_to_params",
3707 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3708 let mut attrs = String::new();
3710 for attr in &it.attrs.other_attrs {
3711 let name = attr.name();
3712 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3715 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3716 attrs.push_str(&format!("#[{}]\n", s));
3719 if attrs.len() > 0 {
3720 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3725 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3726 g: Option<&clean::Generics>,
3727 ty: doctree::StructType,
3728 fields: &[clean::Item],
3730 structhead: bool) -> fmt::Result {
3732 VisSpace(&it.visibility),
3733 if structhead {"struct "} else {""},
3734 it.name.as_ref().unwrap())?;
3735 if let Some(g) = g {
3740 if let Some(g) = g {
3741 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3743 let mut has_visible_fields = false;
3745 for field in fields {
3746 if let clean::StructFieldItem(ref ty) = field.inner {
3747 write!(w, "\n{} {}{}: {},",
3749 VisSpace(&field.visibility),
3750 field.name.as_ref().unwrap(),
3752 has_visible_fields = true;
3756 if has_visible_fields {
3757 if it.has_stripped_fields().unwrap() {
3758 write!(w, "\n{} // some fields omitted", tab)?;
3760 write!(w, "\n{}", tab)?;
3761 } else if it.has_stripped_fields().unwrap() {
3762 // If there are no visible fields we can just display
3763 // `{ /* fields omitted */ }` to save space.
3764 write!(w, " /* fields omitted */ ")?;
3770 for (i, field) in fields.iter().enumerate() {
3775 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3778 clean::StructFieldItem(ref ty) => {
3779 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3785 if let Some(g) = g {
3786 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3791 // Needed for PhantomData.
3792 if let Some(g) = g {
3793 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3801 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3802 g: Option<&clean::Generics>,
3803 fields: &[clean::Item],
3805 structhead: bool) -> fmt::Result {
3807 VisSpace(&it.visibility),
3808 if structhead {"union "} else {""},
3809 it.name.as_ref().unwrap())?;
3810 if let Some(g) = g {
3811 write!(w, "{}", g)?;
3812 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3815 write!(w, " {{\n{}", tab)?;
3816 for field in fields {
3817 if let clean::StructFieldItem(ref ty) = field.inner {
3818 write!(w, " {}{}: {},\n{}",
3819 VisSpace(&field.visibility),
3820 field.name.as_ref().unwrap(),
3826 if it.has_stripped_fields().unwrap() {
3827 write!(w, " // some fields omitted\n{}", tab)?;
3833 #[derive(Copy, Clone)]
3834 enum AssocItemLink<'a> {
3835 Anchor(Option<&'a str>),
3836 GotoSource(DefId, &'a FxHashSet<String>),
3839 impl<'a> AssocItemLink<'a> {
3840 fn anchor(&self, id: &'a String) -> Self {
3842 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3843 ref other => *other,
3848 enum AssocItemRender<'a> {
3850 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3853 #[derive(Copy, Clone, PartialEq)]
3856 ForDeref { mut_: bool },
3859 fn render_assoc_items(w: &mut fmt::Formatter,
3861 containing_item: &clean::Item,
3863 what: AssocItemRender) -> fmt::Result {
3865 let v = match c.impls.get(&it) {
3867 None => return Ok(()),
3869 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3870 i.inner_impl().trait_.is_none()
3872 if !non_trait.is_empty() {
3873 let render_mode = match what {
3874 AssocItemRender::All => {
3876 <h2 id='methods' class='small-section-header'>\
3877 Methods<a href='#methods' class='anchor'></a>\
3882 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3884 <h2 id='deref-methods' class='small-section-header'>\
3885 Methods from {}<Target = {}>\
3886 <a href='#deref-methods' class='anchor'></a>\
3889 RenderMode::ForDeref { mut_: deref_mut_ }
3892 for i in &non_trait {
3893 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3894 containing_item.stable_since(), true, None)?;
3897 if let AssocItemRender::DerefFor { .. } = what {
3900 if !traits.is_empty() {
3901 let deref_impl = traits.iter().find(|t| {
3902 t.inner_impl().trait_.def_id() == c.deref_trait_did
3904 if let Some(impl_) = deref_impl {
3905 let has_deref_mut = traits.iter().find(|t| {
3906 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3908 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3911 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
3913 .partition(|t| t.inner_impl().synthetic);
3914 let (blanket_impl, concrete) = concrete
3916 .partition(|t| t.inner_impl().blanket_impl.is_some());
3918 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3920 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3921 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3922 render_impls(self.0, fmt, &self.1, self.2)
3926 let impls = RendererStruct(cx, concrete, containing_item).to_string();
3927 if !impls.is_empty() {
3929 <h2 id='implementations' class='small-section-header'>\
3930 Trait Implementations<a href='#implementations' class='anchor'></a>\
3932 <div id='implementations-list'>{}</div>", impls)?;
3935 if !synthetic.is_empty() {
3937 <h2 id='synthetic-implementations' class='small-section-header'>\
3938 Auto Trait Implementations\
3939 <a href='#synthetic-implementations' class='anchor'></a>\
3941 <div id='synthetic-implementations-list'>\
3943 render_impls(cx, w, &synthetic, containing_item)?;
3944 write!(w, "</div>")?;
3947 if !blanket_impl.is_empty() {
3949 <h2 id='blanket-implementations' class='small-section-header'>\
3950 Blanket Implementations\
3951 <a href='#blanket-implementations' class='anchor'></a>\
3953 <div id='blanket-implementations-list'>\
3955 render_impls(cx, w, &blanket_impl, containing_item)?;
3956 write!(w, "</div>")?;
3962 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3963 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3964 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3965 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3967 clean::TypedefItem(ref t, true) => Some(&t.type_),
3970 }).next().expect("Expected associated type binding");
3971 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3972 deref_mut_: deref_mut };
3973 if let Some(did) = target.def_id() {
3974 render_assoc_items(w, cx, container_item, did, what)
3976 if let Some(prim) = target.primitive_type() {
3977 if let Some(&did) = cache().primitive_locations.get(&prim) {
3978 render_assoc_items(w, cx, container_item, did, what)?;
3985 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3986 let self_type_opt = match item.inner {
3987 clean::MethodItem(ref method) => method.decl.self_type(),
3988 clean::TyMethodItem(ref method) => method.decl.self_type(),
3992 if let Some(self_ty) = self_type_opt {
3993 let (by_mut_ref, by_box, by_value) = match self_ty {
3994 SelfTy::SelfBorrowed(_, mutability) |
3995 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3996 (mutability == Mutability::Mutable, false, false)
3998 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3999 (false, Some(did) == cache().owned_box_did, false)
4001 SelfTy::SelfValue => (false, false, true),
4002 _ => (false, false, false),
4005 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
4011 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
4012 let mut out = String::new();
4015 clean::FunctionItem(clean::Function { ref decl, .. }) |
4016 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
4017 clean::MethodItem(clean::Method { ref decl, .. }) |
4018 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
4019 out = spotlight_decl(decl)?;
4027 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
4028 let mut out = String::new();
4029 let mut trait_ = String::new();
4031 if let Some(did) = decl.output.def_id() {
4033 if let Some(impls) = c.impls.get(&did) {
4035 let impl_ = i.inner_impl();
4036 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
4039 &format!("<h3 class=\"important\">Important traits for {}</h3>\
4040 <code class=\"content\">",
4042 trait_.push_str(&impl_.for_.to_string());
4045 //use the "where" class here to make it small
4046 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
4047 let t_did = impl_.trait_.def_id().unwrap();
4048 for it in &impl_.items {
4049 if let clean::TypedefItem(ref tydef, _) = it.inner {
4050 out.push_str("<span class=\"where fmt-newline\"> ");
4051 assoc_type(&mut out, it, &[],
4053 AssocItemLink::GotoSource(t_did, &FxHashSet::default()))?;
4054 out.push_str(";</span>");
4062 if !out.is_empty() {
4063 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
4064 <span class='tooltiptext'>Important traits for {}</span></div>\
4065 <div class=\"content hidden\">",
4067 out.push_str("</code></div></div>");
4073 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
4074 render_mode: RenderMode, outer_version: Option<&str>,
4075 show_def_docs: bool, use_absolute: Option<bool>) -> fmt::Result {
4076 if render_mode == RenderMode::Normal {
4077 let id = cx.derive_id(match i.inner_impl().trait_ {
4078 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
4079 None => "impl".to_string(),
4081 if let Some(use_absolute) = use_absolute {
4082 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id)?;
4083 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute)?;
4085 for it in &i.inner_impl().items {
4086 if let clean::TypedefItem(ref tydef, _) = it.inner {
4087 write!(w, "<span class=\"where fmt-newline\"> ")?;
4088 assoc_type(w, it, &vec![], Some(&tydef.type_),
4089 AssocItemLink::Anchor(None))?;
4090 write!(w, ";</span>")?;
4094 write!(w, "</code>")?;
4096 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
4100 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
4101 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
4102 render_stability_since_raw(w, since, outer_version)?;
4103 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
4104 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4105 l, "goto source code")?;
4107 write!(w, "</h3>")?;
4108 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
4109 let mut ids = cx.id_map.borrow_mut();
4110 write!(w, "<div class='docblock'>{}</div>",
4111 Markdown(&*dox, &i.impl_item.links(), RefCell::new(&mut ids), cx.codes))?;
4115 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
4116 link: AssocItemLink, render_mode: RenderMode,
4117 is_default_item: bool, outer_version: Option<&str>,
4118 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
4119 let item_type = item.type_();
4120 let name = item.name.as_ref().unwrap();
4122 let render_method_item: bool = match render_mode {
4123 RenderMode::Normal => true,
4124 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
4127 let (is_hidden, extra_class) = if trait_.is_none() ||
4128 item.doc_value().is_some() ||
4129 item.inner.is_associated() {
4135 clean::MethodItem(clean::Method { ref decl, .. }) |
4136 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
4137 // Only render when the method is not static or we allow static methods
4138 if render_method_item {
4139 let id = cx.derive_id(format!("{}.{}", item_type, name));
4140 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4141 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4142 write!(w, "{}", spotlight_decl(decl)?)?;
4143 write!(w, "<code id='{}'>", ns_id)?;
4144 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
4145 write!(w, "</code>")?;
4146 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4147 if let Some(l) = (Item { cx, item }).src_href() {
4148 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4149 l, "goto source code")?;
4151 write!(w, "</h4>")?;
4154 clean::TypedefItem(ref tydef, _) => {
4155 let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name));
4156 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4157 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4158 write!(w, "<code id='{}'>", ns_id)?;
4159 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
4160 write!(w, "</code></h4>")?;
4162 clean::AssociatedConstItem(ref ty, ref default) => {
4163 let id = cx.derive_id(format!("{}.{}", item_type, name));
4164 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4165 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4166 write!(w, "<code id='{}'>", ns_id)?;
4167 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
4168 write!(w, "</code>")?;
4169 render_stability_since_raw(w, item.stable_since(), outer_version)?;
4170 if let Some(l) = (Item { cx, item }).src_href() {
4171 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
4172 l, "goto source code")?;
4174 write!(w, "</h4>")?;
4176 clean::AssociatedTypeItem(ref bounds, ref default) => {
4177 let id = cx.derive_id(format!("{}.{}", item_type, name));
4178 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
4179 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class)?;
4180 write!(w, "<code id='{}'>", ns_id)?;
4181 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
4182 write!(w, "</code></h4>")?;
4184 clean::StrippedItem(..) => return Ok(()),
4185 _ => panic!("can't make docs for trait item with name {:?}", item.name)
4188 if render_method_item || render_mode == RenderMode::Normal {
4189 if !is_default_item {
4190 if let Some(t) = trait_ {
4191 // The trait item may have been stripped so we might not
4192 // find any documentation or stability for it.
4193 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
4194 // We need the stability of the item from the trait
4195 // because impls can't have a stability.
4196 document_stability(w, cx, it, is_hidden)?;
4197 if item.doc_value().is_some() {
4198 document_full(w, item, cx, "", is_hidden)?;
4199 } else if show_def_docs {
4200 // In case the item isn't documented,
4201 // provide short documentation from the trait.
4202 document_short(w, cx, it, link, "", is_hidden)?;
4206 document_stability(w, cx, item, is_hidden)?;
4208 document_full(w, item, cx, "", is_hidden)?;
4212 document_stability(w, cx, item, is_hidden)?;
4214 document_short(w, cx, item, link, "", is_hidden)?;
4221 let traits = &cache().traits;
4222 let trait_ = i.trait_did().map(|did| &traits[&did]);
4224 write!(w, "<div class='impl-items'>")?;
4225 for trait_item in &i.inner_impl().items {
4226 doc_impl_item(w, cx, trait_item, link, render_mode,
4227 false, outer_version, trait_, show_def_docs)?;
4230 fn render_default_items(w: &mut fmt::Formatter,
4234 render_mode: RenderMode,
4235 outer_version: Option<&str>,
4236 show_def_docs: bool) -> fmt::Result {
4237 for trait_item in &t.items {
4238 let n = trait_item.name.clone();
4239 if i.items.iter().find(|m| m.name == n).is_some() {
4242 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
4243 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
4245 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
4246 outer_version, None, show_def_docs)?;
4251 // If we've implemented a trait, then also emit documentation for all
4252 // default items which weren't overridden in the implementation block.
4253 if let Some(t) = trait_ {
4254 render_default_items(w, cx, t, &i.inner_impl(),
4255 render_mode, outer_version, show_def_docs)?;
4257 write!(w, "</div>")?;
4262 fn item_existential(
4263 w: &mut fmt::Formatter,
4266 t: &clean::Existential,
4268 write!(w, "<pre class='rust existential'>")?;
4269 render_attributes(w, it)?;
4270 write!(w, "existential type {}{}{where_clause}: {bounds};</pre>",
4271 it.name.as_ref().unwrap(),
4273 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4274 bounds = bounds(&t.bounds))?;
4276 document(w, cx, it)?;
4278 // Render any items associated directly to this alias, as otherwise they
4279 // won't be visible anywhere in the docs. It would be nice to also show
4280 // associated items from the aliased type (see discussion in #32077), but
4281 // we need #14072 to make sense of the generics.
4282 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4285 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4286 t: &clean::Typedef) -> fmt::Result {
4287 write!(w, "<pre class='rust typedef'>")?;
4288 render_attributes(w, it)?;
4289 write!(w, "type {}{}{where_clause} = {type_};</pre>",
4290 it.name.as_ref().unwrap(),
4292 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4295 document(w, cx, it)?;
4297 // Render any items associated directly to this alias, as otherwise they
4298 // won't be visible anywhere in the docs. It would be nice to also show
4299 // associated items from the aliased type (see discussion in #32077), but
4300 // we need #14072 to make sense of the generics.
4301 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4304 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
4305 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
4306 render_attributes(w, it)?;
4309 " {}type {};\n}}</pre>",
4310 VisSpace(&it.visibility),
4311 it.name.as_ref().unwrap(),
4314 document(w, cx, it)?;
4316 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4319 impl<'a> fmt::Display for Sidebar<'a> {
4320 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4323 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
4325 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
4326 || it.is_enum() || it.is_mod() || it.is_typedef() {
4327 write!(fmt, "<p class='location'>{}{}</p>",
4329 clean::StructItem(..) => "Struct ",
4330 clean::TraitItem(..) => "Trait ",
4331 clean::PrimitiveItem(..) => "Primitive Type ",
4332 clean::UnionItem(..) => "Union ",
4333 clean::EnumItem(..) => "Enum ",
4334 clean::TypedefItem(..) => "Type Definition ",
4335 clean::ForeignTypeItem => "Foreign Type ",
4336 clean::ModuleItem(..) => if it.is_crate() {
4343 it.name.as_ref().unwrap())?;
4347 if let Some(ref version) = cache().crate_version {
4349 "<div class='block version'>\
4356 write!(fmt, "<div class=\"sidebar-elems\">")?;
4358 write!(fmt, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
4359 it.name.as_ref().expect("crates always have a name"))?;
4362 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
4363 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
4364 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
4365 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
4366 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
4367 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
4368 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
4369 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
4373 // The sidebar is designed to display sibling functions, modules and
4374 // other miscellaneous information. since there are lots of sibling
4375 // items (and that causes quadratic growth in large modules),
4376 // we refactor common parts into a shared JavaScript file per module.
4377 // still, we don't move everything into JS because we want to preserve
4378 // as much HTML as possible in order to allow non-JS-enabled browsers
4379 // to navigate the documentation (though slightly inefficiently).
4381 write!(fmt, "<p class='location'>")?;
4382 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4384 write!(fmt, "::<wbr>")?;
4386 write!(fmt, "<a href='{}index.html'>{}</a>",
4387 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4390 write!(fmt, "</p>")?;
4392 // Sidebar refers to the enclosing module, not this module.
4393 let relpath = if it.is_mod() { "../" } else { "" };
4395 "<script>window.sidebarCurrent = {{\
4400 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4401 ty = it.type_().css_class(),
4404 // There is no sidebar-items.js beyond the crate root path
4405 // FIXME maybe dynamic crate loading can be merged here
4407 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4410 // Closes sidebar-elems div.
4411 write!(fmt, "</div>")?;
4417 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
4418 if used_links.insert(url.clone()) {
4422 while used_links.insert(format!("{}-{}", url, add)) == false {
4425 format!("{}-{}", url, add)
4431 used_links: &mut FxHashSet<String>,
4433 i.items.iter().filter_map(|item| {
4435 // Maybe check with clean::Visibility::Public as well?
4436 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4437 if !for_deref || should_render_item(item, false) {
4438 Some(format!("<a href=\"#{}\">{}</a>",
4439 get_next_url(used_links, format!("method.{}", name)),
4447 }).collect::<Vec<_>>()
4450 // The point is to url encode any potential character from a type with genericity.
4451 fn small_url_encode(s: &str) -> String {
4452 s.replace("<", "%3C")
4453 .replace(">", "%3E")
4454 .replace(" ", "%20")
4455 .replace("?", "%3F")
4456 .replace("'", "%27")
4457 .replace("&", "%26")
4458 .replace(",", "%2C")
4459 .replace(":", "%3A")
4460 .replace(";", "%3B")
4461 .replace("[", "%5B")
4462 .replace("]", "%5D")
4463 .replace("\"", "%22")
4466 fn sidebar_assoc_items(it: &clean::Item) -> String {
4467 let mut out = String::new();
4469 if let Some(v) = c.impls.get(&it.def_id) {
4470 let mut used_links = FxHashSet::default();
4473 let used_links_bor = Rc::new(RefCell::new(&mut used_links));
4475 .filter(|i| i.inner_impl().trait_.is_none())
4476 .flat_map(move |i| get_methods(i.inner_impl(),
4478 &mut used_links_bor.borrow_mut()))
4479 .collect::<String>();
4480 if !ret.is_empty() {
4481 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4482 </a><div class=\"sidebar-links\">{}</div>", ret));
4486 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4487 if let Some(impl_) = v.iter()
4488 .filter(|i| i.inner_impl().trait_.is_some())
4489 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4490 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4492 clean::TypedefItem(ref t, true) => Some(&t.type_),
4496 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4497 c.primitive_locations.get(&prim).cloned()
4498 })).and_then(|did| c.impls.get(&did));
4499 if let Some(impls) = inner_impl {
4500 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4501 out.push_str(&format!("Methods from {}<Target={}>",
4502 Escape(&format!("{:#}",
4503 impl_.inner_impl().trait_.as_ref().unwrap())),
4504 Escape(&format!("{:#}", target))));
4505 out.push_str("</a>");
4506 let ret = impls.iter()
4507 .filter(|i| i.inner_impl().trait_.is_none())
4508 .flat_map(|i| get_methods(i.inner_impl(),
4511 .collect::<String>();
4512 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
4516 let format_impls = |impls: Vec<&Impl>| {
4517 let mut links = FxHashSet::default();
4521 let is_negative_impl = is_negative_impl(i.inner_impl());
4522 if let Some(ref i) = i.inner_impl().trait_ {
4523 let i_display = format!("{:#}", i);
4524 let out = Escape(&i_display);
4525 let encoded = small_url_encode(&format!("{:#}", i));
4526 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4528 if is_negative_impl { "!" } else { "" },
4530 if links.insert(generated.clone()) {
4539 .collect::<String>()
4542 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
4544 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4545 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4547 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4549 let concrete_format = format_impls(concrete);
4550 let synthetic_format = format_impls(synthetic);
4551 let blanket_format = format_impls(blanket_impl);
4553 if !concrete_format.is_empty() {
4554 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4555 Trait Implementations</a>");
4556 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4559 if !synthetic_format.is_empty() {
4560 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4561 Auto Trait Implementations</a>");
4562 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4565 if !blanket_format.is_empty() {
4566 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4567 Blanket Implementations</a>");
4568 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4576 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4577 s: &clean::Struct) -> fmt::Result {
4578 let mut sidebar = String::new();
4579 let fields = get_struct_fields_name(&s.fields);
4581 if !fields.is_empty() {
4582 if let doctree::Plain = s.struct_type {
4583 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4584 <div class=\"sidebar-links\">{}</div>", fields));
4588 sidebar.push_str(&sidebar_assoc_items(it));
4590 if !sidebar.is_empty() {
4591 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4596 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4598 clean::ItemEnum::ImplItem(ref i) => {
4599 if let Some(ref trait_) = i.trait_ {
4600 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4609 fn is_negative_impl(i: &clean::Impl) -> bool {
4610 i.polarity == Some(clean::ImplPolarity::Negative)
4613 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4614 t: &clean::Trait) -> fmt::Result {
4615 let mut sidebar = String::new();
4621 Some(ref name) if m.is_associated_type() => {
4622 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4628 .collect::<String>();
4629 let consts = t.items
4633 Some(ref name) if m.is_associated_const() => {
4634 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4640 .collect::<String>();
4641 let required = t.items
4645 Some(ref name) if m.is_ty_method() => {
4646 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4652 .collect::<String>();
4653 let provided = t.items
4657 Some(ref name) if m.is_method() => {
4658 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
4663 .collect::<String>();
4665 if !types.is_empty() {
4666 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4667 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4670 if !consts.is_empty() {
4671 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4672 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4675 if !required.is_empty() {
4676 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4677 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4680 if !provided.is_empty() {
4681 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4682 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4688 if let Some(implementors) = c.implementors.get(&it.def_id) {
4689 let res = implementors.iter()
4690 .filter(|i| i.inner_impl().for_.def_id()
4691 .map_or(false, |d| !c.paths.contains_key(&d)))
4693 match extract_for_impl_name(&i.impl_item) {
4694 Some((ref name, ref url)) => {
4695 Some(format!("<a href=\"#impl-{}\">{}</a>",
4696 small_url_encode(url),
4702 .collect::<String>();
4703 if !res.is_empty() {
4704 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4705 Implementations on Foreign Types</a><div \
4706 class=\"sidebar-links\">{}</div>",
4711 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4713 sidebar.push_str("<a class=\"sidebar-title\" \
4714 href=\"#synthetic-implementors\">Auto Implementors</a>");
4717 sidebar.push_str(&sidebar_assoc_items(it));
4719 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4722 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4723 _p: &clean::PrimitiveType) -> fmt::Result {
4724 let sidebar = sidebar_assoc_items(it);
4726 if !sidebar.is_empty() {
4727 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4732 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4733 _t: &clean::Typedef) -> fmt::Result {
4734 let sidebar = sidebar_assoc_items(it);
4736 if !sidebar.is_empty() {
4737 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4742 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4744 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4749 .filter_map(|f| match f.name {
4750 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4751 {name}</a>", name=name)),
4757 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4758 u: &clean::Union) -> fmt::Result {
4759 let mut sidebar = String::new();
4760 let fields = get_struct_fields_name(&u.fields);
4762 if !fields.is_empty() {
4763 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4764 <div class=\"sidebar-links\">{}</div>", fields));
4767 sidebar.push_str(&sidebar_assoc_items(it));
4769 if !sidebar.is_empty() {
4770 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4775 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4776 e: &clean::Enum) -> fmt::Result {
4777 let mut sidebar = String::new();
4779 let variants = e.variants.iter()
4780 .filter_map(|v| match v.name {
4781 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4782 </a>", name = name)),
4785 .collect::<String>();
4786 if !variants.is_empty() {
4787 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4788 <div class=\"sidebar-links\">{}</div>", variants));
4791 sidebar.push_str(&sidebar_assoc_items(it));
4793 if !sidebar.is_empty() {
4794 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4799 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4801 ItemType::ExternCrate |
4802 ItemType::Import => ("reexports", "Re-exports"),
4803 ItemType::Module => ("modules", "Modules"),
4804 ItemType::Struct => ("structs", "Structs"),
4805 ItemType::Union => ("unions", "Unions"),
4806 ItemType::Enum => ("enums", "Enums"),
4807 ItemType::Function => ("functions", "Functions"),
4808 ItemType::Typedef => ("types", "Type Definitions"),
4809 ItemType::Static => ("statics", "Statics"),
4810 ItemType::Constant => ("constants", "Constants"),
4811 ItemType::Trait => ("traits", "Traits"),
4812 ItemType::Impl => ("impls", "Implementations"),
4813 ItemType::TyMethod => ("tymethods", "Type Methods"),
4814 ItemType::Method => ("methods", "Methods"),
4815 ItemType::StructField => ("fields", "Struct Fields"),
4816 ItemType::Variant => ("variants", "Variants"),
4817 ItemType::Macro => ("macros", "Macros"),
4818 ItemType::Primitive => ("primitives", "Primitive Types"),
4819 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4820 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4821 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4822 ItemType::Keyword => ("keywords", "Keywords"),
4823 ItemType::Existential => ("existentials", "Existentials"),
4824 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4825 ItemType::ProcDerive => ("derives", "Derive Macros"),
4829 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4830 items: &[clean::Item]) -> fmt::Result {
4831 let mut sidebar = String::new();
4833 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4834 it.type_() == ItemType::Import) {
4835 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4837 name = "Re-exports"));
4840 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4841 // to print its headings
4842 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4843 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4844 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4845 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4846 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4847 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4848 let (short, name) = item_ty_to_strs(&myty);
4849 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4855 if !sidebar.is_empty() {
4856 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4861 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4862 let sidebar = sidebar_assoc_items(it);
4863 if !sidebar.is_empty() {
4864 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4869 impl<'a> fmt::Display for Source<'a> {
4870 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4871 let Source(s) = *self;
4872 let lines = s.lines().count();
4874 let mut tmp = lines;
4879 write!(fmt, "<pre class=\"line-numbers\">")?;
4880 for i in 1..=lines {
4881 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4883 write!(fmt, "</pre>")?;
4885 highlight::render_with_highlighting(s, None, None, None))?;
4890 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4891 t: &clean::Macro) -> fmt::Result {
4892 wrap_into_docblock(w, |w| {
4893 w.write_str(&highlight::render_with_highlighting(&t.source,
4901 fn item_proc_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, m: &clean::ProcMacro)
4904 let name = it.name.as_ref().expect("proc-macros always have names");
4906 MacroKind::Bang => {
4907 write!(w, "<pre class='rust macro'>")?;
4908 write!(w, "{}!() {{ /* proc-macro */ }}", name)?;
4909 write!(w, "</pre>")?;
4911 MacroKind::Attr => {
4912 write!(w, "<pre class='rust attr'>")?;
4913 write!(w, "#[{}]", name)?;
4914 write!(w, "</pre>")?;
4916 MacroKind::Derive => {
4917 write!(w, "<pre class='rust derive'>")?;
4918 write!(w, "#[derive({})]", name)?;
4919 if !m.helpers.is_empty() {
4920 writeln!(w, "\n{{")?;
4921 writeln!(w, " // Attributes available to this derive:")?;
4922 for attr in &m.helpers {
4923 writeln!(w, " #[{}]", attr)?;
4927 write!(w, "</pre>")?;
4934 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4936 _p: &clean::PrimitiveType) -> fmt::Result {
4937 document(w, cx, it)?;
4938 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4941 fn item_keyword(w: &mut fmt::Formatter, cx: &Context,
4943 _p: &str) -> fmt::Result {
4947 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4949 fn make_item_keywords(it: &clean::Item) -> String {
4950 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4953 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4954 let decl = match item.inner {
4955 clean::FunctionItem(ref f) => &f.decl,
4956 clean::MethodItem(ref m) => &m.decl,
4957 clean::TyMethodItem(ref m) => &m.decl,
4961 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4962 let output = match decl.output {
4963 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4967 Some(IndexItemFunctionType { inputs: inputs, output: output })
4970 fn get_index_type(clean_type: &clean::Type) -> Type {
4972 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4973 generics: get_generics(clean_type),
4978 /// Returns a list of all paths used in the type.
4979 /// This is used to help deduplicate imported impls
4980 /// for reexported types. If any of the contained
4981 /// types are re-exported, we don't use the corresponding
4982 /// entry from the js file, as inlining will have already
4983 /// picked up the impl
4984 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4985 let mut out = Vec::new();
4986 let mut visited = FxHashSet::default();
4987 let mut work = VecDeque::new();
4988 let cache = cache();
4990 work.push_back(first_ty);
4992 while let Some(ty) = work.pop_front() {
4993 if !visited.insert(ty.clone()) {
4998 clean::Type::ResolvedPath { did, .. } => {
4999 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
5000 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
5004 out.push(path.join("::"));
5010 clean::Type::Tuple(tys) => {
5011 work.extend(tys.into_iter());
5013 clean::Type::Slice(ty) => {
5014 work.push_back(*ty);
5016 clean::Type::Array(ty, _) => {
5017 work.push_back(*ty);
5019 clean::Type::Unique(ty) => {
5020 work.push_back(*ty);
5022 clean::Type::RawPointer(_, ty) => {
5023 work.push_back(*ty);
5025 clean::Type::BorrowedRef { type_, .. } => {
5026 work.push_back(*type_);
5028 clean::Type::QPath { self_type, trait_, .. } => {
5029 work.push_back(*self_type);
5030 work.push_back(*trait_);
5038 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
5040 clean::ResolvedPath { ref path, .. } => {
5041 let segments = &path.segments;
5042 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
5043 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
5044 clean_type, accept_generic
5046 Some(path_segment.name.clone())
5048 clean::Generic(ref s) if accept_generic => Some(s.clone()),
5049 clean::Primitive(ref p) => Some(format!("{:?}", p)),
5050 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
5051 // FIXME: add all from clean::Type.
5056 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
5057 clean_type.generics()
5059 let r = types.iter()
5060 .filter_map(|t| get_index_type_name(t, false))
5061 .map(|s| s.to_ascii_lowercase())
5062 .collect::<Vec<_>>();
5071 pub fn cache() -> Arc<Cache> {
5072 CACHE_KEY.with(|c| c.borrow().clone())
5077 fn test_name_key() {
5078 assert_eq!(name_key("0"), ("", 0, 1));
5079 assert_eq!(name_key("123"), ("", 123, 0));
5080 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
5081 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
5082 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
5083 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
5084 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
5085 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
5090 fn test_name_sorting() {
5091 let names = ["Apple",
5093 "Fruit", "Fruit0", "Fruit00",
5094 "Fruit1", "Fruit01",
5095 "Fruit2", "Fruit02",
5100 let mut sorted = names.to_owned();
5101 sorted.sort_by_key(|&s| name_key(s));
5102 assert_eq!(names, sorted);