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};
79 /// A pair of name and its optional document.
80 pub type NameDoc = (String, Option<String>);
82 /// Major driving force in all rustdoc rendering. This contains information
83 /// about where in the tree-like hierarchy rendering is occurring and controls
84 /// how the current page is being rendered.
86 /// It is intended that this context is a lightweight object which can be fairly
87 /// easily cloned because it is cloned per work-job (about once per item in the
91 /// Current hierarchy of components leading down to what's currently being
93 pub current: Vec<String>,
94 /// The current destination folder of where HTML artifacts should be placed.
95 /// This changes as the context descends into the module hierarchy.
97 /// A flag, which when `true`, will render pages which redirect to the
98 /// real location of an item. This is used to allow external links to
99 /// publicly reused items to redirect to the right location.
100 pub render_redirect_pages: bool,
101 pub shared: Arc<SharedContext>,
104 pub struct SharedContext {
105 /// The path to the crate root source minus the file name.
106 /// Used for simplifying paths to the highlighted source code files.
107 pub src_root: PathBuf,
108 /// This describes the layout of each page, and is not modified after
109 /// creation of the context (contains info like the favicon and added html).
110 pub layout: layout::Layout,
111 /// This flag indicates whether `[src]` links should be generated or not. If
112 /// the source files are present in the html rendering, then this will be
114 pub include_sources: bool,
115 /// The local file sources we've emitted and their respective url-paths.
116 pub local_sources: FxHashMap<PathBuf, String>,
117 /// All the passes that were run on this crate.
118 pub passes: FxHashSet<String>,
119 /// The base-URL of the issue tracker for when an item has been tagged with
121 pub issue_tracker_base_url: Option<String>,
122 /// The given user css file which allow to customize the generated
123 /// documentation theme.
124 pub css_file_extension: Option<PathBuf>,
125 /// The directories that have already been created in this doc run. Used to reduce the number
126 /// of spurious `create_dir_all` calls.
127 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
128 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
129 /// should be ordered alphabetically or in order of appearance (in the source code).
130 pub sort_modules_alphabetically: bool,
131 /// Additional themes to be added to the generated docs.
132 pub themes: Vec<PathBuf>,
133 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
135 pub resource_suffix: String,
139 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
140 let mut dirs = self.created_dirs.borrow_mut();
141 if !dirs.contains(dst) {
142 fs::create_dir_all(dst)?;
143 dirs.insert(dst.to_path_buf());
151 /// Returns whether the `collapse-docs` pass was run on this crate.
152 pub fn was_collapsed(&self) -> bool {
153 self.passes.contains("collapse-docs")
156 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
157 /// `collapsed_doc_value` of the given item.
158 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
159 if self.was_collapsed() {
160 item.collapsed_doc_value().map(|s| s.into())
162 item.doc_value().map(|s| s.into())
167 /// Indicates where an external crate can be found.
168 pub enum ExternalLocation {
169 /// Remote URL root of the external crate
171 /// This external crate can be found in the local doc/ folder
173 /// The external crate could not be found.
177 /// Metadata about implementations for a type or trait.
180 pub impl_item: clean::Item,
184 fn inner_impl(&self) -> &clean::Impl {
185 match self.impl_item.inner {
186 clean::ImplItem(ref impl_) => impl_,
187 _ => panic!("non-impl item found in impl")
191 fn trait_did(&self) -> Option<DefId> {
192 self.inner_impl().trait_.def_id()
202 impl error::Error for Error {
203 fn description(&self) -> &str {
204 self.error.description()
208 impl Display for Error {
209 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
210 write!(f, "\"{}\": {}", self.file.display(), self.error)
215 pub fn new(e: io::Error, file: &Path) -> Error {
217 file: file.to_path_buf(),
223 macro_rules! try_none {
224 ($e:expr, $file:expr) => ({
228 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
234 macro_rules! try_err {
235 ($e:expr, $file:expr) => ({
238 Err(e) => return Err(Error::new(e, $file)),
243 /// This cache is used to store information about the `clean::Crate` being
244 /// rendered in order to provide more useful documentation. This contains
245 /// information like all implementors of a trait, all traits a type implements,
246 /// documentation for all known traits, etc.
248 /// This structure purposefully does not implement `Clone` because it's intended
249 /// to be a fairly large and expensive structure to clone. Instead this adheres
250 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
251 /// rendering threads.
254 /// Mapping of typaram ids to the name of the type parameter. This is used
255 /// when pretty-printing a type (so pretty printing doesn't have to
256 /// painfully maintain a context like this)
257 pub typarams: FxHashMap<DefId, String>,
259 /// Maps a type id to all known implementations for that type. This is only
260 /// recognized for intra-crate `ResolvedPath` types, and is used to print
261 /// out extra documentation on the page of an enum/struct.
263 /// The values of the map are a list of implementations and documentation
264 /// found on that implementation.
265 pub impls: FxHashMap<DefId, Vec<Impl>>,
267 /// Maintains a mapping of local crate node ids to the fully qualified name
268 /// and "short type description" of that node. This is used when generating
269 /// URLs when a type is being linked to. External paths are not located in
270 /// this map because the `External` type itself has all the information
272 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
274 /// Similar to `paths`, but only holds external paths. This is only used for
275 /// generating explicit hyperlinks to other crates.
276 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
278 /// Maps local def ids of exported types to fully qualified paths.
279 /// Unlike 'paths', this mapping ignores any renames that occur
280 /// due to 'use' statements.
282 /// This map is used when writing out the special 'implementors'
283 /// javascript file. By using the exact path that the type
284 /// is declared with, we ensure that each path will be identical
285 /// to the path used if the corresponding type is inlined. By
286 /// doing this, we can detect duplicate impls on a trait page, and only display
287 /// the impl for the inlined type.
288 pub exact_paths: FxHashMap<DefId, Vec<String>>,
290 /// This map contains information about all known traits of this crate.
291 /// Implementations of a crate should inherit the documentation of the
292 /// parent trait if no extra documentation is specified, and default methods
293 /// should show up in documentation about trait implementations.
294 pub traits: FxHashMap<DefId, clean::Trait>,
296 /// When rendering traits, it's often useful to be able to list all
297 /// implementors of the trait, and this mapping is exactly, that: a mapping
298 /// of trait ids to the list of known implementors of the trait
299 pub implementors: FxHashMap<DefId, Vec<Impl>>,
301 /// Cache of where external crate documentation can be found.
302 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
304 /// Cache of where documentation for primitives can be found.
305 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
307 // Note that external items for which `doc(hidden)` applies to are shown as
308 // non-reachable while local items aren't. This is because we're reusing
309 // the access levels from crateanalysis.
310 pub access_levels: Arc<AccessLevels<DefId>>,
312 /// The version of the crate being documented, if given fron the `--crate-version` flag.
313 pub crate_version: Option<String>,
315 // Private fields only used when initially crawling a crate to build a cache
318 parent_stack: Vec<DefId>,
319 parent_is_trait_impl: bool,
320 search_index: Vec<IndexItem>,
322 deref_trait_did: Option<DefId>,
323 deref_mut_trait_did: Option<DefId>,
324 owned_box_did: Option<DefId>,
325 masked_crates: FxHashSet<CrateNum>,
327 // In rare case where a structure is defined in one module but implemented
328 // in another, if the implementing module is parsed before defining module,
329 // then the fully qualified name of the structure isn't presented in `paths`
330 // yet when its implementation methods are being indexed. Caches such methods
331 // and their parent id here and indexes them at the end of crate parsing.
332 orphan_impl_items: Vec<(DefId, clean::Item)>,
334 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
335 /// we need the alias element to have an array of items.
336 aliases: FxHashMap<String, Vec<IndexItem>>,
339 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
340 /// Later on moved into `CACHE_KEY`.
342 pub struct RenderInfo {
343 pub inlined: FxHashSet<DefId>,
344 pub external_paths: ::core::ExternalPaths,
345 pub external_typarams: FxHashMap<DefId, String>,
346 pub exact_paths: FxHashMap<DefId, Vec<String>>,
347 pub deref_trait_did: Option<DefId>,
348 pub deref_mut_trait_did: Option<DefId>,
349 pub owned_box_did: Option<DefId>,
352 /// Helper struct to render all source code to HTML pages
353 struct SourceCollector<'a> {
354 scx: &'a mut SharedContext,
356 /// Root destination to place all HTML output into
360 /// Wrapper struct to render the source code of a file. This will do things like
361 /// adding line numbers to the left-hand side.
362 struct Source<'a>(&'a str);
364 // Helper structs for rendering items/sidebars and carrying along contextual
367 #[derive(Copy, Clone)]
370 item: &'a clean::Item,
373 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
375 /// Struct representing one entry in the JS search index. These are all emitted
376 /// by hand to a large JS file at the end of cache-creation.
383 parent: Option<DefId>,
384 parent_idx: Option<usize>,
385 search_type: Option<IndexItemFunctionType>,
388 impl ToJson for IndexItem {
389 fn to_json(&self) -> Json {
390 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
392 let mut data = Vec::with_capacity(6);
393 data.push((self.ty as usize).to_json());
394 data.push(self.name.to_json());
395 data.push(self.path.to_json());
396 data.push(self.desc.to_json());
397 data.push(self.parent_idx.to_json());
398 data.push(self.search_type.to_json());
404 /// A type used for the search index.
407 name: Option<String>,
408 generics: Option<Vec<String>>,
411 impl ToJson for Type {
412 fn to_json(&self) -> Json {
415 let mut data = BTreeMap::new();
416 data.insert("n".to_owned(), name.to_json());
417 if let Some(ref generics) = self.generics {
418 data.insert("g".to_owned(), generics.to_json());
427 /// Full type of functions/methods in the search index.
429 struct IndexItemFunctionType {
431 output: Option<Type>,
434 impl ToJson for IndexItemFunctionType {
435 fn to_json(&self) -> Json {
436 // If we couldn't figure out a type, just write `null`.
437 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
440 let mut data = BTreeMap::new();
441 if !self.inputs.is_empty() {
442 data.insert("i".to_owned(), self.inputs.to_json());
444 if let Some(ref output) = self.output {
445 data.insert("o".to_owned(), output.to_json());
452 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
453 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
454 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
456 fn init_ids() -> FxHashMap<String, usize> {
468 "synthetic-implementors",
470 "synthetic-implementors-list",
474 ].into_iter().map(|id| (String::from(*id), 1)).collect()
477 /// This method resets the local table of used ID attributes. This is typically
478 /// used at the beginning of rendering an entire HTML page to reset from the
479 /// previous state (if any).
480 pub fn reset_ids(embedded: bool) {
481 USED_ID_MAP.with(|s| {
482 *s.borrow_mut() = if embedded {
490 pub fn derive_id(candidate: String) -> String {
491 USED_ID_MAP.with(|map| {
492 let id = match map.borrow_mut().get_mut(&candidate) {
495 let id = format!("{}-{}", candidate, *a);
501 map.borrow_mut().insert(id.clone(), 1);
506 /// Generates the documentation for `crate` into the directory `dst`
507 pub fn run(mut krate: clean::Crate,
508 external_html: &ExternalHtml,
509 playground_url: Option<String>,
511 resource_suffix: String,
512 passes: FxHashSet<String>,
513 css_file_extension: Option<PathBuf>,
514 renderinfo: RenderInfo,
515 sort_modules_alphabetically: bool,
516 themes: Vec<PathBuf>) -> Result<(), Error> {
517 let src_root = match krate.src {
518 FileName::Real(ref p) => match p.parent() {
519 Some(p) => p.to_path_buf(),
520 None => PathBuf::new(),
524 let mut scx = SharedContext {
527 include_sources: true,
528 local_sources: FxHashMap(),
529 issue_tracker_base_url: None,
530 layout: layout::Layout {
531 logo: "".to_string(),
532 favicon: "".to_string(),
533 external_html: external_html.clone(),
534 krate: krate.name.clone(),
536 css_file_extension: css_file_extension.clone(),
537 created_dirs: RefCell::new(FxHashSet()),
538 sort_modules_alphabetically,
543 // If user passed in `--playground-url` arg, we fill in crate name here
544 if let Some(url) = playground_url {
545 markdown::PLAYGROUND.with(|slot| {
546 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
550 // Crawl the crate attributes looking for attributes which control how we're
551 // going to emit HTML
552 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
553 for attr in attrs.lists("doc") {
554 let name = attr.name().map(|s| s.as_str());
555 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
556 (Some("html_favicon_url"), Some(s)) => {
557 scx.layout.favicon = s.to_string();
559 (Some("html_logo_url"), Some(s)) => {
560 scx.layout.logo = s.to_string();
562 (Some("html_playground_url"), Some(s)) => {
563 markdown::PLAYGROUND.with(|slot| {
564 let name = krate.name.clone();
565 *slot.borrow_mut() = Some((Some(name), s.to_string()));
568 (Some("issue_tracker_base_url"), Some(s)) => {
569 scx.issue_tracker_base_url = Some(s.to_string());
571 (Some("html_no_source"), None) if attr.is_word() => {
572 scx.include_sources = false;
578 try_err!(fs::create_dir_all(&dst), &dst);
579 krate = render_sources(&dst, &mut scx, krate)?;
583 render_redirect_pages: false,
584 shared: Arc::new(scx),
587 // Crawl the crate to build various caches used for the output
598 let external_paths = external_paths.into_iter()
599 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
602 let mut cache = Cache {
607 implementors: FxHashMap(),
609 parent_stack: Vec::new(),
610 search_index: Vec::new(),
611 parent_is_trait_impl: false,
612 extern_locations: FxHashMap(),
613 primitive_locations: FxHashMap(),
615 access_levels: krate.access_levels.clone(),
616 crate_version: krate.version.take(),
617 orphan_impl_items: Vec::new(),
618 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
622 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
623 typarams: external_typarams,
624 aliases: FxHashMap(),
627 // Cache where all our extern crates are located
628 for &(n, ref e) in &krate.externs {
629 let src_root = match e.src {
630 FileName::Real(ref p) => match p.parent() {
631 Some(p) => p.to_path_buf(),
632 None => PathBuf::new(),
636 cache.extern_locations.insert(n, (e.name.clone(), src_root,
637 extern_location(e, &cx.dst)));
639 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
640 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
643 // Cache where all known primitives have their documentation located.
645 // Favor linking to as local extern as possible, so iterate all crates in
646 // reverse topological order.
647 for &(_, ref e) in krate.externs.iter().rev() {
648 for &(def_id, prim, _) in &e.primitives {
649 cache.primitive_locations.insert(prim, def_id);
652 for &(def_id, prim, _) in &krate.primitives {
653 cache.primitive_locations.insert(prim, def_id);
656 cache.stack.push(krate.name.clone());
657 krate = cache.fold_crate(krate);
659 // Build our search index
660 let index = build_index(&krate, &mut cache);
662 // Freeze the cache now that the index has been built. Put an Arc into TLS
663 // for future parallelization opportunities
664 let cache = Arc::new(cache);
665 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
666 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
668 write_shared(&cx, &krate, &*cache, index)?;
670 // And finally render the whole crate's documentation
674 /// Build the search index from the collected metadata
675 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
676 let mut nodeid_to_pathid = FxHashMap();
677 let mut crate_items = Vec::with_capacity(cache.search_index.len());
678 let mut crate_paths = Vec::<Json>::new();
680 let Cache { ref mut search_index,
681 ref orphan_impl_items,
682 ref mut paths, .. } = *cache;
684 // Attach all orphan items to the type's definition if the type
685 // has since been learned.
686 for &(did, ref item) in orphan_impl_items {
687 if let Some(&(ref fqp, _)) = paths.get(&did) {
688 search_index.push(IndexItem {
690 name: item.name.clone().unwrap(),
691 path: fqp[..fqp.len() - 1].join("::"),
692 desc: plain_summary_line(item.doc_value()),
695 search_type: get_index_search_type(&item),
700 // Reduce `NodeId` in paths into smaller sequential numbers,
701 // and prune the paths that do not appear in the index.
702 let mut lastpath = String::new();
703 let mut lastpathid = 0usize;
705 for item in search_index {
706 item.parent_idx = item.parent.map(|nodeid| {
707 if nodeid_to_pathid.contains_key(&nodeid) {
708 *nodeid_to_pathid.get(&nodeid).unwrap()
710 let pathid = lastpathid;
711 nodeid_to_pathid.insert(nodeid, pathid);
714 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
715 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
720 // Omit the parent path if it is same to that of the prior item.
721 if lastpath == item.path {
724 lastpath = item.path.clone();
726 crate_items.push(item.to_json());
729 let crate_doc = krate.module.as_ref().map(|module| {
730 plain_summary_line(module.doc_value())
731 }).unwrap_or(String::new());
733 let mut crate_data = BTreeMap::new();
734 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
735 crate_data.insert("items".to_owned(), Json::Array(crate_items));
736 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
738 // Collect the index into a string
739 format!("searchIndex[{}] = {};",
740 as_json(&krate.name),
741 Json::Object(crate_data))
744 fn write_shared(cx: &Context,
745 krate: &clean::Crate,
747 search_index: String) -> 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");
797 function switchThemeButtonState() {{
798 if (themes.style.display === "block") {{
799 themes.style.display = "none";
800 themePicker.style.borderBottomRightRadius = "3px";
801 themePicker.style.borderBottomLeftRadius = "3px";
803 themes.style.display = "block";
804 themePicker.style.borderBottomRightRadius = "0";
805 themePicker.style.borderBottomLeftRadius = "0";
809 function handleThemeButtonsBlur(e) {{
810 var active = document.activeElement;
811 var related = e.relatedTarget;
813 if (active.id !== "themePicker" &&
814 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
816 (related.id !== "themePicker" &&
817 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
818 switchThemeButtonState();
822 themePicker.onclick = switchThemeButtonState;
823 themePicker.onblur = handleThemeButtonsBlur;
824 [{}].forEach(function(item) {{
825 var but = document.createElement('button');
826 but.innerHTML = item;
827 but.onclick = function(el) {{
828 switchTheme(currentTheme, mainTheme, item);
830 but.onblur = handleThemeButtonsBlur;
831 themes.appendChild(but);
834 .map(|s| format!("\"{}\"", s))
835 .collect::<Vec<String>>()
836 .join(",")).as_bytes(),
839 write(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
840 include_bytes!("static/main.js"))?;
841 write(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
842 include_bytes!("static/settings.js"))?;
845 let mut data = format!("var resourcesSuffix = \"{}\";\n",
846 cx.shared.resource_suffix).into_bytes();
847 data.extend_from_slice(include_bytes!("static/storage.js"));
848 write(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)), &data)?;
851 if let Some(ref css) = cx.shared.css_file_extension {
852 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
853 try_err!(fs::copy(css, out), css);
855 write(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
856 include_bytes!("static/normalize.css"))?;
857 write(cx.dst.join("FiraSans-Regular.woff"),
858 include_bytes!("static/FiraSans-Regular.woff"))?;
859 write(cx.dst.join("FiraSans-Medium.woff"),
860 include_bytes!("static/FiraSans-Medium.woff"))?;
861 write(cx.dst.join("FiraSans-LICENSE.txt"),
862 include_bytes!("static/FiraSans-LICENSE.txt"))?;
863 write(cx.dst.join("Heuristica-Italic.woff"),
864 include_bytes!("static/Heuristica-Italic.woff"))?;
865 write(cx.dst.join("Heuristica-LICENSE.txt"),
866 include_bytes!("static/Heuristica-LICENSE.txt"))?;
867 write(cx.dst.join("SourceSerifPro-Regular.woff"),
868 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
869 write(cx.dst.join("SourceSerifPro-Bold.woff"),
870 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
871 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
872 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
873 write(cx.dst.join("SourceCodePro-Regular.woff"),
874 include_bytes!("static/SourceCodePro-Regular.woff"))?;
875 write(cx.dst.join("SourceCodePro-Semibold.woff"),
876 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
877 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
878 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
879 write(cx.dst.join("LICENSE-MIT.txt"),
880 include_bytes!("static/LICENSE-MIT.txt"))?;
881 write(cx.dst.join("LICENSE-APACHE.txt"),
882 include_bytes!("static/LICENSE-APACHE.txt"))?;
883 write(cx.dst.join("COPYRIGHT.txt"),
884 include_bytes!("static/COPYRIGHT.txt"))?;
886 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<Vec<String>> {
887 let mut ret = Vec::new();
889 for line in BufReader::new(File::open(path)?).lines() {
891 if !line.starts_with(key) {
894 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
897 ret.push(line.to_string());
903 fn show_item(item: &IndexItem, krate: &str) -> String {
904 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
905 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
906 if let Some(p) = item.parent_idx {
907 format!(",'parent':{}", p)
913 let dst = cx.dst.join("aliases.js");
915 let mut all_aliases = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
916 let mut w = try_err!(File::create(&dst), &dst);
917 let mut output = String::with_capacity(100);
918 for (alias, items) in &cache.aliases {
919 if items.is_empty() {
922 output.push_str(&format!("\"{}\":[{}],",
925 .map(|v| show_item(v, &krate.name))
929 all_aliases.push(format!("ALIASES['{}'] = {{{}}};", krate.name, output));
931 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
932 for aliases in &all_aliases {
933 try_err!(writeln!(&mut w, "{}", aliases), &dst);
937 // Update the search index
938 let dst = cx.dst.join("search-index.js");
939 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
940 all_indexes.push(search_index);
941 // Sort the indexes by crate so the file will be generated identically even
942 // with rustdoc running in parallel.
944 let mut w = try_err!(File::create(&dst), &dst);
945 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
946 for index in &all_indexes {
947 try_err!(writeln!(&mut w, "{}", *index), &dst);
949 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
951 // Update the list of all implementors for traits
952 let dst = cx.dst.join("implementors");
953 for (&did, imps) in &cache.implementors {
954 // Private modules can leak through to this phase of rustdoc, which
955 // could contain implementations for otherwise private types. In some
956 // rare cases we could find an implementation for an item which wasn't
957 // indexed, so we just skip this step in that case.
959 // FIXME: this is a vague explanation for why this can't be a `get`, in
960 // theory it should be...
961 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
963 None => match cache.external_paths.get(&did) {
969 let mut have_impls = false;
970 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
972 // If the trait and implementation are in the same crate, then
973 // there's no need to emit information about it (there's inlining
974 // going on). If they're in different crates then the crate defining
975 // the trait will be interested in our implementation.
976 if imp.impl_item.def_id.krate == did.krate { continue }
977 // If the implementation is from another crate then that crate
979 if !imp.impl_item.def_id.is_local() { continue }
981 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
982 as_json(&imp.inner_impl().to_string()),
983 imp.inner_impl().synthetic,
984 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
986 implementors.push_str("];");
988 // Only create a js file if we have impls to add to it. If the trait is
989 // documented locally though we always create the file to avoid dead
991 if !have_impls && !cache.paths.contains_key(&did) {
995 let mut mydst = dst.clone();
996 for part in &remote_path[..remote_path.len() - 1] {
999 try_err!(fs::create_dir_all(&mydst), &mydst);
1000 mydst.push(&format!("{}.{}.js",
1001 remote_item_type.css_class(),
1002 remote_path[remote_path.len() - 1]));
1004 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1005 all_implementors.push(implementors);
1006 // Sort the implementors by crate so the file will be generated
1007 // identically even with rustdoc running in parallel.
1008 all_implementors.sort();
1010 let mut f = try_err!(File::create(&mydst), &mydst);
1011 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1012 for implementor in &all_implementors {
1013 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1015 try_err!(writeln!(&mut f, "{}", r"
1016 if (window.register_implementors) {
1017 window.register_implementors(implementors);
1019 window.pending_implementors = implementors;
1022 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1027 fn render_sources(dst: &Path, scx: &mut SharedContext,
1028 krate: clean::Crate) -> Result<clean::Crate, Error> {
1029 info!("emitting source files");
1030 let dst = dst.join("src").join(&krate.name);
1031 try_err!(fs::create_dir_all(&dst), &dst);
1032 let mut folder = SourceCollector {
1036 Ok(folder.fold_crate(krate))
1039 /// Writes the entire contents of a string to a destination, not attempting to
1040 /// catch any errors.
1041 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1042 Ok(try_err!(fs::write(&dst, contents), &dst))
1045 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1046 /// things like ".." to components which preserve the "top down" hierarchy of a
1047 /// static HTML tree. Each component in the cleaned path will be passed as an
1048 /// argument to `f`. The very last component of the path (ie the file name) will
1049 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1050 // FIXME (#9639): The closure should deal with &[u8] instead of &str
1051 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
1052 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1055 // make it relative, if possible
1056 let p = p.strip_prefix(src_root).unwrap_or(p);
1058 let mut iter = p.components().peekable();
1060 while let Some(c) = iter.next() {
1061 if !keep_filename && iter.peek().is_none() {
1066 Component::ParentDir => f("up"),
1067 Component::Normal(c) => f(c.to_str().unwrap()),
1073 /// Attempts to find where an external crate is located, given that we're
1074 /// rendering in to the specified source destination.
1075 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
1076 // See if there's documentation generated into the local directory
1077 let local_location = dst.join(&e.name);
1078 if local_location.is_dir() {
1082 // Failing that, see if there's an attribute specifying where to find this
1084 e.attrs.lists("doc")
1085 .filter(|a| a.check_name("html_root_url"))
1086 .filter_map(|a| a.value_str())
1088 let mut url = url.to_string();
1089 if !url.ends_with("/") {
1093 }).next().unwrap_or(Unknown) // Well, at least we tried.
1096 impl<'a> DocFolder for SourceCollector<'a> {
1097 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1098 // If we're including source files, and we haven't seen this file yet,
1099 // then we need to render it out to the filesystem.
1100 if self.scx.include_sources
1101 // skip all invalid or macro spans
1102 && item.source.filename.is_real()
1103 // skip non-local items
1104 && item.def_id.is_local() {
1106 // If it turns out that we couldn't read this file, then we probably
1107 // can't read any of the files (generating html output from json or
1108 // something like that), so just don't include sources for the
1109 // entire crate. The other option is maintaining this mapping on a
1110 // per-file basis, but that's probably not worth it...
1112 .include_sources = match self.emit_source(&item.source.filename) {
1115 println!("warning: source code was requested to be rendered, \
1116 but processing `{}` had an error: {}",
1117 item.source.filename, e);
1118 println!(" skipping rendering of source code");
1123 self.fold_item_recur(item)
1127 impl<'a> SourceCollector<'a> {
1128 /// Renders the given filename into its corresponding HTML source file.
1129 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1130 let p = match *filename {
1131 FileName::Real(ref file) => file,
1134 if self.scx.local_sources.contains_key(&**p) {
1135 // We've already emitted this source
1139 let contents = fs::read_to_string(&p)?;
1141 // Remove the utf-8 BOM if any
1142 let contents = if contents.starts_with("\u{feff}") {
1148 // Create the intermediate directories
1149 let mut cur = self.dst.clone();
1150 let mut root_path = String::from("../../");
1151 let mut href = String::new();
1152 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1153 cur.push(component);
1154 fs::create_dir_all(&cur).unwrap();
1155 root_path.push_str("../");
1156 href.push_str(component);
1159 let mut fname = p.file_name()
1160 .expect("source has no filename")
1162 fname.push(".html");
1164 href.push_str(&fname.to_string_lossy());
1166 let mut w = BufWriter::new(File::create(&cur)?);
1167 let title = format!("{} -- source", cur.file_name().unwrap()
1168 .to_string_lossy());
1169 let desc = format!("Source to the Rust file `{}`.", filename);
1170 let page = layout::Page {
1172 css_class: "source",
1173 root_path: &root_path,
1175 keywords: BASIC_KEYWORDS,
1176 resource_suffix: &self.scx.resource_suffix,
1178 layout::render(&mut w, &self.scx.layout,
1179 &page, &(""), &Source(contents),
1180 self.scx.css_file_extension.is_some(),
1183 self.scx.local_sources.insert(p.clone(), href);
1188 impl DocFolder for Cache {
1189 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1190 // If this is a stripped module,
1191 // we don't want it or its children in the search index.
1192 let orig_stripped_mod = match item.inner {
1193 clean::StrippedItem(box clean::ModuleItem(..)) => {
1194 mem::replace(&mut self.stripped_mod, true)
1196 _ => self.stripped_mod,
1199 // If the impl is from a masked crate or references something from a
1200 // masked crate then remove it completely.
1201 if let clean::ImplItem(ref i) = item.inner {
1202 if self.masked_crates.contains(&item.def_id.krate) ||
1203 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1204 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1209 // Register any generics to their corresponding string. This is used
1210 // when pretty-printing types.
1211 if let Some(generics) = item.inner.generics() {
1212 self.generics(generics);
1215 // Propagate a trait method's documentation to all implementors of the
1217 if let clean::TraitItem(ref t) = item.inner {
1218 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1221 // Collect all the implementors of traits.
1222 if let clean::ImplItem(ref i) = item.inner {
1223 if let Some(did) = i.trait_.def_id() {
1224 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1225 impl_item: item.clone(),
1230 // Index this method for searching later on.
1231 if let Some(ref s) = item.name {
1232 let (parent, is_inherent_impl_item) = match item.inner {
1233 clean::StrippedItem(..) => ((None, None), false),
1234 clean::AssociatedConstItem(..) |
1235 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1236 // skip associated items in trait impls
1237 ((None, None), false)
1239 clean::AssociatedTypeItem(..) |
1240 clean::TyMethodItem(..) |
1241 clean::StructFieldItem(..) |
1242 clean::VariantItem(..) => {
1243 ((Some(*self.parent_stack.last().unwrap()),
1244 Some(&self.stack[..self.stack.len() - 1])),
1247 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1248 if self.parent_stack.is_empty() {
1249 ((None, None), false)
1251 let last = self.parent_stack.last().unwrap();
1253 let path = match self.paths.get(&did) {
1254 // The current stack not necessarily has correlation
1255 // for where the type was defined. On the other
1256 // hand, `paths` always has the right
1257 // information if present.
1258 Some(&(ref fqp, ItemType::Trait)) |
1259 Some(&(ref fqp, ItemType::Struct)) |
1260 Some(&(ref fqp, ItemType::Union)) |
1261 Some(&(ref fqp, ItemType::Enum)) =>
1262 Some(&fqp[..fqp.len() - 1]),
1263 Some(..) => Some(&*self.stack),
1266 ((Some(*last), path), true)
1269 _ => ((None, Some(&*self.stack)), false)
1273 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1274 debug_assert!(!item.is_stripped());
1276 // A crate has a module at its root, containing all items,
1277 // which should not be indexed. The crate-item itself is
1278 // inserted later on when serializing the search-index.
1279 if item.def_id.index != CRATE_DEF_INDEX {
1280 self.search_index.push(IndexItem {
1282 name: s.to_string(),
1283 path: path.join("::").to_string(),
1284 desc: plain_summary_line(item.doc_value()),
1287 search_type: get_index_search_type(&item),
1291 (Some(parent), None) if is_inherent_impl_item => {
1292 // We have a parent, but we don't know where they're
1293 // defined yet. Wait for later to index this item.
1294 self.orphan_impl_items.push((parent, item.clone()));
1300 // Keep track of the fully qualified path for this item.
1301 let pushed = match item.name {
1302 Some(ref n) if !n.is_empty() => {
1303 self.stack.push(n.to_string());
1310 clean::StructItem(..) | clean::EnumItem(..) |
1311 clean::TypedefItem(..) | clean::TraitItem(..) |
1312 clean::FunctionItem(..) | clean::ModuleItem(..) |
1313 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1314 clean::ConstantItem(..) | clean::StaticItem(..) |
1315 clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1316 if !self.stripped_mod => {
1317 // Re-exported items mean that the same id can show up twice
1318 // in the rustdoc ast that we're looking at. We know,
1319 // however, that a re-exported item doesn't show up in the
1320 // `public_items` map, so we can skip inserting into the
1321 // paths map if there was already an entry present and we're
1322 // not a public item.
1323 if !self.paths.contains_key(&item.def_id) ||
1324 self.access_levels.is_public(item.def_id)
1326 self.paths.insert(item.def_id,
1327 (self.stack.clone(), item.type_()));
1329 self.add_aliases(&item);
1331 // Link variants to their parent enum because pages aren't emitted
1332 // for each variant.
1333 clean::VariantItem(..) if !self.stripped_mod => {
1334 let mut stack = self.stack.clone();
1336 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1339 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1340 self.add_aliases(&item);
1341 self.paths.insert(item.def_id, (self.stack.clone(),
1348 // Maintain the parent stack
1349 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1350 let parent_pushed = match item.inner {
1351 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1352 clean::StructItem(..) | clean::UnionItem(..) => {
1353 self.parent_stack.push(item.def_id);
1354 self.parent_is_trait_impl = false;
1357 clean::ImplItem(ref i) => {
1358 self.parent_is_trait_impl = i.trait_.is_some();
1360 clean::ResolvedPath{ did, .. } => {
1361 self.parent_stack.push(did);
1365 let prim_did = t.primitive_type().and_then(|t| {
1366 self.primitive_locations.get(&t).cloned()
1370 self.parent_stack.push(did);
1381 // Once we've recursively found all the generics, hoard off all the
1382 // implementations elsewhere.
1383 let ret = self.fold_item_recur(item).and_then(|item| {
1384 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1385 // Figure out the id of this impl. This may map to a
1386 // primitive rather than always to a struct/enum.
1387 // Note: matching twice to restrict the lifetime of the `i` borrow.
1388 let mut dids = FxHashSet();
1389 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1391 clean::ResolvedPath { did, .. } |
1392 clean::BorrowedRef {
1393 type_: box clean::ResolvedPath { did, .. }, ..
1398 let did = t.primitive_type().and_then(|t| {
1399 self.primitive_locations.get(&t).cloned()
1402 if let Some(did) = did {
1408 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1409 for bound in generics {
1410 if let Some(did) = bound.def_id() {
1419 self.impls.entry(did).or_insert(vec![]).push(Impl {
1420 impl_item: item.clone(),
1429 if pushed { self.stack.pop().unwrap(); }
1430 if parent_pushed { self.parent_stack.pop().unwrap(); }
1431 self.stripped_mod = orig_stripped_mod;
1432 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1438 fn generics(&mut self, generics: &clean::Generics) {
1439 for param in &generics.params {
1440 if let clean::GenericParam::Type(ref typ) = *param {
1441 self.typarams.insert(typ.did, typ.name.clone());
1446 fn add_aliases(&mut self, item: &clean::Item) {
1447 if item.def_id.index == CRATE_DEF_INDEX {
1450 if let Some(ref item_name) = item.name {
1451 let path = self.paths.get(&item.def_id)
1452 .map(|p| p.0[..p.0.len() - 1].join("::"))
1453 .unwrap_or("std".to_owned());
1454 for alias in item.attrs.lists("doc")
1455 .filter(|a| a.check_name("alias"))
1456 .filter_map(|a| a.value_str()
1457 .map(|s| s.to_string().replace("\"", "")))
1458 .filter(|v| !v.is_empty())
1459 .collect::<FxHashSet<_>>()
1461 self.aliases.entry(alias)
1462 .or_insert(Vec::with_capacity(1))
1465 name: item_name.to_string(),
1467 desc: plain_summary_line(item.doc_value()),
1470 search_type: get_index_search_type(&item),
1477 #[derive(Debug, Eq, PartialEq, Hash)]
1484 fn new(mut url: String, name: String) -> ItemEntry {
1485 while url.starts_with('/') {
1495 impl fmt::Display for ItemEntry {
1496 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1497 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1501 impl PartialOrd for ItemEntry {
1502 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1503 Some(self.cmp(other))
1507 impl Ord for ItemEntry {
1508 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1509 self.name.cmp(&other.name)
1515 structs: HashSet<ItemEntry>,
1516 enums: HashSet<ItemEntry>,
1517 unions: HashSet<ItemEntry>,
1518 primitives: HashSet<ItemEntry>,
1519 traits: HashSet<ItemEntry>,
1520 macros: HashSet<ItemEntry>,
1521 functions: HashSet<ItemEntry>,
1522 typedefs: HashSet<ItemEntry>,
1523 statics: HashSet<ItemEntry>,
1524 constants: HashSet<ItemEntry>,
1528 fn new() -> AllTypes {
1530 structs: HashSet::with_capacity(100),
1531 enums: HashSet::with_capacity(100),
1532 unions: HashSet::with_capacity(100),
1533 primitives: HashSet::with_capacity(26),
1534 traits: HashSet::with_capacity(100),
1535 macros: HashSet::with_capacity(100),
1536 functions: HashSet::with_capacity(100),
1537 typedefs: HashSet::with_capacity(100),
1538 statics: HashSet::with_capacity(100),
1539 constants: HashSet::with_capacity(100),
1543 fn append(&mut self, item_name: String, item_type: &ItemType) {
1544 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1545 if let Some(name) = url.pop() {
1546 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1548 let name = url.join("::");
1550 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1551 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1552 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1553 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1554 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1555 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1556 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1557 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1558 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1559 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1566 fn print_entries(f: &mut fmt::Formatter, e: &HashSet<ItemEntry>, title: &str,
1567 class: &str) -> fmt::Result {
1569 let mut e: Vec<&ItemEntry> = e.iter().collect();
1571 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1575 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1580 impl fmt::Display for AllTypes {
1581 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1584 <span class='in-band'>List of all items</span>\
1585 <span class='out-of-band'>\
1586 <span id='render-detail'>\
1587 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1588 [<span class='inner'>−</span>]\
1593 print_entries(f, &self.structs, "Structs", "structs")?;
1594 print_entries(f, &self.enums, "Enums", "enums")?;
1595 print_entries(f, &self.unions, "Unions", "unions")?;
1596 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1597 print_entries(f, &self.traits, "Traits", "traits")?;
1598 print_entries(f, &self.macros, "Macros", "macros")?;
1599 print_entries(f, &self.functions, "Functions", "functions")?;
1600 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1601 print_entries(f, &self.statics, "Statics", "statics")?;
1602 print_entries(f, &self.constants, "Constants", "constants")
1607 struct Settings<'a> {
1608 // (id, explanation, default value)
1609 settings: Vec<(&'static str, &'static str, bool)>,
1614 impl<'a> Settings<'a> {
1615 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1618 ("item-declarations", "Auto-hide item declarations.", true),
1619 ("item-attributes", "Auto-hide item attributes.", true),
1620 ("go-to-only-result", "Directly go to item in search if there is only one result",
1629 impl<'a> fmt::Display for Settings<'a> {
1630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1633 <span class='in-band'>Rustdoc settings</span>\
1635 <div class='settings'>{}</div>\
1636 <script src='{}settings{}.js'></script>",
1637 self.settings.iter()
1638 .map(|(id, text, enabled)| {
1639 format!("<div class='setting-line'>\
1640 <label class='toggle'>\
1641 <input type='checkbox' id='{}' {}>\
1642 <span class='slider'></span>\
1645 </div>", id, if *enabled { " checked" } else { "" }, text)
1647 .collect::<String>(),
1654 /// String representation of how to get back to the root path of the 'doc/'
1655 /// folder in terms of a relative URL.
1656 fn root_path(&self) -> String {
1657 repeat("../").take(self.current.len()).collect::<String>()
1660 /// Recurse in the directory structure and change the "root path" to make
1661 /// sure it always points to the top (relatively).
1662 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1663 F: FnOnce(&mut Context) -> T,
1666 panic!("Unexpected empty destination: {:?}", self.current);
1668 let prev = self.dst.clone();
1670 self.current.push(s);
1672 info!("Recursing into {}", self.dst.display());
1676 info!("Recursed; leaving {}", self.dst.display());
1678 // Go back to where we were at
1680 self.current.pop().unwrap();
1685 /// Main method for rendering a crate.
1687 /// This currently isn't parallelized, but it'd be pretty easy to add
1688 /// parallelization to this function.
1689 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1690 let mut item = match krate.module.take() {
1692 None => return Ok(()),
1694 let final_file = self.dst.join(&krate.name)
1696 let settings_file = self.dst.join("settings.html");
1698 let crate_name = krate.name.clone();
1699 item.name = Some(krate.name);
1701 let mut all = AllTypes::new();
1704 // Render the crate documentation
1705 let mut work = vec![(self.clone(), item)];
1707 while let Some((mut cx, item)) = work.pop() {
1708 cx.item(item, &mut all, |cx, item| {
1709 work.push((cx.clone(), item))
1714 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
1715 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1716 if !root_path.ends_with('/') {
1717 root_path.push('/');
1719 let mut page = layout::Page {
1720 title: "List of all items in this crate",
1723 description: "List of all items in this crate",
1724 keywords: BASIC_KEYWORDS,
1725 resource_suffix: &self.shared.resource_suffix,
1727 let sidebar = if let Some(ref version) = cache().crate_version {
1728 format!("<p class='location'>Crate {}</p>\
1729 <div class='block version'>\
1732 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1733 crate_name, version)
1737 try_err!(layout::render(&mut w, &self.shared.layout,
1738 &page, &sidebar, &all,
1739 self.shared.css_file_extension.is_some(),
1740 &self.shared.themes),
1743 // Generating settings page.
1744 let settings = Settings::new("./", &self.shared.resource_suffix);
1745 page.title = "Rustdoc settings";
1746 page.description = "Settings of Rustdoc";
1747 page.root_path = "./";
1749 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
1750 let mut themes = self.shared.themes.clone();
1751 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1752 themes.push(PathBuf::from("settings.css"));
1753 let mut layout = self.shared.layout.clone();
1754 layout.krate = String::new();
1755 layout.logo = String::new();
1756 layout.favicon = String::new();
1757 try_err!(layout::render(&mut w, &layout,
1758 &page, &sidebar, &settings,
1759 self.shared.css_file_extension.is_some(),
1766 fn render_item(&self,
1767 writer: &mut io::Write,
1771 // A little unfortunate that this is done like this, but it sure
1772 // does make formatting *a lot* nicer.
1773 CURRENT_LOCATION_KEY.with(|slot| {
1774 *slot.borrow_mut() = self.current.clone();
1777 let mut title = if it.is_primitive() {
1778 // No need to include the namespace for primitive types
1781 self.current.join("::")
1784 if !title.is_empty() {
1785 title.push_str("::");
1787 title.push_str(it.name.as_ref().unwrap());
1789 title.push_str(" - Rust");
1790 let tyname = it.type_().css_class();
1791 let desc = if it.is_crate() {
1792 format!("API documentation for the Rust `{}` crate.",
1793 self.shared.layout.krate)
1795 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1796 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1798 let keywords = make_item_keywords(it);
1799 let page = layout::Page {
1801 root_path: &self.root_path(),
1804 keywords: &keywords,
1805 resource_suffix: &self.shared.resource_suffix,
1810 if !self.render_redirect_pages {
1811 layout::render(writer, &self.shared.layout, &page,
1812 &Sidebar{ cx: self, item: it },
1813 &Item{ cx: self, item: it },
1814 self.shared.css_file_extension.is_some(),
1815 &self.shared.themes)?;
1817 let mut url = self.root_path();
1818 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1819 for name in &names[..names.len() - 1] {
1823 url.push_str(&item_path(ty, names.last().unwrap()));
1824 layout::redirect(writer, &url)?;
1830 /// Non-parallelized version of rendering an item. This will take the input
1831 /// item, render its contents, and then invoke the specified closure with
1832 /// all sub-items which need to be rendered.
1834 /// The rendering driver uses this closure to queue up more work.
1835 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
1836 where F: FnMut(&mut Context, clean::Item),
1838 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1839 // if they contain impls for public types. These modules can also
1840 // contain items such as publicly re-exported structures.
1842 // External crates will provide links to these structures, so
1843 // these modules are recursed into, but not rendered normally
1844 // (a flag on the context).
1845 if !self.render_redirect_pages {
1846 self.render_redirect_pages = item.is_stripped();
1850 // modules are special because they add a namespace. We also need to
1851 // recurse into the items of the module as well.
1852 let name = item.name.as_ref().unwrap().to_string();
1853 let mut item = Some(item);
1854 self.recurse(name, |this| {
1855 let item = item.take().unwrap();
1857 let mut buf = Vec::new();
1858 this.render_item(&mut buf, &item, false).unwrap();
1859 // buf will be empty if the module is stripped and there is no redirect for it
1860 if !buf.is_empty() {
1861 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1862 let joint_dst = this.dst.join("index.html");
1863 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1864 try_err!(dst.write_all(&buf), &joint_dst);
1867 let m = match item.inner {
1868 clean::StrippedItem(box clean::ModuleItem(m)) |
1869 clean::ModuleItem(m) => m,
1873 // Render sidebar-items.js used throughout this module.
1874 if !this.render_redirect_pages {
1875 let items = this.build_sidebar_items(&m);
1876 let js_dst = this.dst.join("sidebar-items.js");
1877 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1878 try_err!(write!(&mut js_out, "initSidebarItems({});",
1879 as_json(&items)), &js_dst);
1882 for item in m.items {
1888 } else if item.name.is_some() {
1889 let mut buf = Vec::new();
1890 self.render_item(&mut buf, &item, true).unwrap();
1891 // buf will be empty if the item is stripped and there is no redirect for it
1892 if !buf.is_empty() {
1893 let name = item.name.as_ref().unwrap();
1894 let item_type = item.type_();
1895 let file_name = &item_path(item_type, name);
1896 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1897 let joint_dst = self.dst.join(file_name);
1898 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1899 try_err!(dst.write_all(&buf), &joint_dst);
1901 if !self.render_redirect_pages {
1902 all.append(full_path(self, &item), &item_type);
1904 // Redirect from a sane URL using the namespace to Rustdoc's
1905 // URL for the page.
1906 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1907 let redir_dst = self.dst.join(redir_name);
1908 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1911 let mut redirect_out = BufWriter::new(redirect_out);
1912 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1915 // If the item is a macro, redirect from the old macro URL (with !)
1916 // to the new one (without).
1917 // FIXME(#35705) remove this redirect.
1918 if item_type == ItemType::Macro {
1919 let redir_name = format!("{}.{}!.html", item_type, name);
1920 let redir_dst = self.dst.join(redir_name);
1921 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1922 let mut redirect_out = BufWriter::new(redirect_out);
1923 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1930 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1931 // BTreeMap instead of HashMap to get a sorted output
1932 let mut map = BTreeMap::new();
1933 for item in &m.items {
1934 if item.is_stripped() { continue }
1936 let short = item.type_().css_class();
1937 let myname = match item.name {
1939 Some(ref s) => s.to_string(),
1941 let short = short.to_string();
1942 map.entry(short).or_insert(vec![])
1943 .push((myname, Some(plain_summary_line(item.doc_value()))));
1946 if self.shared.sort_modules_alphabetically {
1947 for (_, items) in &mut map {
1956 /// Generate a url appropriate for an `href` attribute back to the source of
1959 /// The url generated, when clicked, will redirect the browser back to the
1960 /// original source code.
1962 /// If `None` is returned, then a source link couldn't be generated. This
1963 /// may happen, for example, with externally inlined items where the source
1964 /// of their crate documentation isn't known.
1965 fn src_href(&self) -> Option<String> {
1966 let mut root = self.cx.root_path();
1968 let cache = cache();
1969 let mut path = String::new();
1971 // We can safely ignore macros from other libraries
1972 let file = match self.item.source.filename {
1973 FileName::Real(ref path) => path,
1977 let (krate, path) = if self.item.def_id.is_local() {
1978 if let Some(path) = self.cx.shared.local_sources.get(file) {
1979 (&self.cx.shared.layout.krate, path)
1984 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1985 Some(&(ref name, ref src, Local)) => (name, src),
1986 Some(&(ref name, ref src, Remote(ref s))) => {
1987 root = s.to_string();
1990 Some(&(_, _, Unknown)) | None => return None,
1993 clean_srcpath(&src_root, file, false, |component| {
1994 path.push_str(component);
1997 let mut fname = file.file_name().expect("source has no filename")
1999 fname.push(".html");
2000 path.push_str(&fname.to_string_lossy());
2004 let lines = if self.item.source.loline == self.item.source.hiline {
2005 format!("{}", self.item.source.loline)
2007 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2009 Some(format!("{root}src/{krate}/{path}#{lines}",
2010 root = Escape(&root),
2017 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2018 f: F) -> fmt::Result
2019 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2020 write!(w, "<div class=\"docblock type-decl\">")?;
2025 impl<'a> fmt::Display for Item<'a> {
2026 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2027 debug_assert!(!self.item.is_stripped());
2028 // Write the breadcrumb trail header for the top
2029 write!(fmt, "<h1 class='fqn'><span class='in-band'>")?;
2030 match self.item.inner {
2031 clean::ModuleItem(ref m) => if m.is_crate {
2032 write!(fmt, "Crate ")?;
2034 write!(fmt, "Module ")?;
2036 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2037 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2038 clean::StructItem(..) => write!(fmt, "Struct ")?,
2039 clean::UnionItem(..) => write!(fmt, "Union ")?,
2040 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2041 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2042 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2043 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2044 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2045 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2046 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2048 // We don't generate pages for any other type.
2052 if !self.item.is_primitive() {
2053 let cur = &self.cx.current;
2054 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2055 for (i, component) in cur.iter().enumerate().take(amt) {
2056 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2057 repeat("../").take(cur.len() - i - 1)
2058 .collect::<String>(),
2062 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2063 self.item.type_(), self.item.name.as_ref().unwrap())?;
2065 write!(fmt, "</span>")?; // in-band
2066 write!(fmt, "<span class='out-of-band'>")?;
2067 if let Some(version) = self.item.stable_since() {
2068 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2072 "<span id='render-detail'>\
2073 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2074 title=\"collapse all docs\">\
2075 [<span class='inner'>−</span>]\
2081 // When this item is part of a `pub use` in a downstream crate, the
2082 // [src] link in the downstream documentation will actually come back to
2083 // this page, and this link will be auto-clicked. The `id` attribute is
2084 // used to find the link to auto-click.
2085 if self.cx.shared.include_sources && !self.item.is_primitive() {
2086 if let Some(l) = self.src_href() {
2087 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2088 l, "goto source code")?;
2092 write!(fmt, "</span></h1>")?; // out-of-band
2094 match self.item.inner {
2095 clean::ModuleItem(ref m) =>
2096 item_module(fmt, self.cx, self.item, &m.items),
2097 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2098 item_function(fmt, self.cx, self.item, f),
2099 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2100 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2101 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2102 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2103 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2104 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2105 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2106 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2107 item_static(fmt, self.cx, self.item, i),
2108 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2109 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2111 // We don't generate pages for any other type.
2118 fn item_path(ty: ItemType, name: &str) -> String {
2120 ItemType::Module => format!("{}/index.html", name),
2121 _ => format!("{}.{}.html", ty.css_class(), name),
2125 fn full_path(cx: &Context, item: &clean::Item) -> String {
2126 let mut s = cx.current.join("::");
2128 s.push_str(item.name.as_ref().unwrap());
2132 fn shorter<'a>(s: Option<&'a str>) -> String {
2134 Some(s) => s.lines()
2135 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2137 (*line).chars().any(|chr|{
2138 !chr.is_whitespace()
2140 }).collect::<Vec<_>>().join("\n"),
2141 None => "".to_string()
2146 fn plain_summary_line(s: Option<&str>) -> String {
2147 let line = shorter(s).replace("\n", " ");
2148 markdown::plain_summary_line(&line[..])
2151 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2152 if let Some(ref name) = item.name {
2153 info!("Documenting {}", name);
2155 document_stability(w, cx, item)?;
2156 let prefix = render_assoc_const_value(item);
2157 document_full(w, item, cx, &prefix)?;
2161 /// Render md_text as markdown.
2162 fn render_markdown(w: &mut fmt::Formatter,
2164 links: Vec<(String, String)>,
2167 write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
2170 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
2171 prefix: &str) -> fmt::Result {
2172 if let Some(s) = item.doc_value() {
2173 let markdown = if s.contains('\n') {
2174 format!("{} [Read more]({})",
2175 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2177 format!("{}", &plain_summary_line(Some(s)))
2179 render_markdown(w, &markdown, item.links(), prefix)?;
2180 } else if !prefix.is_empty() {
2181 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2186 fn render_assoc_const_value(item: &clean::Item) -> String {
2188 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
2189 highlight::render_with_highlighting(
2190 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
2201 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2202 cx: &Context, prefix: &str) -> fmt::Result {
2203 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2204 debug!("Doc block: =====\n{}\n=====", s);
2205 render_markdown(w, &*s, item.links(), prefix)?;
2206 } else if !prefix.is_empty() {
2207 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2212 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2213 let stabilities = short_stability(item, cx, true);
2214 if !stabilities.is_empty() {
2215 write!(w, "<div class='stability'>")?;
2216 for stability in stabilities {
2217 write!(w, "{}", stability)?;
2219 write!(w, "</div>")?;
2224 fn name_key(name: &str) -> (&str, u64, usize) {
2225 // find number at end
2226 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
2228 // count leading zeroes
2230 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2232 // sort leading zeroes last
2233 let num_zeroes = after_zeroes - split;
2235 match name[split..].parse() {
2236 Ok(n) => (&name[..split], n, num_zeroes),
2237 Err(_) => (name, 0, num_zeroes),
2241 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2242 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2243 document(w, cx, item)?;
2245 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2247 // the order of item types in the listing
2248 fn reorder(ty: ItemType) -> u8 {
2250 ItemType::ExternCrate => 0,
2251 ItemType::Import => 1,
2252 ItemType::Primitive => 2,
2253 ItemType::Module => 3,
2254 ItemType::Macro => 4,
2255 ItemType::Struct => 5,
2256 ItemType::Enum => 6,
2257 ItemType::Constant => 7,
2258 ItemType::Static => 8,
2259 ItemType::Trait => 9,
2260 ItemType::Function => 10,
2261 ItemType::Typedef => 12,
2262 ItemType::Union => 13,
2267 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2268 let ty1 = i1.type_();
2269 let ty2 = i2.type_();
2271 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2273 let s1 = i1.stability.as_ref().map(|s| s.level);
2274 let s2 = i2.stability.as_ref().map(|s| s.level);
2276 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2277 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2280 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2281 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2282 name_key(lhs).cmp(&name_key(rhs))
2285 if cx.shared.sort_modules_alphabetically {
2286 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2288 // This call is to remove re-export duplicates in cases such as:
2293 // pub trait Double { fn foo(); }
2297 // pub use foo::bar::*;
2301 // `Double` will appear twice in the generated docs.
2303 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2304 // can be identical even if the elements are different (mostly in imports).
2305 // So in case this is an import, we keep everything by adding a "unique id"
2306 // (which is the position in the vector).
2307 indices.dedup_by_key(|i| (items[*i].def_id,
2308 if items[*i].name.as_ref().is_some() {
2309 Some(full_path(cx, &items[*i]).clone())
2314 if items[*i].is_import() {
2320 debug!("{:?}", indices);
2321 let mut curty = None;
2322 for &idx in &indices {
2323 let myitem = &items[idx];
2324 if myitem.is_stripped() {
2328 let myty = Some(myitem.type_());
2329 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2330 // Put `extern crate` and `use` re-exports in the same section.
2332 } else if myty != curty {
2333 if curty.is_some() {
2334 write!(w, "</table>")?;
2337 let (short, name) = match myty.unwrap() {
2338 ItemType::ExternCrate |
2339 ItemType::Import => ("reexports", "Re-exports"),
2340 ItemType::Module => ("modules", "Modules"),
2341 ItemType::Struct => ("structs", "Structs"),
2342 ItemType::Union => ("unions", "Unions"),
2343 ItemType::Enum => ("enums", "Enums"),
2344 ItemType::Function => ("functions", "Functions"),
2345 ItemType::Typedef => ("types", "Type Definitions"),
2346 ItemType::Static => ("statics", "Statics"),
2347 ItemType::Constant => ("constants", "Constants"),
2348 ItemType::Trait => ("traits", "Traits"),
2349 ItemType::Impl => ("impls", "Implementations"),
2350 ItemType::TyMethod => ("tymethods", "Type Methods"),
2351 ItemType::Method => ("methods", "Methods"),
2352 ItemType::StructField => ("fields", "Struct Fields"),
2353 ItemType::Variant => ("variants", "Variants"),
2354 ItemType::Macro => ("macros", "Macros"),
2355 ItemType::Primitive => ("primitives", "Primitive Types"),
2356 ItemType::AssociatedType => ("associated-types", "Associated Types"),
2357 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
2358 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2360 write!(w, "<h2 id='{id}' class='section-header'>\
2361 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2362 id = derive_id(short.to_owned()), name = name)?;
2365 match myitem.inner {
2366 clean::ExternCrateItem(ref name, ref src) => {
2367 use html::format::HRef;
2371 write!(w, "<tr><td><code>{}extern crate {} as {};",
2372 VisSpace(&myitem.visibility),
2373 HRef::new(myitem.def_id, src),
2377 write!(w, "<tr><td><code>{}extern crate {};",
2378 VisSpace(&myitem.visibility),
2379 HRef::new(myitem.def_id, name))?
2382 write!(w, "</code></td></tr>")?;
2385 clean::ImportItem(ref import) => {
2386 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2387 VisSpace(&myitem.visibility), *import)?;
2391 if myitem.name.is_none() { continue }
2393 let stabilities = short_stability(myitem, cx, false);
2395 let stab_docs = if !stabilities.is_empty() {
2397 .map(|s| format!("[{}]", s))
2398 .collect::<Vec<_>>()
2405 let unsafety_flag = match myitem.inner {
2406 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2407 if func.unsafety == hir::Unsafety::Unsafe => {
2408 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2413 let doc_value = myitem.doc_value().unwrap_or("");
2415 <tr class='{stab} module-item'>
2416 <td><a class=\"{class}\" href=\"{href}\"
2417 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2418 <td class='docblock-short'>
2422 name = *myitem.name.as_ref().unwrap(),
2423 stab_docs = stab_docs,
2424 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2425 class = myitem.type_(),
2426 stab = myitem.stability_class().unwrap_or("".to_string()),
2427 unsafety_flag = unsafety_flag,
2428 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2429 title_type = myitem.type_(),
2430 title = full_path(cx, myitem))?;
2435 if curty.is_some() {
2436 write!(w, "</table>")?;
2441 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2442 let mut stability = vec![];
2444 if let Some(stab) = item.stability.as_ref() {
2445 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2446 format!(": {}", stab.deprecated_reason)
2450 if !stab.deprecated_since.is_empty() {
2451 let since = if show_reason {
2452 format!(" since {}", Escape(&stab.deprecated_since))
2456 let text = if stability::deprecation_in_effect(&stab.deprecated_since) {
2457 format!("Deprecated{}{}",
2459 MarkdownHtml(&deprecated_reason))
2461 format!("Deprecating in {}{}",
2462 Escape(&stab.deprecated_since),
2463 MarkdownHtml(&deprecated_reason))
2465 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2468 if stab.level == stability::Unstable {
2470 let unstable_extra = match (!stab.feature.is_empty(),
2471 &cx.shared.issue_tracker_base_url,
2473 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2474 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2475 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2476 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2477 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2480 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2483 if stab.unstable_reason.is_empty() {
2484 stability.push(format!("<div class='stab unstable'>\
2485 <span class=microscope>🔬</span> \
2486 This is a nightly-only experimental API. {}\
2490 let text = format!("<summary><span class=microscope>🔬</span> \
2491 This is a nightly-only experimental API. {}\
2494 MarkdownHtml(&stab.unstable_reason));
2495 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2499 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2502 } else if let Some(depr) = item.deprecation.as_ref() {
2503 let note = if show_reason && !depr.note.is_empty() {
2504 format!(": {}", depr.note)
2508 let since = if show_reason && !depr.since.is_empty() {
2509 format!(" since {}", Escape(&depr.since))
2514 let text = if stability::deprecation_in_effect(&depr.since) {
2515 format!("Deprecated{}{}",
2517 MarkdownHtml(¬e))
2519 format!("Deprecating in {}{}",
2520 Escape(&depr.since),
2521 MarkdownHtml(¬e))
2523 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2526 if let Some(ref cfg) = item.attrs.cfg {
2527 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2528 cfg.render_long_html()
2530 cfg.render_short_html()
2537 struct Initializer<'a>(&'a str);
2539 impl<'a> fmt::Display for Initializer<'a> {
2540 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2541 let Initializer(s) = *self;
2542 if s.is_empty() { return Ok(()); }
2543 write!(f, "<code> = </code>")?;
2544 write!(f, "<code>{}</code>", Escape(s))
2548 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2549 c: &clean::Constant) -> fmt::Result {
2550 write!(w, "<pre class='rust const'>")?;
2551 render_attributes(w, it)?;
2552 write!(w, "{vis}const \
2553 {name}: {typ}{init}</pre>",
2554 vis = VisSpace(&it.visibility),
2555 name = it.name.as_ref().unwrap(),
2557 init = Initializer(&c.expr))?;
2561 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2562 s: &clean::Static) -> fmt::Result {
2563 write!(w, "<pre class='rust static'>")?;
2564 render_attributes(w, it)?;
2565 write!(w, "{vis}static {mutability}\
2566 {name}: {typ}{init}</pre>",
2567 vis = VisSpace(&it.visibility),
2568 mutability = MutableSpace(s.mutability),
2569 name = it.name.as_ref().unwrap(),
2571 init = Initializer(&s.expr))?;
2575 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2576 f: &clean::Function) -> fmt::Result {
2577 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2578 VisSpace(&it.visibility),
2579 ConstnessSpace(f.constness),
2580 UnsafetySpace(f.unsafety),
2582 it.name.as_ref().unwrap(),
2584 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2585 render_attributes(w, it)?;
2587 "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2588 vis = VisSpace(&it.visibility),
2589 constness = ConstnessSpace(f.constness),
2590 unsafety = UnsafetySpace(f.unsafety),
2591 abi = AbiSpace(f.abi),
2592 name = it.name.as_ref().unwrap(),
2593 generics = f.generics,
2594 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2603 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2604 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2605 write!(w, "<li><table class='table-display'><tbody><tr><td><code>")?;
2606 // If there's already another implementor that has the same abbridged name, use the
2607 // full path, for example in `std::iter::ExactSizeIterator`
2608 let use_absolute = match implementor.inner_impl().for_ {
2609 clean::ResolvedPath { ref path, is_generic: false, .. } |
2610 clean::BorrowedRef {
2611 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2613 } => implementor_dups[path.last_name()].1,
2616 fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2617 for it in &implementor.inner_impl().items {
2618 if let clean::TypedefItem(ref tydef, _) = it.inner {
2619 write!(w, "<span class=\"where fmt-newline\"> ")?;
2620 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2621 write!(w, ";</span>")?;
2624 write!(w, "</code><td>")?;
2625 if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2626 write!(w, "<div class='out-of-band'>")?;
2627 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2628 l, "goto source code")?;
2629 write!(w, "</div>")?;
2631 writeln!(w, "</td></tr></tbody></table></li>")?;
2635 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2637 containing_item: &clean::Item) -> fmt::Result {
2639 let did = i.trait_did().unwrap();
2640 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2641 render_impl(w, cx, i, assoc_link,
2642 RenderMode::Normal, containing_item.stable_since(), true)?;
2647 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2648 t: &clean::Trait) -> fmt::Result {
2649 let mut bounds = String::new();
2650 let mut bounds_plain = String::new();
2651 if !t.bounds.is_empty() {
2652 if !bounds.is_empty() {
2654 bounds_plain.push(' ');
2656 bounds.push_str(": ");
2657 bounds_plain.push_str(": ");
2658 for (i, p) in t.bounds.iter().enumerate() {
2660 bounds.push_str(" + ");
2661 bounds_plain.push_str(" + ");
2663 bounds.push_str(&format!("{}", *p));
2664 bounds_plain.push_str(&format!("{:#}", *p));
2668 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2669 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2670 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2671 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2673 // Output the trait definition
2674 wrap_into_docblock(w, |w| {
2675 write!(w, "<pre class='rust trait'>")?;
2676 render_attributes(w, it)?;
2677 write!(w, "{}{}{}trait {}{}{}",
2678 VisSpace(&it.visibility),
2679 UnsafetySpace(t.unsafety),
2680 if t.is_auto { "auto " } else { "" },
2681 it.name.as_ref().unwrap(),
2685 if !t.generics.where_predicates.is_empty() {
2686 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2691 if t.items.is_empty() {
2692 write!(w, "{{ }}")?;
2694 // FIXME: we should be using a derived_id for the Anchors here
2698 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2701 if !types.is_empty() && !consts.is_empty() {
2706 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2709 if !consts.is_empty() && !required.is_empty() {
2712 for (pos, m) in required.iter().enumerate() {
2714 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2717 if pos < required.len() - 1 {
2718 write!(w, "<div class='item-spacer'></div>")?;
2721 if !required.is_empty() && !provided.is_empty() {
2724 for (pos, m) in provided.iter().enumerate() {
2726 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2728 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2729 write!(w, ",\n {{ ... }}\n")?;
2732 write!(w, " {{ ... }}\n")?;
2735 if pos < provided.len() - 1 {
2736 write!(w, "<div class='item-spacer'></div>")?;
2744 // Trait documentation
2745 document(w, cx, it)?;
2747 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2749 let name = m.name.as_ref().unwrap();
2750 let item_type = m.type_();
2751 let id = derive_id(format!("{}.{}", item_type, name));
2752 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2753 write!(w, "{extra}<h3 id='{id}' class='method'>\
2754 <span id='{ns_id}' class='invisible'><code>",
2755 extra = render_spotlight_traits(m)?,
2758 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2759 write!(w, "</code>")?;
2760 render_stability_since(w, m, t)?;
2761 write!(w, "</span></h3>")?;
2762 document(w, cx, m)?;
2766 if !types.is_empty() {
2768 <h2 id='associated-types' class='small-section-header'>
2769 Associated Types<a href='#associated-types' class='anchor'></a>
2771 <div class='methods'>
2774 trait_item(w, cx, *t, it)?;
2776 write!(w, "</div>")?;
2779 if !consts.is_empty() {
2781 <h2 id='associated-const' class='small-section-header'>
2782 Associated Constants<a href='#associated-const' class='anchor'></a>
2784 <div class='methods'>
2787 trait_item(w, cx, *t, it)?;
2789 write!(w, "</div>")?;
2792 // Output the documentation for each function individually
2793 if !required.is_empty() {
2795 <h2 id='required-methods' class='small-section-header'>
2796 Required Methods<a href='#required-methods' class='anchor'></a>
2798 <div class='methods'>
2800 for m in &required {
2801 trait_item(w, cx, *m, it)?;
2803 write!(w, "</div>")?;
2805 if !provided.is_empty() {
2807 <h2 id='provided-methods' class='small-section-header'>
2808 Provided Methods<a href='#provided-methods' class='anchor'></a>
2810 <div class='methods'>
2812 for m in &provided {
2813 trait_item(w, cx, *m, it)?;
2815 write!(w, "</div>")?;
2818 // If there are methods directly on this trait object, render them here.
2819 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2821 let cache = cache();
2823 <h2 id='implementors' class='small-section-header'>
2824 Implementors<a href='#implementors' class='anchor'></a>
2826 <ul class='item-list' id='implementors-list'>
2829 let synthetic_impl_header = "
2830 <h2 id='synthetic-implementors' class='small-section-header'>
2831 Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
2833 <ul class='item-list' id='synthetic-implementors-list'>
2836 let mut synthetic_types = Vec::new();
2838 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2839 // The DefId is for the first Type found with that name. The bool is
2840 // if any Types with the same name but different DefId have been found.
2841 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2842 for implementor in implementors {
2843 match implementor.inner_impl().for_ {
2844 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2845 clean::BorrowedRef {
2846 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2849 let &mut (prev_did, ref mut has_duplicates) =
2850 implementor_dups.entry(path.last_name()).or_insert((did, false));
2851 if prev_did != did {
2852 *has_duplicates = true;
2859 let (local, foreign) = implementors.iter()
2860 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2861 .map_or(true, |d| cache.paths.contains_key(&d)));
2864 let (synthetic, concrete) = local.iter()
2865 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2868 if !foreign.is_empty() {
2870 <h2 id='foreign-impls' class='small-section-header'>
2871 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2875 for implementor in foreign {
2876 let assoc_link = AssocItemLink::GotoSource(
2877 implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2879 render_impl(w, cx, &implementor, assoc_link,
2880 RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2884 write!(w, "{}", impl_header)?;
2885 for implementor in concrete {
2886 render_implementor(cx, implementor, w, &implementor_dups)?;
2888 write!(w, "</ul>")?;
2891 write!(w, "{}", synthetic_impl_header)?;
2892 for implementor in synthetic {
2893 synthetic_types.extend(
2894 collect_paths_for_type(implementor.inner_impl().for_.clone())
2896 render_implementor(cx, implementor, w, &implementor_dups)?;
2898 write!(w, "</ul>")?;
2901 // even without any implementations to write in, we still want the heading and list, so the
2902 // implementors javascript file pulled in below has somewhere to write the impls into
2903 write!(w, "{}", impl_header)?;
2904 write!(w, "</ul>")?;
2907 write!(w, "{}", synthetic_impl_header)?;
2908 write!(w, "</ul>")?;
2911 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2912 as_json(&synthetic_types))?;
2914 write!(w, r#"<script type="text/javascript" async
2915 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2917 root_path = vec![".."; cx.current.len()].join("/"),
2918 path = if it.def_id.is_local() {
2919 cx.current.join("/")
2921 let (ref path, _) = cache.external_paths[&it.def_id];
2922 path[..path.len() - 1].join("/")
2924 ty = it.type_().css_class(),
2925 name = *it.name.as_ref().unwrap())?;
2929 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2930 use html::item_type::ItemType::*;
2932 let name = it.name.as_ref().unwrap();
2933 let ty = match it.type_() {
2934 Typedef | AssociatedType => AssociatedType,
2938 let anchor = format!("#{}.{}", ty, name);
2940 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2941 AssocItemLink::Anchor(None) => anchor,
2942 AssocItemLink::GotoSource(did, _) => {
2943 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2948 fn assoc_const(w: &mut fmt::Formatter,
2951 _default: Option<&String>,
2952 link: AssocItemLink) -> fmt::Result {
2953 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2954 VisSpace(&it.visibility),
2955 naive_assoc_href(it, link),
2956 it.name.as_ref().unwrap(),
2961 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2962 bounds: &Vec<clean::TyParamBound>,
2963 default: Option<&clean::Type>,
2964 link: AssocItemLink) -> fmt::Result {
2965 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2966 naive_assoc_href(it, link),
2967 it.name.as_ref().unwrap())?;
2968 if !bounds.is_empty() {
2969 write!(w, ": {}", TyParamBounds(bounds))?
2971 if let Some(default) = default {
2972 write!(w, " = {}", default)?;
2977 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2978 ver: Option<&'a str>,
2979 containing_ver: Option<&'a str>) -> fmt::Result {
2980 if let Some(v) = ver {
2981 if containing_ver != ver && v.len() > 0 {
2982 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2989 fn render_stability_since(w: &mut fmt::Formatter,
2991 containing_item: &clean::Item) -> fmt::Result {
2992 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2995 fn render_assoc_item(w: &mut fmt::Formatter,
2997 link: AssocItemLink,
2998 parent: ItemType) -> fmt::Result {
2999 fn method(w: &mut fmt::Formatter,
3001 unsafety: hir::Unsafety,
3002 constness: hir::Constness,
3004 g: &clean::Generics,
3006 link: AssocItemLink,
3009 let name = meth.name.as_ref().unwrap();
3010 let anchor = format!("#{}.{}", meth.type_(), name);
3011 let href = match link {
3012 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3013 AssocItemLink::Anchor(None) => anchor,
3014 AssocItemLink::GotoSource(did, provided_methods) => {
3015 // We're creating a link from an impl-item to the corresponding
3016 // trait-item and need to map the anchored type accordingly.
3017 let ty = if provided_methods.contains(name) {
3023 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3026 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
3027 VisSpace(&meth.visibility),
3028 ConstnessSpace(constness),
3029 UnsafetySpace(unsafety),
3033 let (indent, end_newline) = if parent == ItemType::Trait {
3039 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3040 {generics}{decl}{where_clause}",
3041 VisSpace(&meth.visibility),
3042 ConstnessSpace(constness),
3043 UnsafetySpace(unsafety),
3053 where_clause = WhereClause {
3060 clean::StrippedItem(..) => Ok(()),
3061 clean::TyMethodItem(ref m) => {
3062 method(w, item, m.unsafety, hir::Constness::NotConst,
3063 m.abi, &m.generics, &m.decl, link, parent)
3065 clean::MethodItem(ref m) => {
3066 method(w, item, m.unsafety, m.constness,
3067 m.abi, &m.generics, &m.decl, link, parent)
3069 clean::AssociatedConstItem(ref ty, ref default) => {
3070 assoc_const(w, item, ty, default.as_ref(), link)
3072 clean::AssociatedTypeItem(ref bounds, ref default) => {
3073 assoc_type(w, item, bounds, default.as_ref(), link)
3075 _ => panic!("render_assoc_item called on non-associated-item")
3079 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3080 s: &clean::Struct) -> fmt::Result {
3081 wrap_into_docblock(w, |w| {
3082 write!(w, "<pre class='rust struct'>")?;
3083 render_attributes(w, it)?;
3094 document(w, cx, it)?;
3095 let mut fields = s.fields.iter().filter_map(|f| {
3097 clean::StructFieldItem(ref ty) => Some((f, ty)),
3101 if let doctree::Plain = s.struct_type {
3102 if fields.peek().is_some() {
3103 write!(w, "<h2 id='fields' class='fields small-section-header'>
3104 Fields<a href='#fields' class='anchor'></a></h2>")?;
3105 for (field, ty) in fields {
3106 let id = derive_id(format!("{}.{}",
3107 ItemType::StructField,
3108 field.name.as_ref().unwrap()));
3109 let ns_id = derive_id(format!("{}.{}",
3110 field.name.as_ref().unwrap(),
3111 ItemType::StructField.name_space()));
3112 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
3113 <a href=\"#{id}\" class=\"anchor field\"></a>
3114 <span id=\"{ns_id}\" class='invisible'>
3115 <code>{name}: {ty}</code>
3117 item_type = ItemType::StructField,
3120 name = field.name.as_ref().unwrap(),
3122 if let Some(stability_class) = field.stability_class() {
3123 write!(w, "<span class='stab {stab}'></span>",
3124 stab = stability_class)?;
3126 document(w, cx, field)?;
3130 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3133 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3134 s: &clean::Union) -> fmt::Result {
3135 wrap_into_docblock(w, |w| {
3136 write!(w, "<pre class='rust union'>")?;
3137 render_attributes(w, it)?;
3147 document(w, cx, it)?;
3148 let mut fields = s.fields.iter().filter_map(|f| {
3150 clean::StructFieldItem(ref ty) => Some((f, ty)),
3154 if fields.peek().is_some() {
3155 write!(w, "<h2 id='fields' class='fields small-section-header'>
3156 Fields<a href='#fields' class='anchor'></a></h2>")?;
3157 for (field, ty) in fields {
3158 let name = field.name.as_ref().expect("union field name");
3159 let id = format!("{}.{}", ItemType::StructField, name);
3160 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3161 <a href=\"#{id}\" class=\"anchor field\"></a>\
3162 <span class='invisible'><code>{name}: {ty}</code></span>\
3166 shortty = ItemType::StructField,
3168 if let Some(stability_class) = field.stability_class() {
3169 write!(w, "<span class='stab {stab}'></span>",
3170 stab = stability_class)?;
3172 document(w, cx, field)?;
3175 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3178 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3179 e: &clean::Enum) -> fmt::Result {
3180 wrap_into_docblock(w, |w| {
3181 write!(w, "<pre class='rust enum'>")?;
3182 render_attributes(w, it)?;
3183 write!(w, "{}enum {}{}{}",
3184 VisSpace(&it.visibility),
3185 it.name.as_ref().unwrap(),
3187 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3188 if e.variants.is_empty() && !e.variants_stripped {
3189 write!(w, " {{}}")?;
3191 write!(w, " {{\n")?;
3192 for v in &e.variants {
3194 let name = v.name.as_ref().unwrap();
3196 clean::VariantItem(ref var) => {
3198 clean::VariantKind::CLike => write!(w, "{}", name)?,
3199 clean::VariantKind::Tuple(ref tys) => {
3200 write!(w, "{}(", name)?;
3201 for (i, ty) in tys.iter().enumerate() {
3203 write!(w, ", ")?
3205 write!(w, "{}", *ty)?;
3209 clean::VariantKind::Struct(ref s) => {
3225 if e.variants_stripped {
3226 write!(w, " // some variants omitted\n")?;
3233 document(w, cx, it)?;
3234 if !e.variants.is_empty() {
3235 write!(w, "<h2 id='variants' class='variants small-section-header'>
3236 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
3237 for variant in &e.variants {
3238 let id = derive_id(format!("{}.{}",
3240 variant.name.as_ref().unwrap()));
3241 let ns_id = derive_id(format!("{}.{}",
3242 variant.name.as_ref().unwrap(),
3243 ItemType::Variant.name_space()));
3244 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3245 <a href=\"#{id}\" class=\"anchor field\"></a>\
3246 <span id='{ns_id}' class='invisible'><code>{name}",
3249 name = variant.name.as_ref().unwrap())?;
3250 if let clean::VariantItem(ref var) = variant.inner {
3251 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3253 for (i, ty) in tys.iter().enumerate() {
3255 write!(w, ", ")?;
3257 write!(w, "{}", *ty)?;
3262 write!(w, "</code></span></span>")?;
3263 document(w, cx, variant)?;
3265 use clean::{Variant, VariantKind};
3266 if let clean::VariantItem(Variant {
3267 kind: VariantKind::Struct(ref s)
3268 }) = variant.inner {
3269 let variant_id = derive_id(format!("{}.{}.fields",
3271 variant.name.as_ref().unwrap()));
3272 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
3274 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
3275 <table>", name = variant.name.as_ref().unwrap())?;
3276 for field in &s.fields {
3277 use clean::StructFieldItem;
3278 if let StructFieldItem(ref ty) = field.inner {
3279 let id = derive_id(format!("variant.{}.field.{}",
3280 variant.name.as_ref().unwrap(),
3281 field.name.as_ref().unwrap()));
3282 let ns_id = derive_id(format!("{}.{}.{}.{}",
3283 variant.name.as_ref().unwrap(),
3284 ItemType::Variant.name_space(),
3285 field.name.as_ref().unwrap(),
3286 ItemType::StructField.name_space()));
3287 write!(w, "<tr><td \
3289 <span id='{ns_id}' class='invisible'>\
3290 <code>{f}: {t}</code></span></td><td>",
3293 f = field.name.as_ref().unwrap(),
3295 document(w, cx, field)?;
3296 write!(w, "</td></tr>")?;
3299 write!(w, "</table></span>")?;
3301 render_stability_since(w, variant, it)?;
3304 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3308 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3309 let name = attr.name();
3312 Some(format!("{}", name))
3313 } else if let Some(v) = attr.value_str() {
3314 Some(format!("{} = {:?}", name, v.as_str()))
3315 } else if let Some(values) = attr.meta_item_list() {
3316 let display: Vec<_> = values.iter().filter_map(|attr| {
3317 attr.meta_item().and_then(|mi| render_attribute(mi))
3320 if display.len() > 0 {
3321 Some(format!("{}({})", name, display.join(", ")))
3330 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3337 "unsafe_destructor_blind_to_params"
3340 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3341 let mut attrs = String::new();
3343 for attr in &it.attrs.other_attrs {
3344 let name = attr.name();
3345 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3348 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3349 attrs.push_str(&format!("#[{}]\n", s));
3352 if attrs.len() > 0 {
3353 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3358 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3359 g: Option<&clean::Generics>,
3360 ty: doctree::StructType,
3361 fields: &[clean::Item],
3363 structhead: bool) -> fmt::Result {
3365 VisSpace(&it.visibility),
3366 if structhead {"struct "} else {""},
3367 it.name.as_ref().unwrap())?;
3368 if let Some(g) = g {
3373 if let Some(g) = g {
3374 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3376 let mut has_visible_fields = false;
3378 for field in fields {
3379 if let clean::StructFieldItem(ref ty) = field.inner {
3380 write!(w, "\n{} {}{}: {},",
3382 VisSpace(&field.visibility),
3383 field.name.as_ref().unwrap(),
3385 has_visible_fields = true;
3389 if has_visible_fields {
3390 if it.has_stripped_fields().unwrap() {
3391 write!(w, "\n{} // some fields omitted", tab)?;
3393 write!(w, "\n{}", tab)?;
3394 } else if it.has_stripped_fields().unwrap() {
3395 // If there are no visible fields we can just display
3396 // `{ /* fields omitted */ }` to save space.
3397 write!(w, " /* fields omitted */ ")?;
3403 for (i, field) in fields.iter().enumerate() {
3408 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3411 clean::StructFieldItem(ref ty) => {
3412 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3418 if let Some(g) = g {
3419 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3424 // Needed for PhantomData.
3425 if let Some(g) = g {
3426 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3434 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3435 g: Option<&clean::Generics>,
3436 fields: &[clean::Item],
3438 structhead: bool) -> fmt::Result {
3440 VisSpace(&it.visibility),
3441 if structhead {"union "} else {""},
3442 it.name.as_ref().unwrap())?;
3443 if let Some(g) = g {
3444 write!(w, "{}", g)?;
3445 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3448 write!(w, " {{\n{}", tab)?;
3449 for field in fields {
3450 if let clean::StructFieldItem(ref ty) = field.inner {
3451 write!(w, " {}{}: {},\n{}",
3452 VisSpace(&field.visibility),
3453 field.name.as_ref().unwrap(),
3459 if it.has_stripped_fields().unwrap() {
3460 write!(w, " // some fields omitted\n{}", tab)?;
3466 #[derive(Copy, Clone)]
3467 enum AssocItemLink<'a> {
3468 Anchor(Option<&'a str>),
3469 GotoSource(DefId, &'a FxHashSet<String>),
3472 impl<'a> AssocItemLink<'a> {
3473 fn anchor(&self, id: &'a String) -> Self {
3475 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3476 ref other => *other,
3481 enum AssocItemRender<'a> {
3483 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3486 #[derive(Copy, Clone, PartialEq)]
3489 ForDeref { mut_: bool },
3492 fn render_assoc_items(w: &mut fmt::Formatter,
3494 containing_item: &clean::Item,
3496 what: AssocItemRender) -> fmt::Result {
3498 let v = match c.impls.get(&it) {
3500 None => return Ok(()),
3502 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3503 i.inner_impl().trait_.is_none()
3505 if !non_trait.is_empty() {
3506 let render_mode = match what {
3507 AssocItemRender::All => {
3509 <h2 id='methods' class='small-section-header'>
3510 Methods<a href='#methods' class='anchor'></a>
3515 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3517 <h2 id='deref-methods' class='small-section-header'>
3518 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3521 RenderMode::ForDeref { mut_: deref_mut_ }
3524 for i in &non_trait {
3525 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3526 containing_item.stable_since(), true)?;
3529 if let AssocItemRender::DerefFor { .. } = what {
3532 if !traits.is_empty() {
3533 let deref_impl = traits.iter().find(|t| {
3534 t.inner_impl().trait_.def_id() == c.deref_trait_did
3536 if let Some(impl_) = deref_impl {
3537 let has_deref_mut = traits.iter().find(|t| {
3538 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3540 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3543 let (synthetic, concrete) = traits
3545 .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3547 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3549 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3550 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3551 render_impls(self.0, fmt, &self.1, self.2)
3555 let impls = format!("{}", RendererStruct(cx, concrete, containing_item));
3556 if !impls.is_empty() {
3558 <h2 id='implementations' class='small-section-header'>
3559 Trait Implementations<a href='#implementations' class='anchor'></a>
3561 <div id='implementations-list'>{}</div>", impls)?;
3564 if !synthetic.is_empty() {
3566 <h2 id='synthetic-implementations' class='small-section-header'>
3567 Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3569 <div id='synthetic-implementations-list'>
3571 render_impls(cx, w, &synthetic, containing_item)?;
3572 write!(w, "</div>")?;
3578 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3579 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3580 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3581 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3583 clean::TypedefItem(ref t, true) => Some(&t.type_),
3586 }).next().expect("Expected associated type binding");
3587 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3588 deref_mut_: deref_mut };
3589 if let Some(did) = target.def_id() {
3590 render_assoc_items(w, cx, container_item, did, what)
3592 if let Some(prim) = target.primitive_type() {
3593 if let Some(&did) = cache().primitive_locations.get(&prim) {
3594 render_assoc_items(w, cx, container_item, did, what)?;
3601 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3602 let self_type_opt = match item.inner {
3603 clean::MethodItem(ref method) => method.decl.self_type(),
3604 clean::TyMethodItem(ref method) => method.decl.self_type(),
3608 if let Some(self_ty) = self_type_opt {
3609 let (by_mut_ref, by_box, by_value) = match self_ty {
3610 SelfTy::SelfBorrowed(_, mutability) |
3611 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3612 (mutability == Mutability::Mutable, false, false)
3614 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3615 (false, Some(did) == cache().owned_box_did, false)
3617 SelfTy::SelfValue => (false, false, true),
3618 _ => (false, false, false),
3621 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3627 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3628 let mut out = String::new();
3631 clean::FunctionItem(clean::Function { ref decl, .. }) |
3632 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3633 clean::MethodItem(clean::Method { ref decl, .. }) |
3634 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3635 out = spotlight_decl(decl)?;
3643 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3644 let mut out = String::new();
3645 let mut trait_ = String::new();
3647 if let Some(did) = decl.output.def_id() {
3649 if let Some(impls) = c.impls.get(&did) {
3651 let impl_ = i.inner_impl();
3652 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3655 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3656 <code class=\"content\">",
3658 trait_.push_str(&format!("{}", impl_.for_));
3661 //use the "where" class here to make it small
3662 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3663 let t_did = impl_.trait_.def_id().unwrap();
3664 for it in &impl_.items {
3665 if let clean::TypedefItem(ref tydef, _) = it.inner {
3666 out.push_str("<span class=\"where fmt-newline\"> ");
3667 assoc_type(&mut out, it, &vec![],
3669 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3670 out.push_str(";</span>");
3678 if !out.is_empty() {
3679 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3680 <span class='tooltiptext'>Important traits for {}</span></div>\
3681 <div class=\"content hidden\">",
3683 out.push_str("</code></div></div>");
3689 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3690 render_mode: RenderMode, outer_version: Option<&str>,
3691 show_def_docs: bool) -> fmt::Result {
3692 if render_mode == RenderMode::Normal {
3693 let id = derive_id(match i.inner_impl().trait_ {
3694 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3695 None => "impl".to_string(),
3697 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
3698 <tbody><tr><td><code>{}</code>",
3699 id, i.inner_impl())?;
3700 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3701 write!(w, "</span></td><td><span class='out-of-band'>")?;
3702 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3703 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3704 write!(w, "<div class='ghost'></div>")?;
3705 render_stability_since_raw(w, since, outer_version)?;
3706 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3707 l, "goto source code")?;
3709 render_stability_since_raw(w, since, outer_version)?;
3711 write!(w, "</span></td></tr></tbody></table></h3>")?;
3712 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3713 write!(w, "<div class='docblock'>{}</div>",
3714 Markdown(&*dox, &i.impl_item.links()))?;
3718 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3719 link: AssocItemLink, render_mode: RenderMode,
3720 is_default_item: bool, outer_version: Option<&str>,
3721 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3722 let item_type = item.type_();
3723 let name = item.name.as_ref().unwrap();
3725 let render_method_item: bool = match render_mode {
3726 RenderMode::Normal => true,
3727 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3731 clean::MethodItem(clean::Method { ref decl, .. }) |
3732 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3733 // Only render when the method is not static or we allow static methods
3734 if render_method_item {
3735 let id = derive_id(format!("{}.{}", item_type, name));
3736 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3737 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3738 write!(w, "{}", spotlight_decl(decl)?)?;
3739 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3740 write!(w, "<table class='table-display'><tbody><tr><td><code>")?;
3741 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3742 write!(w, "</code>")?;
3743 if let Some(l) = (Item { cx, item }).src_href() {
3744 write!(w, "</span></td><td><span class='out-of-band'>")?;
3745 write!(w, "<div class='ghost'></div>")?;
3746 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3747 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3748 l, "goto source code")?;
3750 write!(w, "</td><td>")?;
3751 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3753 write!(w, "</td></tr></tbody></table></span></h4>")?;
3756 clean::TypedefItem(ref tydef, _) => {
3757 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3758 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3759 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3760 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3761 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3762 write!(w, "</code></span></h4>\n")?;
3764 clean::AssociatedConstItem(ref ty, ref default) => {
3765 let id = derive_id(format!("{}.{}", item_type, name));
3766 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3767 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3768 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3769 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3770 write!(w, "</code></span></h4>\n")?;
3772 clean::AssociatedTypeItem(ref bounds, ref default) => {
3773 let id = derive_id(format!("{}.{}", item_type, name));
3774 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3775 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3776 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3777 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3778 write!(w, "</code></span></h4>\n")?;
3780 clean::StrippedItem(..) => return Ok(()),
3781 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3784 if render_method_item || render_mode == RenderMode::Normal {
3785 let prefix = render_assoc_const_value(item);
3787 if !is_default_item {
3788 if let Some(t) = trait_ {
3789 // The trait item may have been stripped so we might not
3790 // find any documentation or stability for it.
3791 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3792 // We need the stability of the item from the trait
3793 // because impls can't have a stability.
3794 document_stability(w, cx, it)?;
3795 if item.doc_value().is_some() {
3796 document_full(w, item, cx, &prefix)?;
3797 } else if show_def_docs {
3798 // In case the item isn't documented,
3799 // provide short documentation from the trait.
3800 document_short(w, it, link, &prefix)?;
3804 document_stability(w, cx, item)?;
3806 document_full(w, item, cx, &prefix)?;
3810 document_stability(w, cx, item)?;
3812 document_short(w, item, link, &prefix)?;
3819 let traits = &cache().traits;
3820 let trait_ = i.trait_did().map(|did| &traits[&did]);
3823 write!(w, "<span class='docblock autohide'>")?;
3826 write!(w, "<div class='impl-items'>")?;
3827 for trait_item in &i.inner_impl().items {
3828 doc_impl_item(w, cx, trait_item, link, render_mode,
3829 false, outer_version, trait_, show_def_docs)?;
3832 fn render_default_items(w: &mut fmt::Formatter,
3836 render_mode: RenderMode,
3837 outer_version: Option<&str>,
3838 show_def_docs: bool) -> fmt::Result {
3839 for trait_item in &t.items {
3840 let n = trait_item.name.clone();
3841 if i.items.iter().find(|m| m.name == n).is_some() {
3844 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3845 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3847 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3848 outer_version, None, show_def_docs)?;
3853 // If we've implemented a trait, then also emit documentation for all
3854 // default items which weren't overridden in the implementation block.
3855 if let Some(t) = trait_ {
3856 render_default_items(w, cx, t, &i.inner_impl(),
3857 render_mode, outer_version, show_def_docs)?;
3859 write!(w, "</div>")?;
3862 write!(w, "</span>")?;
3868 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3869 t: &clean::Typedef) -> fmt::Result {
3870 write!(w, "<pre class='rust typedef'>")?;
3871 render_attributes(w, it)?;
3872 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3873 it.name.as_ref().unwrap(),
3875 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3878 document(w, cx, it)?;
3880 // Render any items associated directly to this alias, as otherwise they
3881 // won't be visible anywhere in the docs. It would be nice to also show
3882 // associated items from the aliased type (see discussion in #32077), but
3883 // we need #14072 to make sense of the generics.
3884 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3887 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3888 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3889 render_attributes(w, it)?;
3892 " {}type {};\n}}</pre>",
3893 VisSpace(&it.visibility),
3894 it.name.as_ref().unwrap(),
3897 document(w, cx, it)?;
3899 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3902 impl<'a> fmt::Display for Sidebar<'a> {
3903 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3906 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3908 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3909 || it.is_enum() || it.is_mod() || it.is_typedef() {
3910 write!(fmt, "<p class='location'>{}{}</p>",
3912 clean::StructItem(..) => "Struct ",
3913 clean::TraitItem(..) => "Trait ",
3914 clean::PrimitiveItem(..) => "Primitive Type ",
3915 clean::UnionItem(..) => "Union ",
3916 clean::EnumItem(..) => "Enum ",
3917 clean::TypedefItem(..) => "Type Definition ",
3918 clean::ForeignTypeItem => "Foreign Type ",
3919 clean::ModuleItem(..) => if it.is_crate() {
3926 it.name.as_ref().unwrap())?;
3930 if let Some(ref version) = cache().crate_version {
3932 "<div class='block version'>\
3935 <a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3937 it.name.as_ref().unwrap())?;
3941 write!(fmt, "<div class=\"sidebar-elems\">")?;
3943 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3944 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3945 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3946 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3947 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3948 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3949 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3950 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3954 // The sidebar is designed to display sibling functions, modules and
3955 // other miscellaneous information. since there are lots of sibling
3956 // items (and that causes quadratic growth in large modules),
3957 // we refactor common parts into a shared JavaScript file per module.
3958 // still, we don't move everything into JS because we want to preserve
3959 // as much HTML as possible in order to allow non-JS-enabled browsers
3960 // to navigate the documentation (though slightly inefficiently).
3962 write!(fmt, "<p class='location'>")?;
3963 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3965 write!(fmt, "::<wbr>")?;
3967 write!(fmt, "<a href='{}index.html'>{}</a>",
3968 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3971 write!(fmt, "</p>")?;
3973 // Sidebar refers to the enclosing module, not this module.
3974 let relpath = if it.is_mod() { "../" } else { "" };
3976 "<script>window.sidebarCurrent = {{\
3981 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3982 ty = it.type_().css_class(),
3985 // There is no sidebar-items.js beyond the crate root path
3986 // FIXME maybe dynamic crate loading can be merged here
3988 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3991 // Closes sidebar-elems div.
3992 write!(fmt, "</div>")?;
3998 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3999 i.items.iter().filter_map(|item| {
4001 // Maybe check with clean::Visibility::Public as well?
4002 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4003 if !for_deref || should_render_item(item, false) {
4004 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
4011 }).collect::<Vec<_>>()
4014 // The point is to url encode any potential character from a type with genericity.
4015 fn small_url_encode(s: &str) -> String {
4016 s.replace("<", "%3C")
4017 .replace(">", "%3E")
4018 .replace(" ", "%20")
4019 .replace("?", "%3F")
4020 .replace("'", "%27")
4021 .replace("&", "%26")
4022 .replace(",", "%2C")
4023 .replace(":", "%3A")
4024 .replace(";", "%3B")
4025 .replace("[", "%5B")
4026 .replace("]", "%5D")
4027 .replace("\"", "%22")
4030 fn sidebar_assoc_items(it: &clean::Item) -> String {
4031 let mut out = String::new();
4033 if let Some(v) = c.impls.get(&it.def_id) {
4035 .filter(|i| i.inner_impl().trait_.is_none())
4036 .flat_map(|i| get_methods(i.inner_impl(), false))
4037 .collect::<String>();
4038 if !ret.is_empty() {
4039 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4040 </a><div class=\"sidebar-links\">{}</div>", ret));
4043 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4044 if let Some(impl_) = v.iter()
4045 .filter(|i| i.inner_impl().trait_.is_some())
4046 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4047 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4049 clean::TypedefItem(ref t, true) => Some(&t.type_),
4053 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4054 c.primitive_locations.get(&prim).cloned()
4055 })).and_then(|did| c.impls.get(&did));
4056 if let Some(impls) = inner_impl {
4057 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4058 out.push_str(&format!("Methods from {}<Target={}>",
4059 Escape(&format!("{:#}",
4060 impl_.inner_impl().trait_.as_ref().unwrap())),
4061 Escape(&format!("{:#}", target))));
4062 out.push_str("</a>");
4063 let ret = impls.iter()
4064 .filter(|i| i.inner_impl().trait_.is_none())
4065 .flat_map(|i| get_methods(i.inner_impl(), true))
4066 .collect::<String>();
4067 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
4071 let format_impls = |impls: Vec<&Impl>| {
4072 let mut links = HashSet::new();
4075 let is_negative_impl = is_negative_impl(i.inner_impl());
4076 if let Some(ref i) = i.inner_impl().trait_ {
4077 let i_display = format!("{:#}", i);
4078 let out = Escape(&i_display);
4079 let encoded = small_url_encode(&format!("{:#}", i));
4080 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4082 if is_negative_impl { "!" } else { "" },
4084 if links.insert(generated.clone()) {
4093 .collect::<String>()
4096 let (synthetic, concrete) = v
4098 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4100 let concrete_format = format_impls(concrete);
4101 let synthetic_format = format_impls(synthetic);
4103 if !concrete_format.is_empty() {
4104 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4105 Trait Implementations</a>");
4106 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4109 if !synthetic_format.is_empty() {
4110 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4111 Auto Trait Implementations</a>");
4112 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4120 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4121 s: &clean::Struct) -> fmt::Result {
4122 let mut sidebar = String::new();
4123 let fields = get_struct_fields_name(&s.fields);
4125 if !fields.is_empty() {
4126 if let doctree::Plain = s.struct_type {
4127 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4128 <div class=\"sidebar-links\">{}</div>", fields));
4132 sidebar.push_str(&sidebar_assoc_items(it));
4134 if !sidebar.is_empty() {
4135 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4140 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4142 clean::ItemEnum::ImplItem(ref i) => {
4143 if let Some(ref trait_) = i.trait_ {
4144 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4153 fn is_negative_impl(i: &clean::Impl) -> bool {
4154 i.polarity == Some(clean::ImplPolarity::Negative)
4157 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4158 t: &clean::Trait) -> fmt::Result {
4159 let mut sidebar = String::new();
4165 Some(ref name) if m.is_associated_type() => {
4166 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4172 .collect::<String>();
4173 let consts = t.items
4177 Some(ref name) if m.is_associated_const() => {
4178 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4184 .collect::<String>();
4185 let required = t.items
4189 Some(ref name) if m.is_ty_method() => {
4190 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4196 .collect::<String>();
4197 let provided = t.items
4201 Some(ref name) if m.is_method() => {
4202 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
4207 .collect::<String>();
4209 if !types.is_empty() {
4210 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4211 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4214 if !consts.is_empty() {
4215 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4216 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4219 if !required.is_empty() {
4220 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4221 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4224 if !provided.is_empty() {
4225 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4226 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4232 if let Some(implementors) = c.implementors.get(&it.def_id) {
4233 let res = implementors.iter()
4234 .filter(|i| i.inner_impl().for_.def_id()
4235 .map_or(false, |d| !c.paths.contains_key(&d)))
4237 match extract_for_impl_name(&i.impl_item) {
4238 Some((ref name, ref url)) => {
4239 Some(format!("<a href=\"#impl-{}\">{}</a>",
4240 small_url_encode(url),
4246 .collect::<String>();
4247 if !res.is_empty() {
4248 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4249 Implementations on Foreign Types</a><div \
4250 class=\"sidebar-links\">{}</div>",
4255 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4257 sidebar.push_str("<a class=\"sidebar-title\" \
4258 href=\"#synthetic-implementors\">Auto Implementors</a>");
4261 sidebar.push_str(&sidebar_assoc_items(it));
4263 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4266 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4267 _p: &clean::PrimitiveType) -> fmt::Result {
4268 let sidebar = sidebar_assoc_items(it);
4270 if !sidebar.is_empty() {
4271 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4276 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4277 _t: &clean::Typedef) -> fmt::Result {
4278 let sidebar = sidebar_assoc_items(it);
4280 if !sidebar.is_empty() {
4281 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4286 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4288 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4293 .filter_map(|f| match f.name {
4294 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4295 {name}</a>", name=name)),
4301 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4302 u: &clean::Union) -> fmt::Result {
4303 let mut sidebar = String::new();
4304 let fields = get_struct_fields_name(&u.fields);
4306 if !fields.is_empty() {
4307 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4308 <div class=\"sidebar-links\">{}</div>", fields));
4311 sidebar.push_str(&sidebar_assoc_items(it));
4313 if !sidebar.is_empty() {
4314 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4319 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4320 e: &clean::Enum) -> fmt::Result {
4321 let mut sidebar = String::new();
4323 let variants = e.variants.iter()
4324 .filter_map(|v| match v.name {
4325 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4326 </a>", name = name)),
4329 .collect::<String>();
4330 if !variants.is_empty() {
4331 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4332 <div class=\"sidebar-links\">{}</div>", variants));
4335 sidebar.push_str(&sidebar_assoc_items(it));
4337 if !sidebar.is_empty() {
4338 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4343 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4344 items: &[clean::Item]) -> fmt::Result {
4345 let mut sidebar = String::new();
4347 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4348 it.type_() == ItemType::Import) {
4349 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4351 name = "Re-exports"));
4354 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4355 // to print its headings
4356 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4357 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4358 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4359 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4360 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4361 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4362 let (short, name) = match myty {
4363 ItemType::ExternCrate |
4364 ItemType::Import => ("reexports", "Re-exports"),
4365 ItemType::Module => ("modules", "Modules"),
4366 ItemType::Struct => ("structs", "Structs"),
4367 ItemType::Union => ("unions", "Unions"),
4368 ItemType::Enum => ("enums", "Enums"),
4369 ItemType::Function => ("functions", "Functions"),
4370 ItemType::Typedef => ("types", "Type Definitions"),
4371 ItemType::Static => ("statics", "Statics"),
4372 ItemType::Constant => ("constants", "Constants"),
4373 ItemType::Trait => ("traits", "Traits"),
4374 ItemType::Impl => ("impls", "Implementations"),
4375 ItemType::TyMethod => ("tymethods", "Type Methods"),
4376 ItemType::Method => ("methods", "Methods"),
4377 ItemType::StructField => ("fields", "Struct Fields"),
4378 ItemType::Variant => ("variants", "Variants"),
4379 ItemType::Macro => ("macros", "Macros"),
4380 ItemType::Primitive => ("primitives", "Primitive Types"),
4381 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4382 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4383 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4385 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4391 if !sidebar.is_empty() {
4392 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4397 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4398 let sidebar = sidebar_assoc_items(it);
4399 if !sidebar.is_empty() {
4400 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4405 impl<'a> fmt::Display for Source<'a> {
4406 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4407 let Source(s) = *self;
4408 let lines = s.lines().count();
4410 let mut tmp = lines;
4415 write!(fmt, "<pre class=\"line-numbers\">")?;
4416 for i in 1..lines + 1 {
4417 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4419 write!(fmt, "</pre>")?;
4421 highlight::render_with_highlighting(s, None, None, None, None))?;
4426 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4427 t: &clean::Macro) -> fmt::Result {
4428 wrap_into_docblock(w, |w| {
4429 w.write_str(&highlight::render_with_highlighting(&t.source,
4438 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4440 _p: &clean::PrimitiveType) -> fmt::Result {
4441 document(w, cx, it)?;
4442 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4445 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4447 fn make_item_keywords(it: &clean::Item) -> String {
4448 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4451 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4452 let decl = match item.inner {
4453 clean::FunctionItem(ref f) => &f.decl,
4454 clean::MethodItem(ref m) => &m.decl,
4455 clean::TyMethodItem(ref m) => &m.decl,
4459 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4460 let output = match decl.output {
4461 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4465 Some(IndexItemFunctionType { inputs: inputs, output: output })
4468 fn get_index_type(clean_type: &clean::Type) -> Type {
4470 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4471 generics: get_generics(clean_type),
4476 /// Returns a list of all paths used in the type.
4477 /// This is used to help deduplicate imported impls
4478 /// for reexported types. If any of the contained
4479 /// types are re-exported, we don't use the corresponding
4480 /// entry from the js file, as inlining will have already
4481 /// picked up the impl
4482 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4483 let mut out = Vec::new();
4484 let mut visited = FxHashSet();
4485 let mut work = VecDeque::new();
4486 let cache = cache();
4488 work.push_back(first_ty);
4490 while let Some(ty) = work.pop_front() {
4491 if !visited.insert(ty.clone()) {
4496 clean::Type::ResolvedPath { did, .. } => {
4497 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4498 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4502 out.push(path.join("::"));
4508 clean::Type::Tuple(tys) => {
4509 work.extend(tys.into_iter());
4511 clean::Type::Slice(ty) => {
4512 work.push_back(*ty);
4514 clean::Type::Array(ty, _) => {
4515 work.push_back(*ty);
4517 clean::Type::Unique(ty) => {
4518 work.push_back(*ty);
4520 clean::Type::RawPointer(_, ty) => {
4521 work.push_back(*ty);
4523 clean::Type::BorrowedRef { type_, .. } => {
4524 work.push_back(*type_);
4526 clean::Type::QPath { self_type, trait_, .. } => {
4527 work.push_back(*self_type);
4528 work.push_back(*trait_);
4536 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4538 clean::ResolvedPath { ref path, .. } => {
4539 let segments = &path.segments;
4540 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4541 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4542 clean_type, accept_generic
4544 Some(path_segment.name.clone())
4546 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4547 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4548 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4549 // FIXME: add all from clean::Type.
4554 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4555 clean_type.generics()
4557 let r = types.iter()
4558 .filter_map(|t| get_index_type_name(t, false))
4559 .map(|s| s.to_ascii_lowercase())
4560 .collect::<Vec<_>>();
4569 pub fn cache() -> Arc<Cache> {
4570 CACHE_KEY.with(|c| c.borrow().clone())
4575 fn test_unique_id() {
4576 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4577 "method.into_iter", "foo", "main", "search", "methods",
4578 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4579 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4580 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4581 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4584 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4585 assert_eq!(&actual[..], expected);
4594 fn test_name_key() {
4595 assert_eq!(name_key("0"), ("", 0, 1));
4596 assert_eq!(name_key("123"), ("", 123, 0));
4597 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4598 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4599 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4600 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4601 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4602 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4607 fn test_name_sorting() {
4608 let names = ["Apple",
4610 "Fruit", "Fruit0", "Fruit00",
4611 "Fruit1", "Fruit01",
4612 "Fruit2", "Fruit02",
4616 let mut sorted = names.to_owned();
4617 sorted.sort_by_key(|&s| name_key(s));
4618 assert_eq!(names, sorted);