1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Rustdoc's HTML Rendering module
13 //! This modules contains the bulk of the logic necessary for rendering a
14 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
15 //! rendering process is largely driven by the `format!` syntax extension to
16 //! perform all I/O into files and streams.
18 //! The rendering process is largely driven by the `Context` and `Cache`
19 //! structures. The cache is pre-populated by crawling the crate in question,
20 //! and then it is shared among the various rendering threads. The cache is meant
21 //! to be a fairly large structure not implementing `Clone` (because it's shared
22 //! among threads). The context, however, should be a lightweight structure. This
23 //! is cloned per-thread and contains information about what is currently being
26 //! In order to speed up rendering (mostly because of markdown rendering), the
27 //! rendering process has been parallelized. This parallelization is only
28 //! exposed through the `crate` method on the context, and then also from the
29 //! fact that the shared cache is stored in TLS (and must be accessed as such).
31 //! In addition to rendering the crate itself, this module is also responsible
32 //! for creating the corresponding search index and source file renderings.
33 //! These threads are not parallelized (they haven't been a bottleneck yet), and
34 //! both occur before the crate is rendered.
36 pub use self::ExternalLocation::*;
39 use std::cell::RefCell;
40 use std::cmp::Ordering;
41 use std::collections::{BTreeMap, HashSet, VecDeque};
42 use std::default::Default;
44 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
45 use std::fs::{self, File, OpenOptions};
46 use std::io::prelude::*;
47 use std::io::{self, BufWriter, BufReader};
48 use std::iter::repeat;
50 use std::path::{PathBuf, Path, Component};
54 use externalfiles::ExternalHtml;
56 use serialize::json::{ToJson, Json, as_json};
58 use syntax::codemap::FileName;
59 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
60 use rustc::middle::privacy::AccessLevels;
61 use rustc::middle::stability;
63 use rustc::util::nodemap::{FxHashMap, FxHashSet};
64 use rustc_data_structures::flock;
65 use rustc_target::spec::abi;
67 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
70 use html::escape::Escape;
71 use html::format::{ConstnessSpace};
72 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
73 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
74 use html::format::fmt_impl_for_trait_page;
75 use html::item_type::ItemType;
76 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine};
77 use html::{highlight, layout};
81 /// A pair of name and its optional document.
82 pub type NameDoc = (String, Option<String>);
84 /// Major driving force in all rustdoc rendering. This contains information
85 /// about where in the tree-like hierarchy rendering is occurring and controls
86 /// how the current page is being rendered.
88 /// It is intended that this context is a lightweight object which can be fairly
89 /// easily cloned because it is cloned per work-job (about once per item in the
93 /// Current hierarchy of components leading down to what's currently being
95 pub current: Vec<String>,
96 /// The current destination folder of where HTML artifacts should be placed.
97 /// This changes as the context descends into the module hierarchy.
99 /// A flag, which when `true`, will render pages which redirect to the
100 /// real location of an item. This is used to allow external links to
101 /// publicly reused items to redirect to the right location.
102 pub render_redirect_pages: bool,
103 pub shared: Arc<SharedContext>,
106 pub struct SharedContext {
107 /// The path to the crate root source minus the file name.
108 /// Used for simplifying paths to the highlighted source code files.
109 pub src_root: PathBuf,
110 /// This describes the layout of each page, and is not modified after
111 /// creation of the context (contains info like the favicon and added html).
112 pub layout: layout::Layout,
113 /// This flag indicates whether `[src]` links should be generated or not. If
114 /// the source files are present in the html rendering, then this will be
116 pub include_sources: bool,
117 /// The local file sources we've emitted and their respective url-paths.
118 pub local_sources: FxHashMap<PathBuf, String>,
119 /// All the passes that were run on this crate.
120 pub passes: FxHashSet<String>,
121 /// The base-URL of the issue tracker for when an item has been tagged with
123 pub issue_tracker_base_url: Option<String>,
124 /// The given user css file which allow to customize the generated
125 /// documentation theme.
126 pub css_file_extension: Option<PathBuf>,
127 /// The directories that have already been created in this doc run. Used to reduce the number
128 /// of spurious `create_dir_all` calls.
129 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
130 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
131 /// should be ordered alphabetically or in order of appearance (in the source code).
132 pub sort_modules_alphabetically: bool,
133 /// Additional themes to be added to the generated docs.
134 pub themes: Vec<PathBuf>,
135 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
137 pub resource_suffix: String,
141 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
142 let mut dirs = self.created_dirs.borrow_mut();
143 if !dirs.contains(dst) {
144 fs::create_dir_all(dst)?;
145 dirs.insert(dst.to_path_buf());
153 /// Returns whether the `collapse-docs` pass was run on this crate.
154 pub fn was_collapsed(&self) -> bool {
155 self.passes.contains("collapse-docs")
158 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
159 /// `collapsed_doc_value` of the given item.
160 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
161 if self.was_collapsed() {
162 item.collapsed_doc_value().map(|s| s.into())
164 item.doc_value().map(|s| s.into())
169 /// Indicates where an external crate can be found.
170 pub enum ExternalLocation {
171 /// Remote URL root of the external crate
173 /// This external crate can be found in the local doc/ folder
175 /// The external crate could not be found.
179 /// Metadata about implementations for a type or trait.
182 pub impl_item: clean::Item,
186 fn inner_impl(&self) -> &clean::Impl {
187 match self.impl_item.inner {
188 clean::ImplItem(ref impl_) => impl_,
189 _ => panic!("non-impl item found in impl")
193 fn trait_did(&self) -> Option<DefId> {
194 self.inner_impl().trait_.def_id()
204 impl error::Error for Error {
205 fn description(&self) -> &str {
206 self.error.description()
210 impl Display for Error {
211 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
212 write!(f, "\"{}\": {}", self.file.display(), self.error)
217 pub fn new(e: io::Error, file: &Path) -> Error {
219 file: file.to_path_buf(),
225 macro_rules! try_none {
226 ($e:expr, $file:expr) => ({
230 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
236 macro_rules! try_err {
237 ($e:expr, $file:expr) => ({
240 Err(e) => return Err(Error::new(e, $file)),
245 /// This cache is used to store information about the `clean::Crate` being
246 /// rendered in order to provide more useful documentation. This contains
247 /// information like all implementors of a trait, all traits a type implements,
248 /// documentation for all known traits, etc.
250 /// This structure purposefully does not implement `Clone` because it's intended
251 /// to be a fairly large and expensive structure to clone. Instead this adheres
252 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
253 /// rendering threads.
256 /// Mapping of typaram ids to the name of the type parameter. This is used
257 /// when pretty-printing a type (so pretty printing doesn't have to
258 /// painfully maintain a context like this)
259 pub typarams: FxHashMap<DefId, String>,
261 /// Maps a type id to all known implementations for that type. This is only
262 /// recognized for intra-crate `ResolvedPath` types, and is used to print
263 /// out extra documentation on the page of an enum/struct.
265 /// The values of the map are a list of implementations and documentation
266 /// found on that implementation.
267 pub impls: FxHashMap<DefId, Vec<Impl>>,
269 /// Maintains a mapping of local crate node ids to the fully qualified name
270 /// and "short type description" of that node. This is used when generating
271 /// URLs when a type is being linked to. External paths are not located in
272 /// this map because the `External` type itself has all the information
274 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
276 /// Similar to `paths`, but only holds external paths. This is only used for
277 /// generating explicit hyperlinks to other crates.
278 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
280 /// Maps local def ids of exported types to fully qualified paths.
281 /// Unlike 'paths', this mapping ignores any renames that occur
282 /// due to 'use' statements.
284 /// This map is used when writing out the special 'implementors'
285 /// javascript file. By using the exact path that the type
286 /// is declared with, we ensure that each path will be identical
287 /// to the path used if the corresponding type is inlined. By
288 /// doing this, we can detect duplicate impls on a trait page, and only display
289 /// the impl for the inlined type.
290 pub exact_paths: FxHashMap<DefId, Vec<String>>,
292 /// This map contains information about all known traits of this crate.
293 /// Implementations of a crate should inherit the documentation of the
294 /// parent trait if no extra documentation is specified, and default methods
295 /// should show up in documentation about trait implementations.
296 pub traits: FxHashMap<DefId, clean::Trait>,
298 /// When rendering traits, it's often useful to be able to list all
299 /// implementors of the trait, and this mapping is exactly, that: a mapping
300 /// of trait ids to the list of known implementors of the trait
301 pub implementors: FxHashMap<DefId, Vec<Impl>>,
303 /// Cache of where external crate documentation can be found.
304 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
306 /// Cache of where documentation for primitives can be found.
307 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
309 // Note that external items for which `doc(hidden)` applies to are shown as
310 // non-reachable while local items aren't. This is because we're reusing
311 // the access levels from crateanalysis.
312 pub access_levels: Arc<AccessLevels<DefId>>,
314 /// The version of the crate being documented, if given fron the `--crate-version` flag.
315 pub crate_version: Option<String>,
317 // Private fields only used when initially crawling a crate to build a cache
320 parent_stack: Vec<DefId>,
321 parent_is_trait_impl: bool,
322 search_index: Vec<IndexItem>,
324 deref_trait_did: Option<DefId>,
325 deref_mut_trait_did: Option<DefId>,
326 owned_box_did: Option<DefId>,
327 masked_crates: FxHashSet<CrateNum>,
329 // In rare case where a structure is defined in one module but implemented
330 // in another, if the implementing module is parsed before defining module,
331 // then the fully qualified name of the structure isn't presented in `paths`
332 // yet when its implementation methods are being indexed. Caches such methods
333 // and their parent id here and indexes them at the end of crate parsing.
334 orphan_impl_items: Vec<(DefId, clean::Item)>,
336 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
337 /// we need the alias element to have an array of items.
338 aliases: FxHashMap<String, Vec<IndexItem>>,
341 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
342 /// Later on moved into `CACHE_KEY`.
344 pub struct RenderInfo {
345 pub inlined: FxHashSet<DefId>,
346 pub external_paths: ::core::ExternalPaths,
347 pub external_typarams: FxHashMap<DefId, String>,
348 pub exact_paths: FxHashMap<DefId, Vec<String>>,
349 pub deref_trait_did: Option<DefId>,
350 pub deref_mut_trait_did: Option<DefId>,
351 pub owned_box_did: Option<DefId>,
354 /// Helper struct to render all source code to HTML pages
355 struct SourceCollector<'a> {
356 scx: &'a mut SharedContext,
358 /// Root destination to place all HTML output into
362 /// Wrapper struct to render the source code of a file. This will do things like
363 /// adding line numbers to the left-hand side.
364 struct Source<'a>(&'a str);
366 // Helper structs for rendering items/sidebars and carrying along contextual
369 #[derive(Copy, Clone)]
372 item: &'a clean::Item,
375 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
377 /// Struct representing one entry in the JS search index. These are all emitted
378 /// by hand to a large JS file at the end of cache-creation.
385 parent: Option<DefId>,
386 parent_idx: Option<usize>,
387 search_type: Option<IndexItemFunctionType>,
390 impl ToJson for IndexItem {
391 fn to_json(&self) -> Json {
392 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
394 let mut data = Vec::with_capacity(6);
395 data.push((self.ty as usize).to_json());
396 data.push(self.name.to_json());
397 data.push(self.path.to_json());
398 data.push(self.desc.to_json());
399 data.push(self.parent_idx.to_json());
400 data.push(self.search_type.to_json());
406 /// A type used for the search index.
409 name: Option<String>,
410 generics: Option<Vec<String>>,
413 impl ToJson for Type {
414 fn to_json(&self) -> Json {
417 let mut data = BTreeMap::new();
418 data.insert("name".to_owned(), name.to_json());
419 if let Some(ref generics) = self.generics {
420 data.insert("generics".to_owned(), generics.to_json());
429 /// Full type of functions/methods in the search index.
431 struct IndexItemFunctionType {
433 output: Option<Type>,
436 impl ToJson for IndexItemFunctionType {
437 fn to_json(&self) -> Json {
438 // If we couldn't figure out a type, just write `null`.
439 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
442 let mut data = BTreeMap::new();
443 data.insert("inputs".to_owned(), self.inputs.to_json());
444 data.insert("output".to_owned(), self.output.to_json());
450 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
451 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
452 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
454 fn init_ids() -> FxHashMap<String, usize> {
466 "synthetic-implementors",
468 "synthetic-implementors-list",
472 ].into_iter().map(|id| (String::from(*id), 1)).collect()
475 /// This method resets the local table of used ID attributes. This is typically
476 /// used at the beginning of rendering an entire HTML page to reset from the
477 /// previous state (if any).
478 pub fn reset_ids(embedded: bool) {
479 USED_ID_MAP.with(|s| {
480 *s.borrow_mut() = if embedded {
488 pub fn derive_id(candidate: String) -> String {
489 USED_ID_MAP.with(|map| {
490 let id = match map.borrow_mut().get_mut(&candidate) {
493 let id = format!("{}-{}", candidate, *a);
499 map.borrow_mut().insert(id.clone(), 1);
504 /// Generates the documentation for `crate` into the directory `dst`
505 pub fn run(mut krate: clean::Crate,
506 external_html: &ExternalHtml,
507 playground_url: Option<String>,
509 resource_suffix: String,
510 passes: FxHashSet<String>,
511 css_file_extension: Option<PathBuf>,
512 renderinfo: RenderInfo,
513 sort_modules_alphabetically: bool,
514 themes: Vec<PathBuf>,
515 enable_minification: bool) -> Result<(), Error> {
516 let src_root = match krate.src {
517 FileName::Real(ref p) => match p.parent() {
518 Some(p) => p.to_path_buf(),
519 None => PathBuf::new(),
523 let mut scx = SharedContext {
526 include_sources: true,
527 local_sources: FxHashMap(),
528 issue_tracker_base_url: None,
529 layout: layout::Layout {
530 logo: "".to_string(),
531 favicon: "".to_string(),
532 external_html: external_html.clone(),
533 krate: krate.name.clone(),
535 css_file_extension: css_file_extension.clone(),
536 created_dirs: RefCell::new(FxHashSet()),
537 sort_modules_alphabetically,
542 // If user passed in `--playground-url` arg, we fill in crate name here
543 if let Some(url) = playground_url {
544 markdown::PLAYGROUND.with(|slot| {
545 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
549 // Crawl the crate attributes looking for attributes which control how we're
550 // going to emit HTML
551 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
552 for attr in attrs.lists("doc") {
553 let name = attr.name().map(|s| s.as_str());
554 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
555 (Some("html_favicon_url"), Some(s)) => {
556 scx.layout.favicon = s.to_string();
558 (Some("html_logo_url"), Some(s)) => {
559 scx.layout.logo = s.to_string();
561 (Some("html_playground_url"), Some(s)) => {
562 markdown::PLAYGROUND.with(|slot| {
563 let name = krate.name.clone();
564 *slot.borrow_mut() = Some((Some(name), s.to_string()));
567 (Some("issue_tracker_base_url"), Some(s)) => {
568 scx.issue_tracker_base_url = Some(s.to_string());
570 (Some("html_no_source"), None) if attr.is_word() => {
571 scx.include_sources = false;
577 try_err!(fs::create_dir_all(&dst), &dst);
578 krate = render_sources(&dst, &mut scx, krate)?;
582 render_redirect_pages: false,
583 shared: Arc::new(scx),
586 // 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 {
606 implementors: FxHashMap(),
608 parent_stack: Vec::new(),
609 search_index: Vec::new(),
610 parent_is_trait_impl: false,
611 extern_locations: FxHashMap(),
612 primitive_locations: FxHashMap(),
614 access_levels: krate.access_levels.clone(),
615 crate_version: krate.version.take(),
616 orphan_impl_items: Vec::new(),
617 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
621 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
622 typarams: external_typarams,
623 aliases: FxHashMap(),
626 // Cache where all our extern crates are located
627 for &(n, ref e) in &krate.externs {
628 let src_root = match e.src {
629 FileName::Real(ref p) => match p.parent() {
630 Some(p) => p.to_path_buf(),
631 None => PathBuf::new(),
635 cache.extern_locations.insert(n, (e.name.clone(), src_root,
636 extern_location(e, &cx.dst)));
638 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
639 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
642 // Cache where all known primitives have their documentation located.
644 // Favor linking to as local extern as possible, so iterate all crates in
645 // reverse topological order.
646 for &(_, ref e) in krate.externs.iter().rev() {
647 for &(def_id, prim, _) in &e.primitives {
648 cache.primitive_locations.insert(prim, def_id);
651 for &(def_id, prim, _) in &krate.primitives {
652 cache.primitive_locations.insert(prim, def_id);
655 cache.stack.push(krate.name.clone());
656 krate = cache.fold_crate(krate);
658 // Build our search index
659 let index = build_index(&krate, &mut cache);
661 // Freeze the cache now that the index has been built. Put an Arc into TLS
662 // for future parallelization opportunities
663 let cache = Arc::new(cache);
664 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
665 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
667 write_shared(&cx, &krate, &*cache, index, enable_minification)?;
669 // And finally render the whole crate's documentation
673 /// Build the search index from the collected metadata
674 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
675 let mut nodeid_to_pathid = FxHashMap();
676 let mut crate_items = Vec::with_capacity(cache.search_index.len());
677 let mut crate_paths = Vec::<Json>::new();
679 let Cache { ref mut search_index,
680 ref orphan_impl_items,
681 ref mut paths, .. } = *cache;
683 // Attach all orphan items to the type's definition if the type
684 // has since been learned.
685 for &(did, ref item) in orphan_impl_items {
686 if let Some(&(ref fqp, _)) = paths.get(&did) {
687 search_index.push(IndexItem {
689 name: item.name.clone().unwrap(),
690 path: fqp[..fqp.len() - 1].join("::"),
691 desc: plain_summary_line(item.doc_value()),
694 search_type: get_index_search_type(&item),
699 // Reduce `NodeId` in paths into smaller sequential numbers,
700 // and prune the paths that do not appear in the index.
701 let mut lastpath = String::new();
702 let mut lastpathid = 0usize;
704 for item in search_index {
705 item.parent_idx = item.parent.map(|nodeid| {
706 if nodeid_to_pathid.contains_key(&nodeid) {
707 *nodeid_to_pathid.get(&nodeid).unwrap()
709 let pathid = lastpathid;
710 nodeid_to_pathid.insert(nodeid, pathid);
713 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
714 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
719 // Omit the parent path if it is same to that of the prior item.
720 if lastpath == item.path {
723 lastpath = item.path.clone();
725 crate_items.push(item.to_json());
728 let crate_doc = krate.module.as_ref().map(|module| {
729 plain_summary_line(module.doc_value())
730 }).unwrap_or(String::new());
732 let mut crate_data = BTreeMap::new();
733 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
734 crate_data.insert("items".to_owned(), Json::Array(crate_items));
735 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
737 // Collect the index into a string
738 format!("searchIndex[{}] = {};",
739 as_json(&krate.name),
740 Json::Object(crate_data))
743 fn write_shared(cx: &Context,
744 krate: &clean::Crate,
746 search_index: String,
747 enable_minification: bool) -> Result<(), Error> {
748 // Write out the shared files. Note that these are shared among all rustdoc
749 // docs placed in the output directory, so this needs to be a synchronized
750 // operation with respect to all other rustdocs running around.
751 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
753 // Add all the static files. These may already exist, but we just
754 // overwrite them anyway to make sure that they're fresh and up-to-date.
756 write(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
757 include_bytes!("static/rustdoc.css"))?;
758 write(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
759 include_bytes!("static/settings.css"))?;
761 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
762 // then we'll run over the "official" styles.
763 let mut themes: HashSet<String> = HashSet::new();
765 for entry in &cx.shared.themes {
766 let mut content = Vec::with_capacity(100000);
768 let mut f = try_err!(File::open(&entry), &entry);
769 try_err!(f.read_to_end(&mut content), &entry);
770 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
771 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
772 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
773 content.as_slice())?;
774 themes.insert(theme.to_owned());
777 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
778 include_bytes!("static/brush.svg"))?;
779 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
780 include_bytes!("static/wheel.svg"))?;
781 write(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
782 include_bytes!("static/themes/light.css"))?;
783 themes.insert("light".to_owned());
784 write(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
785 include_bytes!("static/themes/dark.css"))?;
786 themes.insert("dark".to_owned());
788 let mut themes: Vec<&String> = themes.iter().collect();
790 // To avoid theme switch latencies as much as possible, we put everything theme related
791 // at the beginning of the html files into another js file.
792 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
794 r#"var themes = document.getElementById("theme-choices");
795 var themePicker = document.getElementById("theme-picker");
796 themePicker.onclick = function() {{
797 if (themes.style.display === "block") {{
798 themes.style.display = "none";
799 themePicker.style.borderBottomRightRadius = "3px";
800 themePicker.style.borderBottomLeftRadius = "3px";
802 themes.style.display = "block";
803 themePicker.style.borderBottomRightRadius = "0";
804 themePicker.style.borderBottomLeftRadius = "0";
807 [{}].forEach(function(item) {{
808 var but = document.createElement('button');
809 but.innerHTML = item;
810 but.onclick = function(el) {{
811 switchTheme(currentTheme, mainTheme, item);
813 themes.appendChild(but);
816 .map(|s| format!("\"{}\"", s))
817 .collect::<Vec<String>>()
818 .join(",")).as_bytes(),
821 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
822 include_str!("static/main.js"),
823 enable_minification)?;
824 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
825 include_str!("static/settings.js"),
826 enable_minification)?;
829 let mut data = format!("var resourcesSuffix = \"{}\";\n",
830 cx.shared.resource_suffix);
831 data.push_str(include_str!("static/storage.js"));
832 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
834 enable_minification)?;
837 if let Some(ref css) = cx.shared.css_file_extension {
838 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
839 try_err!(fs::copy(css, out), css);
841 write(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
842 include_bytes!("static/normalize.css"))?;
843 write(cx.dst.join("FiraSans-Regular.woff"),
844 include_bytes!("static/FiraSans-Regular.woff"))?;
845 write(cx.dst.join("FiraSans-Medium.woff"),
846 include_bytes!("static/FiraSans-Medium.woff"))?;
847 write(cx.dst.join("FiraSans-LICENSE.txt"),
848 include_bytes!("static/FiraSans-LICENSE.txt"))?;
849 write(cx.dst.join("Heuristica-Italic.woff"),
850 include_bytes!("static/Heuristica-Italic.woff"))?;
851 write(cx.dst.join("Heuristica-LICENSE.txt"),
852 include_bytes!("static/Heuristica-LICENSE.txt"))?;
853 write(cx.dst.join("SourceSerifPro-Regular.woff"),
854 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
855 write(cx.dst.join("SourceSerifPro-Bold.woff"),
856 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
857 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
858 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
859 write(cx.dst.join("SourceCodePro-Regular.woff"),
860 include_bytes!("static/SourceCodePro-Regular.woff"))?;
861 write(cx.dst.join("SourceCodePro-Semibold.woff"),
862 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
863 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
864 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
865 write(cx.dst.join("LICENSE-MIT.txt"),
866 include_bytes!("static/LICENSE-MIT.txt"))?;
867 write(cx.dst.join("LICENSE-APACHE.txt"),
868 include_bytes!("static/LICENSE-APACHE.txt"))?;
869 write(cx.dst.join("COPYRIGHT.txt"),
870 include_bytes!("static/COPYRIGHT.txt"))?;
872 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<Vec<String>> {
873 let mut ret = Vec::new();
875 for line in BufReader::new(File::open(path)?).lines() {
877 if !line.starts_with(key) {
880 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
883 ret.push(line.to_string());
889 fn show_item(item: &IndexItem, krate: &str) -> String {
890 format!("{{'crate':'{}','ty':{},'name':'{}','path':'{}'{}}}",
891 krate, item.ty as usize, item.name, item.path,
892 if let Some(p) = item.parent_idx {
893 format!(",'parent':{}", p)
899 let dst = cx.dst.join("aliases.js");
901 let mut all_aliases = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
902 let mut w = try_err!(File::create(&dst), &dst);
903 let mut output = String::with_capacity(100);
904 for (alias, items) in &cache.aliases {
905 if items.is_empty() {
908 output.push_str(&format!("\"{}\":[{}],",
911 .map(|v| show_item(v, &krate.name))
915 all_aliases.push(format!("ALIASES['{}'] = {{{}}};", krate.name, output));
917 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
918 for aliases in &all_aliases {
919 try_err!(writeln!(&mut w, "{}", aliases), &dst);
923 // Update the search index
924 let dst = cx.dst.join("search-index.js");
925 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
926 all_indexes.push(search_index);
927 // Sort the indexes by crate so the file will be generated identically even
928 // with rustdoc running in parallel.
930 let mut w = try_err!(File::create(&dst), &dst);
931 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
932 for index in &all_indexes {
933 try_err!(writeln!(&mut w, "{}", *index), &dst);
935 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
937 // Update the list of all implementors for traits
938 let dst = cx.dst.join("implementors");
939 for (&did, imps) in &cache.implementors {
940 // Private modules can leak through to this phase of rustdoc, which
941 // could contain implementations for otherwise private types. In some
942 // rare cases we could find an implementation for an item which wasn't
943 // indexed, so we just skip this step in that case.
945 // FIXME: this is a vague explanation for why this can't be a `get`, in
946 // theory it should be...
947 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
949 None => match cache.external_paths.get(&did) {
955 let mut have_impls = false;
956 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
958 // If the trait and implementation are in the same crate, then
959 // there's no need to emit information about it (there's inlining
960 // going on). If they're in different crates then the crate defining
961 // the trait will be interested in our implementation.
962 if imp.impl_item.def_id.krate == did.krate { continue }
963 // If the implementation is from another crate then that crate
965 if !imp.impl_item.def_id.is_local() { continue }
967 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
968 as_json(&imp.inner_impl().to_string()),
969 imp.inner_impl().synthetic,
970 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
972 implementors.push_str("];");
974 // Only create a js file if we have impls to add to it. If the trait is
975 // documented locally though we always create the file to avoid dead
977 if !have_impls && !cache.paths.contains_key(&did) {
981 let mut mydst = dst.clone();
982 for part in &remote_path[..remote_path.len() - 1] {
985 try_err!(fs::create_dir_all(&mydst), &mydst);
986 mydst.push(&format!("{}.{}.js",
987 remote_item_type.css_class(),
988 remote_path[remote_path.len() - 1]));
990 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
991 all_implementors.push(implementors);
992 // Sort the implementors by crate so the file will be generated
993 // identically even with rustdoc running in parallel.
994 all_implementors.sort();
996 let mut f = try_err!(File::create(&mydst), &mydst);
997 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
998 for implementor in &all_implementors {
999 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1001 try_err!(writeln!(&mut f, "{}", r"
1002 if (window.register_implementors) {
1003 window.register_implementors(implementors);
1005 window.pending_implementors = implementors;
1008 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1013 fn render_sources(dst: &Path, scx: &mut SharedContext,
1014 krate: clean::Crate) -> Result<clean::Crate, Error> {
1015 info!("emitting source files");
1016 let dst = dst.join("src").join(&krate.name);
1017 try_err!(fs::create_dir_all(&dst), &dst);
1018 let mut folder = SourceCollector {
1022 Ok(folder.fold_crate(krate))
1025 /// Writes the entire contents of a string to a destination, not attempting to
1026 /// catch any errors.
1027 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1028 Ok(try_err!(fs::write(&dst, contents), &dst))
1031 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1032 if enable_minification {
1033 write(dst, minifier::js::minify(contents).as_bytes())
1035 write(dst, contents.as_bytes())
1039 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1040 /// things like ".." to components which preserve the "top down" hierarchy of a
1041 /// static HTML tree. Each component in the cleaned path will be passed as an
1042 /// argument to `f`. The very last component of the path (ie the file name) will
1043 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1044 // FIXME (#9639): The closure should deal with &[u8] instead of &str
1045 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
1046 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1049 // make it relative, if possible
1050 let p = p.strip_prefix(src_root).unwrap_or(p);
1052 let mut iter = p.components().peekable();
1054 while let Some(c) = iter.next() {
1055 if !keep_filename && iter.peek().is_none() {
1060 Component::ParentDir => f("up"),
1061 Component::Normal(c) => f(c.to_str().unwrap()),
1067 /// Attempts to find where an external crate is located, given that we're
1068 /// rendering in to the specified source destination.
1069 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
1070 // See if there's documentation generated into the local directory
1071 let local_location = dst.join(&e.name);
1072 if local_location.is_dir() {
1076 // Failing that, see if there's an attribute specifying where to find this
1078 e.attrs.lists("doc")
1079 .filter(|a| a.check_name("html_root_url"))
1080 .filter_map(|a| a.value_str())
1082 let mut url = url.to_string();
1083 if !url.ends_with("/") {
1087 }).next().unwrap_or(Unknown) // Well, at least we tried.
1090 impl<'a> DocFolder for SourceCollector<'a> {
1091 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1092 // If we're including source files, and we haven't seen this file yet,
1093 // then we need to render it out to the filesystem.
1094 if self.scx.include_sources
1095 // skip all invalid or macro spans
1096 && item.source.filename.is_real()
1097 // skip non-local items
1098 && item.def_id.is_local() {
1100 // If it turns out that we couldn't read this file, then we probably
1101 // can't read any of the files (generating html output from json or
1102 // something like that), so just don't include sources for the
1103 // entire crate. The other option is maintaining this mapping on a
1104 // per-file basis, but that's probably not worth it...
1106 .include_sources = match self.emit_source(&item.source.filename) {
1109 println!("warning: source code was requested to be rendered, \
1110 but processing `{}` had an error: {}",
1111 item.source.filename, e);
1112 println!(" skipping rendering of source code");
1117 self.fold_item_recur(item)
1121 impl<'a> SourceCollector<'a> {
1122 /// Renders the given filename into its corresponding HTML source file.
1123 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1124 let p = match *filename {
1125 FileName::Real(ref file) => file,
1128 if self.scx.local_sources.contains_key(&**p) {
1129 // We've already emitted this source
1133 let contents = fs::read_to_string(&p)?;
1135 // Remove the utf-8 BOM if any
1136 let contents = if contents.starts_with("\u{feff}") {
1142 // Create the intermediate directories
1143 let mut cur = self.dst.clone();
1144 let mut root_path = String::from("../../");
1145 let mut href = String::new();
1146 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1147 cur.push(component);
1148 fs::create_dir_all(&cur).unwrap();
1149 root_path.push_str("../");
1150 href.push_str(component);
1153 let mut fname = p.file_name()
1154 .expect("source has no filename")
1156 fname.push(".html");
1158 href.push_str(&fname.to_string_lossy());
1160 let mut w = BufWriter::new(File::create(&cur)?);
1161 let title = format!("{} -- source", cur.file_name().unwrap()
1162 .to_string_lossy());
1163 let desc = format!("Source to the Rust file `{}`.", filename);
1164 let page = layout::Page {
1166 css_class: "source",
1167 root_path: &root_path,
1169 keywords: BASIC_KEYWORDS,
1170 resource_suffix: &self.scx.resource_suffix,
1172 layout::render(&mut w, &self.scx.layout,
1173 &page, &(""), &Source(contents),
1174 self.scx.css_file_extension.is_some(),
1177 self.scx.local_sources.insert(p.clone(), href);
1182 impl DocFolder for Cache {
1183 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1184 // If this is a stripped module,
1185 // we don't want it or its children in the search index.
1186 let orig_stripped_mod = match item.inner {
1187 clean::StrippedItem(box clean::ModuleItem(..)) => {
1188 mem::replace(&mut self.stripped_mod, true)
1190 _ => self.stripped_mod,
1193 // If the impl is from a masked crate or references something from a
1194 // masked crate then remove it completely.
1195 if let clean::ImplItem(ref i) = item.inner {
1196 if self.masked_crates.contains(&item.def_id.krate) ||
1197 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1198 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1203 // Register any generics to their corresponding string. This is used
1204 // when pretty-printing types.
1205 if let Some(generics) = item.inner.generics() {
1206 self.generics(generics);
1209 // Propagate a trait method's documentation to all implementors of the
1211 if let clean::TraitItem(ref t) = item.inner {
1212 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1215 // Collect all the implementors of traits.
1216 if let clean::ImplItem(ref i) = item.inner {
1217 if let Some(did) = i.trait_.def_id() {
1218 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1219 impl_item: item.clone(),
1224 // Index this method for searching later on.
1225 if let Some(ref s) = item.name {
1226 let (parent, is_inherent_impl_item) = match item.inner {
1227 clean::StrippedItem(..) => ((None, None), false),
1228 clean::AssociatedConstItem(..) |
1229 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1230 // skip associated items in trait impls
1231 ((None, None), false)
1233 clean::AssociatedTypeItem(..) |
1234 clean::TyMethodItem(..) |
1235 clean::StructFieldItem(..) |
1236 clean::VariantItem(..) => {
1237 ((Some(*self.parent_stack.last().unwrap()),
1238 Some(&self.stack[..self.stack.len() - 1])),
1241 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1242 if self.parent_stack.is_empty() {
1243 ((None, None), false)
1245 let last = self.parent_stack.last().unwrap();
1247 let path = match self.paths.get(&did) {
1248 // The current stack not necessarily has correlation
1249 // for where the type was defined. On the other
1250 // hand, `paths` always has the right
1251 // information if present.
1252 Some(&(ref fqp, ItemType::Trait)) |
1253 Some(&(ref fqp, ItemType::Struct)) |
1254 Some(&(ref fqp, ItemType::Union)) |
1255 Some(&(ref fqp, ItemType::Enum)) =>
1256 Some(&fqp[..fqp.len() - 1]),
1257 Some(..) => Some(&*self.stack),
1260 ((Some(*last), path), true)
1263 _ => ((None, Some(&*self.stack)), false)
1267 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1268 debug_assert!(!item.is_stripped());
1270 // A crate has a module at its root, containing all items,
1271 // which should not be indexed. The crate-item itself is
1272 // inserted later on when serializing the search-index.
1273 if item.def_id.index != CRATE_DEF_INDEX {
1274 self.search_index.push(IndexItem {
1276 name: s.to_string(),
1277 path: path.join("::").to_string(),
1278 desc: plain_summary_line(item.doc_value()),
1281 search_type: get_index_search_type(&item),
1285 (Some(parent), None) if is_inherent_impl_item => {
1286 // We have a parent, but we don't know where they're
1287 // defined yet. Wait for later to index this item.
1288 self.orphan_impl_items.push((parent, item.clone()));
1294 // Keep track of the fully qualified path for this item.
1295 let pushed = match item.name {
1296 Some(ref n) if !n.is_empty() => {
1297 self.stack.push(n.to_string());
1304 clean::StructItem(..) | clean::EnumItem(..) |
1305 clean::TypedefItem(..) | clean::TraitItem(..) |
1306 clean::FunctionItem(..) | clean::ModuleItem(..) |
1307 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1308 clean::ConstantItem(..) | clean::StaticItem(..) |
1309 clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1310 if !self.stripped_mod => {
1311 // Re-exported items mean that the same id can show up twice
1312 // in the rustdoc ast that we're looking at. We know,
1313 // however, that a re-exported item doesn't show up in the
1314 // `public_items` map, so we can skip inserting into the
1315 // paths map if there was already an entry present and we're
1316 // not a public item.
1317 if !self.paths.contains_key(&item.def_id) ||
1318 self.access_levels.is_public(item.def_id)
1320 self.paths.insert(item.def_id,
1321 (self.stack.clone(), item.type_()));
1323 self.add_aliases(&item);
1325 // Link variants to their parent enum because pages aren't emitted
1326 // for each variant.
1327 clean::VariantItem(..) if !self.stripped_mod => {
1328 let mut stack = self.stack.clone();
1330 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1333 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1334 self.add_aliases(&item);
1335 self.paths.insert(item.def_id, (self.stack.clone(),
1342 // Maintain the parent stack
1343 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1344 let parent_pushed = match item.inner {
1345 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1346 clean::StructItem(..) | clean::UnionItem(..) => {
1347 self.parent_stack.push(item.def_id);
1348 self.parent_is_trait_impl = false;
1351 clean::ImplItem(ref i) => {
1352 self.parent_is_trait_impl = i.trait_.is_some();
1354 clean::ResolvedPath{ did, .. } => {
1355 self.parent_stack.push(did);
1359 let prim_did = t.primitive_type().and_then(|t| {
1360 self.primitive_locations.get(&t).cloned()
1364 self.parent_stack.push(did);
1375 // Once we've recursively found all the generics, hoard off all the
1376 // implementations elsewhere.
1377 let ret = self.fold_item_recur(item).and_then(|item| {
1378 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1379 // Figure out the id of this impl. This may map to a
1380 // primitive rather than always to a struct/enum.
1381 // Note: matching twice to restrict the lifetime of the `i` borrow.
1382 let mut dids = FxHashSet();
1383 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1385 clean::ResolvedPath { did, .. } |
1386 clean::BorrowedRef {
1387 type_: box clean::ResolvedPath { did, .. }, ..
1392 let did = t.primitive_type().and_then(|t| {
1393 self.primitive_locations.get(&t).cloned()
1396 if let Some(did) = did {
1402 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1403 for bound in generics {
1404 if let Some(did) = bound.def_id() {
1413 self.impls.entry(did).or_insert(vec![]).push(Impl {
1414 impl_item: item.clone(),
1423 if pushed { self.stack.pop().unwrap(); }
1424 if parent_pushed { self.parent_stack.pop().unwrap(); }
1425 self.stripped_mod = orig_stripped_mod;
1426 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1432 fn generics(&mut self, generics: &clean::Generics) {
1433 for param in &generics.params {
1434 if let clean::GenericParam::Type(ref typ) = *param {
1435 self.typarams.insert(typ.did, typ.name.clone());
1440 fn add_aliases(&mut self, item: &clean::Item) {
1441 if item.def_id.index == CRATE_DEF_INDEX {
1444 if let Some(ref item_name) = item.name {
1445 let path = self.paths.get(&item.def_id)
1446 .map(|p| p.0[..p.0.len() - 1].join("::"))
1447 .unwrap_or("std".to_owned());
1448 for alias in item.attrs.lists("doc")
1449 .filter(|a| a.check_name("alias"))
1450 .filter_map(|a| a.value_str()
1451 .map(|s| s.to_string().replace("\"", "")))
1452 .filter(|v| !v.is_empty())
1453 .collect::<FxHashSet<_>>()
1455 self.aliases.entry(alias)
1456 .or_insert(Vec::with_capacity(1))
1459 name: item_name.to_string(),
1461 desc: String::new(),
1464 search_type: get_index_search_type(&item),
1471 #[derive(Debug, Eq, PartialEq, Hash)]
1478 fn new(mut url: String, name: String) -> ItemEntry {
1479 while url.starts_with('/') {
1489 impl fmt::Display for ItemEntry {
1490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1491 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1495 impl PartialOrd for ItemEntry {
1496 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1497 Some(self.cmp(other))
1501 impl Ord for ItemEntry {
1502 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1503 self.name.cmp(&other.name)
1509 structs: HashSet<ItemEntry>,
1510 enums: HashSet<ItemEntry>,
1511 unions: HashSet<ItemEntry>,
1512 primitives: HashSet<ItemEntry>,
1513 traits: HashSet<ItemEntry>,
1514 macros: HashSet<ItemEntry>,
1515 functions: HashSet<ItemEntry>,
1516 typedefs: HashSet<ItemEntry>,
1517 statics: HashSet<ItemEntry>,
1518 constants: HashSet<ItemEntry>,
1522 fn new() -> AllTypes {
1524 structs: HashSet::with_capacity(100),
1525 enums: HashSet::with_capacity(100),
1526 unions: HashSet::with_capacity(100),
1527 primitives: HashSet::with_capacity(26),
1528 traits: HashSet::with_capacity(100),
1529 macros: HashSet::with_capacity(100),
1530 functions: HashSet::with_capacity(100),
1531 typedefs: HashSet::with_capacity(100),
1532 statics: HashSet::with_capacity(100),
1533 constants: HashSet::with_capacity(100),
1537 fn append(&mut self, item_name: String, item_type: &ItemType) {
1538 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1539 if let Some(name) = url.pop() {
1540 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1542 let name = url.join("::");
1544 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1545 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1546 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1547 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1548 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1549 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1550 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1551 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1552 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1553 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1560 fn print_entries(f: &mut fmt::Formatter, e: &HashSet<ItemEntry>, title: &str,
1561 class: &str) -> fmt::Result {
1563 let mut e: Vec<&ItemEntry> = e.iter().collect();
1565 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1569 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1574 impl fmt::Display for AllTypes {
1575 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1578 <span class='in-band'>List of all items</span>\
1579 <span class='out-of-band'>\
1580 <span id='render-detail'>\
1581 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1582 [<span class='inner'>−</span>]\
1587 print_entries(f, &self.structs, "Structs", "structs")?;
1588 print_entries(f, &self.enums, "Enums", "enums")?;
1589 print_entries(f, &self.unions, "Unions", "unions")?;
1590 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1591 print_entries(f, &self.traits, "Traits", "traits")?;
1592 print_entries(f, &self.macros, "Macros", "macros")?;
1593 print_entries(f, &self.functions, "Functions", "functions")?;
1594 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1595 print_entries(f, &self.statics, "Statics", "statics")?;
1596 print_entries(f, &self.constants, "Constants", "constants")
1601 struct Settings<'a> {
1602 // (id, explanation, default value)
1603 settings: Vec<(&'static str, &'static str, bool)>,
1608 impl<'a> Settings<'a> {
1609 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1612 ("item-declarations", "Auto-hide item declarations.", true),
1613 ("item-attributes", "Auto-hide item attributes.", true),
1614 ("go-to-only-result", "Directly go to item in search if there is only one result",
1623 impl<'a> fmt::Display for Settings<'a> {
1624 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1627 <span class='in-band'>Rustdoc settings</span>\
1629 <div class='settings'>{}</div>\
1630 <script src='{}settings{}.js'></script>",
1631 self.settings.iter()
1632 .map(|(id, text, enabled)| {
1633 format!("<div class='setting-line'>\
1634 <label class='toggle'>\
1635 <input type='checkbox' id='{}' {}>\
1636 <span class='slider'></span>\
1639 </div>", id, if *enabled { " checked" } else { "" }, text)
1641 .collect::<String>(),
1648 /// String representation of how to get back to the root path of the 'doc/'
1649 /// folder in terms of a relative URL.
1650 fn root_path(&self) -> String {
1651 repeat("../").take(self.current.len()).collect::<String>()
1654 /// Recurse in the directory structure and change the "root path" to make
1655 /// sure it always points to the top (relatively).
1656 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1657 F: FnOnce(&mut Context) -> T,
1660 panic!("Unexpected empty destination: {:?}", self.current);
1662 let prev = self.dst.clone();
1664 self.current.push(s);
1666 info!("Recursing into {}", self.dst.display());
1670 info!("Recursed; leaving {}", self.dst.display());
1672 // Go back to where we were at
1674 self.current.pop().unwrap();
1679 /// Main method for rendering a crate.
1681 /// This currently isn't parallelized, but it'd be pretty easy to add
1682 /// parallelization to this function.
1683 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1684 let mut item = match krate.module.take() {
1686 None => return Ok(()),
1688 let final_file = self.dst.join(&krate.name)
1690 let settings_file = self.dst.join("settings.html");
1692 let crate_name = krate.name.clone();
1693 item.name = Some(krate.name);
1695 let mut all = AllTypes::new();
1698 // Render the crate documentation
1699 let mut work = vec![(self.clone(), item)];
1701 while let Some((mut cx, item)) = work.pop() {
1702 cx.item(item, &mut all, |cx, item| {
1703 work.push((cx.clone(), item))
1708 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
1709 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1710 if !root_path.ends_with('/') {
1711 root_path.push('/');
1713 let mut page = layout::Page {
1714 title: "List of all items in this crate",
1717 description: "List of all items in this crate",
1718 keywords: BASIC_KEYWORDS,
1719 resource_suffix: &self.shared.resource_suffix,
1721 let sidebar = if let Some(ref version) = cache().crate_version {
1722 format!("<p class='location'>Crate {}</p>\
1723 <div class='block version'>\
1726 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1727 crate_name, version)
1731 try_err!(layout::render(&mut w, &self.shared.layout,
1732 &page, &sidebar, &all,
1733 self.shared.css_file_extension.is_some(),
1734 &self.shared.themes),
1737 // Generating settings page.
1738 let settings = Settings::new("./", &self.shared.resource_suffix);
1739 page.title = "Rustdoc settings";
1740 page.description = "Settings of Rustdoc";
1741 page.root_path = "./";
1743 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
1744 let mut themes = self.shared.themes.clone();
1745 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1746 themes.push(PathBuf::from("settings.css"));
1747 let mut layout = self.shared.layout.clone();
1748 layout.krate = String::new();
1749 layout.logo = String::new();
1750 layout.favicon = String::new();
1751 try_err!(layout::render(&mut w, &layout,
1752 &page, &sidebar, &settings,
1753 self.shared.css_file_extension.is_some(),
1760 fn render_item(&self,
1761 writer: &mut io::Write,
1765 // A little unfortunate that this is done like this, but it sure
1766 // does make formatting *a lot* nicer.
1767 CURRENT_LOCATION_KEY.with(|slot| {
1768 *slot.borrow_mut() = self.current.clone();
1771 let mut title = if it.is_primitive() {
1772 // No need to include the namespace for primitive types
1775 self.current.join("::")
1778 if !title.is_empty() {
1779 title.push_str("::");
1781 title.push_str(it.name.as_ref().unwrap());
1783 title.push_str(" - Rust");
1784 let tyname = it.type_().css_class();
1785 let desc = if it.is_crate() {
1786 format!("API documentation for the Rust `{}` crate.",
1787 self.shared.layout.krate)
1789 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1790 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1792 let keywords = make_item_keywords(it);
1793 let page = layout::Page {
1795 root_path: &self.root_path(),
1798 keywords: &keywords,
1799 resource_suffix: &self.shared.resource_suffix,
1804 if !self.render_redirect_pages {
1805 layout::render(writer, &self.shared.layout, &page,
1806 &Sidebar{ cx: self, item: it },
1807 &Item{ cx: self, item: it },
1808 self.shared.css_file_extension.is_some(),
1809 &self.shared.themes)?;
1811 let mut url = self.root_path();
1812 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1813 for name in &names[..names.len() - 1] {
1817 url.push_str(&item_path(ty, names.last().unwrap()));
1818 layout::redirect(writer, &url)?;
1824 /// Non-parallelized version of rendering an item. This will take the input
1825 /// item, render its contents, and then invoke the specified closure with
1826 /// all sub-items which need to be rendered.
1828 /// The rendering driver uses this closure to queue up more work.
1829 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
1830 where F: FnMut(&mut Context, clean::Item),
1832 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1833 // if they contain impls for public types. These modules can also
1834 // contain items such as publicly re-exported structures.
1836 // External crates will provide links to these structures, so
1837 // these modules are recursed into, but not rendered normally
1838 // (a flag on the context).
1839 if !self.render_redirect_pages {
1840 self.render_redirect_pages = item.is_stripped();
1844 // modules are special because they add a namespace. We also need to
1845 // recurse into the items of the module as well.
1846 let name = item.name.as_ref().unwrap().to_string();
1847 let mut item = Some(item);
1848 self.recurse(name, |this| {
1849 let item = item.take().unwrap();
1851 let mut buf = Vec::new();
1852 this.render_item(&mut buf, &item, false).unwrap();
1853 // buf will be empty if the module is stripped and there is no redirect for it
1854 if !buf.is_empty() {
1855 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1856 let joint_dst = this.dst.join("index.html");
1857 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1858 try_err!(dst.write_all(&buf), &joint_dst);
1861 let m = match item.inner {
1862 clean::StrippedItem(box clean::ModuleItem(m)) |
1863 clean::ModuleItem(m) => m,
1867 // Render sidebar-items.js used throughout this module.
1868 if !this.render_redirect_pages {
1869 let items = this.build_sidebar_items(&m);
1870 let js_dst = this.dst.join("sidebar-items.js");
1871 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1872 try_err!(write!(&mut js_out, "initSidebarItems({});",
1873 as_json(&items)), &js_dst);
1876 for item in m.items {
1882 } else if item.name.is_some() {
1883 let mut buf = Vec::new();
1884 self.render_item(&mut buf, &item, true).unwrap();
1885 // buf will be empty if the item is stripped and there is no redirect for it
1886 if !buf.is_empty() {
1887 let name = item.name.as_ref().unwrap();
1888 let item_type = item.type_();
1889 let file_name = &item_path(item_type, name);
1890 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1891 let joint_dst = self.dst.join(file_name);
1892 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1893 try_err!(dst.write_all(&buf), &joint_dst);
1895 if !self.render_redirect_pages {
1896 all.append(full_path(self, &item), &item_type);
1898 // Redirect from a sane URL using the namespace to Rustdoc's
1899 // URL for the page.
1900 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1901 let redir_dst = self.dst.join(redir_name);
1902 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1905 let mut redirect_out = BufWriter::new(redirect_out);
1906 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1909 // If the item is a macro, redirect from the old macro URL (with !)
1910 // to the new one (without).
1911 // FIXME(#35705) remove this redirect.
1912 if item_type == ItemType::Macro {
1913 let redir_name = format!("{}.{}!.html", item_type, name);
1914 let redir_dst = self.dst.join(redir_name);
1915 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1916 let mut redirect_out = BufWriter::new(redirect_out);
1917 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1924 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1925 // BTreeMap instead of HashMap to get a sorted output
1926 let mut map = BTreeMap::new();
1927 for item in &m.items {
1928 if item.is_stripped() { continue }
1930 let short = item.type_().css_class();
1931 let myname = match item.name {
1933 Some(ref s) => s.to_string(),
1935 let short = short.to_string();
1936 map.entry(short).or_insert(vec![])
1937 .push((myname, Some(plain_summary_line(item.doc_value()))));
1940 if self.shared.sort_modules_alphabetically {
1941 for (_, items) in &mut map {
1950 /// Generate a url appropriate for an `href` attribute back to the source of
1953 /// The url generated, when clicked, will redirect the browser back to the
1954 /// original source code.
1956 /// If `None` is returned, then a source link couldn't be generated. This
1957 /// may happen, for example, with externally inlined items where the source
1958 /// of their crate documentation isn't known.
1959 fn src_href(&self) -> Option<String> {
1960 let mut root = self.cx.root_path();
1962 let cache = cache();
1963 let mut path = String::new();
1965 // We can safely ignore macros from other libraries
1966 let file = match self.item.source.filename {
1967 FileName::Real(ref path) => path,
1971 let (krate, path) = if self.item.def_id.is_local() {
1972 if let Some(path) = self.cx.shared.local_sources.get(file) {
1973 (&self.cx.shared.layout.krate, path)
1978 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1979 Some(&(ref name, ref src, Local)) => (name, src),
1980 Some(&(ref name, ref src, Remote(ref s))) => {
1981 root = s.to_string();
1984 Some(&(_, _, Unknown)) | None => return None,
1987 clean_srcpath(&src_root, file, false, |component| {
1988 path.push_str(component);
1991 let mut fname = file.file_name().expect("source has no filename")
1993 fname.push(".html");
1994 path.push_str(&fname.to_string_lossy());
1998 let lines = if self.item.source.loline == self.item.source.hiline {
1999 format!("{}", self.item.source.loline)
2001 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2003 Some(format!("{root}src/{krate}/{path}#{lines}",
2004 root = Escape(&root),
2011 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2012 f: F) -> fmt::Result
2013 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2014 write!(w, "<div class=\"docblock type-decl\">")?;
2019 impl<'a> fmt::Display for Item<'a> {
2020 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2021 debug_assert!(!self.item.is_stripped());
2022 // Write the breadcrumb trail header for the top
2023 write!(fmt, "<h1 class='fqn'><span class='in-band'>")?;
2024 match self.item.inner {
2025 clean::ModuleItem(ref m) => if m.is_crate {
2026 write!(fmt, "Crate ")?;
2028 write!(fmt, "Module ")?;
2030 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2031 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2032 clean::StructItem(..) => write!(fmt, "Struct ")?,
2033 clean::UnionItem(..) => write!(fmt, "Union ")?,
2034 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2035 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2036 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2037 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2038 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2039 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2040 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2042 // We don't generate pages for any other type.
2046 if !self.item.is_primitive() {
2047 let cur = &self.cx.current;
2048 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2049 for (i, component) in cur.iter().enumerate().take(amt) {
2050 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2051 repeat("../").take(cur.len() - i - 1)
2052 .collect::<String>(),
2056 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2057 self.item.type_(), self.item.name.as_ref().unwrap())?;
2059 write!(fmt, "</span>")?; // in-band
2060 write!(fmt, "<span class='out-of-band'>")?;
2061 if let Some(version) = self.item.stable_since() {
2062 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2066 "<span id='render-detail'>\
2067 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2068 title=\"collapse all docs\">\
2069 [<span class='inner'>−</span>]\
2075 // When this item is part of a `pub use` in a downstream crate, the
2076 // [src] link in the downstream documentation will actually come back to
2077 // this page, and this link will be auto-clicked. The `id` attribute is
2078 // used to find the link to auto-click.
2079 if self.cx.shared.include_sources && !self.item.is_primitive() {
2080 if let Some(l) = self.src_href() {
2081 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2082 l, "goto source code")?;
2086 write!(fmt, "</span></h1>")?; // out-of-band
2088 match self.item.inner {
2089 clean::ModuleItem(ref m) =>
2090 item_module(fmt, self.cx, self.item, &m.items),
2091 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2092 item_function(fmt, self.cx, self.item, f),
2093 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2094 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2095 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2096 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2097 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2098 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2099 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2100 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2101 item_static(fmt, self.cx, self.item, i),
2102 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2103 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2105 // We don't generate pages for any other type.
2112 fn item_path(ty: ItemType, name: &str) -> String {
2114 ItemType::Module => format!("{}/index.html", name),
2115 _ => format!("{}.{}.html", ty.css_class(), name),
2119 fn full_path(cx: &Context, item: &clean::Item) -> String {
2120 let mut s = cx.current.join("::");
2122 s.push_str(item.name.as_ref().unwrap());
2126 fn shorter<'a>(s: Option<&'a str>) -> String {
2128 Some(s) => s.lines()
2129 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2131 (*line).chars().any(|chr|{
2132 !chr.is_whitespace()
2134 }).collect::<Vec<_>>().join("\n"),
2135 None => "".to_string()
2140 fn plain_summary_line(s: Option<&str>) -> String {
2141 let line = shorter(s).replace("\n", " ");
2142 markdown::plain_summary_line(&line[..])
2145 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2146 if let Some(ref name) = item.name {
2147 info!("Documenting {}", name);
2149 document_stability(w, cx, item)?;
2150 let prefix = render_assoc_const_value(item);
2151 document_full(w, item, cx, &prefix)?;
2155 /// Render md_text as markdown.
2156 fn render_markdown(w: &mut fmt::Formatter,
2158 links: Vec<(String, String)>,
2161 write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
2164 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
2165 prefix: &str) -> fmt::Result {
2166 if let Some(s) = item.doc_value() {
2167 let markdown = if s.contains('\n') {
2168 format!("{} [Read more]({})",
2169 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2171 format!("{}", &plain_summary_line(Some(s)))
2173 render_markdown(w, &markdown, item.links(), prefix)?;
2174 } else if !prefix.is_empty() {
2175 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2180 fn render_assoc_const_value(item: &clean::Item) -> String {
2182 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
2183 highlight::render_with_highlighting(
2184 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
2195 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2196 cx: &Context, prefix: &str) -> fmt::Result {
2197 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2198 debug!("Doc block: =====\n{}\n=====", s);
2199 render_markdown(w, &*s, item.links(), prefix)?;
2200 } else if !prefix.is_empty() {
2201 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2206 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2207 let stabilities = short_stability(item, cx, true);
2208 if !stabilities.is_empty() {
2209 write!(w, "<div class='stability'>")?;
2210 for stability in stabilities {
2211 write!(w, "{}", stability)?;
2213 write!(w, "</div>")?;
2218 fn name_key(name: &str) -> (&str, u64, usize) {
2219 // find number at end
2220 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
2222 // count leading zeroes
2224 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2226 // sort leading zeroes last
2227 let num_zeroes = after_zeroes - split;
2229 match name[split..].parse() {
2230 Ok(n) => (&name[..split], n, num_zeroes),
2231 Err(_) => (name, 0, num_zeroes),
2235 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2236 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2237 document(w, cx, item)?;
2239 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2241 // the order of item types in the listing
2242 fn reorder(ty: ItemType) -> u8 {
2244 ItemType::ExternCrate => 0,
2245 ItemType::Import => 1,
2246 ItemType::Primitive => 2,
2247 ItemType::Module => 3,
2248 ItemType::Macro => 4,
2249 ItemType::Struct => 5,
2250 ItemType::Enum => 6,
2251 ItemType::Constant => 7,
2252 ItemType::Static => 8,
2253 ItemType::Trait => 9,
2254 ItemType::Function => 10,
2255 ItemType::Typedef => 12,
2256 ItemType::Union => 13,
2261 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2262 let ty1 = i1.type_();
2263 let ty2 = i2.type_();
2265 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2267 let s1 = i1.stability.as_ref().map(|s| s.level);
2268 let s2 = i2.stability.as_ref().map(|s| s.level);
2270 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2271 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2274 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2275 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2276 name_key(lhs).cmp(&name_key(rhs))
2279 if cx.shared.sort_modules_alphabetically {
2280 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2282 // This call is to remove re-export duplicates in cases such as:
2287 // pub trait Double { fn foo(); }
2291 // pub use foo::bar::*;
2295 // `Double` will appear twice in the generated docs.
2297 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2298 // can be identical even if the elements are different (mostly in imports).
2299 // So in case this is an import, we keep everything by adding a "unique id"
2300 // (which is the position in the vector).
2301 indices.dedup_by_key(|i| (items[*i].def_id,
2302 if items[*i].name.as_ref().is_some() {
2303 Some(full_path(cx, &items[*i]).clone())
2308 if items[*i].is_import() {
2314 debug!("{:?}", indices);
2315 let mut curty = None;
2316 for &idx in &indices {
2317 let myitem = &items[idx];
2318 if myitem.is_stripped() {
2322 let myty = Some(myitem.type_());
2323 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2324 // Put `extern crate` and `use` re-exports in the same section.
2326 } else if myty != curty {
2327 if curty.is_some() {
2328 write!(w, "</table>")?;
2331 let (short, name) = match myty.unwrap() {
2332 ItemType::ExternCrate |
2333 ItemType::Import => ("reexports", "Re-exports"),
2334 ItemType::Module => ("modules", "Modules"),
2335 ItemType::Struct => ("structs", "Structs"),
2336 ItemType::Union => ("unions", "Unions"),
2337 ItemType::Enum => ("enums", "Enums"),
2338 ItemType::Function => ("functions", "Functions"),
2339 ItemType::Typedef => ("types", "Type Definitions"),
2340 ItemType::Static => ("statics", "Statics"),
2341 ItemType::Constant => ("constants", "Constants"),
2342 ItemType::Trait => ("traits", "Traits"),
2343 ItemType::Impl => ("impls", "Implementations"),
2344 ItemType::TyMethod => ("tymethods", "Type Methods"),
2345 ItemType::Method => ("methods", "Methods"),
2346 ItemType::StructField => ("fields", "Struct Fields"),
2347 ItemType::Variant => ("variants", "Variants"),
2348 ItemType::Macro => ("macros", "Macros"),
2349 ItemType::Primitive => ("primitives", "Primitive Types"),
2350 ItemType::AssociatedType => ("associated-types", "Associated Types"),
2351 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
2352 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2354 write!(w, "<h2 id='{id}' class='section-header'>\
2355 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2356 id = derive_id(short.to_owned()), name = name)?;
2359 match myitem.inner {
2360 clean::ExternCrateItem(ref name, ref src) => {
2361 use html::format::HRef;
2365 write!(w, "<tr><td><code>{}extern crate {} as {};",
2366 VisSpace(&myitem.visibility),
2367 HRef::new(myitem.def_id, src),
2371 write!(w, "<tr><td><code>{}extern crate {};",
2372 VisSpace(&myitem.visibility),
2373 HRef::new(myitem.def_id, name))?
2376 write!(w, "</code></td></tr>")?;
2379 clean::ImportItem(ref import) => {
2380 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2381 VisSpace(&myitem.visibility), *import)?;
2385 if myitem.name.is_none() { continue }
2387 let stabilities = short_stability(myitem, cx, false);
2389 let stab_docs = if !stabilities.is_empty() {
2391 .map(|s| format!("[{}]", s))
2392 .collect::<Vec<_>>()
2399 let unsafety_flag = match myitem.inner {
2400 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2401 if func.unsafety == hir::Unsafety::Unsafe => {
2402 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2407 let doc_value = myitem.doc_value().unwrap_or("");
2409 <tr class='{stab} module-item'>
2410 <td><a class=\"{class}\" href=\"{href}\"
2411 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2412 <td class='docblock-short'>
2416 name = *myitem.name.as_ref().unwrap(),
2417 stab_docs = stab_docs,
2418 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2419 class = myitem.type_(),
2420 stab = myitem.stability_class().unwrap_or("".to_string()),
2421 unsafety_flag = unsafety_flag,
2422 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2423 title_type = myitem.type_(),
2424 title = full_path(cx, myitem))?;
2429 if curty.is_some() {
2430 write!(w, "</table>")?;
2435 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2436 let mut stability = vec![];
2438 if let Some(stab) = item.stability.as_ref() {
2439 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2440 format!(": {}", stab.deprecated_reason)
2444 if !stab.deprecated_since.is_empty() {
2445 let since = if show_reason {
2446 format!(" since {}", Escape(&stab.deprecated_since))
2450 let text = if stability::deprecation_in_effect(&stab.deprecated_since) {
2451 format!("Deprecated{}{}",
2453 MarkdownHtml(&deprecated_reason))
2455 format!("Deprecating in {}{}",
2456 Escape(&stab.deprecated_since),
2457 MarkdownHtml(&deprecated_reason))
2459 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2462 if stab.level == stability::Unstable {
2464 let unstable_extra = match (!stab.feature.is_empty(),
2465 &cx.shared.issue_tracker_base_url,
2467 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2468 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2469 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2470 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2471 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2474 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2477 if stab.unstable_reason.is_empty() {
2478 stability.push(format!("<div class='stab unstable'>\
2479 <span class=microscope>🔬</span> \
2480 This is a nightly-only experimental API. {}\
2484 let text = format!("<summary><span class=microscope>🔬</span> \
2485 This is a nightly-only experimental API. {}\
2488 MarkdownHtml(&stab.unstable_reason));
2489 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2493 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2496 } else if let Some(depr) = item.deprecation.as_ref() {
2497 let note = if show_reason && !depr.note.is_empty() {
2498 format!(": {}", depr.note)
2502 let since = if show_reason && !depr.since.is_empty() {
2503 format!(" since {}", Escape(&depr.since))
2508 let text = if stability::deprecation_in_effect(&depr.since) {
2509 format!("Deprecated{}{}",
2511 MarkdownHtml(¬e))
2513 format!("Deprecating in {}{}",
2514 Escape(&depr.since),
2515 MarkdownHtml(¬e))
2517 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2520 if let Some(ref cfg) = item.attrs.cfg {
2521 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2522 cfg.render_long_html()
2524 cfg.render_short_html()
2531 struct Initializer<'a>(&'a str);
2533 impl<'a> fmt::Display for Initializer<'a> {
2534 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2535 let Initializer(s) = *self;
2536 if s.is_empty() { return Ok(()); }
2537 write!(f, "<code> = </code>")?;
2538 write!(f, "<code>{}</code>", Escape(s))
2542 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2543 c: &clean::Constant) -> fmt::Result {
2544 write!(w, "<pre class='rust const'>")?;
2545 render_attributes(w, it)?;
2546 write!(w, "{vis}const \
2547 {name}: {typ}{init}</pre>",
2548 vis = VisSpace(&it.visibility),
2549 name = it.name.as_ref().unwrap(),
2551 init = Initializer(&c.expr))?;
2555 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2556 s: &clean::Static) -> fmt::Result {
2557 write!(w, "<pre class='rust static'>")?;
2558 render_attributes(w, it)?;
2559 write!(w, "{vis}static {mutability}\
2560 {name}: {typ}{init}</pre>",
2561 vis = VisSpace(&it.visibility),
2562 mutability = MutableSpace(s.mutability),
2563 name = it.name.as_ref().unwrap(),
2565 init = Initializer(&s.expr))?;
2569 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2570 f: &clean::Function) -> fmt::Result {
2571 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2572 VisSpace(&it.visibility),
2573 ConstnessSpace(f.constness),
2574 UnsafetySpace(f.unsafety),
2576 it.name.as_ref().unwrap(),
2578 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2579 render_attributes(w, it)?;
2581 "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2582 vis = VisSpace(&it.visibility),
2583 constness = ConstnessSpace(f.constness),
2584 unsafety = UnsafetySpace(f.unsafety),
2585 abi = AbiSpace(f.abi),
2586 name = it.name.as_ref().unwrap(),
2587 generics = f.generics,
2588 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2597 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2598 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> Result<(), fmt::Error> {
2599 write!(w, "<li><table class='table-display'><tbody><tr><td><code>")?;
2600 // If there's already another implementor that has the same abbridged name, use the
2601 // full path, for example in `std::iter::ExactSizeIterator`
2602 let use_absolute = match implementor.inner_impl().for_ {
2603 clean::ResolvedPath { ref path, is_generic: false, .. } |
2604 clean::BorrowedRef {
2605 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2607 } => implementor_dups[path.last_name()].1,
2610 fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2611 for it in &implementor.inner_impl().items {
2612 if let clean::TypedefItem(ref tydef, _) = it.inner {
2613 write!(w, "<span class=\"where fmt-newline\"> ")?;
2614 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2615 write!(w, ";</span>")?;
2618 write!(w, "</code><td>")?;
2619 if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2620 write!(w, "<div class='out-of-band'>")?;
2621 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2622 l, "goto source code")?;
2623 write!(w, "</div>")?;
2625 writeln!(w, "</td></tr></tbody></table></li>")?;
2629 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2631 containing_item: &clean::Item) -> Result<(), fmt::Error> {
2633 let did = i.trait_did().unwrap();
2634 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2635 render_impl(w, cx, i, assoc_link,
2636 RenderMode::Normal, containing_item.stable_since(), true)?;
2641 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2642 t: &clean::Trait) -> fmt::Result {
2643 let mut bounds = String::new();
2644 let mut bounds_plain = String::new();
2645 if !t.bounds.is_empty() {
2646 if !bounds.is_empty() {
2648 bounds_plain.push(' ');
2650 bounds.push_str(": ");
2651 bounds_plain.push_str(": ");
2652 for (i, p) in t.bounds.iter().enumerate() {
2654 bounds.push_str(" + ");
2655 bounds_plain.push_str(" + ");
2657 bounds.push_str(&format!("{}", *p));
2658 bounds_plain.push_str(&format!("{:#}", *p));
2662 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2663 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2664 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2665 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2667 // Output the trait definition
2668 wrap_into_docblock(w, |w| {
2669 write!(w, "<pre class='rust trait'>")?;
2670 render_attributes(w, it)?;
2671 write!(w, "{}{}{}trait {}{}{}",
2672 VisSpace(&it.visibility),
2673 UnsafetySpace(t.unsafety),
2674 if t.is_auto { "auto " } else { "" },
2675 it.name.as_ref().unwrap(),
2679 if !t.generics.where_predicates.is_empty() {
2680 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2685 if t.items.is_empty() {
2686 write!(w, "{{ }}")?;
2688 // FIXME: we should be using a derived_id for the Anchors here
2692 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2695 if !types.is_empty() && !consts.is_empty() {
2700 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2703 if !consts.is_empty() && !required.is_empty() {
2706 for (pos, m) in required.iter().enumerate() {
2708 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2711 if pos < required.len() - 1 {
2712 write!(w, "<div class='item-spacer'></div>")?;
2715 if !required.is_empty() && !provided.is_empty() {
2718 for (pos, m) in provided.iter().enumerate() {
2720 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2722 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2723 write!(w, ",\n {{ ... }}\n")?;
2726 write!(w, " {{ ... }}\n")?;
2729 if pos < provided.len() - 1 {
2730 write!(w, "<div class='item-spacer'></div>")?;
2738 // Trait documentation
2739 document(w, cx, it)?;
2741 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2743 let name = m.name.as_ref().unwrap();
2744 let item_type = m.type_();
2745 let id = derive_id(format!("{}.{}", item_type, name));
2746 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2747 write!(w, "{extra}<h3 id='{id}' class='method'>\
2748 <span id='{ns_id}' class='invisible'><code>",
2749 extra = render_spotlight_traits(m)?,
2752 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2753 write!(w, "</code>")?;
2754 render_stability_since(w, m, t)?;
2755 write!(w, "</span></h3>")?;
2756 document(w, cx, m)?;
2760 if !types.is_empty() {
2762 <h2 id='associated-types' class='small-section-header'>
2763 Associated Types<a href='#associated-types' class='anchor'></a>
2765 <div class='methods'>
2768 trait_item(w, cx, *t, it)?;
2770 write!(w, "</div>")?;
2773 if !consts.is_empty() {
2775 <h2 id='associated-const' class='small-section-header'>
2776 Associated Constants<a href='#associated-const' class='anchor'></a>
2778 <div class='methods'>
2781 trait_item(w, cx, *t, it)?;
2783 write!(w, "</div>")?;
2786 // Output the documentation for each function individually
2787 if !required.is_empty() {
2789 <h2 id='required-methods' class='small-section-header'>
2790 Required Methods<a href='#required-methods' class='anchor'></a>
2792 <div class='methods'>
2794 for m in &required {
2795 trait_item(w, cx, *m, it)?;
2797 write!(w, "</div>")?;
2799 if !provided.is_empty() {
2801 <h2 id='provided-methods' class='small-section-header'>
2802 Provided Methods<a href='#provided-methods' class='anchor'></a>
2804 <div class='methods'>
2806 for m in &provided {
2807 trait_item(w, cx, *m, it)?;
2809 write!(w, "</div>")?;
2812 // If there are methods directly on this trait object, render them here.
2813 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2815 let cache = cache();
2817 <h2 id='implementors' class='small-section-header'>
2818 Implementors<a href='#implementors' class='anchor'></a>
2820 <ul class='item-list' id='implementors-list'>
2823 let synthetic_impl_header = "
2824 <h2 id='synthetic-implementors' class='small-section-header'>
2825 Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
2827 <ul class='item-list' id='synthetic-implementors-list'>
2830 let mut synthetic_types = Vec::new();
2832 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2833 // The DefId is for the first Type found with that name. The bool is
2834 // if any Types with the same name but different DefId have been found.
2835 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2836 for implementor in implementors {
2837 match implementor.inner_impl().for_ {
2838 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2839 clean::BorrowedRef {
2840 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2843 let &mut (prev_did, ref mut has_duplicates) =
2844 implementor_dups.entry(path.last_name()).or_insert((did, false));
2845 if prev_did != did {
2846 *has_duplicates = true;
2853 let (local, foreign) = implementors.iter()
2854 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2855 .map_or(true, |d| cache.paths.contains_key(&d)));
2858 let (synthetic, concrete) = local.iter()
2859 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2862 if !foreign.is_empty() {
2864 <h2 id='foreign-impls' class='small-section-header'>
2865 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2869 for implementor in foreign {
2870 let assoc_link = AssocItemLink::GotoSource(
2871 implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2873 render_impl(w, cx, &implementor, assoc_link,
2874 RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2878 write!(w, "{}", impl_header)?;
2879 for implementor in concrete {
2880 render_implementor(cx, implementor, w, &implementor_dups)?;
2882 write!(w, "</ul>")?;
2885 write!(w, "{}", synthetic_impl_header)?;
2886 for implementor in synthetic {
2887 synthetic_types.extend(
2888 collect_paths_for_type(implementor.inner_impl().for_.clone())
2890 render_implementor(cx, implementor, w, &implementor_dups)?;
2892 write!(w, "</ul>")?;
2895 // even without any implementations to write in, we still want the heading and list, so the
2896 // implementors javascript file pulled in below has somewhere to write the impls into
2897 write!(w, "{}", impl_header)?;
2898 write!(w, "</ul>")?;
2901 write!(w, "{}", synthetic_impl_header)?;
2902 write!(w, "</ul>")?;
2905 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2906 as_json(&synthetic_types))?;
2908 write!(w, r#"<script type="text/javascript" async
2909 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2911 root_path = vec![".."; cx.current.len()].join("/"),
2912 path = if it.def_id.is_local() {
2913 cx.current.join("/")
2915 let (ref path, _) = cache.external_paths[&it.def_id];
2916 path[..path.len() - 1].join("/")
2918 ty = it.type_().css_class(),
2919 name = *it.name.as_ref().unwrap())?;
2923 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2924 use html::item_type::ItemType::*;
2926 let name = it.name.as_ref().unwrap();
2927 let ty = match it.type_() {
2928 Typedef | AssociatedType => AssociatedType,
2932 let anchor = format!("#{}.{}", ty, name);
2934 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2935 AssocItemLink::Anchor(None) => anchor,
2936 AssocItemLink::GotoSource(did, _) => {
2937 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2942 fn assoc_const(w: &mut fmt::Formatter,
2945 _default: Option<&String>,
2946 link: AssocItemLink) -> fmt::Result {
2947 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2948 VisSpace(&it.visibility),
2949 naive_assoc_href(it, link),
2950 it.name.as_ref().unwrap(),
2955 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2956 bounds: &Vec<clean::TyParamBound>,
2957 default: Option<&clean::Type>,
2958 link: AssocItemLink) -> fmt::Result {
2959 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2960 naive_assoc_href(it, link),
2961 it.name.as_ref().unwrap())?;
2962 if !bounds.is_empty() {
2963 write!(w, ": {}", TyParamBounds(bounds))?
2965 if let Some(default) = default {
2966 write!(w, " = {}", default)?;
2971 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2972 ver: Option<&'a str>,
2973 containing_ver: Option<&'a str>) -> fmt::Result {
2974 if let Some(v) = ver {
2975 if containing_ver != ver && v.len() > 0 {
2976 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2983 fn render_stability_since(w: &mut fmt::Formatter,
2985 containing_item: &clean::Item) -> fmt::Result {
2986 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2989 fn render_assoc_item(w: &mut fmt::Formatter,
2991 link: AssocItemLink,
2992 parent: ItemType) -> fmt::Result {
2993 fn method(w: &mut fmt::Formatter,
2995 unsafety: hir::Unsafety,
2996 constness: hir::Constness,
2998 g: &clean::Generics,
3000 link: AssocItemLink,
3003 let name = meth.name.as_ref().unwrap();
3004 let anchor = format!("#{}.{}", meth.type_(), name);
3005 let href = match link {
3006 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3007 AssocItemLink::Anchor(None) => anchor,
3008 AssocItemLink::GotoSource(did, provided_methods) => {
3009 // We're creating a link from an impl-item to the corresponding
3010 // trait-item and need to map the anchored type accordingly.
3011 let ty = if provided_methods.contains(name) {
3017 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3020 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
3021 VisSpace(&meth.visibility),
3022 ConstnessSpace(constness),
3023 UnsafetySpace(unsafety),
3027 let (indent, end_newline) = if parent == ItemType::Trait {
3033 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3034 {generics}{decl}{where_clause}",
3035 VisSpace(&meth.visibility),
3036 ConstnessSpace(constness),
3037 UnsafetySpace(unsafety),
3047 where_clause = WhereClause {
3054 clean::StrippedItem(..) => Ok(()),
3055 clean::TyMethodItem(ref m) => {
3056 method(w, item, m.unsafety, hir::Constness::NotConst,
3057 m.abi, &m.generics, &m.decl, link, parent)
3059 clean::MethodItem(ref m) => {
3060 method(w, item, m.unsafety, m.constness,
3061 m.abi, &m.generics, &m.decl, link, parent)
3063 clean::AssociatedConstItem(ref ty, ref default) => {
3064 assoc_const(w, item, ty, default.as_ref(), link)
3066 clean::AssociatedTypeItem(ref bounds, ref default) => {
3067 assoc_type(w, item, bounds, default.as_ref(), link)
3069 _ => panic!("render_assoc_item called on non-associated-item")
3073 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3074 s: &clean::Struct) -> fmt::Result {
3075 wrap_into_docblock(w, |w| {
3076 write!(w, "<pre class='rust struct'>")?;
3077 render_attributes(w, it)?;
3088 document(w, cx, it)?;
3089 let mut fields = s.fields.iter().filter_map(|f| {
3091 clean::StructFieldItem(ref ty) => Some((f, ty)),
3095 if let doctree::Plain = s.struct_type {
3096 if fields.peek().is_some() {
3097 write!(w, "<h2 id='fields' class='fields small-section-header'>
3098 Fields<a href='#fields' class='anchor'></a></h2>")?;
3099 for (field, ty) in fields {
3100 let id = derive_id(format!("{}.{}",
3101 ItemType::StructField,
3102 field.name.as_ref().unwrap()));
3103 let ns_id = derive_id(format!("{}.{}",
3104 field.name.as_ref().unwrap(),
3105 ItemType::StructField.name_space()));
3106 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
3107 <a href=\"#{id}\" class=\"anchor field\"></a>
3108 <span id=\"{ns_id}\" class='invisible'>
3109 <code>{name}: {ty}</code>
3111 item_type = ItemType::StructField,
3114 name = field.name.as_ref().unwrap(),
3116 if let Some(stability_class) = field.stability_class() {
3117 write!(w, "<span class='stab {stab}'></span>",
3118 stab = stability_class)?;
3120 document(w, cx, field)?;
3124 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3127 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3128 s: &clean::Union) -> fmt::Result {
3129 wrap_into_docblock(w, |w| {
3130 write!(w, "<pre class='rust union'>")?;
3131 render_attributes(w, it)?;
3141 document(w, cx, it)?;
3142 let mut fields = s.fields.iter().filter_map(|f| {
3144 clean::StructFieldItem(ref ty) => Some((f, ty)),
3148 if fields.peek().is_some() {
3149 write!(w, "<h2 id='fields' class='fields small-section-header'>
3150 Fields<a href='#fields' class='anchor'></a></h2>")?;
3151 for (field, ty) in fields {
3152 let name = field.name.as_ref().expect("union field name");
3153 let id = format!("{}.{}", ItemType::StructField, name);
3154 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3155 <a href=\"#{id}\" class=\"anchor field\"></a>\
3156 <span class='invisible'><code>{name}: {ty}</code></span>\
3160 shortty = ItemType::StructField,
3162 if let Some(stability_class) = field.stability_class() {
3163 write!(w, "<span class='stab {stab}'></span>",
3164 stab = stability_class)?;
3166 document(w, cx, field)?;
3169 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3172 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3173 e: &clean::Enum) -> fmt::Result {
3174 wrap_into_docblock(w, |w| {
3175 write!(w, "<pre class='rust enum'>")?;
3176 render_attributes(w, it)?;
3177 write!(w, "{}enum {}{}{}",
3178 VisSpace(&it.visibility),
3179 it.name.as_ref().unwrap(),
3181 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3182 if e.variants.is_empty() && !e.variants_stripped {
3183 write!(w, " {{}}")?;
3185 write!(w, " {{\n")?;
3186 for v in &e.variants {
3188 let name = v.name.as_ref().unwrap();
3190 clean::VariantItem(ref var) => {
3192 clean::VariantKind::CLike => write!(w, "{}", name)?,
3193 clean::VariantKind::Tuple(ref tys) => {
3194 write!(w, "{}(", name)?;
3195 for (i, ty) in tys.iter().enumerate() {
3197 write!(w, ", ")?
3199 write!(w, "{}", *ty)?;
3203 clean::VariantKind::Struct(ref s) => {
3219 if e.variants_stripped {
3220 write!(w, " // some variants omitted\n")?;
3227 document(w, cx, it)?;
3228 if !e.variants.is_empty() {
3229 write!(w, "<h2 id='variants' class='variants small-section-header'>
3230 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
3231 for variant in &e.variants {
3232 let id = derive_id(format!("{}.{}",
3234 variant.name.as_ref().unwrap()));
3235 let ns_id = derive_id(format!("{}.{}",
3236 variant.name.as_ref().unwrap(),
3237 ItemType::Variant.name_space()));
3238 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3239 <a href=\"#{id}\" class=\"anchor field\"></a>\
3240 <span id='{ns_id}' class='invisible'><code>{name}",
3243 name = variant.name.as_ref().unwrap())?;
3244 if let clean::VariantItem(ref var) = variant.inner {
3245 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3247 for (i, ty) in tys.iter().enumerate() {
3249 write!(w, ", ")?;
3251 write!(w, "{}", *ty)?;
3256 write!(w, "</code></span></span>")?;
3257 document(w, cx, variant)?;
3259 use clean::{Variant, VariantKind};
3260 if let clean::VariantItem(Variant {
3261 kind: VariantKind::Struct(ref s)
3262 }) = variant.inner {
3263 let variant_id = derive_id(format!("{}.{}.fields",
3265 variant.name.as_ref().unwrap()));
3266 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
3268 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
3269 <table>", name = variant.name.as_ref().unwrap())?;
3270 for field in &s.fields {
3271 use clean::StructFieldItem;
3272 if let StructFieldItem(ref ty) = field.inner {
3273 let id = derive_id(format!("variant.{}.field.{}",
3274 variant.name.as_ref().unwrap(),
3275 field.name.as_ref().unwrap()));
3276 let ns_id = derive_id(format!("{}.{}.{}.{}",
3277 variant.name.as_ref().unwrap(),
3278 ItemType::Variant.name_space(),
3279 field.name.as_ref().unwrap(),
3280 ItemType::StructField.name_space()));
3281 write!(w, "<tr><td \
3283 <span id='{ns_id}' class='invisible'>\
3284 <code>{f}: {t}</code></span></td><td>",
3287 f = field.name.as_ref().unwrap(),
3289 document(w, cx, field)?;
3290 write!(w, "</td></tr>")?;
3293 write!(w, "</table></span>")?;
3295 render_stability_since(w, variant, it)?;
3298 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3302 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3303 let name = attr.name();
3306 Some(format!("{}", name))
3307 } else if let Some(v) = attr.value_str() {
3308 Some(format!("{} = {:?}", name, v.as_str()))
3309 } else if let Some(values) = attr.meta_item_list() {
3310 let display: Vec<_> = values.iter().filter_map(|attr| {
3311 attr.meta_item().and_then(|mi| render_attribute(mi))
3314 if display.len() > 0 {
3315 Some(format!("{}({})", name, display.join(", ")))
3324 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3331 "unsafe_destructor_blind_to_params"
3334 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3335 let mut attrs = String::new();
3337 for attr in &it.attrs.other_attrs {
3338 let name = attr.name();
3339 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3342 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3343 attrs.push_str(&format!("#[{}]\n", s));
3346 if attrs.len() > 0 {
3347 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3352 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3353 g: Option<&clean::Generics>,
3354 ty: doctree::StructType,
3355 fields: &[clean::Item],
3357 structhead: bool) -> fmt::Result {
3359 VisSpace(&it.visibility),
3360 if structhead {"struct "} else {""},
3361 it.name.as_ref().unwrap())?;
3362 if let Some(g) = g {
3367 if let Some(g) = g {
3368 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3370 let mut has_visible_fields = false;
3372 for field in fields {
3373 if let clean::StructFieldItem(ref ty) = field.inner {
3374 write!(w, "\n{} {}{}: {},",
3376 VisSpace(&field.visibility),
3377 field.name.as_ref().unwrap(),
3379 has_visible_fields = true;
3383 if has_visible_fields {
3384 if it.has_stripped_fields().unwrap() {
3385 write!(w, "\n{} // some fields omitted", tab)?;
3387 write!(w, "\n{}", tab)?;
3388 } else if it.has_stripped_fields().unwrap() {
3389 // If there are no visible fields we can just display
3390 // `{ /* fields omitted */ }` to save space.
3391 write!(w, " /* fields omitted */ ")?;
3397 for (i, field) in fields.iter().enumerate() {
3402 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3405 clean::StructFieldItem(ref ty) => {
3406 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3412 if let Some(g) = g {
3413 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3418 // Needed for PhantomData.
3419 if let Some(g) = g {
3420 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3428 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3429 g: Option<&clean::Generics>,
3430 fields: &[clean::Item],
3432 structhead: bool) -> fmt::Result {
3434 VisSpace(&it.visibility),
3435 if structhead {"union "} else {""},
3436 it.name.as_ref().unwrap())?;
3437 if let Some(g) = g {
3438 write!(w, "{}", g)?;
3439 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3442 write!(w, " {{\n{}", tab)?;
3443 for field in fields {
3444 if let clean::StructFieldItem(ref ty) = field.inner {
3445 write!(w, " {}{}: {},\n{}",
3446 VisSpace(&field.visibility),
3447 field.name.as_ref().unwrap(),
3453 if it.has_stripped_fields().unwrap() {
3454 write!(w, " // some fields omitted\n{}", tab)?;
3460 #[derive(Copy, Clone)]
3461 enum AssocItemLink<'a> {
3462 Anchor(Option<&'a str>),
3463 GotoSource(DefId, &'a FxHashSet<String>),
3466 impl<'a> AssocItemLink<'a> {
3467 fn anchor(&self, id: &'a String) -> Self {
3469 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3470 ref other => *other,
3475 enum AssocItemRender<'a> {
3477 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3480 #[derive(Copy, Clone, PartialEq)]
3483 ForDeref { mut_: bool },
3486 fn render_assoc_items(w: &mut fmt::Formatter,
3488 containing_item: &clean::Item,
3490 what: AssocItemRender) -> fmt::Result {
3492 let v = match c.impls.get(&it) {
3494 None => return Ok(()),
3496 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3497 i.inner_impl().trait_.is_none()
3499 if !non_trait.is_empty() {
3500 let render_mode = match what {
3501 AssocItemRender::All => {
3503 <h2 id='methods' class='small-section-header'>
3504 Methods<a href='#methods' class='anchor'></a>
3509 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3511 <h2 id='deref-methods' class='small-section-header'>
3512 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3515 RenderMode::ForDeref { mut_: deref_mut_ }
3518 for i in &non_trait {
3519 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3520 containing_item.stable_since(), true)?;
3523 if let AssocItemRender::DerefFor { .. } = what {
3526 if !traits.is_empty() {
3527 let deref_impl = traits.iter().find(|t| {
3528 t.inner_impl().trait_.def_id() == c.deref_trait_did
3530 if let Some(impl_) = deref_impl {
3531 let has_deref_mut = traits.iter().find(|t| {
3532 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3534 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3537 let (synthetic, concrete) = traits
3539 .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3541 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3543 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3544 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3545 render_impls(self.0, fmt, &self.1, self.2)
3549 let impls = format!("{}", RendererStruct(cx, concrete, containing_item));
3550 if !impls.is_empty() {
3552 <h2 id='implementations' class='small-section-header'>
3553 Trait Implementations<a href='#implementations' class='anchor'></a>
3555 <div id='implementations-list'>{}</div>", impls)?;
3558 if !synthetic.is_empty() {
3560 <h2 id='synthetic-implementations' class='small-section-header'>
3561 Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3563 <div id='synthetic-implementations-list'>
3565 render_impls(cx, w, &synthetic, containing_item)?;
3566 write!(w, "</div>")?;
3572 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3573 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3574 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3575 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3577 clean::TypedefItem(ref t, true) => Some(&t.type_),
3580 }).next().expect("Expected associated type binding");
3581 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3582 deref_mut_: deref_mut };
3583 if let Some(did) = target.def_id() {
3584 render_assoc_items(w, cx, container_item, did, what)
3586 if let Some(prim) = target.primitive_type() {
3587 if let Some(&did) = cache().primitive_locations.get(&prim) {
3588 render_assoc_items(w, cx, container_item, did, what)?;
3595 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3596 let self_type_opt = match item.inner {
3597 clean::MethodItem(ref method) => method.decl.self_type(),
3598 clean::TyMethodItem(ref method) => method.decl.self_type(),
3602 if let Some(self_ty) = self_type_opt {
3603 let (by_mut_ref, by_box, by_value) = match self_ty {
3604 SelfTy::SelfBorrowed(_, mutability) |
3605 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3606 (mutability == Mutability::Mutable, false, false)
3608 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3609 (false, Some(did) == cache().owned_box_did, false)
3611 SelfTy::SelfValue => (false, false, true),
3612 _ => (false, false, false),
3615 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3621 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3622 let mut out = String::new();
3625 clean::FunctionItem(clean::Function { ref decl, .. }) |
3626 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3627 clean::MethodItem(clean::Method { ref decl, .. }) |
3628 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3629 out = spotlight_decl(decl)?;
3637 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3638 let mut out = String::new();
3639 let mut trait_ = String::new();
3641 if let Some(did) = decl.output.def_id() {
3643 if let Some(impls) = c.impls.get(&did) {
3645 let impl_ = i.inner_impl();
3646 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3649 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3650 <code class=\"content\">",
3652 trait_.push_str(&format!("{}", impl_.for_));
3655 //use the "where" class here to make it small
3656 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3657 let t_did = impl_.trait_.def_id().unwrap();
3658 for it in &impl_.items {
3659 if let clean::TypedefItem(ref tydef, _) = it.inner {
3660 out.push_str("<span class=\"where fmt-newline\"> ");
3661 assoc_type(&mut out, it, &vec![],
3663 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3664 out.push_str(";</span>");
3672 if !out.is_empty() {
3673 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3674 <span class='tooltiptext'>Important traits for {}</span></div>\
3675 <div class=\"content hidden\">",
3677 out.push_str("</code></div></div>");
3683 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3684 render_mode: RenderMode, outer_version: Option<&str>,
3685 show_def_docs: bool) -> fmt::Result {
3686 if render_mode == RenderMode::Normal {
3687 let id = derive_id(match i.inner_impl().trait_ {
3688 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3689 None => "impl".to_string(),
3691 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
3692 <tbody><tr><td><code>{}</code>",
3693 id, i.inner_impl())?;
3694 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3695 write!(w, "</span></td><td><span class='out-of-band'>")?;
3696 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3697 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3698 write!(w, "<div class='ghost'></div>")?;
3699 render_stability_since_raw(w, since, outer_version)?;
3700 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3701 l, "goto source code")?;
3703 render_stability_since_raw(w, since, outer_version)?;
3705 write!(w, "</span></td></tr></tbody></table></h3>")?;
3706 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3707 write!(w, "<div class='docblock'>{}</div>",
3708 Markdown(&*dox, &i.impl_item.links()))?;
3712 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3713 link: AssocItemLink, render_mode: RenderMode,
3714 is_default_item: bool, outer_version: Option<&str>,
3715 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3716 let item_type = item.type_();
3717 let name = item.name.as_ref().unwrap();
3719 let render_method_item: bool = match render_mode {
3720 RenderMode::Normal => true,
3721 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3725 clean::MethodItem(clean::Method { ref decl, .. }) |
3726 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3727 // Only render when the method is not static or we allow static methods
3728 if render_method_item {
3729 let id = derive_id(format!("{}.{}", item_type, name));
3730 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3731 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3732 write!(w, "{}", spotlight_decl(decl)?)?;
3733 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3734 write!(w, "<table class='table-display'><tbody><tr><td><code>")?;
3735 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3736 write!(w, "</code>")?;
3737 if let Some(l) = (Item { cx, item }).src_href() {
3738 write!(w, "</span></td><td><span class='out-of-band'>")?;
3739 write!(w, "<div class='ghost'></div>")?;
3740 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3741 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3742 l, "goto source code")?;
3744 write!(w, "</td><td>")?;
3745 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3747 write!(w, "</td></tr></tbody></table></span></h4>")?;
3750 clean::TypedefItem(ref tydef, _) => {
3751 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3752 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3753 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3754 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3755 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3756 write!(w, "</code></span></h4>\n")?;
3758 clean::AssociatedConstItem(ref ty, ref default) => {
3759 let id = derive_id(format!("{}.{}", item_type, name));
3760 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3761 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3762 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3763 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3764 write!(w, "</code></span></h4>\n")?;
3766 clean::AssociatedTypeItem(ref bounds, ref default) => {
3767 let id = derive_id(format!("{}.{}", item_type, name));
3768 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3769 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3770 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3771 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3772 write!(w, "</code></span></h4>\n")?;
3774 clean::StrippedItem(..) => return Ok(()),
3775 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3778 if render_method_item || render_mode == RenderMode::Normal {
3779 let prefix = render_assoc_const_value(item);
3781 if !is_default_item {
3782 if let Some(t) = trait_ {
3783 // The trait item may have been stripped so we might not
3784 // find any documentation or stability for it.
3785 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3786 // We need the stability of the item from the trait
3787 // because impls can't have a stability.
3788 document_stability(w, cx, it)?;
3789 if item.doc_value().is_some() {
3790 document_full(w, item, cx, &prefix)?;
3791 } else if show_def_docs {
3792 // In case the item isn't documented,
3793 // provide short documentation from the trait.
3794 document_short(w, it, link, &prefix)?;
3798 document_stability(w, cx, item)?;
3800 document_full(w, item, cx, &prefix)?;
3804 document_stability(w, cx, item)?;
3806 document_short(w, item, link, &prefix)?;
3813 let traits = &cache().traits;
3814 let trait_ = i.trait_did().map(|did| &traits[&did]);
3817 write!(w, "<span class='docblock autohide'>")?;
3820 write!(w, "<div class='impl-items'>")?;
3821 for trait_item in &i.inner_impl().items {
3822 doc_impl_item(w, cx, trait_item, link, render_mode,
3823 false, outer_version, trait_, show_def_docs)?;
3826 fn render_default_items(w: &mut fmt::Formatter,
3830 render_mode: RenderMode,
3831 outer_version: Option<&str>,
3832 show_def_docs: bool) -> fmt::Result {
3833 for trait_item in &t.items {
3834 let n = trait_item.name.clone();
3835 if i.items.iter().find(|m| m.name == n).is_some() {
3838 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3839 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3841 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3842 outer_version, None, show_def_docs)?;
3847 // If we've implemented a trait, then also emit documentation for all
3848 // default items which weren't overridden in the implementation block.
3849 if let Some(t) = trait_ {
3850 render_default_items(w, cx, t, &i.inner_impl(),
3851 render_mode, outer_version, show_def_docs)?;
3853 write!(w, "</div>")?;
3856 write!(w, "</span>")?;
3862 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3863 t: &clean::Typedef) -> fmt::Result {
3864 write!(w, "<pre class='rust typedef'>")?;
3865 render_attributes(w, it)?;
3866 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3867 it.name.as_ref().unwrap(),
3869 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3872 document(w, cx, it)?;
3874 // Render any items associated directly to this alias, as otherwise they
3875 // won't be visible anywhere in the docs. It would be nice to also show
3876 // associated items from the aliased type (see discussion in #32077), but
3877 // we need #14072 to make sense of the generics.
3878 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3881 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3882 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3883 render_attributes(w, it)?;
3886 " {}type {};\n}}</pre>",
3887 VisSpace(&it.visibility),
3888 it.name.as_ref().unwrap(),
3891 document(w, cx, it)?;
3893 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3896 impl<'a> fmt::Display for Sidebar<'a> {
3897 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3900 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3902 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3903 || it.is_enum() || it.is_mod() || it.is_typedef() {
3904 write!(fmt, "<p class='location'>{}{}</p>",
3906 clean::StructItem(..) => "Struct ",
3907 clean::TraitItem(..) => "Trait ",
3908 clean::PrimitiveItem(..) => "Primitive Type ",
3909 clean::UnionItem(..) => "Union ",
3910 clean::EnumItem(..) => "Enum ",
3911 clean::TypedefItem(..) => "Type Definition ",
3912 clean::ForeignTypeItem => "Foreign Type ",
3913 clean::ModuleItem(..) => if it.is_crate() {
3920 it.name.as_ref().unwrap())?;
3924 if let Some(ref version) = cache().crate_version {
3926 "<div class='block version'>\
3929 <a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3931 it.name.as_ref().unwrap())?;
3935 write!(fmt, "<div class=\"sidebar-elems\">")?;
3937 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3938 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3939 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3940 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3941 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3942 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3943 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3944 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3948 // The sidebar is designed to display sibling functions, modules and
3949 // other miscellaneous information. since there are lots of sibling
3950 // items (and that causes quadratic growth in large modules),
3951 // we refactor common parts into a shared JavaScript file per module.
3952 // still, we don't move everything into JS because we want to preserve
3953 // as much HTML as possible in order to allow non-JS-enabled browsers
3954 // to navigate the documentation (though slightly inefficiently).
3956 write!(fmt, "<p class='location'>")?;
3957 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3959 write!(fmt, "::<wbr>")?;
3961 write!(fmt, "<a href='{}index.html'>{}</a>",
3962 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3965 write!(fmt, "</p>")?;
3967 // Sidebar refers to the enclosing module, not this module.
3968 let relpath = if it.is_mod() { "../" } else { "" };
3970 "<script>window.sidebarCurrent = {{\
3975 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3976 ty = it.type_().css_class(),
3979 // There is no sidebar-items.js beyond the crate root path
3980 // FIXME maybe dynamic crate loading can be merged here
3982 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3985 // Closes sidebar-elems div.
3986 write!(fmt, "</div>")?;
3992 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3993 i.items.iter().filter_map(|item| {
3995 // Maybe check with clean::Visibility::Public as well?
3996 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3997 if !for_deref || should_render_item(item, false) {
3998 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
4005 }).collect::<Vec<_>>()
4008 // The point is to url encode any potential character from a type with genericity.
4009 fn small_url_encode(s: &str) -> String {
4010 s.replace("<", "%3C")
4011 .replace(">", "%3E")
4012 .replace(" ", "%20")
4013 .replace("?", "%3F")
4014 .replace("'", "%27")
4015 .replace("&", "%26")
4016 .replace(",", "%2C")
4017 .replace(":", "%3A")
4018 .replace(";", "%3B")
4019 .replace("[", "%5B")
4020 .replace("]", "%5D")
4021 .replace("\"", "%22")
4024 fn sidebar_assoc_items(it: &clean::Item) -> String {
4025 let mut out = String::new();
4027 if let Some(v) = c.impls.get(&it.def_id) {
4029 .filter(|i| i.inner_impl().trait_.is_none())
4030 .flat_map(|i| get_methods(i.inner_impl(), false))
4031 .collect::<String>();
4032 if !ret.is_empty() {
4033 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4034 </a><div class=\"sidebar-links\">{}</div>", ret));
4037 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4038 if let Some(impl_) = v.iter()
4039 .filter(|i| i.inner_impl().trait_.is_some())
4040 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4041 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4043 clean::TypedefItem(ref t, true) => Some(&t.type_),
4047 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4048 c.primitive_locations.get(&prim).cloned()
4049 })).and_then(|did| c.impls.get(&did));
4050 if let Some(impls) = inner_impl {
4051 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4052 out.push_str(&format!("Methods from {}<Target={}>",
4053 Escape(&format!("{:#}",
4054 impl_.inner_impl().trait_.as_ref().unwrap())),
4055 Escape(&format!("{:#}", target))));
4056 out.push_str("</a>");
4057 let ret = impls.iter()
4058 .filter(|i| i.inner_impl().trait_.is_none())
4059 .flat_map(|i| get_methods(i.inner_impl(), true))
4060 .collect::<String>();
4061 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
4065 let format_impls = |impls: Vec<&Impl>| {
4066 let mut links = HashSet::new();
4069 let is_negative_impl = is_negative_impl(i.inner_impl());
4070 if let Some(ref i) = i.inner_impl().trait_ {
4071 let i_display = format!("{:#}", i);
4072 let out = Escape(&i_display);
4073 let encoded = small_url_encode(&format!("{:#}", i));
4074 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4076 if is_negative_impl { "!" } else { "" },
4078 if links.insert(generated.clone()) {
4087 .collect::<String>()
4090 let (synthetic, concrete) = v
4092 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4094 let concrete_format = format_impls(concrete);
4095 let synthetic_format = format_impls(synthetic);
4097 if !concrete_format.is_empty() {
4098 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4099 Trait Implementations</a>");
4100 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4103 if !synthetic_format.is_empty() {
4104 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4105 Auto Trait Implementations</a>");
4106 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4114 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4115 s: &clean::Struct) -> fmt::Result {
4116 let mut sidebar = String::new();
4117 let fields = get_struct_fields_name(&s.fields);
4119 if !fields.is_empty() {
4120 if let doctree::Plain = s.struct_type {
4121 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4122 <div class=\"sidebar-links\">{}</div>", fields));
4126 sidebar.push_str(&sidebar_assoc_items(it));
4128 if !sidebar.is_empty() {
4129 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4134 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4136 clean::ItemEnum::ImplItem(ref i) => {
4137 if let Some(ref trait_) = i.trait_ {
4138 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4147 fn is_negative_impl(i: &clean::Impl) -> bool {
4148 i.polarity == Some(clean::ImplPolarity::Negative)
4151 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4152 t: &clean::Trait) -> fmt::Result {
4153 let mut sidebar = String::new();
4159 Some(ref name) if m.is_associated_type() => {
4160 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4166 .collect::<String>();
4167 let consts = t.items
4171 Some(ref name) if m.is_associated_const() => {
4172 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4178 .collect::<String>();
4179 let required = t.items
4183 Some(ref name) if m.is_ty_method() => {
4184 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4190 .collect::<String>();
4191 let provided = t.items
4195 Some(ref name) if m.is_method() => {
4196 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
4201 .collect::<String>();
4203 if !types.is_empty() {
4204 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4205 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4208 if !consts.is_empty() {
4209 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4210 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4213 if !required.is_empty() {
4214 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4215 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4218 if !provided.is_empty() {
4219 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4220 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4226 if let Some(implementors) = c.implementors.get(&it.def_id) {
4227 let res = implementors.iter()
4228 .filter(|i| i.inner_impl().for_.def_id()
4229 .map_or(false, |d| !c.paths.contains_key(&d)))
4231 match extract_for_impl_name(&i.impl_item) {
4232 Some((ref name, ref url)) => {
4233 Some(format!("<a href=\"#impl-{}\">{}</a>",
4234 small_url_encode(url),
4240 .collect::<String>();
4241 if !res.is_empty() {
4242 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4243 Implementations on Foreign Types</a><div \
4244 class=\"sidebar-links\">{}</div>",
4249 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4251 sidebar.push_str("<a class=\"sidebar-title\" \
4252 href=\"#synthetic-implementors\">Auto Implementors</a>");
4255 sidebar.push_str(&sidebar_assoc_items(it));
4257 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4260 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4261 _p: &clean::PrimitiveType) -> fmt::Result {
4262 let sidebar = sidebar_assoc_items(it);
4264 if !sidebar.is_empty() {
4265 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4270 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4271 _t: &clean::Typedef) -> fmt::Result {
4272 let sidebar = sidebar_assoc_items(it);
4274 if !sidebar.is_empty() {
4275 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4280 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4282 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4287 .filter_map(|f| match f.name {
4288 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4289 {name}</a>", name=name)),
4295 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4296 u: &clean::Union) -> fmt::Result {
4297 let mut sidebar = String::new();
4298 let fields = get_struct_fields_name(&u.fields);
4300 if !fields.is_empty() {
4301 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4302 <div class=\"sidebar-links\">{}</div>", fields));
4305 sidebar.push_str(&sidebar_assoc_items(it));
4307 if !sidebar.is_empty() {
4308 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4313 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4314 e: &clean::Enum) -> fmt::Result {
4315 let mut sidebar = String::new();
4317 let variants = e.variants.iter()
4318 .filter_map(|v| match v.name {
4319 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4320 </a>", name = name)),
4323 .collect::<String>();
4324 if !variants.is_empty() {
4325 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4326 <div class=\"sidebar-links\">{}</div>", variants));
4329 sidebar.push_str(&sidebar_assoc_items(it));
4331 if !sidebar.is_empty() {
4332 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4337 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4338 items: &[clean::Item]) -> fmt::Result {
4339 let mut sidebar = String::new();
4341 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4342 it.type_() == ItemType::Import) {
4343 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4345 name = "Re-exports"));
4348 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4349 // to print its headings
4350 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4351 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4352 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4353 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4354 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4355 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4356 let (short, name) = match myty {
4357 ItemType::ExternCrate |
4358 ItemType::Import => ("reexports", "Re-exports"),
4359 ItemType::Module => ("modules", "Modules"),
4360 ItemType::Struct => ("structs", "Structs"),
4361 ItemType::Union => ("unions", "Unions"),
4362 ItemType::Enum => ("enums", "Enums"),
4363 ItemType::Function => ("functions", "Functions"),
4364 ItemType::Typedef => ("types", "Type Definitions"),
4365 ItemType::Static => ("statics", "Statics"),
4366 ItemType::Constant => ("constants", "Constants"),
4367 ItemType::Trait => ("traits", "Traits"),
4368 ItemType::Impl => ("impls", "Implementations"),
4369 ItemType::TyMethod => ("tymethods", "Type Methods"),
4370 ItemType::Method => ("methods", "Methods"),
4371 ItemType::StructField => ("fields", "Struct Fields"),
4372 ItemType::Variant => ("variants", "Variants"),
4373 ItemType::Macro => ("macros", "Macros"),
4374 ItemType::Primitive => ("primitives", "Primitive Types"),
4375 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4376 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4377 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4379 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4385 if !sidebar.is_empty() {
4386 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4391 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4392 let sidebar = sidebar_assoc_items(it);
4393 if !sidebar.is_empty() {
4394 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4399 impl<'a> fmt::Display for Source<'a> {
4400 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4401 let Source(s) = *self;
4402 let lines = s.lines().count();
4404 let mut tmp = lines;
4409 write!(fmt, "<pre class=\"line-numbers\">")?;
4410 for i in 1..lines + 1 {
4411 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4413 write!(fmt, "</pre>")?;
4415 highlight::render_with_highlighting(s, None, None, None, None))?;
4420 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4421 t: &clean::Macro) -> fmt::Result {
4422 wrap_into_docblock(w, |w| {
4423 w.write_str(&highlight::render_with_highlighting(&t.source,
4432 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4434 _p: &clean::PrimitiveType) -> fmt::Result {
4435 document(w, cx, it)?;
4436 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4439 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4441 fn make_item_keywords(it: &clean::Item) -> String {
4442 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4445 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4446 let decl = match item.inner {
4447 clean::FunctionItem(ref f) => &f.decl,
4448 clean::MethodItem(ref m) => &m.decl,
4449 clean::TyMethodItem(ref m) => &m.decl,
4453 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4454 let output = match decl.output {
4455 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4459 Some(IndexItemFunctionType { inputs: inputs, output: output })
4462 fn get_index_type(clean_type: &clean::Type) -> Type {
4464 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4465 generics: get_generics(clean_type),
4470 /// Returns a list of all paths used in the type.
4471 /// This is used to help deduplicate imported impls
4472 /// for reexported types. If any of the contained
4473 /// types are re-exported, we don't use the corresponding
4474 /// entry from the js file, as inlining will have already
4475 /// picked up the impl
4476 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4477 let mut out = Vec::new();
4478 let mut visited = FxHashSet();
4479 let mut work = VecDeque::new();
4480 let cache = cache();
4482 work.push_back(first_ty);
4484 while let Some(ty) = work.pop_front() {
4485 if !visited.insert(ty.clone()) {
4490 clean::Type::ResolvedPath { did, .. } => {
4491 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4492 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4496 out.push(path.join("::"));
4502 clean::Type::Tuple(tys) => {
4503 work.extend(tys.into_iter());
4505 clean::Type::Slice(ty) => {
4506 work.push_back(*ty);
4508 clean::Type::Array(ty, _) => {
4509 work.push_back(*ty);
4511 clean::Type::Unique(ty) => {
4512 work.push_back(*ty);
4514 clean::Type::RawPointer(_, ty) => {
4515 work.push_back(*ty);
4517 clean::Type::BorrowedRef { type_, .. } => {
4518 work.push_back(*type_);
4520 clean::Type::QPath { self_type, trait_, .. } => {
4521 work.push_back(*self_type);
4522 work.push_back(*trait_);
4530 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4532 clean::ResolvedPath { ref path, .. } => {
4533 let segments = &path.segments;
4534 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4535 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4536 clean_type, accept_generic
4538 Some(path_segment.name.clone())
4540 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4541 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4542 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4543 // FIXME: add all from clean::Type.
4548 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4549 clean_type.generics()
4551 let r = types.iter()
4552 .filter_map(|t| get_index_type_name(t, false))
4553 .map(|s| s.to_ascii_lowercase())
4554 .collect::<Vec<_>>();
4563 pub fn cache() -> Arc<Cache> {
4564 CACHE_KEY.with(|c| c.borrow().clone())
4569 fn test_unique_id() {
4570 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4571 "method.into_iter", "foo", "main", "search", "methods",
4572 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4573 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4574 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4575 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4578 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4579 assert_eq!(&actual[..], expected);
4588 fn test_name_key() {
4589 assert_eq!(name_key("0"), ("", 0, 1));
4590 assert_eq!(name_key("123"), ("", 123, 0));
4591 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4592 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4593 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4594 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4595 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4596 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4601 fn test_name_sorting() {
4602 let names = ["Apple",
4604 "Fruit", "Fruit0", "Fruit00",
4605 "Fruit1", "Fruit01",
4606 "Fruit2", "Fruit02",
4610 let mut sorted = names.to_owned();
4611 sorted.sort_by_key(|&s| name_key(s));
4612 assert_eq!(names, sorted);