1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Rustdoc's HTML Rendering module
13 //! This modules contains the bulk of the logic necessary for rendering a
14 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
15 //! rendering process is largely driven by the `format!` syntax extension to
16 //! perform all I/O into files and streams.
18 //! The rendering process is largely driven by the `Context` and `Cache`
19 //! structures. The cache is pre-populated by crawling the crate in question,
20 //! and then it is shared among the various rendering threads. The cache is meant
21 //! to be a fairly large structure not implementing `Clone` (because it's shared
22 //! among threads). The context, however, should be a lightweight structure. This
23 //! is cloned per-thread and contains information about what is currently being
26 //! In order to speed up rendering (mostly because of markdown rendering), the
27 //! rendering process has been parallelized. This parallelization is only
28 //! exposed through the `crate` method on the context, and then also from the
29 //! fact that the shared cache is stored in TLS (and must be accessed as such).
31 //! In addition to rendering the crate itself, this module is also responsible
32 //! for creating the corresponding search index and source file renderings.
33 //! These threads are not parallelized (they haven't been a bottleneck yet), and
34 //! both occur before the crate is rendered.
36 pub use self::ExternalLocation::*;
39 use std::cell::RefCell;
40 use std::cmp::Ordering;
41 use std::collections::{BTreeMap, HashSet, VecDeque};
42 use std::default::Default;
44 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
45 use std::fs::{self, File, OpenOptions};
46 use std::io::prelude::*;
47 use std::io::{self, BufWriter, BufReader};
48 use std::iter::repeat;
50 use std::path::{PathBuf, Path, Component};
54 use externalfiles::ExternalHtml;
56 use serialize::json::{ToJson, Json, as_json};
58 use syntax::codemap::FileName;
59 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
60 use rustc::middle::privacy::AccessLevels;
61 use rustc::middle::stability;
63 use rustc::util::nodemap::{FxHashMap, FxHashSet};
64 use rustc_data_structures::flock;
65 use rustc_target::spec::abi;
67 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
70 use html::escape::Escape;
71 use html::format::{ConstnessSpace};
72 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
73 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
74 use html::format::fmt_impl_for_trait_page;
75 use html::item_type::ItemType;
76 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine};
77 use html::{highlight, layout};
81 /// A pair of name and its optional document.
82 pub type NameDoc = (String, Option<String>);
84 /// Major driving force in all rustdoc rendering. This contains information
85 /// about where in the tree-like hierarchy rendering is occurring and controls
86 /// how the current page is being rendered.
88 /// It is intended that this context is a lightweight object which can be fairly
89 /// easily cloned because it is cloned per work-job (about once per item in the
93 /// Current hierarchy of components leading down to what's currently being
95 pub current: Vec<String>,
96 /// The current destination folder of where HTML artifacts should be placed.
97 /// This changes as the context descends into the module hierarchy.
99 /// A flag, which when `true`, will render pages which redirect to the
100 /// real location of an item. This is used to allow external links to
101 /// publicly reused items to redirect to the right location.
102 pub render_redirect_pages: bool,
103 pub shared: Arc<SharedContext>,
106 pub struct SharedContext {
107 /// The path to the crate root source minus the file name.
108 /// Used for simplifying paths to the highlighted source code files.
109 pub src_root: PathBuf,
110 /// This describes the layout of each page, and is not modified after
111 /// creation of the context (contains info like the favicon and added html).
112 pub layout: layout::Layout,
113 /// This flag indicates whether `[src]` links should be generated or not. If
114 /// the source files are present in the html rendering, then this will be
116 pub include_sources: bool,
117 /// The local file sources we've emitted and their respective url-paths.
118 pub local_sources: FxHashMap<PathBuf, String>,
119 /// All the passes that were run on this crate.
120 pub passes: FxHashSet<String>,
121 /// The base-URL of the issue tracker for when an item has been tagged with
123 pub issue_tracker_base_url: Option<String>,
124 /// The given user css file which allow to customize the generated
125 /// documentation theme.
126 pub css_file_extension: Option<PathBuf>,
127 /// The directories that have already been created in this doc run. Used to reduce the number
128 /// of spurious `create_dir_all` calls.
129 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
130 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
131 /// should be ordered alphabetically or in order of appearance (in the source code).
132 pub sort_modules_alphabetically: bool,
133 /// Additional themes to be added to the generated docs.
134 pub themes: Vec<PathBuf>,
135 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
137 pub resource_suffix: String,
141 fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
142 let mut dirs = self.created_dirs.borrow_mut();
143 if !dirs.contains(dst) {
144 fs::create_dir_all(dst)?;
145 dirs.insert(dst.to_path_buf());
153 /// Returns whether the `collapse-docs` pass was run on this crate.
154 pub fn was_collapsed(&self) -> bool {
155 self.passes.contains("collapse-docs")
158 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
159 /// `collapsed_doc_value` of the given item.
160 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
161 if self.was_collapsed() {
162 item.collapsed_doc_value().map(|s| s.into())
164 item.doc_value().map(|s| s.into())
169 /// Indicates where an external crate can be found.
170 pub enum ExternalLocation {
171 /// Remote URL root of the external crate
173 /// This external crate can be found in the local doc/ folder
175 /// The external crate could not be found.
179 /// Metadata about implementations for a type or trait.
182 pub impl_item: clean::Item,
186 fn inner_impl(&self) -> &clean::Impl {
187 match self.impl_item.inner {
188 clean::ImplItem(ref impl_) => impl_,
189 _ => panic!("non-impl item found in impl")
193 fn trait_did(&self) -> Option<DefId> {
194 self.inner_impl().trait_.def_id()
204 impl error::Error for Error {
205 fn description(&self) -> &str {
206 self.error.description()
210 impl Display for Error {
211 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
212 write!(f, "\"{}\": {}", self.file.display(), self.error)
217 pub fn new(e: io::Error, file: &Path) -> Error {
219 file: file.to_path_buf(),
225 macro_rules! try_none {
226 ($e:expr, $file:expr) => ({
230 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
236 macro_rules! try_err {
237 ($e:expr, $file:expr) => ({
240 Err(e) => return Err(Error::new(e, $file)),
245 /// This cache is used to store information about the `clean::Crate` being
246 /// rendered in order to provide more useful documentation. This contains
247 /// information like all implementors of a trait, all traits a type implements,
248 /// documentation for all known traits, etc.
250 /// This structure purposefully does not implement `Clone` because it's intended
251 /// to be a fairly large and expensive structure to clone. Instead this adheres
252 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
253 /// rendering threads.
256 /// Mapping of typaram ids to the name of the type parameter. This is used
257 /// when pretty-printing a type (so pretty printing doesn't have to
258 /// painfully maintain a context like this)
259 pub typarams: FxHashMap<DefId, String>,
261 /// Maps a type id to all known implementations for that type. This is only
262 /// recognized for intra-crate `ResolvedPath` types, and is used to print
263 /// out extra documentation on the page of an enum/struct.
265 /// The values of the map are a list of implementations and documentation
266 /// found on that implementation.
267 pub impls: FxHashMap<DefId, Vec<Impl>>,
269 /// Maintains a mapping of local crate node ids to the fully qualified name
270 /// and "short type description" of that node. This is used when generating
271 /// URLs when a type is being linked to. External paths are not located in
272 /// this map because the `External` type itself has all the information
274 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
276 /// Similar to `paths`, but only holds external paths. This is only used for
277 /// generating explicit hyperlinks to other crates.
278 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
280 /// Maps local def ids of exported types to fully qualified paths.
281 /// Unlike 'paths', this mapping ignores any renames that occur
282 /// due to 'use' statements.
284 /// This map is used when writing out the special 'implementors'
285 /// javascript file. By using the exact path that the type
286 /// is declared with, we ensure that each path will be identical
287 /// to the path used if the corresponding type is inlined. By
288 /// doing this, we can detect duplicate impls on a trait page, and only display
289 /// the impl for the inlined type.
290 pub exact_paths: FxHashMap<DefId, Vec<String>>,
292 /// This map contains information about all known traits of this crate.
293 /// Implementations of a crate should inherit the documentation of the
294 /// parent trait if no extra documentation is specified, and default methods
295 /// should show up in documentation about trait implementations.
296 pub traits: FxHashMap<DefId, clean::Trait>,
298 /// When rendering traits, it's often useful to be able to list all
299 /// implementors of the trait, and this mapping is exactly, that: a mapping
300 /// of trait ids to the list of known implementors of the trait
301 pub implementors: FxHashMap<DefId, Vec<Impl>>,
303 /// Cache of where external crate documentation can be found.
304 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
306 /// Cache of where documentation for primitives can be found.
307 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
309 // Note that external items for which `doc(hidden)` applies to are shown as
310 // non-reachable while local items aren't. This is because we're reusing
311 // the access levels from crateanalysis.
312 pub access_levels: Arc<AccessLevels<DefId>>,
314 /// The version of the crate being documented, if given fron the `--crate-version` flag.
315 pub crate_version: Option<String>,
317 // Private fields only used when initially crawling a crate to build a cache
320 parent_stack: Vec<DefId>,
321 parent_is_trait_impl: bool,
322 search_index: Vec<IndexItem>,
324 deref_trait_did: Option<DefId>,
325 deref_mut_trait_did: Option<DefId>,
326 owned_box_did: Option<DefId>,
327 masked_crates: FxHashSet<CrateNum>,
329 // In rare case where a structure is defined in one module but implemented
330 // in another, if the implementing module is parsed before defining module,
331 // then the fully qualified name of the structure isn't presented in `paths`
332 // yet when its implementation methods are being indexed. Caches such methods
333 // and their parent id here and indexes them at the end of crate parsing.
334 orphan_impl_items: Vec<(DefId, clean::Item)>,
336 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
337 /// we need the alias element to have an array of items.
338 aliases: FxHashMap<String, Vec<IndexItem>>,
341 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
342 /// Later on moved into `CACHE_KEY`.
344 pub struct RenderInfo {
345 pub inlined: FxHashSet<DefId>,
346 pub external_paths: ::core::ExternalPaths,
347 pub external_typarams: FxHashMap<DefId, String>,
348 pub exact_paths: FxHashMap<DefId, Vec<String>>,
349 pub deref_trait_did: Option<DefId>,
350 pub deref_mut_trait_did: Option<DefId>,
351 pub owned_box_did: Option<DefId>,
354 /// Helper struct to render all source code to HTML pages
355 struct SourceCollector<'a> {
356 scx: &'a mut SharedContext,
358 /// Root destination to place all HTML output into
362 /// Wrapper struct to render the source code of a file. This will do things like
363 /// adding line numbers to the left-hand side.
364 struct Source<'a>(&'a str);
366 // Helper structs for rendering items/sidebars and carrying along contextual
369 #[derive(Copy, Clone)]
372 item: &'a clean::Item,
375 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
377 /// Struct representing one entry in the JS search index. These are all emitted
378 /// by hand to a large JS file at the end of cache-creation.
385 parent: Option<DefId>,
386 parent_idx: Option<usize>,
387 search_type: Option<IndexItemFunctionType>,
390 impl ToJson for IndexItem {
391 fn to_json(&self) -> Json {
392 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
394 let mut data = Vec::with_capacity(6);
395 data.push((self.ty as usize).to_json());
396 data.push(self.name.to_json());
397 data.push(self.path.to_json());
398 data.push(self.desc.to_json());
399 data.push(self.parent_idx.to_json());
400 data.push(self.search_type.to_json());
406 /// A type used for the search index.
409 name: Option<String>,
410 generics: Option<Vec<String>>,
413 impl ToJson for Type {
414 fn to_json(&self) -> Json {
417 let mut data = BTreeMap::new();
418 data.insert("n".to_owned(), name.to_json());
419 if let Some(ref generics) = self.generics {
420 data.insert("g".to_owned(), generics.to_json());
429 /// Full type of functions/methods in the search index.
431 struct IndexItemFunctionType {
433 output: Option<Type>,
436 impl ToJson for IndexItemFunctionType {
437 fn to_json(&self) -> Json {
438 // If we couldn't figure out a type, just write `null`.
439 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
442 let mut data = BTreeMap::new();
443 if !self.inputs.is_empty() {
444 data.insert("i".to_owned(), self.inputs.to_json());
446 if let Some(ref output) = self.output {
447 data.insert("o".to_owned(), output.to_json());
454 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
455 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
456 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
458 fn init_ids() -> FxHashMap<String, usize> {
470 "synthetic-implementors",
472 "synthetic-implementors-list",
476 ].into_iter().map(|id| (String::from(*id), 1)).collect()
479 /// This method resets the local table of used ID attributes. This is typically
480 /// used at the beginning of rendering an entire HTML page to reset from the
481 /// previous state (if any).
482 pub fn reset_ids(embedded: bool) {
483 USED_ID_MAP.with(|s| {
484 *s.borrow_mut() = if embedded {
492 pub fn derive_id(candidate: String) -> String {
493 USED_ID_MAP.with(|map| {
494 let id = match map.borrow_mut().get_mut(&candidate) {
497 let id = format!("{}-{}", candidate, *a);
503 map.borrow_mut().insert(id.clone(), 1);
508 /// Generates the documentation for `crate` into the directory `dst`
509 pub fn run(mut krate: clean::Crate,
510 external_html: &ExternalHtml,
511 playground_url: Option<String>,
513 resource_suffix: String,
514 passes: FxHashSet<String>,
515 css_file_extension: Option<PathBuf>,
516 renderinfo: RenderInfo,
517 sort_modules_alphabetically: bool,
518 themes: Vec<PathBuf>,
519 enable_minification: bool) -> Result<(), Error> {
520 let src_root = match krate.src {
521 FileName::Real(ref p) => match p.parent() {
522 Some(p) => p.to_path_buf(),
523 None => PathBuf::new(),
527 let mut scx = SharedContext {
530 include_sources: true,
531 local_sources: FxHashMap(),
532 issue_tracker_base_url: None,
533 layout: layout::Layout {
534 logo: "".to_string(),
535 favicon: "".to_string(),
536 external_html: external_html.clone(),
537 krate: krate.name.clone(),
539 css_file_extension: css_file_extension.clone(),
540 created_dirs: RefCell::new(FxHashSet()),
541 sort_modules_alphabetically,
546 // If user passed in `--playground-url` arg, we fill in crate name here
547 if let Some(url) = playground_url {
548 markdown::PLAYGROUND.with(|slot| {
549 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
553 // Crawl the crate attributes looking for attributes which control how we're
554 // going to emit HTML
555 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
556 for attr in attrs.lists("doc") {
557 let name = attr.name().map(|s| s.as_str());
558 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
559 (Some("html_favicon_url"), Some(s)) => {
560 scx.layout.favicon = s.to_string();
562 (Some("html_logo_url"), Some(s)) => {
563 scx.layout.logo = s.to_string();
565 (Some("html_playground_url"), Some(s)) => {
566 markdown::PLAYGROUND.with(|slot| {
567 let name = krate.name.clone();
568 *slot.borrow_mut() = Some((Some(name), s.to_string()));
571 (Some("issue_tracker_base_url"), Some(s)) => {
572 scx.issue_tracker_base_url = Some(s.to_string());
574 (Some("html_no_source"), None) if attr.is_word() => {
575 scx.include_sources = false;
581 try_err!(fs::create_dir_all(&dst), &dst);
582 krate = render_sources(&dst, &mut scx, krate)?;
586 render_redirect_pages: false,
587 shared: Arc::new(scx),
590 // Crawl the crate to build various caches used for the output
601 let external_paths = external_paths.into_iter()
602 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
605 let mut cache = Cache {
610 implementors: FxHashMap(),
612 parent_stack: Vec::new(),
613 search_index: Vec::new(),
614 parent_is_trait_impl: false,
615 extern_locations: FxHashMap(),
616 primitive_locations: FxHashMap(),
618 access_levels: krate.access_levels.clone(),
619 crate_version: krate.version.take(),
620 orphan_impl_items: Vec::new(),
621 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
625 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
626 typarams: external_typarams,
627 aliases: FxHashMap(),
630 // Cache where all our extern crates are located
631 for &(n, ref e) in &krate.externs {
632 let src_root = match e.src {
633 FileName::Real(ref p) => match p.parent() {
634 Some(p) => p.to_path_buf(),
635 None => PathBuf::new(),
639 cache.extern_locations.insert(n, (e.name.clone(), src_root,
640 extern_location(e, &cx.dst)));
642 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
643 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
646 // Cache where all known primitives have their documentation located.
648 // Favor linking to as local extern as possible, so iterate all crates in
649 // reverse topological order.
650 for &(_, ref e) in krate.externs.iter().rev() {
651 for &(def_id, prim, _) in &e.primitives {
652 cache.primitive_locations.insert(prim, def_id);
655 for &(def_id, prim, _) in &krate.primitives {
656 cache.primitive_locations.insert(prim, def_id);
659 cache.stack.push(krate.name.clone());
660 krate = cache.fold_crate(krate);
662 // Build our search index
663 let index = build_index(&krate, &mut cache);
665 // Freeze the cache now that the index has been built. Put an Arc into TLS
666 // for future parallelization opportunities
667 let cache = Arc::new(cache);
668 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
669 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
671 write_shared(&cx, &krate, &*cache, index, enable_minification)?;
673 // And finally render the whole crate's documentation
677 /// Build the search index from the collected metadata
678 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
679 let mut nodeid_to_pathid = FxHashMap();
680 let mut crate_items = Vec::with_capacity(cache.search_index.len());
681 let mut crate_paths = Vec::<Json>::new();
683 let Cache { ref mut search_index,
684 ref orphan_impl_items,
685 ref mut paths, .. } = *cache;
687 // Attach all orphan items to the type's definition if the type
688 // has since been learned.
689 for &(did, ref item) in orphan_impl_items {
690 if let Some(&(ref fqp, _)) = paths.get(&did) {
691 search_index.push(IndexItem {
693 name: item.name.clone().unwrap(),
694 path: fqp[..fqp.len() - 1].join("::"),
695 desc: plain_summary_line(item.doc_value()),
698 search_type: get_index_search_type(&item),
703 // Reduce `NodeId` in paths into smaller sequential numbers,
704 // and prune the paths that do not appear in the index.
705 let mut lastpath = String::new();
706 let mut lastpathid = 0usize;
708 for item in search_index {
709 item.parent_idx = item.parent.map(|nodeid| {
710 if nodeid_to_pathid.contains_key(&nodeid) {
711 *nodeid_to_pathid.get(&nodeid).unwrap()
713 let pathid = lastpathid;
714 nodeid_to_pathid.insert(nodeid, pathid);
717 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
718 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
723 // Omit the parent path if it is same to that of the prior item.
724 if lastpath == item.path {
727 lastpath = item.path.clone();
729 crate_items.push(item.to_json());
732 let crate_doc = krate.module.as_ref().map(|module| {
733 plain_summary_line(module.doc_value())
734 }).unwrap_or(String::new());
736 let mut crate_data = BTreeMap::new();
737 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
738 crate_data.insert("items".to_owned(), Json::Array(crate_items));
739 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
741 // Collect the index into a string
742 format!("searchIndex[{}] = {};",
743 as_json(&krate.name),
744 Json::Object(crate_data))
747 fn write_shared(cx: &Context,
748 krate: &clean::Crate,
750 search_index: String,
751 enable_minification: bool) -> Result<(), Error> {
752 // Write out the shared files. Note that these are shared among all rustdoc
753 // docs placed in the output directory, so this needs to be a synchronized
754 // operation with respect to all other rustdocs running around.
755 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
757 // Add all the static files. These may already exist, but we just
758 // overwrite them anyway to make sure that they're fresh and up-to-date.
760 write(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
761 include_bytes!("static/rustdoc.css"))?;
762 write(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
763 include_bytes!("static/settings.css"))?;
765 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
766 // then we'll run over the "official" styles.
767 let mut themes: HashSet<String> = HashSet::new();
769 for entry in &cx.shared.themes {
770 let mut content = Vec::with_capacity(100000);
772 let mut f = try_err!(File::open(&entry), &entry);
773 try_err!(f.read_to_end(&mut content), &entry);
774 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
775 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
776 write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
777 content.as_slice())?;
778 themes.insert(theme.to_owned());
781 write(cx.dst.join(&format!("brush{}.svg", cx.shared.resource_suffix)),
782 include_bytes!("static/brush.svg"))?;
783 write(cx.dst.join(&format!("wheel{}.svg", cx.shared.resource_suffix)),
784 include_bytes!("static/wheel.svg"))?;
785 write(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
786 include_bytes!("static/themes/light.css"))?;
787 themes.insert("light".to_owned());
788 write(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
789 include_bytes!("static/themes/dark.css"))?;
790 themes.insert("dark".to_owned());
792 let mut themes: Vec<&String> = themes.iter().collect();
794 // To avoid theme switch latencies as much as possible, we put everything theme related
795 // at the beginning of the html files into another js file.
796 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
798 r#"var themes = document.getElementById("theme-choices");
799 var themePicker = document.getElementById("theme-picker");
801 function switchThemeButtonState() {{
802 if (themes.style.display === "block") {{
803 themes.style.display = "none";
804 themePicker.style.borderBottomRightRadius = "3px";
805 themePicker.style.borderBottomLeftRadius = "3px";
807 themes.style.display = "block";
808 themePicker.style.borderBottomRightRadius = "0";
809 themePicker.style.borderBottomLeftRadius = "0";
813 function handleThemeButtonsBlur(e) {{
814 var active = document.activeElement;
815 var related = e.relatedTarget;
817 if (active.id !== "themePicker" &&
818 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
820 (related.id !== "themePicker" &&
821 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
822 switchThemeButtonState();
826 themePicker.onclick = switchThemeButtonState;
827 themePicker.onblur = handleThemeButtonsBlur;
828 [{}].forEach(function(item) {{
829 var but = document.createElement('button');
830 but.innerHTML = item;
831 but.onclick = function(el) {{
832 switchTheme(currentTheme, mainTheme, item);
834 but.onblur = handleThemeButtonsBlur;
835 themes.appendChild(but);
838 .map(|s| format!("\"{}\"", s))
839 .collect::<Vec<String>>()
840 .join(",")).as_bytes(),
843 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
844 include_str!("static/main.js"),
845 enable_minification)?;
846 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
847 include_str!("static/settings.js"),
848 enable_minification)?;
851 let mut data = format!("var resourcesSuffix = \"{}\";\n",
852 cx.shared.resource_suffix);
853 data.push_str(include_str!("static/storage.js"));
854 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
856 enable_minification)?;
859 if let Some(ref css) = cx.shared.css_file_extension {
860 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
861 try_err!(fs::copy(css, out), css);
863 write(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
864 include_bytes!("static/normalize.css"))?;
865 write(cx.dst.join("FiraSans-Regular.woff"),
866 include_bytes!("static/FiraSans-Regular.woff"))?;
867 write(cx.dst.join("FiraSans-Medium.woff"),
868 include_bytes!("static/FiraSans-Medium.woff"))?;
869 write(cx.dst.join("FiraSans-LICENSE.txt"),
870 include_bytes!("static/FiraSans-LICENSE.txt"))?;
871 write(cx.dst.join("Heuristica-Italic.woff"),
872 include_bytes!("static/Heuristica-Italic.woff"))?;
873 write(cx.dst.join("Heuristica-LICENSE.txt"),
874 include_bytes!("static/Heuristica-LICENSE.txt"))?;
875 write(cx.dst.join("SourceSerifPro-Regular.woff"),
876 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
877 write(cx.dst.join("SourceSerifPro-Bold.woff"),
878 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
879 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
880 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
881 write(cx.dst.join("SourceCodePro-Regular.woff"),
882 include_bytes!("static/SourceCodePro-Regular.woff"))?;
883 write(cx.dst.join("SourceCodePro-Semibold.woff"),
884 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
885 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
886 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
887 write(cx.dst.join("LICENSE-MIT.txt"),
888 include_bytes!("static/LICENSE-MIT.txt"))?;
889 write(cx.dst.join("LICENSE-APACHE.txt"),
890 include_bytes!("static/LICENSE-APACHE.txt"))?;
891 write(cx.dst.join("COPYRIGHT.txt"),
892 include_bytes!("static/COPYRIGHT.txt"))?;
894 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<Vec<String>> {
895 let mut ret = Vec::new();
897 for line in BufReader::new(File::open(path)?).lines() {
899 if !line.starts_with(key) {
902 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
905 ret.push(line.to_string());
911 fn show_item(item: &IndexItem, krate: &str) -> String {
912 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
913 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
914 if let Some(p) = item.parent_idx {
915 format!(",'parent':{}", p)
921 let dst = cx.dst.join("aliases.js");
923 let mut all_aliases = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
924 let mut w = try_err!(File::create(&dst), &dst);
925 let mut output = String::with_capacity(100);
926 for (alias, items) in &cache.aliases {
927 if items.is_empty() {
930 output.push_str(&format!("\"{}\":[{}],",
933 .map(|v| show_item(v, &krate.name))
937 all_aliases.push(format!("ALIASES['{}'] = {{{}}};", krate.name, output));
939 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
940 for aliases in &all_aliases {
941 try_err!(writeln!(&mut w, "{}", aliases), &dst);
945 // Update the search index
946 let dst = cx.dst.join("search-index.js");
947 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
948 all_indexes.push(search_index);
949 // Sort the indexes by crate so the file will be generated identically even
950 // with rustdoc running in parallel.
952 let mut w = try_err!(File::create(&dst), &dst);
953 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
954 for index in &all_indexes {
955 try_err!(writeln!(&mut w, "{}", *index), &dst);
957 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
959 // Update the list of all implementors for traits
960 let dst = cx.dst.join("implementors");
961 for (&did, imps) in &cache.implementors {
962 // Private modules can leak through to this phase of rustdoc, which
963 // could contain implementations for otherwise private types. In some
964 // rare cases we could find an implementation for an item which wasn't
965 // indexed, so we just skip this step in that case.
967 // FIXME: this is a vague explanation for why this can't be a `get`, in
968 // theory it should be...
969 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
971 None => match cache.external_paths.get(&did) {
977 let mut have_impls = false;
978 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
980 // If the trait and implementation are in the same crate, then
981 // there's no need to emit information about it (there's inlining
982 // going on). If they're in different crates then the crate defining
983 // the trait will be interested in our implementation.
984 if imp.impl_item.def_id.krate == did.krate { continue }
985 // If the implementation is from another crate then that crate
987 if !imp.impl_item.def_id.is_local() { continue }
989 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
990 as_json(&imp.inner_impl().to_string()),
991 imp.inner_impl().synthetic,
992 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
994 implementors.push_str("];");
996 // Only create a js file if we have impls to add to it. If the trait is
997 // documented locally though we always create the file to avoid dead
999 if !have_impls && !cache.paths.contains_key(&did) {
1003 let mut mydst = dst.clone();
1004 for part in &remote_path[..remote_path.len() - 1] {
1007 try_err!(fs::create_dir_all(&mydst), &mydst);
1008 mydst.push(&format!("{}.{}.js",
1009 remote_item_type.css_class(),
1010 remote_path[remote_path.len() - 1]));
1012 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1013 all_implementors.push(implementors);
1014 // Sort the implementors by crate so the file will be generated
1015 // identically even with rustdoc running in parallel.
1016 all_implementors.sort();
1018 let mut f = try_err!(File::create(&mydst), &mydst);
1019 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1020 for implementor in &all_implementors {
1021 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1023 try_err!(writeln!(&mut f, "{}", r"
1024 if (window.register_implementors) {
1025 window.register_implementors(implementors);
1027 window.pending_implementors = implementors;
1030 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1035 fn render_sources(dst: &Path, scx: &mut SharedContext,
1036 krate: clean::Crate) -> Result<clean::Crate, Error> {
1037 info!("emitting source files");
1038 let dst = dst.join("src").join(&krate.name);
1039 try_err!(fs::create_dir_all(&dst), &dst);
1040 let mut folder = SourceCollector {
1044 Ok(folder.fold_crate(krate))
1047 /// Writes the entire contents of a string to a destination, not attempting to
1048 /// catch any errors.
1049 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1050 Ok(try_err!(fs::write(&dst, contents), &dst))
1053 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1054 if enable_minification {
1055 write(dst, minifier::js::minify(contents).as_bytes())
1057 write(dst, contents.as_bytes())
1061 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1062 /// things like ".." to components which preserve the "top down" hierarchy of a
1063 /// static HTML tree. Each component in the cleaned path will be passed as an
1064 /// argument to `f`. The very last component of the path (ie the file name) will
1065 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1066 // FIXME (#9639): The closure should deal with &[u8] instead of &str
1067 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
1068 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1071 // make it relative, if possible
1072 let p = p.strip_prefix(src_root).unwrap_or(p);
1074 let mut iter = p.components().peekable();
1076 while let Some(c) = iter.next() {
1077 if !keep_filename && iter.peek().is_none() {
1082 Component::ParentDir => f("up"),
1083 Component::Normal(c) => f(c.to_str().unwrap()),
1089 /// Attempts to find where an external crate is located, given that we're
1090 /// rendering in to the specified source destination.
1091 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
1092 // See if there's documentation generated into the local directory
1093 let local_location = dst.join(&e.name);
1094 if local_location.is_dir() {
1098 // Failing that, see if there's an attribute specifying where to find this
1100 e.attrs.lists("doc")
1101 .filter(|a| a.check_name("html_root_url"))
1102 .filter_map(|a| a.value_str())
1104 let mut url = url.to_string();
1105 if !url.ends_with("/") {
1109 }).next().unwrap_or(Unknown) // Well, at least we tried.
1112 impl<'a> DocFolder for SourceCollector<'a> {
1113 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1114 // If we're including source files, and we haven't seen this file yet,
1115 // then we need to render it out to the filesystem.
1116 if self.scx.include_sources
1117 // skip all invalid or macro spans
1118 && item.source.filename.is_real()
1119 // skip non-local items
1120 && item.def_id.is_local() {
1122 // If it turns out that we couldn't read this file, then we probably
1123 // can't read any of the files (generating html output from json or
1124 // something like that), so just don't include sources for the
1125 // entire crate. The other option is maintaining this mapping on a
1126 // per-file basis, but that's probably not worth it...
1128 .include_sources = match self.emit_source(&item.source.filename) {
1131 println!("warning: source code was requested to be rendered, \
1132 but processing `{}` had an error: {}",
1133 item.source.filename, e);
1134 println!(" skipping rendering of source code");
1139 self.fold_item_recur(item)
1143 impl<'a> SourceCollector<'a> {
1144 /// Renders the given filename into its corresponding HTML source file.
1145 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1146 let p = match *filename {
1147 FileName::Real(ref file) => file,
1150 if self.scx.local_sources.contains_key(&**p) {
1151 // We've already emitted this source
1155 let contents = fs::read_to_string(&p)?;
1157 // Remove the utf-8 BOM if any
1158 let contents = if contents.starts_with("\u{feff}") {
1164 // Create the intermediate directories
1165 let mut cur = self.dst.clone();
1166 let mut root_path = String::from("../../");
1167 let mut href = String::new();
1168 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1169 cur.push(component);
1170 fs::create_dir_all(&cur).unwrap();
1171 root_path.push_str("../");
1172 href.push_str(component);
1175 let mut fname = p.file_name()
1176 .expect("source has no filename")
1178 fname.push(".html");
1180 href.push_str(&fname.to_string_lossy());
1182 let mut w = BufWriter::new(File::create(&cur)?);
1183 let title = format!("{} -- source", cur.file_name().unwrap()
1184 .to_string_lossy());
1185 let desc = format!("Source to the Rust file `{}`.", filename);
1186 let page = layout::Page {
1188 css_class: "source",
1189 root_path: &root_path,
1191 keywords: BASIC_KEYWORDS,
1192 resource_suffix: &self.scx.resource_suffix,
1194 layout::render(&mut w, &self.scx.layout,
1195 &page, &(""), &Source(contents),
1196 self.scx.css_file_extension.is_some(),
1199 self.scx.local_sources.insert(p.clone(), href);
1204 impl DocFolder for Cache {
1205 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1206 // If this is a stripped module,
1207 // we don't want it or its children in the search index.
1208 let orig_stripped_mod = match item.inner {
1209 clean::StrippedItem(box clean::ModuleItem(..)) => {
1210 mem::replace(&mut self.stripped_mod, true)
1212 _ => self.stripped_mod,
1215 // If the impl is from a masked crate or references something from a
1216 // masked crate then remove it completely.
1217 if let clean::ImplItem(ref i) = item.inner {
1218 if self.masked_crates.contains(&item.def_id.krate) ||
1219 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1220 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1225 // Register any generics to their corresponding string. This is used
1226 // when pretty-printing types.
1227 if let Some(generics) = item.inner.generics() {
1228 self.generics(generics);
1231 // Propagate a trait method's documentation to all implementors of the
1233 if let clean::TraitItem(ref t) = item.inner {
1234 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1237 // Collect all the implementors of traits.
1238 if let clean::ImplItem(ref i) = item.inner {
1239 if let Some(did) = i.trait_.def_id() {
1240 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1241 impl_item: item.clone(),
1246 // Index this method for searching later on.
1247 if let Some(ref s) = item.name {
1248 let (parent, is_inherent_impl_item) = match item.inner {
1249 clean::StrippedItem(..) => ((None, None), false),
1250 clean::AssociatedConstItem(..) |
1251 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1252 // skip associated items in trait impls
1253 ((None, None), false)
1255 clean::AssociatedTypeItem(..) |
1256 clean::TyMethodItem(..) |
1257 clean::StructFieldItem(..) |
1258 clean::VariantItem(..) => {
1259 ((Some(*self.parent_stack.last().unwrap()),
1260 Some(&self.stack[..self.stack.len() - 1])),
1263 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1264 if self.parent_stack.is_empty() {
1265 ((None, None), false)
1267 let last = self.parent_stack.last().unwrap();
1269 let path = match self.paths.get(&did) {
1270 // The current stack not necessarily has correlation
1271 // for where the type was defined. On the other
1272 // hand, `paths` always has the right
1273 // information if present.
1274 Some(&(ref fqp, ItemType::Trait)) |
1275 Some(&(ref fqp, ItemType::Struct)) |
1276 Some(&(ref fqp, ItemType::Union)) |
1277 Some(&(ref fqp, ItemType::Enum)) =>
1278 Some(&fqp[..fqp.len() - 1]),
1279 Some(..) => Some(&*self.stack),
1282 ((Some(*last), path), true)
1285 _ => ((None, Some(&*self.stack)), false)
1289 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1290 debug_assert!(!item.is_stripped());
1292 // A crate has a module at its root, containing all items,
1293 // which should not be indexed. The crate-item itself is
1294 // inserted later on when serializing the search-index.
1295 if item.def_id.index != CRATE_DEF_INDEX {
1296 self.search_index.push(IndexItem {
1298 name: s.to_string(),
1299 path: path.join("::").to_string(),
1300 desc: plain_summary_line(item.doc_value()),
1303 search_type: get_index_search_type(&item),
1307 (Some(parent), None) if is_inherent_impl_item => {
1308 // We have a parent, but we don't know where they're
1309 // defined yet. Wait for later to index this item.
1310 self.orphan_impl_items.push((parent, item.clone()));
1316 // Keep track of the fully qualified path for this item.
1317 let pushed = match item.name {
1318 Some(ref n) if !n.is_empty() => {
1319 self.stack.push(n.to_string());
1326 clean::StructItem(..) | clean::EnumItem(..) |
1327 clean::TypedefItem(..) | clean::TraitItem(..) |
1328 clean::FunctionItem(..) | clean::ModuleItem(..) |
1329 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1330 clean::ConstantItem(..) | clean::StaticItem(..) |
1331 clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1332 if !self.stripped_mod => {
1333 // Re-exported items mean that the same id can show up twice
1334 // in the rustdoc ast that we're looking at. We know,
1335 // however, that a re-exported item doesn't show up in the
1336 // `public_items` map, so we can skip inserting into the
1337 // paths map if there was already an entry present and we're
1338 // not a public item.
1339 if !self.paths.contains_key(&item.def_id) ||
1340 self.access_levels.is_public(item.def_id)
1342 self.paths.insert(item.def_id,
1343 (self.stack.clone(), item.type_()));
1345 self.add_aliases(&item);
1347 // Link variants to their parent enum because pages aren't emitted
1348 // for each variant.
1349 clean::VariantItem(..) if !self.stripped_mod => {
1350 let mut stack = self.stack.clone();
1352 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1355 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1356 self.add_aliases(&item);
1357 self.paths.insert(item.def_id, (self.stack.clone(),
1364 // Maintain the parent stack
1365 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1366 let parent_pushed = match item.inner {
1367 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1368 clean::StructItem(..) | clean::UnionItem(..) => {
1369 self.parent_stack.push(item.def_id);
1370 self.parent_is_trait_impl = false;
1373 clean::ImplItem(ref i) => {
1374 self.parent_is_trait_impl = i.trait_.is_some();
1376 clean::ResolvedPath{ did, .. } => {
1377 self.parent_stack.push(did);
1381 let prim_did = t.primitive_type().and_then(|t| {
1382 self.primitive_locations.get(&t).cloned()
1386 self.parent_stack.push(did);
1397 // Once we've recursively found all the generics, hoard off all the
1398 // implementations elsewhere.
1399 let ret = self.fold_item_recur(item).and_then(|item| {
1400 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1401 // Figure out the id of this impl. This may map to a
1402 // primitive rather than always to a struct/enum.
1403 // Note: matching twice to restrict the lifetime of the `i` borrow.
1404 let mut dids = FxHashSet();
1405 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1407 clean::ResolvedPath { did, .. } |
1408 clean::BorrowedRef {
1409 type_: box clean::ResolvedPath { did, .. }, ..
1414 let did = t.primitive_type().and_then(|t| {
1415 self.primitive_locations.get(&t).cloned()
1418 if let Some(did) = did {
1424 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1425 for bound in generics {
1426 if let Some(did) = bound.def_id() {
1435 self.impls.entry(did).or_insert(vec![]).push(Impl {
1436 impl_item: item.clone(),
1445 if pushed { self.stack.pop().unwrap(); }
1446 if parent_pushed { self.parent_stack.pop().unwrap(); }
1447 self.stripped_mod = orig_stripped_mod;
1448 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1454 fn generics(&mut self, generics: &clean::Generics) {
1455 for param in &generics.params {
1456 if let clean::GenericParam::Type(ref typ) = *param {
1457 self.typarams.insert(typ.did, typ.name.clone());
1462 fn add_aliases(&mut self, item: &clean::Item) {
1463 if item.def_id.index == CRATE_DEF_INDEX {
1466 if let Some(ref item_name) = item.name {
1467 let path = self.paths.get(&item.def_id)
1468 .map(|p| p.0[..p.0.len() - 1].join("::"))
1469 .unwrap_or("std".to_owned());
1470 for alias in item.attrs.lists("doc")
1471 .filter(|a| a.check_name("alias"))
1472 .filter_map(|a| a.value_str()
1473 .map(|s| s.to_string().replace("\"", "")))
1474 .filter(|v| !v.is_empty())
1475 .collect::<FxHashSet<_>>()
1477 self.aliases.entry(alias)
1478 .or_insert(Vec::with_capacity(1))
1481 name: item_name.to_string(),
1483 desc: plain_summary_line(item.doc_value()),
1486 search_type: get_index_search_type(&item),
1493 #[derive(Debug, Eq, PartialEq, Hash)]
1500 fn new(mut url: String, name: String) -> ItemEntry {
1501 while url.starts_with('/') {
1511 impl fmt::Display for ItemEntry {
1512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1513 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1517 impl PartialOrd for ItemEntry {
1518 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1519 Some(self.cmp(other))
1523 impl Ord for ItemEntry {
1524 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1525 self.name.cmp(&other.name)
1531 structs: HashSet<ItemEntry>,
1532 enums: HashSet<ItemEntry>,
1533 unions: HashSet<ItemEntry>,
1534 primitives: HashSet<ItemEntry>,
1535 traits: HashSet<ItemEntry>,
1536 macros: HashSet<ItemEntry>,
1537 functions: HashSet<ItemEntry>,
1538 typedefs: HashSet<ItemEntry>,
1539 statics: HashSet<ItemEntry>,
1540 constants: HashSet<ItemEntry>,
1544 fn new() -> AllTypes {
1546 structs: HashSet::with_capacity(100),
1547 enums: HashSet::with_capacity(100),
1548 unions: HashSet::with_capacity(100),
1549 primitives: HashSet::with_capacity(26),
1550 traits: HashSet::with_capacity(100),
1551 macros: HashSet::with_capacity(100),
1552 functions: HashSet::with_capacity(100),
1553 typedefs: HashSet::with_capacity(100),
1554 statics: HashSet::with_capacity(100),
1555 constants: HashSet::with_capacity(100),
1559 fn append(&mut self, item_name: String, item_type: &ItemType) {
1560 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1561 if let Some(name) = url.pop() {
1562 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1564 let name = url.join("::");
1566 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1567 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1568 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1569 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1570 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1571 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1572 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1573 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1574 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1575 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1582 fn print_entries(f: &mut fmt::Formatter, e: &HashSet<ItemEntry>, title: &str,
1583 class: &str) -> fmt::Result {
1585 let mut e: Vec<&ItemEntry> = e.iter().collect();
1587 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1591 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1596 impl fmt::Display for AllTypes {
1597 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1600 <span class='in-band'>List of all items</span>\
1601 <span class='out-of-band'>\
1602 <span id='render-detail'>\
1603 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1604 [<span class='inner'>−</span>]\
1609 print_entries(f, &self.structs, "Structs", "structs")?;
1610 print_entries(f, &self.enums, "Enums", "enums")?;
1611 print_entries(f, &self.unions, "Unions", "unions")?;
1612 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1613 print_entries(f, &self.traits, "Traits", "traits")?;
1614 print_entries(f, &self.macros, "Macros", "macros")?;
1615 print_entries(f, &self.functions, "Functions", "functions")?;
1616 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1617 print_entries(f, &self.statics, "Statics", "statics")?;
1618 print_entries(f, &self.constants, "Constants", "constants")
1623 struct Settings<'a> {
1624 // (id, explanation, default value)
1625 settings: Vec<(&'static str, &'static str, bool)>,
1630 impl<'a> Settings<'a> {
1631 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1634 ("item-declarations", "Auto-hide item declarations.", true),
1635 ("item-attributes", "Auto-hide item attributes.", true),
1636 ("go-to-only-result", "Directly go to item in search if there is only one result",
1645 impl<'a> fmt::Display for Settings<'a> {
1646 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1649 <span class='in-band'>Rustdoc settings</span>\
1651 <div class='settings'>{}</div>\
1652 <script src='{}settings{}.js'></script>",
1653 self.settings.iter()
1654 .map(|(id, text, enabled)| {
1655 format!("<div class='setting-line'>\
1656 <label class='toggle'>\
1657 <input type='checkbox' id='{}' {}>\
1658 <span class='slider'></span>\
1661 </div>", id, if *enabled { " checked" } else { "" }, text)
1663 .collect::<String>(),
1670 /// String representation of how to get back to the root path of the 'doc/'
1671 /// folder in terms of a relative URL.
1672 fn root_path(&self) -> String {
1673 repeat("../").take(self.current.len()).collect::<String>()
1676 /// Recurse in the directory structure and change the "root path" to make
1677 /// sure it always points to the top (relatively).
1678 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1679 F: FnOnce(&mut Context) -> T,
1682 panic!("Unexpected empty destination: {:?}", self.current);
1684 let prev = self.dst.clone();
1686 self.current.push(s);
1688 info!("Recursing into {}", self.dst.display());
1692 info!("Recursed; leaving {}", self.dst.display());
1694 // Go back to where we were at
1696 self.current.pop().unwrap();
1701 /// Main method for rendering a crate.
1703 /// This currently isn't parallelized, but it'd be pretty easy to add
1704 /// parallelization to this function.
1705 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1706 let mut item = match krate.module.take() {
1708 None => return Ok(()),
1710 let final_file = self.dst.join(&krate.name)
1712 let settings_file = self.dst.join("settings.html");
1714 let crate_name = krate.name.clone();
1715 item.name = Some(krate.name);
1717 let mut all = AllTypes::new();
1720 // Render the crate documentation
1721 let mut work = vec![(self.clone(), item)];
1723 while let Some((mut cx, item)) = work.pop() {
1724 cx.item(item, &mut all, |cx, item| {
1725 work.push((cx.clone(), item))
1730 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
1731 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1732 if !root_path.ends_with('/') {
1733 root_path.push('/');
1735 let mut page = layout::Page {
1736 title: "List of all items in this crate",
1739 description: "List of all items in this crate",
1740 keywords: BASIC_KEYWORDS,
1741 resource_suffix: &self.shared.resource_suffix,
1743 let sidebar = if let Some(ref version) = cache().crate_version {
1744 format!("<p class='location'>Crate {}</p>\
1745 <div class='block version'>\
1748 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1749 crate_name, version)
1753 try_err!(layout::render(&mut w, &self.shared.layout,
1754 &page, &sidebar, &all,
1755 self.shared.css_file_extension.is_some(),
1756 &self.shared.themes),
1759 // Generating settings page.
1760 let settings = Settings::new("./", &self.shared.resource_suffix);
1761 page.title = "Rustdoc settings";
1762 page.description = "Settings of Rustdoc";
1763 page.root_path = "./";
1765 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
1766 let mut themes = self.shared.themes.clone();
1767 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1768 themes.push(PathBuf::from("settings.css"));
1769 let mut layout = self.shared.layout.clone();
1770 layout.krate = String::new();
1771 layout.logo = String::new();
1772 layout.favicon = String::new();
1773 try_err!(layout::render(&mut w, &layout,
1774 &page, &sidebar, &settings,
1775 self.shared.css_file_extension.is_some(),
1782 fn render_item(&self,
1783 writer: &mut io::Write,
1787 // A little unfortunate that this is done like this, but it sure
1788 // does make formatting *a lot* nicer.
1789 CURRENT_LOCATION_KEY.with(|slot| {
1790 *slot.borrow_mut() = self.current.clone();
1793 let mut title = if it.is_primitive() {
1794 // No need to include the namespace for primitive types
1797 self.current.join("::")
1800 if !title.is_empty() {
1801 title.push_str("::");
1803 title.push_str(it.name.as_ref().unwrap());
1805 title.push_str(" - Rust");
1806 let tyname = it.type_().css_class();
1807 let desc = if it.is_crate() {
1808 format!("API documentation for the Rust `{}` crate.",
1809 self.shared.layout.krate)
1811 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1812 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1814 let keywords = make_item_keywords(it);
1815 let page = layout::Page {
1817 root_path: &self.root_path(),
1820 keywords: &keywords,
1821 resource_suffix: &self.shared.resource_suffix,
1826 if !self.render_redirect_pages {
1827 layout::render(writer, &self.shared.layout, &page,
1828 &Sidebar{ cx: self, item: it },
1829 &Item{ cx: self, item: it },
1830 self.shared.css_file_extension.is_some(),
1831 &self.shared.themes)?;
1833 let mut url = self.root_path();
1834 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1835 for name in &names[..names.len() - 1] {
1839 url.push_str(&item_path(ty, names.last().unwrap()));
1840 layout::redirect(writer, &url)?;
1846 /// Non-parallelized version of rendering an item. This will take the input
1847 /// item, render its contents, and then invoke the specified closure with
1848 /// all sub-items which need to be rendered.
1850 /// The rendering driver uses this closure to queue up more work.
1851 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
1852 where F: FnMut(&mut Context, clean::Item),
1854 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1855 // if they contain impls for public types. These modules can also
1856 // contain items such as publicly re-exported structures.
1858 // External crates will provide links to these structures, so
1859 // these modules are recursed into, but not rendered normally
1860 // (a flag on the context).
1861 if !self.render_redirect_pages {
1862 self.render_redirect_pages = item.is_stripped();
1866 // modules are special because they add a namespace. We also need to
1867 // recurse into the items of the module as well.
1868 let name = item.name.as_ref().unwrap().to_string();
1869 let mut item = Some(item);
1870 self.recurse(name, |this| {
1871 let item = item.take().unwrap();
1873 let mut buf = Vec::new();
1874 this.render_item(&mut buf, &item, false).unwrap();
1875 // buf will be empty if the module is stripped and there is no redirect for it
1876 if !buf.is_empty() {
1877 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1878 let joint_dst = this.dst.join("index.html");
1879 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1880 try_err!(dst.write_all(&buf), &joint_dst);
1883 let m = match item.inner {
1884 clean::StrippedItem(box clean::ModuleItem(m)) |
1885 clean::ModuleItem(m) => m,
1889 // Render sidebar-items.js used throughout this module.
1890 if !this.render_redirect_pages {
1891 let items = this.build_sidebar_items(&m);
1892 let js_dst = this.dst.join("sidebar-items.js");
1893 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1894 try_err!(write!(&mut js_out, "initSidebarItems({});",
1895 as_json(&items)), &js_dst);
1898 for item in m.items {
1904 } else if item.name.is_some() {
1905 let mut buf = Vec::new();
1906 self.render_item(&mut buf, &item, true).unwrap();
1907 // buf will be empty if the item is stripped and there is no redirect for it
1908 if !buf.is_empty() {
1909 let name = item.name.as_ref().unwrap();
1910 let item_type = item.type_();
1911 let file_name = &item_path(item_type, name);
1912 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1913 let joint_dst = self.dst.join(file_name);
1914 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1915 try_err!(dst.write_all(&buf), &joint_dst);
1917 if !self.render_redirect_pages {
1918 all.append(full_path(self, &item), &item_type);
1920 // Redirect from a sane URL using the namespace to Rustdoc's
1921 // URL for the page.
1922 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1923 let redir_dst = self.dst.join(redir_name);
1924 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1927 let mut redirect_out = BufWriter::new(redirect_out);
1928 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1931 // If the item is a macro, redirect from the old macro URL (with !)
1932 // to the new one (without).
1933 // FIXME(#35705) remove this redirect.
1934 if item_type == ItemType::Macro {
1935 let redir_name = format!("{}.{}!.html", item_type, name);
1936 let redir_dst = self.dst.join(redir_name);
1937 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1938 let mut redirect_out = BufWriter::new(redirect_out);
1939 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1946 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1947 // BTreeMap instead of HashMap to get a sorted output
1948 let mut map = BTreeMap::new();
1949 for item in &m.items {
1950 if item.is_stripped() { continue }
1952 let short = item.type_().css_class();
1953 let myname = match item.name {
1955 Some(ref s) => s.to_string(),
1957 let short = short.to_string();
1958 map.entry(short).or_insert(vec![])
1959 .push((myname, Some(plain_summary_line(item.doc_value()))));
1962 if self.shared.sort_modules_alphabetically {
1963 for (_, items) in &mut map {
1972 /// Generate a url appropriate for an `href` attribute back to the source of
1975 /// The url generated, when clicked, will redirect the browser back to the
1976 /// original source code.
1978 /// If `None` is returned, then a source link couldn't be generated. This
1979 /// may happen, for example, with externally inlined items where the source
1980 /// of their crate documentation isn't known.
1981 fn src_href(&self) -> Option<String> {
1982 let mut root = self.cx.root_path();
1984 let cache = cache();
1985 let mut path = String::new();
1987 // We can safely ignore macros from other libraries
1988 let file = match self.item.source.filename {
1989 FileName::Real(ref path) => path,
1993 let (krate, path) = if self.item.def_id.is_local() {
1994 if let Some(path) = self.cx.shared.local_sources.get(file) {
1995 (&self.cx.shared.layout.krate, path)
2000 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
2001 Some(&(ref name, ref src, Local)) => (name, src),
2002 Some(&(ref name, ref src, Remote(ref s))) => {
2003 root = s.to_string();
2006 Some(&(_, _, Unknown)) | None => return None,
2009 clean_srcpath(&src_root, file, false, |component| {
2010 path.push_str(component);
2013 let mut fname = file.file_name().expect("source has no filename")
2015 fname.push(".html");
2016 path.push_str(&fname.to_string_lossy());
2020 let lines = if self.item.source.loline == self.item.source.hiline {
2021 format!("{}", self.item.source.loline)
2023 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2025 Some(format!("{root}src/{krate}/{path}#{lines}",
2026 root = Escape(&root),
2033 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2034 f: F) -> fmt::Result
2035 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2036 write!(w, "<div class=\"docblock type-decl\">")?;
2041 impl<'a> fmt::Display for Item<'a> {
2042 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2043 debug_assert!(!self.item.is_stripped());
2044 // Write the breadcrumb trail header for the top
2045 write!(fmt, "<h1 class='fqn'><span class='in-band'>")?;
2046 match self.item.inner {
2047 clean::ModuleItem(ref m) => if m.is_crate {
2048 write!(fmt, "Crate ")?;
2050 write!(fmt, "Module ")?;
2052 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2053 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2054 clean::StructItem(..) => write!(fmt, "Struct ")?,
2055 clean::UnionItem(..) => write!(fmt, "Union ")?,
2056 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2057 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2058 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2059 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2060 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2061 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2062 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2064 // We don't generate pages for any other type.
2068 if !self.item.is_primitive() {
2069 let cur = &self.cx.current;
2070 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2071 for (i, component) in cur.iter().enumerate().take(amt) {
2072 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2073 repeat("../").take(cur.len() - i - 1)
2074 .collect::<String>(),
2078 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2079 self.item.type_(), self.item.name.as_ref().unwrap())?;
2081 write!(fmt, "</span>")?; // in-band
2082 write!(fmt, "<span class='out-of-band'>")?;
2083 if let Some(version) = self.item.stable_since() {
2084 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2088 "<span id='render-detail'>\
2089 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2090 title=\"collapse all docs\">\
2091 [<span class='inner'>−</span>]\
2097 // When this item is part of a `pub use` in a downstream crate, the
2098 // [src] link in the downstream documentation will actually come back to
2099 // this page, and this link will be auto-clicked. The `id` attribute is
2100 // used to find the link to auto-click.
2101 if self.cx.shared.include_sources && !self.item.is_primitive() {
2102 if let Some(l) = self.src_href() {
2103 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2104 l, "goto source code")?;
2108 write!(fmt, "</span></h1>")?; // out-of-band
2110 match self.item.inner {
2111 clean::ModuleItem(ref m) =>
2112 item_module(fmt, self.cx, self.item, &m.items),
2113 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2114 item_function(fmt, self.cx, self.item, f),
2115 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2116 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2117 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2118 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2119 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2120 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2121 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2122 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2123 item_static(fmt, self.cx, self.item, i),
2124 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2125 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2127 // We don't generate pages for any other type.
2134 fn item_path(ty: ItemType, name: &str) -> String {
2136 ItemType::Module => format!("{}/index.html", name),
2137 _ => format!("{}.{}.html", ty.css_class(), name),
2141 fn full_path(cx: &Context, item: &clean::Item) -> String {
2142 let mut s = cx.current.join("::");
2144 s.push_str(item.name.as_ref().unwrap());
2148 fn shorter<'a>(s: Option<&'a str>) -> String {
2150 Some(s) => s.lines()
2151 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2153 (*line).chars().any(|chr|{
2154 !chr.is_whitespace()
2156 }).collect::<Vec<_>>().join("\n"),
2157 None => "".to_string()
2162 fn plain_summary_line(s: Option<&str>) -> String {
2163 let line = shorter(s).replace("\n", " ");
2164 markdown::plain_summary_line(&line[..])
2167 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2168 if let Some(ref name) = item.name {
2169 info!("Documenting {}", name);
2171 document_stability(w, cx, item)?;
2172 let prefix = render_assoc_const_value(item);
2173 document_full(w, item, cx, &prefix)?;
2177 /// Render md_text as markdown.
2178 fn render_markdown(w: &mut fmt::Formatter,
2180 links: Vec<(String, String)>,
2183 write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
2186 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
2187 prefix: &str) -> fmt::Result {
2188 if let Some(s) = item.doc_value() {
2189 let markdown = if s.contains('\n') {
2190 format!("{} [Read more]({})",
2191 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2193 format!("{}", &plain_summary_line(Some(s)))
2195 render_markdown(w, &markdown, item.links(), prefix)?;
2196 } else if !prefix.is_empty() {
2197 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2202 fn render_assoc_const_value(item: &clean::Item) -> String {
2204 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
2205 highlight::render_with_highlighting(
2206 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
2217 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2218 cx: &Context, prefix: &str) -> fmt::Result {
2219 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2220 debug!("Doc block: =====\n{}\n=====", s);
2221 render_markdown(w, &*s, item.links(), prefix)?;
2222 } else if !prefix.is_empty() {
2223 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2228 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2229 let stabilities = short_stability(item, cx, true);
2230 if !stabilities.is_empty() {
2231 write!(w, "<div class='stability'>")?;
2232 for stability in stabilities {
2233 write!(w, "{}", stability)?;
2235 write!(w, "</div>")?;
2240 fn name_key(name: &str) -> (&str, u64, usize) {
2241 // find number at end
2242 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
2244 // count leading zeroes
2246 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2248 // sort leading zeroes last
2249 let num_zeroes = after_zeroes - split;
2251 match name[split..].parse() {
2252 Ok(n) => (&name[..split], n, num_zeroes),
2253 Err(_) => (name, 0, num_zeroes),
2257 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2258 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2259 document(w, cx, item)?;
2261 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2263 // the order of item types in the listing
2264 fn reorder(ty: ItemType) -> u8 {
2266 ItemType::ExternCrate => 0,
2267 ItemType::Import => 1,
2268 ItemType::Primitive => 2,
2269 ItemType::Module => 3,
2270 ItemType::Macro => 4,
2271 ItemType::Struct => 5,
2272 ItemType::Enum => 6,
2273 ItemType::Constant => 7,
2274 ItemType::Static => 8,
2275 ItemType::Trait => 9,
2276 ItemType::Function => 10,
2277 ItemType::Typedef => 12,
2278 ItemType::Union => 13,
2283 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2284 let ty1 = i1.type_();
2285 let ty2 = i2.type_();
2287 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2289 let s1 = i1.stability.as_ref().map(|s| s.level);
2290 let s2 = i2.stability.as_ref().map(|s| s.level);
2292 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2293 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2296 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2297 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2298 name_key(lhs).cmp(&name_key(rhs))
2301 if cx.shared.sort_modules_alphabetically {
2302 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2304 // This call is to remove re-export duplicates in cases such as:
2309 // pub trait Double { fn foo(); }
2313 // pub use foo::bar::*;
2317 // `Double` will appear twice in the generated docs.
2319 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2320 // can be identical even if the elements are different (mostly in imports).
2321 // So in case this is an import, we keep everything by adding a "unique id"
2322 // (which is the position in the vector).
2323 indices.dedup_by_key(|i| (items[*i].def_id,
2324 if items[*i].name.as_ref().is_some() {
2325 Some(full_path(cx, &items[*i]).clone())
2330 if items[*i].is_import() {
2336 debug!("{:?}", indices);
2337 let mut curty = None;
2338 for &idx in &indices {
2339 let myitem = &items[idx];
2340 if myitem.is_stripped() {
2344 let myty = Some(myitem.type_());
2345 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2346 // Put `extern crate` and `use` re-exports in the same section.
2348 } else if myty != curty {
2349 if curty.is_some() {
2350 write!(w, "</table>")?;
2353 let (short, name) = match myty.unwrap() {
2354 ItemType::ExternCrate |
2355 ItemType::Import => ("reexports", "Re-exports"),
2356 ItemType::Module => ("modules", "Modules"),
2357 ItemType::Struct => ("structs", "Structs"),
2358 ItemType::Union => ("unions", "Unions"),
2359 ItemType::Enum => ("enums", "Enums"),
2360 ItemType::Function => ("functions", "Functions"),
2361 ItemType::Typedef => ("types", "Type Definitions"),
2362 ItemType::Static => ("statics", "Statics"),
2363 ItemType::Constant => ("constants", "Constants"),
2364 ItemType::Trait => ("traits", "Traits"),
2365 ItemType::Impl => ("impls", "Implementations"),
2366 ItemType::TyMethod => ("tymethods", "Type Methods"),
2367 ItemType::Method => ("methods", "Methods"),
2368 ItemType::StructField => ("fields", "Struct Fields"),
2369 ItemType::Variant => ("variants", "Variants"),
2370 ItemType::Macro => ("macros", "Macros"),
2371 ItemType::Primitive => ("primitives", "Primitive Types"),
2372 ItemType::AssociatedType => ("associated-types", "Associated Types"),
2373 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
2374 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2376 write!(w, "<h2 id='{id}' class='section-header'>\
2377 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2378 id = derive_id(short.to_owned()), name = name)?;
2381 match myitem.inner {
2382 clean::ExternCrateItem(ref name, ref src) => {
2383 use html::format::HRef;
2387 write!(w, "<tr><td><code>{}extern crate {} as {};",
2388 VisSpace(&myitem.visibility),
2389 HRef::new(myitem.def_id, src),
2393 write!(w, "<tr><td><code>{}extern crate {};",
2394 VisSpace(&myitem.visibility),
2395 HRef::new(myitem.def_id, name))?
2398 write!(w, "</code></td></tr>")?;
2401 clean::ImportItem(ref import) => {
2402 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2403 VisSpace(&myitem.visibility), *import)?;
2407 if myitem.name.is_none() { continue }
2409 let stabilities = short_stability(myitem, cx, false);
2411 let stab_docs = if !stabilities.is_empty() {
2413 .map(|s| format!("[{}]", s))
2414 .collect::<Vec<_>>()
2421 let unsafety_flag = match myitem.inner {
2422 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2423 if func.unsafety == hir::Unsafety::Unsafe => {
2424 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2429 let doc_value = myitem.doc_value().unwrap_or("");
2431 <tr class='{stab} module-item'>
2432 <td><a class=\"{class}\" href=\"{href}\"
2433 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2434 <td class='docblock-short'>
2438 name = *myitem.name.as_ref().unwrap(),
2439 stab_docs = stab_docs,
2440 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2441 class = myitem.type_(),
2442 stab = myitem.stability_class().unwrap_or("".to_string()),
2443 unsafety_flag = unsafety_flag,
2444 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2445 title_type = myitem.type_(),
2446 title = full_path(cx, myitem))?;
2451 if curty.is_some() {
2452 write!(w, "</table>")?;
2457 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2458 let mut stability = vec![];
2460 if let Some(stab) = item.stability.as_ref() {
2461 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2462 format!(": {}", stab.deprecated_reason)
2466 if !stab.deprecated_since.is_empty() {
2467 let since = if show_reason {
2468 format!(" since {}", Escape(&stab.deprecated_since))
2472 let text = if stability::deprecation_in_effect(&stab.deprecated_since) {
2473 format!("Deprecated{}{}",
2475 MarkdownHtml(&deprecated_reason))
2477 format!("Deprecating in {}{}",
2478 Escape(&stab.deprecated_since),
2479 MarkdownHtml(&deprecated_reason))
2481 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2484 if stab.level == stability::Unstable {
2486 let unstable_extra = match (!stab.feature.is_empty(),
2487 &cx.shared.issue_tracker_base_url,
2489 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2490 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2491 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2492 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2493 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2496 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2499 if stab.unstable_reason.is_empty() {
2500 stability.push(format!("<div class='stab unstable'>\
2501 <span class=microscope>🔬</span> \
2502 This is a nightly-only experimental API. {}\
2506 let text = format!("<summary><span class=microscope>🔬</span> \
2507 This is a nightly-only experimental API. {}\
2510 MarkdownHtml(&stab.unstable_reason));
2511 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2515 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2518 } else if let Some(depr) = item.deprecation.as_ref() {
2519 let note = if show_reason && !depr.note.is_empty() {
2520 format!(": {}", depr.note)
2524 let since = if show_reason && !depr.since.is_empty() {
2525 format!(" since {}", Escape(&depr.since))
2530 let text = if stability::deprecation_in_effect(&depr.since) {
2531 format!("Deprecated{}{}",
2533 MarkdownHtml(¬e))
2535 format!("Deprecating in {}{}",
2536 Escape(&depr.since),
2537 MarkdownHtml(¬e))
2539 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2542 if let Some(ref cfg) = item.attrs.cfg {
2543 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2544 cfg.render_long_html()
2546 cfg.render_short_html()
2553 struct Initializer<'a>(&'a str);
2555 impl<'a> fmt::Display for Initializer<'a> {
2556 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2557 let Initializer(s) = *self;
2558 if s.is_empty() { return Ok(()); }
2559 write!(f, "<code> = </code>")?;
2560 write!(f, "<code>{}</code>", Escape(s))
2564 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2565 c: &clean::Constant) -> fmt::Result {
2566 write!(w, "<pre class='rust const'>")?;
2567 render_attributes(w, it)?;
2568 write!(w, "{vis}const \
2569 {name}: {typ}{init}</pre>",
2570 vis = VisSpace(&it.visibility),
2571 name = it.name.as_ref().unwrap(),
2573 init = Initializer(&c.expr))?;
2577 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2578 s: &clean::Static) -> fmt::Result {
2579 write!(w, "<pre class='rust static'>")?;
2580 render_attributes(w, it)?;
2581 write!(w, "{vis}static {mutability}\
2582 {name}: {typ}{init}</pre>",
2583 vis = VisSpace(&it.visibility),
2584 mutability = MutableSpace(s.mutability),
2585 name = it.name.as_ref().unwrap(),
2587 init = Initializer(&s.expr))?;
2591 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2592 f: &clean::Function) -> fmt::Result {
2593 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2594 VisSpace(&it.visibility),
2595 ConstnessSpace(f.constness),
2596 UnsafetySpace(f.unsafety),
2598 it.name.as_ref().unwrap(),
2600 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2601 render_attributes(w, it)?;
2603 "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2604 vis = VisSpace(&it.visibility),
2605 constness = ConstnessSpace(f.constness),
2606 unsafety = UnsafetySpace(f.unsafety),
2607 abi = AbiSpace(f.abi),
2608 name = it.name.as_ref().unwrap(),
2609 generics = f.generics,
2610 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2619 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2620 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2621 write!(w, "<li><table class='table-display'><tbody><tr><td><code>")?;
2622 // If there's already another implementor that has the same abbridged name, use the
2623 // full path, for example in `std::iter::ExactSizeIterator`
2624 let use_absolute = match implementor.inner_impl().for_ {
2625 clean::ResolvedPath { ref path, is_generic: false, .. } |
2626 clean::BorrowedRef {
2627 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2629 } => implementor_dups[path.last_name()].1,
2632 fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2633 for it in &implementor.inner_impl().items {
2634 if let clean::TypedefItem(ref tydef, _) = it.inner {
2635 write!(w, "<span class=\"where fmt-newline\"> ")?;
2636 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2637 write!(w, ";</span>")?;
2640 write!(w, "</code><td>")?;
2641 if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2642 write!(w, "<div class='out-of-band'>")?;
2643 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2644 l, "goto source code")?;
2645 write!(w, "</div>")?;
2647 writeln!(w, "</td></tr></tbody></table></li>")?;
2651 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2653 containing_item: &clean::Item) -> fmt::Result {
2655 let did = i.trait_did().unwrap();
2656 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2657 render_impl(w, cx, i, assoc_link,
2658 RenderMode::Normal, containing_item.stable_since(), true)?;
2663 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2664 t: &clean::Trait) -> fmt::Result {
2665 let mut bounds = String::new();
2666 let mut bounds_plain = String::new();
2667 if !t.bounds.is_empty() {
2668 if !bounds.is_empty() {
2670 bounds_plain.push(' ');
2672 bounds.push_str(": ");
2673 bounds_plain.push_str(": ");
2674 for (i, p) in t.bounds.iter().enumerate() {
2676 bounds.push_str(" + ");
2677 bounds_plain.push_str(" + ");
2679 bounds.push_str(&format!("{}", *p));
2680 bounds_plain.push_str(&format!("{:#}", *p));
2684 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2685 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2686 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2687 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2689 // Output the trait definition
2690 wrap_into_docblock(w, |w| {
2691 write!(w, "<pre class='rust trait'>")?;
2692 render_attributes(w, it)?;
2693 write!(w, "{}{}{}trait {}{}{}",
2694 VisSpace(&it.visibility),
2695 UnsafetySpace(t.unsafety),
2696 if t.is_auto { "auto " } else { "" },
2697 it.name.as_ref().unwrap(),
2701 if !t.generics.where_predicates.is_empty() {
2702 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2707 if t.items.is_empty() {
2708 write!(w, "{{ }}")?;
2710 // FIXME: we should be using a derived_id for the Anchors here
2714 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2717 if !types.is_empty() && !consts.is_empty() {
2722 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2725 if !consts.is_empty() && !required.is_empty() {
2728 for (pos, m) in required.iter().enumerate() {
2730 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2733 if pos < required.len() - 1 {
2734 write!(w, "<div class='item-spacer'></div>")?;
2737 if !required.is_empty() && !provided.is_empty() {
2740 for (pos, m) in provided.iter().enumerate() {
2742 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2744 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2745 write!(w, ",\n {{ ... }}\n")?;
2748 write!(w, " {{ ... }}\n")?;
2751 if pos < provided.len() - 1 {
2752 write!(w, "<div class='item-spacer'></div>")?;
2760 // Trait documentation
2761 document(w, cx, it)?;
2763 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2765 let name = m.name.as_ref().unwrap();
2766 let item_type = m.type_();
2767 let id = derive_id(format!("{}.{}", item_type, name));
2768 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2769 write!(w, "{extra}<h3 id='{id}' class='method'>\
2770 <span id='{ns_id}' class='invisible'><code>",
2771 extra = render_spotlight_traits(m)?,
2774 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2775 write!(w, "</code>")?;
2776 render_stability_since(w, m, t)?;
2777 write!(w, "</span></h3>")?;
2778 document(w, cx, m)?;
2782 if !types.is_empty() {
2784 <h2 id='associated-types' class='small-section-header'>
2785 Associated Types<a href='#associated-types' class='anchor'></a>
2787 <div class='methods'>
2790 trait_item(w, cx, *t, it)?;
2792 write!(w, "</div>")?;
2795 if !consts.is_empty() {
2797 <h2 id='associated-const' class='small-section-header'>
2798 Associated Constants<a href='#associated-const' class='anchor'></a>
2800 <div class='methods'>
2803 trait_item(w, cx, *t, it)?;
2805 write!(w, "</div>")?;
2808 // Output the documentation for each function individually
2809 if !required.is_empty() {
2811 <h2 id='required-methods' class='small-section-header'>
2812 Required Methods<a href='#required-methods' class='anchor'></a>
2814 <div class='methods'>
2816 for m in &required {
2817 trait_item(w, cx, *m, it)?;
2819 write!(w, "</div>")?;
2821 if !provided.is_empty() {
2823 <h2 id='provided-methods' class='small-section-header'>
2824 Provided Methods<a href='#provided-methods' class='anchor'></a>
2826 <div class='methods'>
2828 for m in &provided {
2829 trait_item(w, cx, *m, it)?;
2831 write!(w, "</div>")?;
2834 // If there are methods directly on this trait object, render them here.
2835 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2837 let cache = cache();
2839 <h2 id='implementors' class='small-section-header'>
2840 Implementors<a href='#implementors' class='anchor'></a>
2842 <ul class='item-list' id='implementors-list'>
2845 let synthetic_impl_header = "
2846 <h2 id='synthetic-implementors' class='small-section-header'>
2847 Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
2849 <ul class='item-list' id='synthetic-implementors-list'>
2852 let mut synthetic_types = Vec::new();
2854 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2855 // The DefId is for the first Type found with that name. The bool is
2856 // if any Types with the same name but different DefId have been found.
2857 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2858 for implementor in implementors {
2859 match implementor.inner_impl().for_ {
2860 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2861 clean::BorrowedRef {
2862 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2865 let &mut (prev_did, ref mut has_duplicates) =
2866 implementor_dups.entry(path.last_name()).or_insert((did, false));
2867 if prev_did != did {
2868 *has_duplicates = true;
2875 let (local, foreign) = implementors.iter()
2876 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2877 .map_or(true, |d| cache.paths.contains_key(&d)));
2880 let (synthetic, concrete) = local.iter()
2881 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2884 if !foreign.is_empty() {
2886 <h2 id='foreign-impls' class='small-section-header'>
2887 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2891 for implementor in foreign {
2892 let assoc_link = AssocItemLink::GotoSource(
2893 implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2895 render_impl(w, cx, &implementor, assoc_link,
2896 RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2900 write!(w, "{}", impl_header)?;
2901 for implementor in concrete {
2902 render_implementor(cx, implementor, w, &implementor_dups)?;
2904 write!(w, "</ul>")?;
2907 write!(w, "{}", synthetic_impl_header)?;
2908 for implementor in synthetic {
2909 synthetic_types.extend(
2910 collect_paths_for_type(implementor.inner_impl().for_.clone())
2912 render_implementor(cx, implementor, w, &implementor_dups)?;
2914 write!(w, "</ul>")?;
2917 // even without any implementations to write in, we still want the heading and list, so the
2918 // implementors javascript file pulled in below has somewhere to write the impls into
2919 write!(w, "{}", impl_header)?;
2920 write!(w, "</ul>")?;
2923 write!(w, "{}", synthetic_impl_header)?;
2924 write!(w, "</ul>")?;
2927 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2928 as_json(&synthetic_types))?;
2930 write!(w, r#"<script type="text/javascript" async
2931 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2933 root_path = vec![".."; cx.current.len()].join("/"),
2934 path = if it.def_id.is_local() {
2935 cx.current.join("/")
2937 let (ref path, _) = cache.external_paths[&it.def_id];
2938 path[..path.len() - 1].join("/")
2940 ty = it.type_().css_class(),
2941 name = *it.name.as_ref().unwrap())?;
2945 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2946 use html::item_type::ItemType::*;
2948 let name = it.name.as_ref().unwrap();
2949 let ty = match it.type_() {
2950 Typedef | AssociatedType => AssociatedType,
2954 let anchor = format!("#{}.{}", ty, name);
2956 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2957 AssocItemLink::Anchor(None) => anchor,
2958 AssocItemLink::GotoSource(did, _) => {
2959 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2964 fn assoc_const(w: &mut fmt::Formatter,
2967 _default: Option<&String>,
2968 link: AssocItemLink) -> fmt::Result {
2969 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2970 VisSpace(&it.visibility),
2971 naive_assoc_href(it, link),
2972 it.name.as_ref().unwrap(),
2977 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2978 bounds: &Vec<clean::TyParamBound>,
2979 default: Option<&clean::Type>,
2980 link: AssocItemLink) -> fmt::Result {
2981 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2982 naive_assoc_href(it, link),
2983 it.name.as_ref().unwrap())?;
2984 if !bounds.is_empty() {
2985 write!(w, ": {}", TyParamBounds(bounds))?
2987 if let Some(default) = default {
2988 write!(w, " = {}", default)?;
2993 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2994 ver: Option<&'a str>,
2995 containing_ver: Option<&'a str>) -> fmt::Result {
2996 if let Some(v) = ver {
2997 if containing_ver != ver && v.len() > 0 {
2998 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
3005 fn render_stability_since(w: &mut fmt::Formatter,
3007 containing_item: &clean::Item) -> fmt::Result {
3008 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3011 fn render_assoc_item(w: &mut fmt::Formatter,
3013 link: AssocItemLink,
3014 parent: ItemType) -> fmt::Result {
3015 fn method(w: &mut fmt::Formatter,
3017 unsafety: hir::Unsafety,
3018 constness: hir::Constness,
3020 g: &clean::Generics,
3022 link: AssocItemLink,
3025 let name = meth.name.as_ref().unwrap();
3026 let anchor = format!("#{}.{}", meth.type_(), name);
3027 let href = match link {
3028 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3029 AssocItemLink::Anchor(None) => anchor,
3030 AssocItemLink::GotoSource(did, provided_methods) => {
3031 // We're creating a link from an impl-item to the corresponding
3032 // trait-item and need to map the anchored type accordingly.
3033 let ty = if provided_methods.contains(name) {
3039 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3042 let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
3043 VisSpace(&meth.visibility),
3044 ConstnessSpace(constness),
3045 UnsafetySpace(unsafety),
3049 let (indent, end_newline) = if parent == ItemType::Trait {
3055 write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3056 {generics}{decl}{where_clause}",
3057 VisSpace(&meth.visibility),
3058 ConstnessSpace(constness),
3059 UnsafetySpace(unsafety),
3069 where_clause = WhereClause {
3076 clean::StrippedItem(..) => Ok(()),
3077 clean::TyMethodItem(ref m) => {
3078 method(w, item, m.unsafety, hir::Constness::NotConst,
3079 m.abi, &m.generics, &m.decl, link, parent)
3081 clean::MethodItem(ref m) => {
3082 method(w, item, m.unsafety, m.constness,
3083 m.abi, &m.generics, &m.decl, link, parent)
3085 clean::AssociatedConstItem(ref ty, ref default) => {
3086 assoc_const(w, item, ty, default.as_ref(), link)
3088 clean::AssociatedTypeItem(ref bounds, ref default) => {
3089 assoc_type(w, item, bounds, default.as_ref(), link)
3091 _ => panic!("render_assoc_item called on non-associated-item")
3095 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3096 s: &clean::Struct) -> fmt::Result {
3097 wrap_into_docblock(w, |w| {
3098 write!(w, "<pre class='rust struct'>")?;
3099 render_attributes(w, it)?;
3110 document(w, cx, it)?;
3111 let mut fields = s.fields.iter().filter_map(|f| {
3113 clean::StructFieldItem(ref ty) => Some((f, ty)),
3117 if let doctree::Plain = s.struct_type {
3118 if fields.peek().is_some() {
3119 write!(w, "<h2 id='fields' class='fields small-section-header'>
3120 Fields<a href='#fields' class='anchor'></a></h2>")?;
3121 for (field, ty) in fields {
3122 let id = derive_id(format!("{}.{}",
3123 ItemType::StructField,
3124 field.name.as_ref().unwrap()));
3125 let ns_id = derive_id(format!("{}.{}",
3126 field.name.as_ref().unwrap(),
3127 ItemType::StructField.name_space()));
3128 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
3129 <a href=\"#{id}\" class=\"anchor field\"></a>
3130 <span id=\"{ns_id}\" class='invisible'>
3131 <code>{name}: {ty}</code>
3133 item_type = ItemType::StructField,
3136 name = field.name.as_ref().unwrap(),
3138 if let Some(stability_class) = field.stability_class() {
3139 write!(w, "<span class='stab {stab}'></span>",
3140 stab = stability_class)?;
3142 document(w, cx, field)?;
3146 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3149 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3150 s: &clean::Union) -> fmt::Result {
3151 wrap_into_docblock(w, |w| {
3152 write!(w, "<pre class='rust union'>")?;
3153 render_attributes(w, it)?;
3163 document(w, cx, it)?;
3164 let mut fields = s.fields.iter().filter_map(|f| {
3166 clean::StructFieldItem(ref ty) => Some((f, ty)),
3170 if fields.peek().is_some() {
3171 write!(w, "<h2 id='fields' class='fields small-section-header'>
3172 Fields<a href='#fields' class='anchor'></a></h2>")?;
3173 for (field, ty) in fields {
3174 let name = field.name.as_ref().expect("union field name");
3175 let id = format!("{}.{}", ItemType::StructField, name);
3176 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3177 <a href=\"#{id}\" class=\"anchor field\"></a>\
3178 <span class='invisible'><code>{name}: {ty}</code></span>\
3182 shortty = ItemType::StructField,
3184 if let Some(stability_class) = field.stability_class() {
3185 write!(w, "<span class='stab {stab}'></span>",
3186 stab = stability_class)?;
3188 document(w, cx, field)?;
3191 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3194 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3195 e: &clean::Enum) -> fmt::Result {
3196 wrap_into_docblock(w, |w| {
3197 write!(w, "<pre class='rust enum'>")?;
3198 render_attributes(w, it)?;
3199 write!(w, "{}enum {}{}{}",
3200 VisSpace(&it.visibility),
3201 it.name.as_ref().unwrap(),
3203 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3204 if e.variants.is_empty() && !e.variants_stripped {
3205 write!(w, " {{}}")?;
3207 write!(w, " {{\n")?;
3208 for v in &e.variants {
3210 let name = v.name.as_ref().unwrap();
3212 clean::VariantItem(ref var) => {
3214 clean::VariantKind::CLike => write!(w, "{}", name)?,
3215 clean::VariantKind::Tuple(ref tys) => {
3216 write!(w, "{}(", name)?;
3217 for (i, ty) in tys.iter().enumerate() {
3219 write!(w, ", ")?
3221 write!(w, "{}", *ty)?;
3225 clean::VariantKind::Struct(ref s) => {
3241 if e.variants_stripped {
3242 write!(w, " // some variants omitted\n")?;
3249 document(w, cx, it)?;
3250 if !e.variants.is_empty() {
3251 write!(w, "<h2 id='variants' class='variants small-section-header'>
3252 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
3253 for variant in &e.variants {
3254 let id = derive_id(format!("{}.{}",
3256 variant.name.as_ref().unwrap()));
3257 let ns_id = derive_id(format!("{}.{}",
3258 variant.name.as_ref().unwrap(),
3259 ItemType::Variant.name_space()));
3260 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3261 <a href=\"#{id}\" class=\"anchor field\"></a>\
3262 <span id='{ns_id}' class='invisible'><code>{name}",
3265 name = variant.name.as_ref().unwrap())?;
3266 if let clean::VariantItem(ref var) = variant.inner {
3267 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3269 for (i, ty) in tys.iter().enumerate() {
3271 write!(w, ", ")?;
3273 write!(w, "{}", *ty)?;
3278 write!(w, "</code></span></span>")?;
3279 document(w, cx, variant)?;
3281 use clean::{Variant, VariantKind};
3282 if let clean::VariantItem(Variant {
3283 kind: VariantKind::Struct(ref s)
3284 }) = variant.inner {
3285 let variant_id = derive_id(format!("{}.{}.fields",
3287 variant.name.as_ref().unwrap()));
3288 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
3290 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
3291 <table>", name = variant.name.as_ref().unwrap())?;
3292 for field in &s.fields {
3293 use clean::StructFieldItem;
3294 if let StructFieldItem(ref ty) = field.inner {
3295 let id = derive_id(format!("variant.{}.field.{}",
3296 variant.name.as_ref().unwrap(),
3297 field.name.as_ref().unwrap()));
3298 let ns_id = derive_id(format!("{}.{}.{}.{}",
3299 variant.name.as_ref().unwrap(),
3300 ItemType::Variant.name_space(),
3301 field.name.as_ref().unwrap(),
3302 ItemType::StructField.name_space()));
3303 write!(w, "<tr><td \
3305 <span id='{ns_id}' class='invisible'>\
3306 <code>{f}: {t}</code></span></td><td>",
3309 f = field.name.as_ref().unwrap(),
3311 document(w, cx, field)?;
3312 write!(w, "</td></tr>")?;
3315 write!(w, "</table></span>")?;
3317 render_stability_since(w, variant, it)?;
3320 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3324 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3325 let name = attr.name();
3328 Some(format!("{}", name))
3329 } else if let Some(v) = attr.value_str() {
3330 Some(format!("{} = {:?}", name, v.as_str()))
3331 } else if let Some(values) = attr.meta_item_list() {
3332 let display: Vec<_> = values.iter().filter_map(|attr| {
3333 attr.meta_item().and_then(|mi| render_attribute(mi))
3336 if display.len() > 0 {
3337 Some(format!("{}({})", name, display.join(", ")))
3346 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3353 "unsafe_destructor_blind_to_params"
3356 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3357 let mut attrs = String::new();
3359 for attr in &it.attrs.other_attrs {
3360 let name = attr.name();
3361 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3364 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3365 attrs.push_str(&format!("#[{}]\n", s));
3368 if attrs.len() > 0 {
3369 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3374 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3375 g: Option<&clean::Generics>,
3376 ty: doctree::StructType,
3377 fields: &[clean::Item],
3379 structhead: bool) -> fmt::Result {
3381 VisSpace(&it.visibility),
3382 if structhead {"struct "} else {""},
3383 it.name.as_ref().unwrap())?;
3384 if let Some(g) = g {
3389 if let Some(g) = g {
3390 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3392 let mut has_visible_fields = false;
3394 for field in fields {
3395 if let clean::StructFieldItem(ref ty) = field.inner {
3396 write!(w, "\n{} {}{}: {},",
3398 VisSpace(&field.visibility),
3399 field.name.as_ref().unwrap(),
3401 has_visible_fields = true;
3405 if has_visible_fields {
3406 if it.has_stripped_fields().unwrap() {
3407 write!(w, "\n{} // some fields omitted", tab)?;
3409 write!(w, "\n{}", tab)?;
3410 } else if it.has_stripped_fields().unwrap() {
3411 // If there are no visible fields we can just display
3412 // `{ /* fields omitted */ }` to save space.
3413 write!(w, " /* fields omitted */ ")?;
3419 for (i, field) in fields.iter().enumerate() {
3424 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3427 clean::StructFieldItem(ref ty) => {
3428 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3434 if let Some(g) = g {
3435 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3440 // Needed for PhantomData.
3441 if let Some(g) = g {
3442 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3450 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3451 g: Option<&clean::Generics>,
3452 fields: &[clean::Item],
3454 structhead: bool) -> fmt::Result {
3456 VisSpace(&it.visibility),
3457 if structhead {"union "} else {""},
3458 it.name.as_ref().unwrap())?;
3459 if let Some(g) = g {
3460 write!(w, "{}", g)?;
3461 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3464 write!(w, " {{\n{}", tab)?;
3465 for field in fields {
3466 if let clean::StructFieldItem(ref ty) = field.inner {
3467 write!(w, " {}{}: {},\n{}",
3468 VisSpace(&field.visibility),
3469 field.name.as_ref().unwrap(),
3475 if it.has_stripped_fields().unwrap() {
3476 write!(w, " // some fields omitted\n{}", tab)?;
3482 #[derive(Copy, Clone)]
3483 enum AssocItemLink<'a> {
3484 Anchor(Option<&'a str>),
3485 GotoSource(DefId, &'a FxHashSet<String>),
3488 impl<'a> AssocItemLink<'a> {
3489 fn anchor(&self, id: &'a String) -> Self {
3491 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3492 ref other => *other,
3497 enum AssocItemRender<'a> {
3499 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3502 #[derive(Copy, Clone, PartialEq)]
3505 ForDeref { mut_: bool },
3508 fn render_assoc_items(w: &mut fmt::Formatter,
3510 containing_item: &clean::Item,
3512 what: AssocItemRender) -> fmt::Result {
3514 let v = match c.impls.get(&it) {
3516 None => return Ok(()),
3518 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3519 i.inner_impl().trait_.is_none()
3521 if !non_trait.is_empty() {
3522 let render_mode = match what {
3523 AssocItemRender::All => {
3525 <h2 id='methods' class='small-section-header'>
3526 Methods<a href='#methods' class='anchor'></a>
3531 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3533 <h2 id='deref-methods' class='small-section-header'>
3534 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3537 RenderMode::ForDeref { mut_: deref_mut_ }
3540 for i in &non_trait {
3541 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3542 containing_item.stable_since(), true)?;
3545 if let AssocItemRender::DerefFor { .. } = what {
3548 if !traits.is_empty() {
3549 let deref_impl = traits.iter().find(|t| {
3550 t.inner_impl().trait_.def_id() == c.deref_trait_did
3552 if let Some(impl_) = deref_impl {
3553 let has_deref_mut = traits.iter().find(|t| {
3554 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3556 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3559 let (synthetic, concrete) = traits
3561 .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3563 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3565 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3566 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3567 render_impls(self.0, fmt, &self.1, self.2)
3571 let impls = format!("{}", RendererStruct(cx, concrete, containing_item));
3572 if !impls.is_empty() {
3574 <h2 id='implementations' class='small-section-header'>
3575 Trait Implementations<a href='#implementations' class='anchor'></a>
3577 <div id='implementations-list'>{}</div>", impls)?;
3580 if !synthetic.is_empty() {
3582 <h2 id='synthetic-implementations' class='small-section-header'>
3583 Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3585 <div id='synthetic-implementations-list'>
3587 render_impls(cx, w, &synthetic, containing_item)?;
3588 write!(w, "</div>")?;
3594 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3595 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3596 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3597 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3599 clean::TypedefItem(ref t, true) => Some(&t.type_),
3602 }).next().expect("Expected associated type binding");
3603 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3604 deref_mut_: deref_mut };
3605 if let Some(did) = target.def_id() {
3606 render_assoc_items(w, cx, container_item, did, what)
3608 if let Some(prim) = target.primitive_type() {
3609 if let Some(&did) = cache().primitive_locations.get(&prim) {
3610 render_assoc_items(w, cx, container_item, did, what)?;
3617 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3618 let self_type_opt = match item.inner {
3619 clean::MethodItem(ref method) => method.decl.self_type(),
3620 clean::TyMethodItem(ref method) => method.decl.self_type(),
3624 if let Some(self_ty) = self_type_opt {
3625 let (by_mut_ref, by_box, by_value) = match self_ty {
3626 SelfTy::SelfBorrowed(_, mutability) |
3627 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3628 (mutability == Mutability::Mutable, false, false)
3630 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3631 (false, Some(did) == cache().owned_box_did, false)
3633 SelfTy::SelfValue => (false, false, true),
3634 _ => (false, false, false),
3637 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3643 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3644 let mut out = String::new();
3647 clean::FunctionItem(clean::Function { ref decl, .. }) |
3648 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3649 clean::MethodItem(clean::Method { ref decl, .. }) |
3650 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3651 out = spotlight_decl(decl)?;
3659 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3660 let mut out = String::new();
3661 let mut trait_ = String::new();
3663 if let Some(did) = decl.output.def_id() {
3665 if let Some(impls) = c.impls.get(&did) {
3667 let impl_ = i.inner_impl();
3668 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3671 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3672 <code class=\"content\">",
3674 trait_.push_str(&format!("{}", impl_.for_));
3677 //use the "where" class here to make it small
3678 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3679 let t_did = impl_.trait_.def_id().unwrap();
3680 for it in &impl_.items {
3681 if let clean::TypedefItem(ref tydef, _) = it.inner {
3682 out.push_str("<span class=\"where fmt-newline\"> ");
3683 assoc_type(&mut out, it, &vec![],
3685 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3686 out.push_str(";</span>");
3694 if !out.is_empty() {
3695 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3696 <span class='tooltiptext'>Important traits for {}</span></div>\
3697 <div class=\"content hidden\">",
3699 out.push_str("</code></div></div>");
3705 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3706 render_mode: RenderMode, outer_version: Option<&str>,
3707 show_def_docs: bool) -> fmt::Result {
3708 if render_mode == RenderMode::Normal {
3709 let id = derive_id(match i.inner_impl().trait_ {
3710 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3711 None => "impl".to_string(),
3713 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
3714 <tbody><tr><td><code>{}</code>",
3715 id, i.inner_impl())?;
3716 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3717 write!(w, "</span></td><td><span class='out-of-band'>")?;
3718 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3719 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3720 write!(w, "<div class='ghost'></div>")?;
3721 render_stability_since_raw(w, since, outer_version)?;
3722 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3723 l, "goto source code")?;
3725 render_stability_since_raw(w, since, outer_version)?;
3727 write!(w, "</span></td></tr></tbody></table></h3>")?;
3728 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3729 write!(w, "<div class='docblock'>{}</div>",
3730 Markdown(&*dox, &i.impl_item.links()))?;
3734 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3735 link: AssocItemLink, render_mode: RenderMode,
3736 is_default_item: bool, outer_version: Option<&str>,
3737 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3738 let item_type = item.type_();
3739 let name = item.name.as_ref().unwrap();
3741 let render_method_item: bool = match render_mode {
3742 RenderMode::Normal => true,
3743 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3747 clean::MethodItem(clean::Method { ref decl, .. }) |
3748 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3749 // Only render when the method is not static or we allow static methods
3750 if render_method_item {
3751 let id = derive_id(format!("{}.{}", item_type, name));
3752 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3753 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3754 write!(w, "{}", spotlight_decl(decl)?)?;
3755 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3756 write!(w, "<table class='table-display'><tbody><tr><td><code>")?;
3757 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3758 write!(w, "</code>")?;
3759 if let Some(l) = (Item { cx, item }).src_href() {
3760 write!(w, "</span></td><td><span class='out-of-band'>")?;
3761 write!(w, "<div class='ghost'></div>")?;
3762 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3763 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3764 l, "goto source code")?;
3766 write!(w, "</td><td>")?;
3767 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3769 write!(w, "</td></tr></tbody></table></span></h4>")?;
3772 clean::TypedefItem(ref tydef, _) => {
3773 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, 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, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3778 write!(w, "</code></span></h4>\n")?;
3780 clean::AssociatedConstItem(ref ty, ref default) => {
3781 let id = derive_id(format!("{}.{}", item_type, name));
3782 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3783 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3784 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3785 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3786 write!(w, "</code></span></h4>\n")?;
3788 clean::AssociatedTypeItem(ref bounds, ref default) => {
3789 let id = derive_id(format!("{}.{}", item_type, name));
3790 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3791 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3792 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3793 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3794 write!(w, "</code></span></h4>\n")?;
3796 clean::StrippedItem(..) => return Ok(()),
3797 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3800 if render_method_item || render_mode == RenderMode::Normal {
3801 let prefix = render_assoc_const_value(item);
3803 if !is_default_item {
3804 if let Some(t) = trait_ {
3805 // The trait item may have been stripped so we might not
3806 // find any documentation or stability for it.
3807 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3808 // We need the stability of the item from the trait
3809 // because impls can't have a stability.
3810 document_stability(w, cx, it)?;
3811 if item.doc_value().is_some() {
3812 document_full(w, item, cx, &prefix)?;
3813 } else if show_def_docs {
3814 // In case the item isn't documented,
3815 // provide short documentation from the trait.
3816 document_short(w, it, link, &prefix)?;
3820 document_stability(w, cx, item)?;
3822 document_full(w, item, cx, &prefix)?;
3826 document_stability(w, cx, item)?;
3828 document_short(w, item, link, &prefix)?;
3835 let traits = &cache().traits;
3836 let trait_ = i.trait_did().map(|did| &traits[&did]);
3839 write!(w, "<span class='docblock autohide'>")?;
3842 write!(w, "<div class='impl-items'>")?;
3843 for trait_item in &i.inner_impl().items {
3844 doc_impl_item(w, cx, trait_item, link, render_mode,
3845 false, outer_version, trait_, show_def_docs)?;
3848 fn render_default_items(w: &mut fmt::Formatter,
3852 render_mode: RenderMode,
3853 outer_version: Option<&str>,
3854 show_def_docs: bool) -> fmt::Result {
3855 for trait_item in &t.items {
3856 let n = trait_item.name.clone();
3857 if i.items.iter().find(|m| m.name == n).is_some() {
3860 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3861 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3863 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3864 outer_version, None, show_def_docs)?;
3869 // If we've implemented a trait, then also emit documentation for all
3870 // default items which weren't overridden in the implementation block.
3871 if let Some(t) = trait_ {
3872 render_default_items(w, cx, t, &i.inner_impl(),
3873 render_mode, outer_version, show_def_docs)?;
3875 write!(w, "</div>")?;
3878 write!(w, "</span>")?;
3884 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3885 t: &clean::Typedef) -> fmt::Result {
3886 write!(w, "<pre class='rust typedef'>")?;
3887 render_attributes(w, it)?;
3888 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3889 it.name.as_ref().unwrap(),
3891 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3894 document(w, cx, it)?;
3896 // Render any items associated directly to this alias, as otherwise they
3897 // won't be visible anywhere in the docs. It would be nice to also show
3898 // associated items from the aliased type (see discussion in #32077), but
3899 // we need #14072 to make sense of the generics.
3900 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3903 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3904 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3905 render_attributes(w, it)?;
3908 " {}type {};\n}}</pre>",
3909 VisSpace(&it.visibility),
3910 it.name.as_ref().unwrap(),
3913 document(w, cx, it)?;
3915 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3918 impl<'a> fmt::Display for Sidebar<'a> {
3919 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3922 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3924 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3925 || it.is_enum() || it.is_mod() || it.is_typedef() {
3926 write!(fmt, "<p class='location'>{}{}</p>",
3928 clean::StructItem(..) => "Struct ",
3929 clean::TraitItem(..) => "Trait ",
3930 clean::PrimitiveItem(..) => "Primitive Type ",
3931 clean::UnionItem(..) => "Union ",
3932 clean::EnumItem(..) => "Enum ",
3933 clean::TypedefItem(..) => "Type Definition ",
3934 clean::ForeignTypeItem => "Foreign Type ",
3935 clean::ModuleItem(..) => if it.is_crate() {
3942 it.name.as_ref().unwrap())?;
3946 if let Some(ref version) = cache().crate_version {
3948 "<div class='block version'>\
3951 <a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3953 it.name.as_ref().unwrap())?;
3957 write!(fmt, "<div class=\"sidebar-elems\">")?;
3959 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3960 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3961 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3962 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3963 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3964 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3965 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3966 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3970 // The sidebar is designed to display sibling functions, modules and
3971 // other miscellaneous information. since there are lots of sibling
3972 // items (and that causes quadratic growth in large modules),
3973 // we refactor common parts into a shared JavaScript file per module.
3974 // still, we don't move everything into JS because we want to preserve
3975 // as much HTML as possible in order to allow non-JS-enabled browsers
3976 // to navigate the documentation (though slightly inefficiently).
3978 write!(fmt, "<p class='location'>")?;
3979 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3981 write!(fmt, "::<wbr>")?;
3983 write!(fmt, "<a href='{}index.html'>{}</a>",
3984 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3987 write!(fmt, "</p>")?;
3989 // Sidebar refers to the enclosing module, not this module.
3990 let relpath = if it.is_mod() { "../" } else { "" };
3992 "<script>window.sidebarCurrent = {{\
3997 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3998 ty = it.type_().css_class(),
4001 // There is no sidebar-items.js beyond the crate root path
4002 // FIXME maybe dynamic crate loading can be merged here
4004 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4007 // Closes sidebar-elems div.
4008 write!(fmt, "</div>")?;
4014 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
4015 i.items.iter().filter_map(|item| {
4017 // Maybe check with clean::Visibility::Public as well?
4018 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4019 if !for_deref || should_render_item(item, false) {
4020 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
4027 }).collect::<Vec<_>>()
4030 // The point is to url encode any potential character from a type with genericity.
4031 fn small_url_encode(s: &str) -> String {
4032 s.replace("<", "%3C")
4033 .replace(">", "%3E")
4034 .replace(" ", "%20")
4035 .replace("?", "%3F")
4036 .replace("'", "%27")
4037 .replace("&", "%26")
4038 .replace(",", "%2C")
4039 .replace(":", "%3A")
4040 .replace(";", "%3B")
4041 .replace("[", "%5B")
4042 .replace("]", "%5D")
4043 .replace("\"", "%22")
4046 fn sidebar_assoc_items(it: &clean::Item) -> String {
4047 let mut out = String::new();
4049 if let Some(v) = c.impls.get(&it.def_id) {
4051 .filter(|i| i.inner_impl().trait_.is_none())
4052 .flat_map(|i| get_methods(i.inner_impl(), false))
4053 .collect::<String>();
4054 if !ret.is_empty() {
4055 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4056 </a><div class=\"sidebar-links\">{}</div>", ret));
4059 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4060 if let Some(impl_) = v.iter()
4061 .filter(|i| i.inner_impl().trait_.is_some())
4062 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4063 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4065 clean::TypedefItem(ref t, true) => Some(&t.type_),
4069 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4070 c.primitive_locations.get(&prim).cloned()
4071 })).and_then(|did| c.impls.get(&did));
4072 if let Some(impls) = inner_impl {
4073 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4074 out.push_str(&format!("Methods from {}<Target={}>",
4075 Escape(&format!("{:#}",
4076 impl_.inner_impl().trait_.as_ref().unwrap())),
4077 Escape(&format!("{:#}", target))));
4078 out.push_str("</a>");
4079 let ret = impls.iter()
4080 .filter(|i| i.inner_impl().trait_.is_none())
4081 .flat_map(|i| get_methods(i.inner_impl(), true))
4082 .collect::<String>();
4083 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
4087 let format_impls = |impls: Vec<&Impl>| {
4088 let mut links = HashSet::new();
4091 let is_negative_impl = is_negative_impl(i.inner_impl());
4092 if let Some(ref i) = i.inner_impl().trait_ {
4093 let i_display = format!("{:#}", i);
4094 let out = Escape(&i_display);
4095 let encoded = small_url_encode(&format!("{:#}", i));
4096 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4098 if is_negative_impl { "!" } else { "" },
4100 if links.insert(generated.clone()) {
4109 .collect::<String>()
4112 let (synthetic, concrete) = v
4114 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4116 let concrete_format = format_impls(concrete);
4117 let synthetic_format = format_impls(synthetic);
4119 if !concrete_format.is_empty() {
4120 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4121 Trait Implementations</a>");
4122 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4125 if !synthetic_format.is_empty() {
4126 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4127 Auto Trait Implementations</a>");
4128 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4136 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4137 s: &clean::Struct) -> fmt::Result {
4138 let mut sidebar = String::new();
4139 let fields = get_struct_fields_name(&s.fields);
4141 if !fields.is_empty() {
4142 if let doctree::Plain = s.struct_type {
4143 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4144 <div class=\"sidebar-links\">{}</div>", fields));
4148 sidebar.push_str(&sidebar_assoc_items(it));
4150 if !sidebar.is_empty() {
4151 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4156 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4158 clean::ItemEnum::ImplItem(ref i) => {
4159 if let Some(ref trait_) = i.trait_ {
4160 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4169 fn is_negative_impl(i: &clean::Impl) -> bool {
4170 i.polarity == Some(clean::ImplPolarity::Negative)
4173 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4174 t: &clean::Trait) -> fmt::Result {
4175 let mut sidebar = String::new();
4181 Some(ref name) if m.is_associated_type() => {
4182 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4188 .collect::<String>();
4189 let consts = t.items
4193 Some(ref name) if m.is_associated_const() => {
4194 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4200 .collect::<String>();
4201 let required = t.items
4205 Some(ref name) if m.is_ty_method() => {
4206 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4212 .collect::<String>();
4213 let provided = t.items
4217 Some(ref name) if m.is_method() => {
4218 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
4223 .collect::<String>();
4225 if !types.is_empty() {
4226 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4227 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4230 if !consts.is_empty() {
4231 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4232 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4235 if !required.is_empty() {
4236 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4237 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4240 if !provided.is_empty() {
4241 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4242 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4248 if let Some(implementors) = c.implementors.get(&it.def_id) {
4249 let res = implementors.iter()
4250 .filter(|i| i.inner_impl().for_.def_id()
4251 .map_or(false, |d| !c.paths.contains_key(&d)))
4253 match extract_for_impl_name(&i.impl_item) {
4254 Some((ref name, ref url)) => {
4255 Some(format!("<a href=\"#impl-{}\">{}</a>",
4256 small_url_encode(url),
4262 .collect::<String>();
4263 if !res.is_empty() {
4264 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4265 Implementations on Foreign Types</a><div \
4266 class=\"sidebar-links\">{}</div>",
4271 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4273 sidebar.push_str("<a class=\"sidebar-title\" \
4274 href=\"#synthetic-implementors\">Auto Implementors</a>");
4277 sidebar.push_str(&sidebar_assoc_items(it));
4279 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4282 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4283 _p: &clean::PrimitiveType) -> fmt::Result {
4284 let sidebar = sidebar_assoc_items(it);
4286 if !sidebar.is_empty() {
4287 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4292 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4293 _t: &clean::Typedef) -> fmt::Result {
4294 let sidebar = sidebar_assoc_items(it);
4296 if !sidebar.is_empty() {
4297 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4302 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4304 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4309 .filter_map(|f| match f.name {
4310 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4311 {name}</a>", name=name)),
4317 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4318 u: &clean::Union) -> fmt::Result {
4319 let mut sidebar = String::new();
4320 let fields = get_struct_fields_name(&u.fields);
4322 if !fields.is_empty() {
4323 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4324 <div class=\"sidebar-links\">{}</div>", fields));
4327 sidebar.push_str(&sidebar_assoc_items(it));
4329 if !sidebar.is_empty() {
4330 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4335 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4336 e: &clean::Enum) -> fmt::Result {
4337 let mut sidebar = String::new();
4339 let variants = e.variants.iter()
4340 .filter_map(|v| match v.name {
4341 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4342 </a>", name = name)),
4345 .collect::<String>();
4346 if !variants.is_empty() {
4347 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4348 <div class=\"sidebar-links\">{}</div>", variants));
4351 sidebar.push_str(&sidebar_assoc_items(it));
4353 if !sidebar.is_empty() {
4354 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4359 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4360 items: &[clean::Item]) -> fmt::Result {
4361 let mut sidebar = String::new();
4363 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4364 it.type_() == ItemType::Import) {
4365 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4367 name = "Re-exports"));
4370 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4371 // to print its headings
4372 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4373 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4374 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4375 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4376 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4377 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4378 let (short, name) = match myty {
4379 ItemType::ExternCrate |
4380 ItemType::Import => ("reexports", "Re-exports"),
4381 ItemType::Module => ("modules", "Modules"),
4382 ItemType::Struct => ("structs", "Structs"),
4383 ItemType::Union => ("unions", "Unions"),
4384 ItemType::Enum => ("enums", "Enums"),
4385 ItemType::Function => ("functions", "Functions"),
4386 ItemType::Typedef => ("types", "Type Definitions"),
4387 ItemType::Static => ("statics", "Statics"),
4388 ItemType::Constant => ("constants", "Constants"),
4389 ItemType::Trait => ("traits", "Traits"),
4390 ItemType::Impl => ("impls", "Implementations"),
4391 ItemType::TyMethod => ("tymethods", "Type Methods"),
4392 ItemType::Method => ("methods", "Methods"),
4393 ItemType::StructField => ("fields", "Struct Fields"),
4394 ItemType::Variant => ("variants", "Variants"),
4395 ItemType::Macro => ("macros", "Macros"),
4396 ItemType::Primitive => ("primitives", "Primitive Types"),
4397 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4398 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4399 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4401 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4407 if !sidebar.is_empty() {
4408 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4413 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4414 let sidebar = sidebar_assoc_items(it);
4415 if !sidebar.is_empty() {
4416 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4421 impl<'a> fmt::Display for Source<'a> {
4422 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4423 let Source(s) = *self;
4424 let lines = s.lines().count();
4426 let mut tmp = lines;
4431 write!(fmt, "<pre class=\"line-numbers\">")?;
4432 for i in 1..lines + 1 {
4433 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4435 write!(fmt, "</pre>")?;
4437 highlight::render_with_highlighting(s, None, None, None, None))?;
4442 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4443 t: &clean::Macro) -> fmt::Result {
4444 wrap_into_docblock(w, |w| {
4445 w.write_str(&highlight::render_with_highlighting(&t.source,
4454 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4456 _p: &clean::PrimitiveType) -> fmt::Result {
4457 document(w, cx, it)?;
4458 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4461 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4463 fn make_item_keywords(it: &clean::Item) -> String {
4464 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4467 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4468 let decl = match item.inner {
4469 clean::FunctionItem(ref f) => &f.decl,
4470 clean::MethodItem(ref m) => &m.decl,
4471 clean::TyMethodItem(ref m) => &m.decl,
4475 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4476 let output = match decl.output {
4477 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4481 Some(IndexItemFunctionType { inputs: inputs, output: output })
4484 fn get_index_type(clean_type: &clean::Type) -> Type {
4486 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4487 generics: get_generics(clean_type),
4492 /// Returns a list of all paths used in the type.
4493 /// This is used to help deduplicate imported impls
4494 /// for reexported types. If any of the contained
4495 /// types are re-exported, we don't use the corresponding
4496 /// entry from the js file, as inlining will have already
4497 /// picked up the impl
4498 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4499 let mut out = Vec::new();
4500 let mut visited = FxHashSet();
4501 let mut work = VecDeque::new();
4502 let cache = cache();
4504 work.push_back(first_ty);
4506 while let Some(ty) = work.pop_front() {
4507 if !visited.insert(ty.clone()) {
4512 clean::Type::ResolvedPath { did, .. } => {
4513 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4514 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4518 out.push(path.join("::"));
4524 clean::Type::Tuple(tys) => {
4525 work.extend(tys.into_iter());
4527 clean::Type::Slice(ty) => {
4528 work.push_back(*ty);
4530 clean::Type::Array(ty, _) => {
4531 work.push_back(*ty);
4533 clean::Type::Unique(ty) => {
4534 work.push_back(*ty);
4536 clean::Type::RawPointer(_, ty) => {
4537 work.push_back(*ty);
4539 clean::Type::BorrowedRef { type_, .. } => {
4540 work.push_back(*type_);
4542 clean::Type::QPath { self_type, trait_, .. } => {
4543 work.push_back(*self_type);
4544 work.push_back(*trait_);
4552 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4554 clean::ResolvedPath { ref path, .. } => {
4555 let segments = &path.segments;
4556 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4557 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4558 clean_type, accept_generic
4560 Some(path_segment.name.clone())
4562 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4563 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4564 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4565 // FIXME: add all from clean::Type.
4570 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4571 clean_type.generics()
4573 let r = types.iter()
4574 .filter_map(|t| get_index_type_name(t, false))
4575 .map(|s| s.to_ascii_lowercase())
4576 .collect::<Vec<_>>();
4585 pub fn cache() -> Arc<Cache> {
4586 CACHE_KEY.with(|c| c.borrow().clone())
4591 fn test_unique_id() {
4592 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4593 "method.into_iter", "foo", "main", "search", "methods",
4594 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4595 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4596 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4597 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4600 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4601 assert_eq!(&actual[..], expected);
4610 fn test_name_key() {
4611 assert_eq!(name_key("0"), ("", 0, 1));
4612 assert_eq!(name_key("123"), ("", 123, 0));
4613 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4614 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4615 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4616 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4617 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4618 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4623 fn test_name_sorting() {
4624 let names = ["Apple",
4626 "Fruit", "Fruit0", "Fruit00",
4627 "Fruit1", "Fruit01",
4628 "Fruit2", "Fruit02",
4632 let mut sorted = names.to_owned();
4633 sorted.sort_by_key(|&s| name_key(s));
4634 assert_eq!(names, sorted);