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};
46 use std::fs::{self, File, OpenOptions};
47 use std::io::prelude::*;
48 use std::io::{self, BufWriter, BufReader};
49 use std::iter::repeat;
51 use std::path::{PathBuf, Path, Component};
55 use externalfiles::ExternalHtml;
57 use serialize::json::{ToJson, Json, as_json};
59 use syntax::codemap::FileName;
60 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
61 use rustc::middle::privacy::AccessLevels;
62 use rustc::middle::stability;
64 use rustc::util::nodemap::{FxHashMap, FxHashSet};
65 use rustc_data_structures::flock;
67 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
70 use html::escape::Escape;
71 use html::format::{AsyncSpace, ConstnessSpace};
72 use html::format::{GenericBounds, 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 = Vec::with_capacity(2);
418 data.push(name.to_json());
419 if let Some(ref generics) = self.generics {
420 data.push(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 = Vec::with_capacity(2);
443 data.push(self.inputs.to_json());
444 if let Some(ref output) = self.output {
445 data.push(output.to_json());
452 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
453 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
454 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
456 fn init_ids() -> FxHashMap<String, usize> {
468 "synthetic-implementors",
470 "synthetic-implementors-list",
474 ].into_iter().map(|id| (String::from(*id), 1)).collect()
477 /// This method resets the local table of used ID attributes. This is typically
478 /// used at the beginning of rendering an entire HTML page to reset from the
479 /// previous state (if any).
480 pub fn reset_ids(embedded: bool) {
481 USED_ID_MAP.with(|s| {
482 *s.borrow_mut() = if embedded {
490 pub fn derive_id(candidate: String) -> String {
491 USED_ID_MAP.with(|map| {
492 let id = match map.borrow_mut().get_mut(&candidate) {
495 let id = format!("{}-{}", candidate, *a);
501 map.borrow_mut().insert(id.clone(), 1);
506 /// Generates the documentation for `crate` into the directory `dst`
507 pub fn run(mut krate: clean::Crate,
508 external_html: &ExternalHtml,
509 playground_url: Option<String>,
511 resource_suffix: String,
512 passes: FxHashSet<String>,
513 css_file_extension: Option<PathBuf>,
514 renderinfo: RenderInfo,
515 sort_modules_alphabetically: bool,
516 themes: Vec<PathBuf>,
517 enable_minification: bool) -> Result<(), Error> {
518 let src_root = match krate.src {
519 FileName::Real(ref p) => match p.parent() {
520 Some(p) => p.to_path_buf(),
521 None => PathBuf::new(),
525 let mut scx = SharedContext {
528 include_sources: true,
529 local_sources: FxHashMap(),
530 issue_tracker_base_url: None,
531 layout: layout::Layout {
532 logo: "".to_string(),
533 favicon: "".to_string(),
534 external_html: external_html.clone(),
535 krate: krate.name.clone(),
537 css_file_extension: css_file_extension.clone(),
538 created_dirs: RefCell::new(FxHashSet()),
539 sort_modules_alphabetically,
544 // If user passed in `--playground-url` arg, we fill in crate name here
545 if let Some(url) = playground_url {
546 markdown::PLAYGROUND.with(|slot| {
547 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
551 // Crawl the crate attributes looking for attributes which control how we're
552 // going to emit HTML
553 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
554 for attr in attrs.lists("doc") {
555 let name = attr.name().map(|s| s.as_str());
556 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
557 (Some("html_favicon_url"), Some(s)) => {
558 scx.layout.favicon = s.to_string();
560 (Some("html_logo_url"), Some(s)) => {
561 scx.layout.logo = s.to_string();
563 (Some("html_playground_url"), Some(s)) => {
564 markdown::PLAYGROUND.with(|slot| {
565 let name = krate.name.clone();
566 *slot.borrow_mut() = Some((Some(name), s.to_string()));
569 (Some("issue_tracker_base_url"), Some(s)) => {
570 scx.issue_tracker_base_url = Some(s.to_string());
572 (Some("html_no_source"), None) if attr.is_word() => {
573 scx.include_sources = false;
579 try_err!(fs::create_dir_all(&dst), &dst);
580 krate = render_sources(&dst, &mut scx, krate)?;
584 render_redirect_pages: false,
585 shared: Arc::new(scx),
588 // Crawl the crate to build various caches used for the output
599 let external_paths = external_paths.into_iter()
600 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
603 let mut cache = Cache {
608 implementors: FxHashMap(),
610 parent_stack: Vec::new(),
611 search_index: Vec::new(),
612 parent_is_trait_impl: false,
613 extern_locations: FxHashMap(),
614 primitive_locations: FxHashMap(),
616 access_levels: krate.access_levels.clone(),
617 crate_version: krate.version.take(),
618 orphan_impl_items: Vec::new(),
619 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
623 masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
624 typarams: external_typarams,
625 aliases: FxHashMap(),
628 // Cache where all our extern crates are located
629 for &(n, ref e) in &krate.externs {
630 let src_root = match e.src {
631 FileName::Real(ref p) => match p.parent() {
632 Some(p) => p.to_path_buf(),
633 None => PathBuf::new(),
637 cache.extern_locations.insert(n, (e.name.clone(), src_root,
638 extern_location(e, &cx.dst)));
640 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
641 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
644 // Cache where all known primitives have their documentation located.
646 // Favor linking to as local extern as possible, so iterate all crates in
647 // reverse topological order.
648 for &(_, ref e) in krate.externs.iter().rev() {
649 for &(def_id, prim, _) in &e.primitives {
650 cache.primitive_locations.insert(prim, def_id);
653 for &(def_id, prim, _) in &krate.primitives {
654 cache.primitive_locations.insert(prim, def_id);
657 cache.stack.push(krate.name.clone());
658 krate = cache.fold_crate(krate);
660 // Build our search index
661 let index = build_index(&krate, &mut cache);
663 // Freeze the cache now that the index has been built. Put an Arc into TLS
664 // for future parallelization opportunities
665 let cache = Arc::new(cache);
666 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
667 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
669 write_shared(&cx, &krate, &*cache, index, enable_minification)?;
671 // And finally render the whole crate's documentation
675 /// Build the search index from the collected metadata
676 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
677 let mut nodeid_to_pathid = FxHashMap();
678 let mut crate_items = Vec::with_capacity(cache.search_index.len());
679 let mut crate_paths = Vec::<Json>::new();
681 let Cache { ref mut search_index,
682 ref orphan_impl_items,
683 ref mut paths, .. } = *cache;
685 // Attach all orphan items to the type's definition if the type
686 // has since been learned.
687 for &(did, ref item) in orphan_impl_items {
688 if let Some(&(ref fqp, _)) = paths.get(&did) {
689 search_index.push(IndexItem {
691 name: item.name.clone().unwrap(),
692 path: fqp[..fqp.len() - 1].join("::"),
693 desc: plain_summary_line(item.doc_value()),
696 search_type: get_index_search_type(&item),
701 // Reduce `NodeId` in paths into smaller sequential numbers,
702 // and prune the paths that do not appear in the index.
703 let mut lastpath = String::new();
704 let mut lastpathid = 0usize;
706 for item in search_index {
707 item.parent_idx = item.parent.map(|nodeid| {
708 if nodeid_to_pathid.contains_key(&nodeid) {
709 *nodeid_to_pathid.get(&nodeid).unwrap()
711 let pathid = lastpathid;
712 nodeid_to_pathid.insert(nodeid, pathid);
715 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
716 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
721 // Omit the parent path if it is same to that of the prior item.
722 if lastpath == item.path {
725 lastpath = item.path.clone();
727 crate_items.push(item.to_json());
730 let crate_doc = krate.module.as_ref().map(|module| {
731 plain_summary_line(module.doc_value())
732 }).unwrap_or(String::new());
734 let mut crate_data = BTreeMap::new();
735 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
736 crate_data.insert("items".to_owned(), Json::Array(crate_items));
737 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
739 // Collect the index into a string
740 format!("searchIndex[{}] = {};",
741 as_json(&krate.name),
742 Json::Object(crate_data))
745 fn write_shared(cx: &Context,
746 krate: &clean::Crate,
748 search_index: String,
749 enable_minification: bool) -> Result<(), Error> {
750 // Write out the shared files. Note that these are shared among all rustdoc
751 // docs placed in the output directory, so this needs to be a synchronized
752 // operation with respect to all other rustdocs running around.
753 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
755 // Add all the static files. These may already exist, but we just
756 // overwrite them anyway to make sure that they're fresh and up-to-date.
758 write_minify(cx.dst.join(&format!("rustdoc{}.css", cx.shared.resource_suffix)),
759 include_str!("static/rustdoc.css"),
760 enable_minification)?;
761 write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
762 include_str!("static/settings.css"),
763 enable_minification)?;
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_minify(cx.dst.join(&format!("light{}.css", cx.shared.resource_suffix)),
786 include_str!("static/themes/light.css"),
787 enable_minification)?;
788 themes.insert("light".to_owned());
789 write_minify(cx.dst.join(&format!("dark{}.css", cx.shared.resource_suffix)),
790 include_str!("static/themes/dark.css"),
791 enable_minification)?;
792 themes.insert("dark".to_owned());
794 let mut themes: Vec<&String> = themes.iter().collect();
796 // To avoid theme switch latencies as much as possible, we put everything theme related
797 // at the beginning of the html files into another js file.
798 write(cx.dst.join(&format!("theme{}.js", cx.shared.resource_suffix)),
800 r#"var themes = document.getElementById("theme-choices");
801 var themePicker = document.getElementById("theme-picker");
803 function switchThemeButtonState() {{
804 if (themes.style.display === "block") {{
805 themes.style.display = "none";
806 themePicker.style.borderBottomRightRadius = "3px";
807 themePicker.style.borderBottomLeftRadius = "3px";
809 themes.style.display = "block";
810 themePicker.style.borderBottomRightRadius = "0";
811 themePicker.style.borderBottomLeftRadius = "0";
815 function handleThemeButtonsBlur(e) {{
816 var active = document.activeElement;
817 var related = e.relatedTarget;
819 if (active.id !== "themePicker" &&
820 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
822 (related.id !== "themePicker" &&
823 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
824 switchThemeButtonState();
828 themePicker.onclick = switchThemeButtonState;
829 themePicker.onblur = handleThemeButtonsBlur;
830 [{}].forEach(function(item) {{
831 var but = document.createElement('button');
832 but.innerHTML = item;
833 but.onclick = function(el) {{
834 switchTheme(currentTheme, mainTheme, item);
836 but.onblur = handleThemeButtonsBlur;
837 themes.appendChild(but);
840 .map(|s| format!("\"{}\"", s))
841 .collect::<Vec<String>>()
842 .join(",")).as_bytes(),
845 write_minify(cx.dst.join(&format!("main{}.js", cx.shared.resource_suffix)),
846 include_str!("static/main.js"),
847 enable_minification)?;
848 write_minify(cx.dst.join(&format!("settings{}.js", cx.shared.resource_suffix)),
849 include_str!("static/settings.js"),
850 enable_minification)?;
853 let mut data = format!("var resourcesSuffix = \"{}\";\n",
854 cx.shared.resource_suffix);
855 data.push_str(include_str!("static/storage.js"));
856 write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
858 enable_minification)?;
861 if let Some(ref css) = cx.shared.css_file_extension {
862 let out = cx.dst.join(&format!("theme{}.css", cx.shared.resource_suffix));
863 if !enable_minification {
864 try_err!(fs::copy(css, out), css);
866 let mut f = try_err!(File::open(css), css);
867 let mut buffer = String::with_capacity(1000);
869 try_err!(f.read_to_string(&mut buffer), css);
870 write_minify(out, &buffer, enable_minification)?;
873 write_minify(cx.dst.join(&format!("normalize{}.css", cx.shared.resource_suffix)),
874 include_str!("static/normalize.css"),
875 enable_minification)?;
876 write(cx.dst.join("FiraSans-Regular.woff"),
877 include_bytes!("static/FiraSans-Regular.woff"))?;
878 write(cx.dst.join("FiraSans-Medium.woff"),
879 include_bytes!("static/FiraSans-Medium.woff"))?;
880 write(cx.dst.join("FiraSans-LICENSE.txt"),
881 include_bytes!("static/FiraSans-LICENSE.txt"))?;
882 write(cx.dst.join("Heuristica-Italic.woff"),
883 include_bytes!("static/Heuristica-Italic.woff"))?;
884 write(cx.dst.join("Heuristica-LICENSE.txt"),
885 include_bytes!("static/Heuristica-LICENSE.txt"))?;
886 write(cx.dst.join("SourceSerifPro-Regular.woff"),
887 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
888 write(cx.dst.join("SourceSerifPro-Bold.woff"),
889 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
890 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
891 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
892 write(cx.dst.join("SourceCodePro-Regular.woff"),
893 include_bytes!("static/SourceCodePro-Regular.woff"))?;
894 write(cx.dst.join("SourceCodePro-Semibold.woff"),
895 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
896 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
897 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
898 write(cx.dst.join("LICENSE-MIT.txt"),
899 include_bytes!("static/LICENSE-MIT.txt"))?;
900 write(cx.dst.join("LICENSE-APACHE.txt"),
901 include_bytes!("static/LICENSE-APACHE.txt"))?;
902 write(cx.dst.join("COPYRIGHT.txt"),
903 include_bytes!("static/COPYRIGHT.txt"))?;
905 fn collect(path: &Path, krate: &str, key: &str) -> io::Result<Vec<String>> {
906 let mut ret = Vec::new();
908 for line in BufReader::new(File::open(path)?).lines() {
910 if !line.starts_with(key) {
913 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
916 ret.push(line.to_string());
922 fn show_item(item: &IndexItem, krate: &str) -> String {
923 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
924 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
925 if let Some(p) = item.parent_idx {
926 format!(",'parent':{}", p)
932 let dst = cx.dst.join("aliases.js");
934 let mut all_aliases = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
935 let mut w = try_err!(File::create(&dst), &dst);
936 let mut output = String::with_capacity(100);
937 for (alias, items) in &cache.aliases {
938 if items.is_empty() {
941 output.push_str(&format!("\"{}\":[{}],",
944 .map(|v| show_item(v, &krate.name))
948 all_aliases.push(format!("ALIASES['{}'] = {{{}}};", krate.name, output));
950 try_err!(writeln!(&mut w, "var ALIASES = {{}};"), &dst);
951 for aliases in &all_aliases {
952 try_err!(writeln!(&mut w, "{}", aliases), &dst);
956 // Update the search index
957 let dst = cx.dst.join("search-index.js");
958 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
959 all_indexes.push(search_index);
960 // Sort the indexes by crate so the file will be generated identically even
961 // with rustdoc running in parallel.
963 let mut w = try_err!(File::create(&dst), &dst);
964 try_err!(writeln!(&mut w, "var N = null;var searchIndex = {{}};"), &dst);
965 for index in &all_indexes {
966 try_err!(write_minify_replacer(&mut w, &*index, enable_minification,
967 &[(minifier::js::Keyword::Null, "N")]),
970 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
972 // Update the list of all implementors for traits
973 let dst = cx.dst.join("implementors");
974 for (&did, imps) in &cache.implementors {
975 // Private modules can leak through to this phase of rustdoc, which
976 // could contain implementations for otherwise private types. In some
977 // rare cases we could find an implementation for an item which wasn't
978 // indexed, so we just skip this step in that case.
980 // FIXME: this is a vague explanation for why this can't be a `get`, in
981 // theory it should be...
982 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
984 None => match cache.external_paths.get(&did) {
990 let mut have_impls = false;
991 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
993 // If the trait and implementation are in the same crate, then
994 // there's no need to emit information about it (there's inlining
995 // going on). If they're in different crates then the crate defining
996 // the trait will be interested in our implementation.
997 if imp.impl_item.def_id.krate == did.krate { continue }
998 // If the implementation is from another crate then that crate
1000 if !imp.impl_item.def_id.is_local() { continue }
1002 write!(implementors, "{{text:{},synthetic:{},types:{}}},",
1003 as_json(&imp.inner_impl().to_string()),
1004 imp.inner_impl().synthetic,
1005 as_json(&collect_paths_for_type(imp.inner_impl().for_.clone()))).unwrap();
1007 implementors.push_str("];");
1009 // Only create a js file if we have impls to add to it. If the trait is
1010 // documented locally though we always create the file to avoid dead
1012 if !have_impls && !cache.paths.contains_key(&did) {
1016 let mut mydst = dst.clone();
1017 for part in &remote_path[..remote_path.len() - 1] {
1020 try_err!(fs::create_dir_all(&mydst), &mydst);
1021 mydst.push(&format!("{}.{}.js",
1022 remote_item_type.css_class(),
1023 remote_path[remote_path.len() - 1]));
1025 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1026 all_implementors.push(implementors);
1027 // Sort the implementors by crate so the file will be generated
1028 // identically even with rustdoc running in parallel.
1029 all_implementors.sort();
1031 let mut f = try_err!(File::create(&mydst), &mydst);
1032 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
1033 for implementor in &all_implementors {
1034 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
1036 try_err!(writeln!(&mut f, "{}", r"
1037 if (window.register_implementors) {
1038 window.register_implementors(implementors);
1040 window.pending_implementors = implementors;
1043 try_err!(writeln!(&mut f, r"}})()"), &mydst);
1048 fn render_sources(dst: &Path, scx: &mut SharedContext,
1049 krate: clean::Crate) -> Result<clean::Crate, Error> {
1050 info!("emitting source files");
1051 let dst = dst.join("src").join(&krate.name);
1052 try_err!(fs::create_dir_all(&dst), &dst);
1053 let mut folder = SourceCollector {
1057 Ok(folder.fold_crate(krate))
1060 /// Writes the entire contents of a string to a destination, not attempting to
1061 /// catch any errors.
1062 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
1063 Ok(try_err!(fs::write(&dst, contents), &dst))
1066 fn write_minify(dst: PathBuf, contents: &str, enable_minification: bool) -> Result<(), Error> {
1067 if enable_minification {
1068 if dst.extension() == Some(&OsStr::new("css")) {
1069 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1070 write(dst, res.as_bytes())
1072 write(dst, minifier::js::minify(contents).as_bytes())
1075 write(dst, contents.as_bytes())
1079 fn write_minify_replacer<W: Write>(dst: &mut W,
1081 enable_minification: bool,
1082 keywords_to_replace: &[(minifier::js::Keyword, &str)])
1084 if enable_minification {
1086 minifier::js::minify_and_replace_keywords(contents, keywords_to_replace))
1088 writeln!(dst, "{}", contents)
1092 /// Takes a path to a source file and cleans the path to it. This canonicalizes
1093 /// things like ".." to components which preserve the "top down" hierarchy of a
1094 /// static HTML tree. Each component in the cleaned path will be passed as an
1095 /// argument to `f`. The very last component of the path (ie the file name) will
1096 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
1097 // FIXME (#9639): The closure should deal with &[u8] instead of &str
1098 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
1099 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
1102 // make it relative, if possible
1103 let p = p.strip_prefix(src_root).unwrap_or(p);
1105 let mut iter = p.components().peekable();
1107 while let Some(c) = iter.next() {
1108 if !keep_filename && iter.peek().is_none() {
1113 Component::ParentDir => f("up"),
1114 Component::Normal(c) => f(c.to_str().unwrap()),
1120 /// Attempts to find where an external crate is located, given that we're
1121 /// rendering in to the specified source destination.
1122 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
1123 // See if there's documentation generated into the local directory
1124 let local_location = dst.join(&e.name);
1125 if local_location.is_dir() {
1129 // Failing that, see if there's an attribute specifying where to find this
1131 e.attrs.lists("doc")
1132 .filter(|a| a.check_name("html_root_url"))
1133 .filter_map(|a| a.value_str())
1135 let mut url = url.to_string();
1136 if !url.ends_with("/") {
1140 }).next().unwrap_or(Unknown) // Well, at least we tried.
1143 impl<'a> DocFolder for SourceCollector<'a> {
1144 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1145 // If we're including source files, and we haven't seen this file yet,
1146 // then we need to render it out to the filesystem.
1147 if self.scx.include_sources
1148 // skip all invalid or macro spans
1149 && item.source.filename.is_real()
1150 // skip non-local items
1151 && item.def_id.is_local() {
1153 // If it turns out that we couldn't read this file, then we probably
1154 // can't read any of the files (generating html output from json or
1155 // something like that), so just don't include sources for the
1156 // entire crate. The other option is maintaining this mapping on a
1157 // per-file basis, but that's probably not worth it...
1159 .include_sources = match self.emit_source(&item.source.filename) {
1162 println!("warning: source code was requested to be rendered, \
1163 but processing `{}` had an error: {}",
1164 item.source.filename, e);
1165 println!(" skipping rendering of source code");
1170 self.fold_item_recur(item)
1174 impl<'a> SourceCollector<'a> {
1175 /// Renders the given filename into its corresponding HTML source file.
1176 fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1177 let p = match *filename {
1178 FileName::Real(ref file) => file,
1181 if self.scx.local_sources.contains_key(&**p) {
1182 // We've already emitted this source
1186 let contents = fs::read_to_string(&p)?;
1188 // Remove the utf-8 BOM if any
1189 let contents = if contents.starts_with("\u{feff}") {
1195 // Create the intermediate directories
1196 let mut cur = self.dst.clone();
1197 let mut root_path = String::from("../../");
1198 let mut href = String::new();
1199 clean_srcpath(&self.scx.src_root, &p, false, |component| {
1200 cur.push(component);
1201 fs::create_dir_all(&cur).unwrap();
1202 root_path.push_str("../");
1203 href.push_str(component);
1206 let mut fname = p.file_name()
1207 .expect("source has no filename")
1209 fname.push(".html");
1211 href.push_str(&fname.to_string_lossy());
1213 let mut w = BufWriter::new(File::create(&cur)?);
1214 let title = format!("{} -- source", cur.file_name().unwrap()
1215 .to_string_lossy());
1216 let desc = format!("Source to the Rust file `{}`.", filename);
1217 let page = layout::Page {
1219 css_class: "source",
1220 root_path: &root_path,
1222 keywords: BASIC_KEYWORDS,
1223 resource_suffix: &self.scx.resource_suffix,
1225 layout::render(&mut w, &self.scx.layout,
1226 &page, &(""), &Source(contents),
1227 self.scx.css_file_extension.is_some(),
1230 self.scx.local_sources.insert(p.clone(), href);
1235 impl DocFolder for Cache {
1236 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1237 // If this is a stripped module,
1238 // we don't want it or its children in the search index.
1239 let orig_stripped_mod = match item.inner {
1240 clean::StrippedItem(box clean::ModuleItem(..)) => {
1241 mem::replace(&mut self.stripped_mod, true)
1243 _ => self.stripped_mod,
1246 // If the impl is from a masked crate or references something from a
1247 // masked crate then remove it completely.
1248 if let clean::ImplItem(ref i) = item.inner {
1249 if self.masked_crates.contains(&item.def_id.krate) ||
1250 i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1251 i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1256 // Register any generics to their corresponding string. This is used
1257 // when pretty-printing types.
1258 if let Some(generics) = item.inner.generics() {
1259 self.generics(generics);
1262 // Propagate a trait method's documentation to all implementors of the
1264 if let clean::TraitItem(ref t) = item.inner {
1265 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1268 // Collect all the implementors of traits.
1269 if let clean::ImplItem(ref i) = item.inner {
1270 if let Some(did) = i.trait_.def_id() {
1271 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1272 impl_item: item.clone(),
1277 // Index this method for searching later on.
1278 if let Some(ref s) = item.name {
1279 let (parent, is_inherent_impl_item) = match item.inner {
1280 clean::StrippedItem(..) => ((None, None), false),
1281 clean::AssociatedConstItem(..) |
1282 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1283 // skip associated items in trait impls
1284 ((None, None), false)
1286 clean::AssociatedTypeItem(..) |
1287 clean::TyMethodItem(..) |
1288 clean::StructFieldItem(..) |
1289 clean::VariantItem(..) => {
1290 ((Some(*self.parent_stack.last().unwrap()),
1291 Some(&self.stack[..self.stack.len() - 1])),
1294 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1295 if self.parent_stack.is_empty() {
1296 ((None, None), false)
1298 let last = self.parent_stack.last().unwrap();
1300 let path = match self.paths.get(&did) {
1301 // The current stack not necessarily has correlation
1302 // for where the type was defined. On the other
1303 // hand, `paths` always has the right
1304 // information if present.
1305 Some(&(ref fqp, ItemType::Trait)) |
1306 Some(&(ref fqp, ItemType::Struct)) |
1307 Some(&(ref fqp, ItemType::Union)) |
1308 Some(&(ref fqp, ItemType::Enum)) =>
1309 Some(&fqp[..fqp.len() - 1]),
1310 Some(..) => Some(&*self.stack),
1313 ((Some(*last), path), true)
1316 _ => ((None, Some(&*self.stack)), false)
1320 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1321 debug_assert!(!item.is_stripped());
1323 // A crate has a module at its root, containing all items,
1324 // which should not be indexed. The crate-item itself is
1325 // inserted later on when serializing the search-index.
1326 if item.def_id.index != CRATE_DEF_INDEX {
1327 self.search_index.push(IndexItem {
1329 name: s.to_string(),
1330 path: path.join("::").to_string(),
1331 desc: plain_summary_line(item.doc_value()),
1334 search_type: get_index_search_type(&item),
1338 (Some(parent), None) if is_inherent_impl_item => {
1339 // We have a parent, but we don't know where they're
1340 // defined yet. Wait for later to index this item.
1341 self.orphan_impl_items.push((parent, item.clone()));
1347 // Keep track of the fully qualified path for this item.
1348 let pushed = match item.name {
1349 Some(ref n) if !n.is_empty() => {
1350 self.stack.push(n.to_string());
1357 clean::StructItem(..) | clean::EnumItem(..) |
1358 clean::TypedefItem(..) | clean::TraitItem(..) |
1359 clean::FunctionItem(..) | clean::ModuleItem(..) |
1360 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1361 clean::ConstantItem(..) | clean::StaticItem(..) |
1362 clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1363 if !self.stripped_mod => {
1364 // Re-exported items mean that the same id can show up twice
1365 // in the rustdoc ast that we're looking at. We know,
1366 // however, that a re-exported item doesn't show up in the
1367 // `public_items` map, so we can skip inserting into the
1368 // paths map if there was already an entry present and we're
1369 // not a public item.
1370 if !self.paths.contains_key(&item.def_id) ||
1371 self.access_levels.is_public(item.def_id)
1373 self.paths.insert(item.def_id,
1374 (self.stack.clone(), item.type_()));
1376 self.add_aliases(&item);
1378 // Link variants to their parent enum because pages aren't emitted
1379 // for each variant.
1380 clean::VariantItem(..) if !self.stripped_mod => {
1381 let mut stack = self.stack.clone();
1383 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1386 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1387 self.add_aliases(&item);
1388 self.paths.insert(item.def_id, (self.stack.clone(),
1395 // Maintain the parent stack
1396 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1397 let parent_pushed = match item.inner {
1398 clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1399 clean::StructItem(..) | clean::UnionItem(..) => {
1400 self.parent_stack.push(item.def_id);
1401 self.parent_is_trait_impl = false;
1404 clean::ImplItem(ref i) => {
1405 self.parent_is_trait_impl = i.trait_.is_some();
1407 clean::ResolvedPath{ did, .. } => {
1408 self.parent_stack.push(did);
1412 let prim_did = t.primitive_type().and_then(|t| {
1413 self.primitive_locations.get(&t).cloned()
1417 self.parent_stack.push(did);
1428 // Once we've recursively found all the generics, hoard off all the
1429 // implementations elsewhere.
1430 let ret = self.fold_item_recur(item).and_then(|item| {
1431 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1432 // Figure out the id of this impl. This may map to a
1433 // primitive rather than always to a struct/enum.
1434 // Note: matching twice to restrict the lifetime of the `i` borrow.
1435 let mut dids = FxHashSet();
1436 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1438 clean::ResolvedPath { did, .. } |
1439 clean::BorrowedRef {
1440 type_: box clean::ResolvedPath { did, .. }, ..
1445 let did = t.primitive_type().and_then(|t| {
1446 self.primitive_locations.get(&t).cloned()
1449 if let Some(did) = did {
1455 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1456 for bound in generics {
1457 if let Some(did) = bound.def_id() {
1466 self.impls.entry(did).or_insert(vec![]).push(Impl {
1467 impl_item: item.clone(),
1476 if pushed { self.stack.pop().unwrap(); }
1477 if parent_pushed { self.parent_stack.pop().unwrap(); }
1478 self.stripped_mod = orig_stripped_mod;
1479 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1485 fn generics(&mut self, generics: &clean::Generics) {
1486 for param in &generics.params {
1488 clean::GenericParamDefKind::Lifetime => {}
1489 clean::GenericParamDefKind::Type { did, .. } => {
1490 self.typarams.insert(did, param.name.clone());
1496 fn add_aliases(&mut self, item: &clean::Item) {
1497 if item.def_id.index == CRATE_DEF_INDEX {
1500 if let Some(ref item_name) = item.name {
1501 let path = self.paths.get(&item.def_id)
1502 .map(|p| p.0[..p.0.len() - 1].join("::"))
1503 .unwrap_or("std".to_owned());
1504 for alias in item.attrs.lists("doc")
1505 .filter(|a| a.check_name("alias"))
1506 .filter_map(|a| a.value_str()
1507 .map(|s| s.to_string().replace("\"", "")))
1508 .filter(|v| !v.is_empty())
1509 .collect::<FxHashSet<_>>()
1511 self.aliases.entry(alias)
1512 .or_insert(Vec::with_capacity(1))
1515 name: item_name.to_string(),
1517 desc: plain_summary_line(item.doc_value()),
1520 search_type: get_index_search_type(&item),
1527 #[derive(Debug, Eq, PartialEq, Hash)]
1534 fn new(mut url: String, name: String) -> ItemEntry {
1535 while url.starts_with('/') {
1545 impl fmt::Display for ItemEntry {
1546 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1547 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1551 impl PartialOrd for ItemEntry {
1552 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1553 Some(self.cmp(other))
1557 impl Ord for ItemEntry {
1558 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1559 self.name.cmp(&other.name)
1565 structs: HashSet<ItemEntry>,
1566 enums: HashSet<ItemEntry>,
1567 unions: HashSet<ItemEntry>,
1568 primitives: HashSet<ItemEntry>,
1569 traits: HashSet<ItemEntry>,
1570 macros: HashSet<ItemEntry>,
1571 functions: HashSet<ItemEntry>,
1572 typedefs: HashSet<ItemEntry>,
1573 statics: HashSet<ItemEntry>,
1574 constants: HashSet<ItemEntry>,
1575 keywords: HashSet<ItemEntry>,
1579 fn new() -> AllTypes {
1581 structs: HashSet::with_capacity(100),
1582 enums: HashSet::with_capacity(100),
1583 unions: HashSet::with_capacity(100),
1584 primitives: HashSet::with_capacity(26),
1585 traits: HashSet::with_capacity(100),
1586 macros: HashSet::with_capacity(100),
1587 functions: HashSet::with_capacity(100),
1588 typedefs: HashSet::with_capacity(100),
1589 statics: HashSet::with_capacity(100),
1590 constants: HashSet::with_capacity(100),
1591 keywords: HashSet::with_capacity(100),
1595 fn append(&mut self, item_name: String, item_type: &ItemType) {
1596 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1597 if let Some(name) = url.pop() {
1598 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1600 let name = url.join("::");
1602 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1603 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1604 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1605 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1606 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1607 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1608 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1609 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1610 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1611 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1618 fn print_entries(f: &mut fmt::Formatter, e: &HashSet<ItemEntry>, title: &str,
1619 class: &str) -> fmt::Result {
1621 let mut e: Vec<&ItemEntry> = e.iter().collect();
1623 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1627 e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
1632 impl fmt::Display for AllTypes {
1633 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1636 <span class='in-band'>List of all items</span>\
1637 <span class='out-of-band'>\
1638 <span id='render-detail'>\
1639 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1640 [<span class='inner'>−</span>]\
1645 print_entries(f, &self.structs, "Structs", "structs")?;
1646 print_entries(f, &self.enums, "Enums", "enums")?;
1647 print_entries(f, &self.unions, "Unions", "unions")?;
1648 print_entries(f, &self.primitives, "Primitives", "primitives")?;
1649 print_entries(f, &self.traits, "Traits", "traits")?;
1650 print_entries(f, &self.macros, "Macros", "macros")?;
1651 print_entries(f, &self.functions, "Functions", "functions")?;
1652 print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1653 print_entries(f, &self.statics, "Statics", "statics")?;
1654 print_entries(f, &self.constants, "Constants", "constants")
1659 struct Settings<'a> {
1660 // (id, explanation, default value)
1661 settings: Vec<(&'static str, &'static str, bool)>,
1666 impl<'a> Settings<'a> {
1667 pub fn new(root_path: &'a str, suffix: &'a str) -> Settings<'a> {
1670 ("item-declarations", "Auto-hide item declarations.", true),
1671 ("item-attributes", "Auto-hide item attributes.", true),
1672 ("trait-implementations", "Auto-hide trait implementations documentation",
1674 ("go-to-only-result", "Directly go to item in search if there is only one result",
1683 impl<'a> fmt::Display for Settings<'a> {
1684 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1687 <span class='in-band'>Rustdoc settings</span>\
1689 <div class='settings'>{}</div>\
1690 <script src='{}settings{}.js'></script>",
1691 self.settings.iter()
1692 .map(|(id, text, enabled)| {
1693 format!("<div class='setting-line'>\
1694 <label class='toggle'>\
1695 <input type='checkbox' id='{}' {}>\
1696 <span class='slider'></span>\
1699 </div>", id, if *enabled { " checked" } else { "" }, text)
1701 .collect::<String>(),
1708 /// String representation of how to get back to the root path of the 'doc/'
1709 /// folder in terms of a relative URL.
1710 fn root_path(&self) -> String {
1711 repeat("../").take(self.current.len()).collect::<String>()
1714 /// Recurse in the directory structure and change the "root path" to make
1715 /// sure it always points to the top (relatively).
1716 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1717 F: FnOnce(&mut Context) -> T,
1720 panic!("Unexpected empty destination: {:?}", self.current);
1722 let prev = self.dst.clone();
1724 self.current.push(s);
1726 info!("Recursing into {}", self.dst.display());
1730 info!("Recursed; leaving {}", self.dst.display());
1732 // Go back to where we were at
1734 self.current.pop().unwrap();
1739 /// Main method for rendering a crate.
1741 /// This currently isn't parallelized, but it'd be pretty easy to add
1742 /// parallelization to this function.
1743 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1744 let mut item = match krate.module.take() {
1746 None => return Ok(()),
1748 let final_file = self.dst.join(&krate.name)
1750 let settings_file = self.dst.join("settings.html");
1752 let crate_name = krate.name.clone();
1753 item.name = Some(krate.name);
1755 let mut all = AllTypes::new();
1758 // Render the crate documentation
1759 let mut work = vec![(self.clone(), item)];
1761 while let Some((mut cx, item)) = work.pop() {
1762 cx.item(item, &mut all, |cx, item| {
1763 work.push((cx.clone(), item))
1768 let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
1769 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1770 if !root_path.ends_with('/') {
1771 root_path.push('/');
1773 let mut page = layout::Page {
1774 title: "List of all items in this crate",
1777 description: "List of all items in this crate",
1778 keywords: BASIC_KEYWORDS,
1779 resource_suffix: &self.shared.resource_suffix,
1781 let sidebar = if let Some(ref version) = cache().crate_version {
1782 format!("<p class='location'>Crate {}</p>\
1783 <div class='block version'>\
1786 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1787 crate_name, version)
1791 try_err!(layout::render(&mut w, &self.shared.layout,
1792 &page, &sidebar, &all,
1793 self.shared.css_file_extension.is_some(),
1794 &self.shared.themes),
1797 // Generating settings page.
1798 let settings = Settings::new("./", &self.shared.resource_suffix);
1799 page.title = "Rustdoc settings";
1800 page.description = "Settings of Rustdoc";
1801 page.root_path = "./";
1803 let mut w = BufWriter::new(try_err!(File::create(&settings_file), &settings_file));
1804 let mut themes = self.shared.themes.clone();
1805 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1806 themes.push(PathBuf::from("settings.css"));
1807 let mut layout = self.shared.layout.clone();
1808 layout.krate = String::new();
1809 layout.logo = String::new();
1810 layout.favicon = String::new();
1811 try_err!(layout::render(&mut w, &layout,
1812 &page, &sidebar, &settings,
1813 self.shared.css_file_extension.is_some(),
1820 fn render_item(&self,
1821 writer: &mut io::Write,
1825 // A little unfortunate that this is done like this, but it sure
1826 // does make formatting *a lot* nicer.
1827 CURRENT_LOCATION_KEY.with(|slot| {
1828 *slot.borrow_mut() = self.current.clone();
1831 let mut title = if it.is_primitive() {
1832 // No need to include the namespace for primitive types
1835 self.current.join("::")
1838 if !title.is_empty() {
1839 title.push_str("::");
1841 title.push_str(it.name.as_ref().unwrap());
1843 title.push_str(" - Rust");
1844 let tyname = it.type_().css_class();
1845 let desc = if it.is_crate() {
1846 format!("API documentation for the Rust `{}` crate.",
1847 self.shared.layout.krate)
1849 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1850 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1852 let keywords = make_item_keywords(it);
1853 let page = layout::Page {
1855 root_path: &self.root_path(),
1858 keywords: &keywords,
1859 resource_suffix: &self.shared.resource_suffix,
1864 if !self.render_redirect_pages {
1865 layout::render(writer, &self.shared.layout, &page,
1866 &Sidebar{ cx: self, item: it },
1867 &Item{ cx: self, item: it },
1868 self.shared.css_file_extension.is_some(),
1869 &self.shared.themes)?;
1871 let mut url = self.root_path();
1872 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1873 for name in &names[..names.len() - 1] {
1877 url.push_str(&item_path(ty, names.last().unwrap()));
1878 layout::redirect(writer, &url)?;
1884 /// Non-parallelized version of rendering an item. This will take the input
1885 /// item, render its contents, and then invoke the specified closure with
1886 /// all sub-items which need to be rendered.
1888 /// The rendering driver uses this closure to queue up more work.
1889 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
1890 where F: FnMut(&mut Context, clean::Item),
1892 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1893 // if they contain impls for public types. These modules can also
1894 // contain items such as publicly re-exported structures.
1896 // External crates will provide links to these structures, so
1897 // these modules are recursed into, but not rendered normally
1898 // (a flag on the context).
1899 if !self.render_redirect_pages {
1900 self.render_redirect_pages = item.is_stripped();
1904 // modules are special because they add a namespace. We also need to
1905 // recurse into the items of the module as well.
1906 let name = item.name.as_ref().unwrap().to_string();
1907 let mut item = Some(item);
1908 self.recurse(name, |this| {
1909 let item = item.take().unwrap();
1911 let mut buf = Vec::new();
1912 this.render_item(&mut buf, &item, false).unwrap();
1913 // buf will be empty if the module is stripped and there is no redirect for it
1914 if !buf.is_empty() {
1915 try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1916 let joint_dst = this.dst.join("index.html");
1917 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1918 try_err!(dst.write_all(&buf), &joint_dst);
1921 let m = match item.inner {
1922 clean::StrippedItem(box clean::ModuleItem(m)) |
1923 clean::ModuleItem(m) => m,
1927 // Render sidebar-items.js used throughout this module.
1928 if !this.render_redirect_pages {
1929 let items = this.build_sidebar_items(&m);
1930 let js_dst = this.dst.join("sidebar-items.js");
1931 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1932 try_err!(write!(&mut js_out, "initSidebarItems({});",
1933 as_json(&items)), &js_dst);
1936 for item in m.items {
1942 } else if item.name.is_some() {
1943 let mut buf = Vec::new();
1944 self.render_item(&mut buf, &item, true).unwrap();
1945 // buf will be empty if the item is stripped and there is no redirect for it
1946 if !buf.is_empty() {
1947 let name = item.name.as_ref().unwrap();
1948 let item_type = item.type_();
1949 let file_name = &item_path(item_type, name);
1950 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1951 let joint_dst = self.dst.join(file_name);
1952 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1953 try_err!(dst.write_all(&buf), &joint_dst);
1955 if !self.render_redirect_pages {
1956 all.append(full_path(self, &item), &item_type);
1958 // Redirect from a sane URL using the namespace to Rustdoc's
1959 // URL for the page.
1960 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1961 let redir_dst = self.dst.join(redir_name);
1962 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1965 let mut redirect_out = BufWriter::new(redirect_out);
1966 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1969 // If the item is a macro, redirect from the old macro URL (with !)
1970 // to the new one (without).
1971 // FIXME(#35705) remove this redirect.
1972 if item_type == ItemType::Macro {
1973 let redir_name = format!("{}.{}!.html", item_type, name);
1974 let redir_dst = self.dst.join(redir_name);
1975 let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1976 let mut redirect_out = BufWriter::new(redirect_out);
1977 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1984 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1985 // BTreeMap instead of HashMap to get a sorted output
1986 let mut map = BTreeMap::new();
1987 for item in &m.items {
1988 if item.is_stripped() { continue }
1990 let short = item.type_().css_class();
1991 let myname = match item.name {
1993 Some(ref s) => s.to_string(),
1995 let short = short.to_string();
1996 map.entry(short).or_insert(vec![])
1997 .push((myname, Some(plain_summary_line(item.doc_value()))));
2000 if self.shared.sort_modules_alphabetically {
2001 for (_, items) in &mut map {
2010 /// Generate a url appropriate for an `href` attribute back to the source of
2013 /// The url generated, when clicked, will redirect the browser back to the
2014 /// original source code.
2016 /// If `None` is returned, then a source link couldn't be generated. This
2017 /// may happen, for example, with externally inlined items where the source
2018 /// of their crate documentation isn't known.
2019 fn src_href(&self) -> Option<String> {
2020 let mut root = self.cx.root_path();
2022 let cache = cache();
2023 let mut path = String::new();
2025 // We can safely ignore macros from other libraries
2026 let file = match self.item.source.filename {
2027 FileName::Real(ref path) => path,
2031 let (krate, path) = if self.item.def_id.is_local() {
2032 if let Some(path) = self.cx.shared.local_sources.get(file) {
2033 (&self.cx.shared.layout.krate, path)
2038 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
2039 Some(&(ref name, ref src, Local)) => (name, src),
2040 Some(&(ref name, ref src, Remote(ref s))) => {
2041 root = s.to_string();
2044 Some(&(_, _, Unknown)) | None => return None,
2047 clean_srcpath(&src_root, file, false, |component| {
2048 path.push_str(component);
2051 let mut fname = file.file_name().expect("source has no filename")
2053 fname.push(".html");
2054 path.push_str(&fname.to_string_lossy());
2058 let lines = if self.item.source.loline == self.item.source.hiline {
2059 format!("{}", self.item.source.loline)
2061 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
2063 Some(format!("{root}src/{krate}/{path}#{lines}",
2064 root = Escape(&root),
2071 fn wrap_into_docblock<F>(w: &mut fmt::Formatter,
2072 f: F) -> fmt::Result
2073 where F: Fn(&mut fmt::Formatter) -> fmt::Result {
2074 write!(w, "<div class=\"docblock type-decl\">")?;
2079 impl<'a> fmt::Display for Item<'a> {
2080 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2081 debug_assert!(!self.item.is_stripped());
2082 // Write the breadcrumb trail header for the top
2083 write!(fmt, "<h1 class='fqn'><span class='in-band'>")?;
2084 match self.item.inner {
2085 clean::ModuleItem(ref m) => if m.is_crate {
2086 write!(fmt, "Crate ")?;
2088 write!(fmt, "Module ")?;
2090 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
2091 clean::TraitItem(..) => write!(fmt, "Trait ")?,
2092 clean::StructItem(..) => write!(fmt, "Struct ")?,
2093 clean::UnionItem(..) => write!(fmt, "Union ")?,
2094 clean::EnumItem(..) => write!(fmt, "Enum ")?,
2095 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
2096 clean::MacroItem(..) => write!(fmt, "Macro ")?,
2097 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
2098 clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
2099 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
2100 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
2101 clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
2103 // We don't generate pages for any other type.
2107 if !self.item.is_primitive() && !self.item.is_keyword() {
2108 let cur = &self.cx.current;
2109 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
2110 for (i, component) in cur.iter().enumerate().take(amt) {
2111 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
2112 repeat("../").take(cur.len() - i - 1)
2113 .collect::<String>(),
2117 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
2118 self.item.type_(), self.item.name.as_ref().unwrap())?;
2120 write!(fmt, "</span>")?; // in-band
2121 write!(fmt, "<span class='out-of-band'>")?;
2122 if let Some(version) = self.item.stable_since() {
2123 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
2127 "<span id='render-detail'>\
2128 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
2129 title=\"collapse all docs\">\
2130 [<span class='inner'>−</span>]\
2136 // When this item is part of a `pub use` in a downstream crate, the
2137 // [src] link in the downstream documentation will actually come back to
2138 // this page, and this link will be auto-clicked. The `id` attribute is
2139 // used to find the link to auto-click.
2140 if self.cx.shared.include_sources && !self.item.is_primitive() {
2141 if let Some(l) = self.src_href() {
2142 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2143 l, "goto source code")?;
2147 write!(fmt, "</span></h1>")?; // out-of-band
2149 match self.item.inner {
2150 clean::ModuleItem(ref m) =>
2151 item_module(fmt, self.cx, self.item, &m.items),
2152 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
2153 item_function(fmt, self.cx, self.item, f),
2154 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
2155 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
2156 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
2157 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
2158 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
2159 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
2160 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
2161 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
2162 item_static(fmt, self.cx, self.item, i),
2163 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
2164 clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
2165 clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
2167 // We don't generate pages for any other type.
2174 fn item_path(ty: ItemType, name: &str) -> String {
2176 ItemType::Module => format!("{}/index.html", name),
2177 _ => format!("{}.{}.html", ty.css_class(), name),
2181 fn full_path(cx: &Context, item: &clean::Item) -> String {
2182 let mut s = cx.current.join("::");
2184 s.push_str(item.name.as_ref().unwrap());
2188 fn shorter<'a>(s: Option<&'a str>) -> String {
2190 Some(s) => s.lines()
2191 .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
2193 (*line).chars().any(|chr|{
2194 !chr.is_whitespace()
2196 }).collect::<Vec<_>>().join("\n"),
2197 None => "".to_string()
2202 fn plain_summary_line(s: Option<&str>) -> String {
2203 let line = shorter(s).replace("\n", " ");
2204 markdown::plain_summary_line(&line[..])
2207 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2208 if let Some(ref name) = item.name {
2209 info!("Documenting {}", name);
2211 document_stability(w, cx, item)?;
2212 let prefix = render_assoc_const_value(item);
2213 document_full(w, item, cx, &prefix)?;
2217 /// Render md_text as markdown.
2218 fn render_markdown(w: &mut fmt::Formatter,
2220 links: Vec<(String, String)>,
2223 write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
2226 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
2227 prefix: &str) -> fmt::Result {
2228 if let Some(s) = item.doc_value() {
2229 let markdown = if s.contains('\n') {
2230 format!("{} [Read more]({})",
2231 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
2233 format!("{}", &plain_summary_line(Some(s)))
2235 render_markdown(w, &markdown, item.links(), prefix)?;
2236 } else if !prefix.is_empty() {
2237 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2242 fn render_assoc_const_value(item: &clean::Item) -> String {
2244 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
2245 highlight::render_with_highlighting(
2246 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
2257 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
2258 cx: &Context, prefix: &str) -> fmt::Result {
2259 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
2260 debug!("Doc block: =====\n{}\n=====", s);
2261 render_markdown(w, &*s, item.links(), prefix)?;
2262 } else if !prefix.is_empty() {
2263 write!(w, "<div class='docblock'>{}</div>", prefix)?;
2268 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
2269 let stabilities = short_stability(item, cx, true);
2270 if !stabilities.is_empty() {
2271 write!(w, "<div class='stability'>")?;
2272 for stability in stabilities {
2273 write!(w, "{}", stability)?;
2275 write!(w, "</div>")?;
2280 fn name_key(name: &str) -> (&str, u64, usize) {
2281 // find number at end
2282 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
2284 // count leading zeroes
2286 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
2288 // sort leading zeroes last
2289 let num_zeroes = after_zeroes - split;
2291 match name[split..].parse() {
2292 Ok(n) => (&name[..split], n, num_zeroes),
2293 Err(_) => (name, 0, num_zeroes),
2297 fn item_module(w: &mut fmt::Formatter, cx: &Context,
2298 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
2299 document(w, cx, item)?;
2301 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
2303 // the order of item types in the listing
2304 fn reorder(ty: ItemType) -> u8 {
2306 ItemType::ExternCrate => 0,
2307 ItemType::Import => 1,
2308 ItemType::Primitive => 2,
2309 ItemType::Module => 3,
2310 ItemType::Macro => 4,
2311 ItemType::Struct => 5,
2312 ItemType::Enum => 6,
2313 ItemType::Constant => 7,
2314 ItemType::Static => 8,
2315 ItemType::Trait => 9,
2316 ItemType::Function => 10,
2317 ItemType::Typedef => 12,
2318 ItemType::Union => 13,
2323 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
2324 let ty1 = i1.type_();
2325 let ty2 = i2.type_();
2327 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
2329 let s1 = i1.stability.as_ref().map(|s| s.level);
2330 let s2 = i2.stability.as_ref().map(|s| s.level);
2332 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
2333 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
2336 let lhs = i1.name.as_ref().map_or("", |s| &**s);
2337 let rhs = i2.name.as_ref().map_or("", |s| &**s);
2338 name_key(lhs).cmp(&name_key(rhs))
2341 if cx.shared.sort_modules_alphabetically {
2342 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
2344 // This call is to remove re-export duplicates in cases such as:
2349 // pub trait Double { fn foo(); }
2353 // pub use foo::bar::*;
2357 // `Double` will appear twice in the generated docs.
2359 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
2360 // can be identical even if the elements are different (mostly in imports).
2361 // So in case this is an import, we keep everything by adding a "unique id"
2362 // (which is the position in the vector).
2363 indices.dedup_by_key(|i| (items[*i].def_id,
2364 if items[*i].name.as_ref().is_some() {
2365 Some(full_path(cx, &items[*i]).clone())
2370 if items[*i].is_import() {
2376 debug!("{:?}", indices);
2377 let mut curty = None;
2378 for &idx in &indices {
2379 let myitem = &items[idx];
2380 if myitem.is_stripped() {
2384 let myty = Some(myitem.type_());
2385 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2386 // Put `extern crate` and `use` re-exports in the same section.
2388 } else if myty != curty {
2389 if curty.is_some() {
2390 write!(w, "</table>")?;
2393 let (short, name) = item_ty_to_strs(&myty.unwrap());
2394 write!(w, "<h2 id='{id}' class='section-header'>\
2395 <a href=\"#{id}\">{name}</a></h2>\n<table>",
2396 id = derive_id(short.to_owned()), name = name)?;
2399 match myitem.inner {
2400 clean::ExternCrateItem(ref name, ref src) => {
2401 use html::format::HRef;
2405 write!(w, "<tr><td><code>{}extern crate {} as {};",
2406 VisSpace(&myitem.visibility),
2407 HRef::new(myitem.def_id, src),
2411 write!(w, "<tr><td><code>{}extern crate {};",
2412 VisSpace(&myitem.visibility),
2413 HRef::new(myitem.def_id, name))?
2416 write!(w, "</code></td></tr>")?;
2419 clean::ImportItem(ref import) => {
2420 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2421 VisSpace(&myitem.visibility), *import)?;
2425 if myitem.name.is_none() { continue }
2427 let stabilities = short_stability(myitem, cx, false);
2429 let stab_docs = if !stabilities.is_empty() {
2431 .map(|s| format!("[{}]", s))
2432 .collect::<Vec<_>>()
2439 let unsafety_flag = match myitem.inner {
2440 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2441 if func.header.unsafety == hir::Unsafety::Unsafe => {
2442 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2447 let doc_value = myitem.doc_value().unwrap_or("");
2449 <tr class='{stab} module-item'>
2450 <td><a class=\"{class}\" href=\"{href}\"
2451 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2452 <td class='docblock-short'>
2456 name = *myitem.name.as_ref().unwrap(),
2457 stab_docs = stab_docs,
2458 docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2459 class = myitem.type_(),
2460 stab = myitem.stability_class().unwrap_or("".to_string()),
2461 unsafety_flag = unsafety_flag,
2462 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2463 title_type = myitem.type_(),
2464 title = full_path(cx, myitem))?;
2469 if curty.is_some() {
2470 write!(w, "</table>")?;
2475 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2476 let mut stability = vec![];
2478 if let Some(stab) = item.stability.as_ref() {
2479 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2480 format!(": {}", stab.deprecated_reason)
2484 if !stab.deprecated_since.is_empty() {
2485 let since = if show_reason {
2486 format!(" since {}", Escape(&stab.deprecated_since))
2490 let text = if stability::deprecation_in_effect(&stab.deprecated_since) {
2491 format!("Deprecated{}{}",
2493 MarkdownHtml(&deprecated_reason))
2495 format!("Deprecating in {}{}",
2496 Escape(&stab.deprecated_since),
2497 MarkdownHtml(&deprecated_reason))
2499 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2502 if stab.level == stability::Unstable {
2504 let unstable_extra = match (!stab.feature.is_empty(),
2505 &cx.shared.issue_tracker_base_url,
2507 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2508 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2509 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2510 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2511 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2514 format!(" (<code>{}</code>)", Escape(&stab.feature)),
2517 if stab.unstable_reason.is_empty() {
2518 stability.push(format!("<div class='stab unstable'>\
2519 <span class=microscope>🔬</span> \
2520 This is a nightly-only experimental API. {}\
2524 let text = format!("<summary><span class=microscope>🔬</span> \
2525 This is a nightly-only experimental API. {}\
2528 MarkdownHtml(&stab.unstable_reason));
2529 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2533 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2536 } else if let Some(depr) = item.deprecation.as_ref() {
2537 let note = if show_reason && !depr.note.is_empty() {
2538 format!(": {}", depr.note)
2542 let since = if show_reason && !depr.since.is_empty() {
2543 format!(" since {}", Escape(&depr.since))
2548 let text = if stability::deprecation_in_effect(&depr.since) {
2549 format!("Deprecated{}{}",
2551 MarkdownHtml(¬e))
2553 format!("Deprecating in {}{}",
2554 Escape(&depr.since),
2555 MarkdownHtml(¬e))
2557 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2560 if let Some(ref cfg) = item.attrs.cfg {
2561 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2562 cfg.render_long_html()
2564 cfg.render_short_html()
2571 struct Initializer<'a>(&'a str);
2573 impl<'a> fmt::Display for Initializer<'a> {
2574 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2575 let Initializer(s) = *self;
2576 if s.is_empty() { return Ok(()); }
2577 write!(f, "<code> = </code>")?;
2578 write!(f, "<code>{}</code>", Escape(s))
2582 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2583 c: &clean::Constant) -> fmt::Result {
2584 write!(w, "<pre class='rust const'>")?;
2585 render_attributes(w, it)?;
2586 write!(w, "{vis}const \
2587 {name}: {typ}{init}</pre>",
2588 vis = VisSpace(&it.visibility),
2589 name = it.name.as_ref().unwrap(),
2591 init = Initializer(&c.expr))?;
2595 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2596 s: &clean::Static) -> fmt::Result {
2597 write!(w, "<pre class='rust static'>")?;
2598 render_attributes(w, it)?;
2599 write!(w, "{vis}static {mutability}\
2600 {name}: {typ}{init}</pre>",
2601 vis = VisSpace(&it.visibility),
2602 mutability = MutableSpace(s.mutability),
2603 name = it.name.as_ref().unwrap(),
2605 init = Initializer(&s.expr))?;
2609 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2610 f: &clean::Function) -> fmt::Result {
2611 let name_len = format!("{}{}{}{}{:#}fn {}{:#}",
2612 VisSpace(&it.visibility),
2613 ConstnessSpace(f.header.constness),
2614 UnsafetySpace(f.header.unsafety),
2615 AsyncSpace(f.header.asyncness),
2616 AbiSpace(f.header.abi),
2617 it.name.as_ref().unwrap(),
2619 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2620 render_attributes(w, it)?;
2622 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2623 {name}{generics}{decl}{where_clause}</pre>",
2624 vis = VisSpace(&it.visibility),
2625 constness = ConstnessSpace(f.header.constness),
2626 unsafety = UnsafetySpace(f.header.unsafety),
2627 asyncness = AsyncSpace(f.header.asyncness),
2628 abi = AbiSpace(f.header.abi),
2629 name = it.name.as_ref().unwrap(),
2630 generics = f.generics,
2631 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2640 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2641 implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result {
2642 write!(w, "<li><table class='table-display'><tbody><tr><td><code>")?;
2643 // If there's already another implementor that has the same abbridged name, use the
2644 // full path, for example in `std::iter::ExactSizeIterator`
2645 let use_absolute = match implementor.inner_impl().for_ {
2646 clean::ResolvedPath { ref path, is_generic: false, .. } |
2647 clean::BorrowedRef {
2648 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2650 } => implementor_dups[path.last_name()].1,
2653 fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2654 for it in &implementor.inner_impl().items {
2655 if let clean::TypedefItem(ref tydef, _) = it.inner {
2656 write!(w, "<span class=\"where fmt-newline\"> ")?;
2657 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2658 write!(w, ";</span>")?;
2661 write!(w, "</code><td>")?;
2662 if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2663 write!(w, "<div class='out-of-band'>")?;
2664 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2665 l, "goto source code")?;
2666 write!(w, "</div>")?;
2668 writeln!(w, "</td></tr></tbody></table></li>")?;
2672 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2674 containing_item: &clean::Item) -> fmt::Result {
2676 let did = i.trait_did().unwrap();
2677 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2678 render_impl(w, cx, i, assoc_link,
2679 RenderMode::Normal, containing_item.stable_since(), true)?;
2684 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2685 t: &clean::Trait) -> fmt::Result {
2686 let mut bounds = String::new();
2687 let mut bounds_plain = String::new();
2688 if !t.bounds.is_empty() {
2689 if !bounds.is_empty() {
2691 bounds_plain.push(' ');
2693 bounds.push_str(": ");
2694 bounds_plain.push_str(": ");
2695 for (i, p) in t.bounds.iter().enumerate() {
2697 bounds.push_str(" + ");
2698 bounds_plain.push_str(" + ");
2700 bounds.push_str(&format!("{}", *p));
2701 bounds_plain.push_str(&format!("{:#}", *p));
2705 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2706 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2707 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2708 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2710 // Output the trait definition
2711 wrap_into_docblock(w, |w| {
2712 write!(w, "<pre class='rust trait'>")?;
2713 render_attributes(w, it)?;
2714 write!(w, "{}{}{}trait {}{}{}",
2715 VisSpace(&it.visibility),
2716 UnsafetySpace(t.unsafety),
2717 if t.is_auto { "auto " } else { "" },
2718 it.name.as_ref().unwrap(),
2722 if !t.generics.where_predicates.is_empty() {
2723 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2728 if t.items.is_empty() {
2729 write!(w, "{{ }}")?;
2731 // FIXME: we should be using a derived_id for the Anchors here
2735 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2738 if !types.is_empty() && !consts.is_empty() {
2743 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2746 if !consts.is_empty() && !required.is_empty() {
2749 for (pos, m) in required.iter().enumerate() {
2751 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2754 if pos < required.len() - 1 {
2755 write!(w, "<div class='item-spacer'></div>")?;
2758 if !required.is_empty() && !provided.is_empty() {
2761 for (pos, m) in provided.iter().enumerate() {
2763 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2765 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2766 write!(w, ",\n {{ ... }}\n")?;
2769 write!(w, " {{ ... }}\n")?;
2772 if pos < provided.len() - 1 {
2773 write!(w, "<div class='item-spacer'></div>")?;
2781 // Trait documentation
2782 document(w, cx, it)?;
2784 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2786 let name = m.name.as_ref().unwrap();
2787 let item_type = m.type_();
2788 let id = derive_id(format!("{}.{}", item_type, name));
2789 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2790 write!(w, "{extra}<h3 id='{id}' class='method'>\
2791 <span id='{ns_id}' class='invisible'><code>",
2792 extra = render_spotlight_traits(m)?,
2795 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2796 write!(w, "</code>")?;
2797 render_stability_since(w, m, t)?;
2798 write!(w, "</span></h3>")?;
2799 document(w, cx, m)?;
2803 if !types.is_empty() {
2805 <h2 id='associated-types' class='small-section-header'>
2806 Associated Types<a href='#associated-types' class='anchor'></a>
2808 <div class='methods'>
2811 trait_item(w, cx, *t, it)?;
2813 write!(w, "</div>")?;
2816 if !consts.is_empty() {
2818 <h2 id='associated-const' class='small-section-header'>
2819 Associated Constants<a href='#associated-const' class='anchor'></a>
2821 <div class='methods'>
2824 trait_item(w, cx, *t, it)?;
2826 write!(w, "</div>")?;
2829 // Output the documentation for each function individually
2830 if !required.is_empty() {
2832 <h2 id='required-methods' class='small-section-header'>
2833 Required Methods<a href='#required-methods' class='anchor'></a>
2835 <div class='methods'>
2837 for m in &required {
2838 trait_item(w, cx, *m, it)?;
2840 write!(w, "</div>")?;
2842 if !provided.is_empty() {
2844 <h2 id='provided-methods' class='small-section-header'>
2845 Provided Methods<a href='#provided-methods' class='anchor'></a>
2847 <div class='methods'>
2849 for m in &provided {
2850 trait_item(w, cx, *m, it)?;
2852 write!(w, "</div>")?;
2855 // If there are methods directly on this trait object, render them here.
2856 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2858 let cache = cache();
2860 <h2 id='implementors' class='small-section-header'>
2861 Implementors<a href='#implementors' class='anchor'></a>
2863 <ul class='item-list' id='implementors-list'>
2866 let synthetic_impl_header = "
2867 <h2 id='synthetic-implementors' class='small-section-header'>
2868 Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
2870 <ul class='item-list' id='synthetic-implementors-list'>
2873 let mut synthetic_types = Vec::new();
2875 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2876 // The DefId is for the first Type found with that name. The bool is
2877 // if any Types with the same name but different DefId have been found.
2878 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2879 for implementor in implementors {
2880 match implementor.inner_impl().for_ {
2881 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2882 clean::BorrowedRef {
2883 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2886 let &mut (prev_did, ref mut has_duplicates) =
2887 implementor_dups.entry(path.last_name()).or_insert((did, false));
2888 if prev_did != did {
2889 *has_duplicates = true;
2896 let (local, foreign) = implementors.iter()
2897 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2898 .map_or(true, |d| cache.paths.contains_key(&d)));
2901 let (synthetic, concrete) = local.iter()
2902 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2905 if !foreign.is_empty() {
2907 <h2 id='foreign-impls' class='small-section-header'>
2908 Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2912 for implementor in foreign {
2913 let assoc_link = AssocItemLink::GotoSource(
2914 implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2916 render_impl(w, cx, &implementor, assoc_link,
2917 RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2921 write!(w, "{}", impl_header)?;
2922 for implementor in concrete {
2923 render_implementor(cx, implementor, w, &implementor_dups)?;
2925 write!(w, "</ul>")?;
2928 write!(w, "{}", synthetic_impl_header)?;
2929 for implementor in synthetic {
2930 synthetic_types.extend(
2931 collect_paths_for_type(implementor.inner_impl().for_.clone())
2933 render_implementor(cx, implementor, w, &implementor_dups)?;
2935 write!(w, "</ul>")?;
2938 // even without any implementations to write in, we still want the heading and list, so the
2939 // implementors javascript file pulled in below has somewhere to write the impls into
2940 write!(w, "{}", impl_header)?;
2941 write!(w, "</ul>")?;
2944 write!(w, "{}", synthetic_impl_header)?;
2945 write!(w, "</ul>")?;
2948 write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2949 as_json(&synthetic_types))?;
2951 write!(w, r#"<script type="text/javascript" async
2952 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2954 root_path = vec![".."; cx.current.len()].join("/"),
2955 path = if it.def_id.is_local() {
2956 cx.current.join("/")
2958 let (ref path, _) = cache.external_paths[&it.def_id];
2959 path[..path.len() - 1].join("/")
2961 ty = it.type_().css_class(),
2962 name = *it.name.as_ref().unwrap())?;
2966 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2967 use html::item_type::ItemType::*;
2969 let name = it.name.as_ref().unwrap();
2970 let ty = match it.type_() {
2971 Typedef | AssociatedType => AssociatedType,
2975 let anchor = format!("#{}.{}", ty, name);
2977 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2978 AssocItemLink::Anchor(None) => anchor,
2979 AssocItemLink::GotoSource(did, _) => {
2980 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2985 fn assoc_const(w: &mut fmt::Formatter,
2988 _default: Option<&String>,
2989 link: AssocItemLink) -> fmt::Result {
2990 write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2991 VisSpace(&it.visibility),
2992 naive_assoc_href(it, link),
2993 it.name.as_ref().unwrap(),
2998 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2999 bounds: &Vec<clean::GenericBound>,
3000 default: Option<&clean::Type>,
3001 link: AssocItemLink) -> fmt::Result {
3002 write!(w, "type <a href='{}' class=\"type\">{}</a>",
3003 naive_assoc_href(it, link),
3004 it.name.as_ref().unwrap())?;
3005 if !bounds.is_empty() {
3006 write!(w, ": {}", GenericBounds(bounds))?
3008 if let Some(default) = default {
3009 write!(w, " = {}", default)?;
3014 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
3015 ver: Option<&'a str>,
3016 containing_ver: Option<&'a str>) -> fmt::Result {
3017 if let Some(v) = ver {
3018 if containing_ver != ver && v.len() > 0 {
3019 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
3026 fn render_stability_since(w: &mut fmt::Formatter,
3028 containing_item: &clean::Item) -> fmt::Result {
3029 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
3032 fn render_assoc_item(w: &mut fmt::Formatter,
3034 link: AssocItemLink,
3035 parent: ItemType) -> fmt::Result {
3036 fn method(w: &mut fmt::Formatter,
3038 header: hir::FnHeader,
3039 g: &clean::Generics,
3041 link: AssocItemLink,
3044 let name = meth.name.as_ref().unwrap();
3045 let anchor = format!("#{}.{}", meth.type_(), name);
3046 let href = match link {
3047 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
3048 AssocItemLink::Anchor(None) => anchor,
3049 AssocItemLink::GotoSource(did, provided_methods) => {
3050 // We're creating a link from an impl-item to the corresponding
3051 // trait-item and need to map the anchored type accordingly.
3052 let ty = if provided_methods.contains(name) {
3058 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
3061 let mut head_len = format!("{}{}{}{}{:#}fn {}{:#}",
3062 VisSpace(&meth.visibility),
3063 ConstnessSpace(header.constness),
3064 UnsafetySpace(header.unsafety),
3065 AsyncSpace(header.asyncness),
3066 AbiSpace(header.abi),
3069 let (indent, end_newline) = if parent == ItemType::Trait {
3075 render_attributes(w, meth)?;
3076 write!(w, "{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
3077 {generics}{decl}{where_clause}",
3078 VisSpace(&meth.visibility),
3079 ConstnessSpace(header.constness),
3080 UnsafetySpace(header.unsafety),
3081 AsyncSpace(header.asyncness),
3082 AbiSpace(header.abi),
3091 where_clause = WhereClause {
3098 clean::StrippedItem(..) => Ok(()),
3099 clean::TyMethodItem(ref m) => {
3100 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3102 clean::MethodItem(ref m) => {
3103 method(w, item, m.header, &m.generics, &m.decl, link, parent)
3105 clean::AssociatedConstItem(ref ty, ref default) => {
3106 assoc_const(w, item, ty, default.as_ref(), link)
3108 clean::AssociatedTypeItem(ref bounds, ref default) => {
3109 assoc_type(w, item, bounds, default.as_ref(), link)
3111 _ => panic!("render_assoc_item called on non-associated-item")
3115 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3116 s: &clean::Struct) -> fmt::Result {
3117 wrap_into_docblock(w, |w| {
3118 write!(w, "<pre class='rust struct'>")?;
3119 render_attributes(w, it)?;
3130 document(w, cx, it)?;
3131 let mut fields = s.fields.iter().filter_map(|f| {
3133 clean::StructFieldItem(ref ty) => Some((f, ty)),
3137 if let doctree::Plain = s.struct_type {
3138 if fields.peek().is_some() {
3139 write!(w, "<h2 id='fields' class='fields small-section-header'>
3140 Fields<a href='#fields' class='anchor'></a></h2>")?;
3141 for (field, ty) in fields {
3142 let id = derive_id(format!("{}.{}",
3143 ItemType::StructField,
3144 field.name.as_ref().unwrap()));
3145 let ns_id = derive_id(format!("{}.{}",
3146 field.name.as_ref().unwrap(),
3147 ItemType::StructField.name_space()));
3148 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
3149 <a href=\"#{id}\" class=\"anchor field\"></a>
3150 <span id=\"{ns_id}\" class='invisible'>
3151 <code>{name}: {ty}</code>
3153 item_type = ItemType::StructField,
3156 name = field.name.as_ref().unwrap(),
3158 if let Some(stability_class) = field.stability_class() {
3159 write!(w, "<span class='stab {stab}'></span>",
3160 stab = stability_class)?;
3162 document(w, cx, field)?;
3166 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3169 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3170 s: &clean::Union) -> fmt::Result {
3171 wrap_into_docblock(w, |w| {
3172 write!(w, "<pre class='rust union'>")?;
3173 render_attributes(w, it)?;
3183 document(w, cx, it)?;
3184 let mut fields = s.fields.iter().filter_map(|f| {
3186 clean::StructFieldItem(ref ty) => Some((f, ty)),
3190 if fields.peek().is_some() {
3191 write!(w, "<h2 id='fields' class='fields small-section-header'>
3192 Fields<a href='#fields' class='anchor'></a></h2>")?;
3193 for (field, ty) in fields {
3194 let name = field.name.as_ref().expect("union field name");
3195 let id = format!("{}.{}", ItemType::StructField, name);
3196 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
3197 <a href=\"#{id}\" class=\"anchor field\"></a>\
3198 <span class='invisible'><code>{name}: {ty}</code></span>\
3202 shortty = ItemType::StructField,
3204 if let Some(stability_class) = field.stability_class() {
3205 write!(w, "<span class='stab {stab}'></span>",
3206 stab = stability_class)?;
3208 document(w, cx, field)?;
3211 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3214 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3215 e: &clean::Enum) -> fmt::Result {
3216 wrap_into_docblock(w, |w| {
3217 write!(w, "<pre class='rust enum'>")?;
3218 render_attributes(w, it)?;
3219 write!(w, "{}enum {}{}{}",
3220 VisSpace(&it.visibility),
3221 it.name.as_ref().unwrap(),
3223 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
3224 if e.variants.is_empty() && !e.variants_stripped {
3225 write!(w, " {{}}")?;
3227 write!(w, " {{\n")?;
3228 for v in &e.variants {
3230 let name = v.name.as_ref().unwrap();
3232 clean::VariantItem(ref var) => {
3234 clean::VariantKind::CLike => write!(w, "{}", name)?,
3235 clean::VariantKind::Tuple(ref tys) => {
3236 write!(w, "{}(", name)?;
3237 for (i, ty) in tys.iter().enumerate() {
3239 write!(w, ", ")?
3241 write!(w, "{}", *ty)?;
3245 clean::VariantKind::Struct(ref s) => {
3261 if e.variants_stripped {
3262 write!(w, " // some variants omitted\n")?;
3269 document(w, cx, it)?;
3270 if !e.variants.is_empty() {
3271 write!(w, "<h2 id='variants' class='variants small-section-header'>
3272 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
3273 for variant in &e.variants {
3274 let id = derive_id(format!("{}.{}",
3276 variant.name.as_ref().unwrap()));
3277 let ns_id = derive_id(format!("{}.{}",
3278 variant.name.as_ref().unwrap(),
3279 ItemType::Variant.name_space()));
3280 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
3281 <a href=\"#{id}\" class=\"anchor field\"></a>\
3282 <span id='{ns_id}' class='invisible'><code>{name}",
3285 name = variant.name.as_ref().unwrap())?;
3286 if let clean::VariantItem(ref var) = variant.inner {
3287 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3289 for (i, ty) in tys.iter().enumerate() {
3291 write!(w, ", ")?;
3293 write!(w, "{}", *ty)?;
3298 write!(w, "</code></span></span>")?;
3299 document(w, cx, variant)?;
3301 use clean::{Variant, VariantKind};
3302 if let clean::VariantItem(Variant {
3303 kind: VariantKind::Struct(ref s)
3304 }) = variant.inner {
3305 let variant_id = derive_id(format!("{}.{}.fields",
3307 variant.name.as_ref().unwrap()));
3308 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
3310 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
3311 <table>", name = variant.name.as_ref().unwrap())?;
3312 for field in &s.fields {
3313 use clean::StructFieldItem;
3314 if let StructFieldItem(ref ty) = field.inner {
3315 let id = derive_id(format!("variant.{}.field.{}",
3316 variant.name.as_ref().unwrap(),
3317 field.name.as_ref().unwrap()));
3318 let ns_id = derive_id(format!("{}.{}.{}.{}",
3319 variant.name.as_ref().unwrap(),
3320 ItemType::Variant.name_space(),
3321 field.name.as_ref().unwrap(),
3322 ItemType::StructField.name_space()));
3323 write!(w, "<tr><td \
3325 <span id='{ns_id}' class='invisible'>\
3326 <code>{f}: {t}</code></span></td><td>",
3329 f = field.name.as_ref().unwrap(),
3331 document(w, cx, field)?;
3332 write!(w, "</td></tr>")?;
3335 write!(w, "</table></span>")?;
3337 render_stability_since(w, variant, it)?;
3340 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
3344 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
3345 let name = attr.name();
3348 Some(format!("{}", name))
3349 } else if let Some(v) = attr.value_str() {
3350 Some(format!("{} = {:?}", name, v.as_str()))
3351 } else if let Some(values) = attr.meta_item_list() {
3352 let display: Vec<_> = values.iter().filter_map(|attr| {
3353 attr.meta_item().and_then(|mi| render_attribute(mi))
3356 if display.len() > 0 {
3357 Some(format!("{}({})", name, display.join(", ")))
3366 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
3373 "unsafe_destructor_blind_to_params"
3376 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3377 let mut attrs = String::new();
3379 for attr in &it.attrs.other_attrs {
3380 let name = attr.name();
3381 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
3384 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
3385 attrs.push_str(&format!("#[{}]\n", s));
3388 if attrs.len() > 0 {
3389 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
3394 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
3395 g: Option<&clean::Generics>,
3396 ty: doctree::StructType,
3397 fields: &[clean::Item],
3399 structhead: bool) -> fmt::Result {
3401 VisSpace(&it.visibility),
3402 if structhead {"struct "} else {""},
3403 it.name.as_ref().unwrap())?;
3404 if let Some(g) = g {
3409 if let Some(g) = g {
3410 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3412 let mut has_visible_fields = false;
3414 for field in fields {
3415 if let clean::StructFieldItem(ref ty) = field.inner {
3416 write!(w, "\n{} {}{}: {},",
3418 VisSpace(&field.visibility),
3419 field.name.as_ref().unwrap(),
3421 has_visible_fields = true;
3425 if has_visible_fields {
3426 if it.has_stripped_fields().unwrap() {
3427 write!(w, "\n{} // some fields omitted", tab)?;
3429 write!(w, "\n{}", tab)?;
3430 } else if it.has_stripped_fields().unwrap() {
3431 // If there are no visible fields we can just display
3432 // `{ /* fields omitted */ }` to save space.
3433 write!(w, " /* fields omitted */ ")?;
3439 for (i, field) in fields.iter().enumerate() {
3444 clean::StrippedItem(box clean::StructFieldItem(..)) => {
3447 clean::StructFieldItem(ref ty) => {
3448 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3454 if let Some(g) = g {
3455 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3460 // Needed for PhantomData.
3461 if let Some(g) = g {
3462 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3470 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3471 g: Option<&clean::Generics>,
3472 fields: &[clean::Item],
3474 structhead: bool) -> fmt::Result {
3476 VisSpace(&it.visibility),
3477 if structhead {"union "} else {""},
3478 it.name.as_ref().unwrap())?;
3479 if let Some(g) = g {
3480 write!(w, "{}", g)?;
3481 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3484 write!(w, " {{\n{}", tab)?;
3485 for field in fields {
3486 if let clean::StructFieldItem(ref ty) = field.inner {
3487 write!(w, " {}{}: {},\n{}",
3488 VisSpace(&field.visibility),
3489 field.name.as_ref().unwrap(),
3495 if it.has_stripped_fields().unwrap() {
3496 write!(w, " // some fields omitted\n{}", tab)?;
3502 #[derive(Copy, Clone)]
3503 enum AssocItemLink<'a> {
3504 Anchor(Option<&'a str>),
3505 GotoSource(DefId, &'a FxHashSet<String>),
3508 impl<'a> AssocItemLink<'a> {
3509 fn anchor(&self, id: &'a String) -> Self {
3511 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3512 ref other => *other,
3517 enum AssocItemRender<'a> {
3519 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3522 #[derive(Copy, Clone, PartialEq)]
3525 ForDeref { mut_: bool },
3528 fn render_assoc_items(w: &mut fmt::Formatter,
3530 containing_item: &clean::Item,
3532 what: AssocItemRender) -> fmt::Result {
3534 let v = match c.impls.get(&it) {
3536 None => return Ok(()),
3538 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3539 i.inner_impl().trait_.is_none()
3541 if !non_trait.is_empty() {
3542 let render_mode = match what {
3543 AssocItemRender::All => {
3545 <h2 id='methods' class='small-section-header'>
3546 Methods<a href='#methods' class='anchor'></a>
3551 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3553 <h2 id='deref-methods' class='small-section-header'>
3554 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
3557 RenderMode::ForDeref { mut_: deref_mut_ }
3560 for i in &non_trait {
3561 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3562 containing_item.stable_since(), true)?;
3565 if let AssocItemRender::DerefFor { .. } = what {
3568 if !traits.is_empty() {
3569 let deref_impl = traits.iter().find(|t| {
3570 t.inner_impl().trait_.def_id() == c.deref_trait_did
3572 if let Some(impl_) = deref_impl {
3573 let has_deref_mut = traits.iter().find(|t| {
3574 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3576 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3579 let (synthetic, concrete) = traits
3581 .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3583 struct RendererStruct<'a, 'b, 'c>(&'a Context, Vec<&'b &'b Impl>, &'c clean::Item);
3585 impl<'a, 'b, 'c> fmt::Display for RendererStruct<'a, 'b, 'c> {
3586 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3587 render_impls(self.0, fmt, &self.1, self.2)
3591 let impls = format!("{}", RendererStruct(cx, concrete, containing_item));
3592 if !impls.is_empty() {
3594 <h2 id='implementations' class='small-section-header'>
3595 Trait Implementations<a href='#implementations' class='anchor'></a>
3597 <div id='implementations-list'>{}</div>", impls)?;
3600 if !synthetic.is_empty() {
3602 <h2 id='synthetic-implementations' class='small-section-header'>
3603 Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3605 <div id='synthetic-implementations-list'>
3607 render_impls(cx, w, &synthetic, containing_item)?;
3608 write!(w, "</div>")?;
3614 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3615 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3616 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3617 let target = impl_.inner_impl().items.iter().filter_map(|item| {
3619 clean::TypedefItem(ref t, true) => Some(&t.type_),
3622 }).next().expect("Expected associated type binding");
3623 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3624 deref_mut_: deref_mut };
3625 if let Some(did) = target.def_id() {
3626 render_assoc_items(w, cx, container_item, did, what)
3628 if let Some(prim) = target.primitive_type() {
3629 if let Some(&did) = cache().primitive_locations.get(&prim) {
3630 render_assoc_items(w, cx, container_item, did, what)?;
3637 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3638 let self_type_opt = match item.inner {
3639 clean::MethodItem(ref method) => method.decl.self_type(),
3640 clean::TyMethodItem(ref method) => method.decl.self_type(),
3644 if let Some(self_ty) = self_type_opt {
3645 let (by_mut_ref, by_box, by_value) = match self_ty {
3646 SelfTy::SelfBorrowed(_, mutability) |
3647 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3648 (mutability == Mutability::Mutable, false, false)
3650 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3651 (false, Some(did) == cache().owned_box_did, false)
3653 SelfTy::SelfValue => (false, false, true),
3654 _ => (false, false, false),
3657 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3663 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3664 let mut out = String::new();
3667 clean::FunctionItem(clean::Function { ref decl, .. }) |
3668 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3669 clean::MethodItem(clean::Method { ref decl, .. }) |
3670 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3671 out = spotlight_decl(decl)?;
3679 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3680 let mut out = String::new();
3681 let mut trait_ = String::new();
3683 if let Some(did) = decl.output.def_id() {
3685 if let Some(impls) = c.impls.get(&did) {
3687 let impl_ = i.inner_impl();
3688 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3691 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3692 <code class=\"content\">",
3694 trait_.push_str(&format!("{}", impl_.for_));
3697 //use the "where" class here to make it small
3698 out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3699 let t_did = impl_.trait_.def_id().unwrap();
3700 for it in &impl_.items {
3701 if let clean::TypedefItem(ref tydef, _) = it.inner {
3702 out.push_str("<span class=\"where fmt-newline\"> ");
3703 assoc_type(&mut out, it, &vec![],
3705 AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3706 out.push_str(";</span>");
3714 if !out.is_empty() {
3715 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3716 <span class='tooltiptext'>Important traits for {}</span></div>\
3717 <div class=\"content hidden\">",
3719 out.push_str("</code></div></div>");
3725 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3726 render_mode: RenderMode, outer_version: Option<&str>,
3727 show_def_docs: bool) -> fmt::Result {
3728 if render_mode == RenderMode::Normal {
3729 let id = derive_id(match i.inner_impl().trait_ {
3730 Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3731 None => "impl".to_string(),
3733 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><table class='table-display'>\
3734 <tbody><tr><td><code>{}</code>",
3735 id, i.inner_impl())?;
3736 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3737 write!(w, "</span></td><td><span class='out-of-band'>")?;
3738 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3739 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3740 write!(w, "<div class='ghost'></div>")?;
3741 render_stability_since_raw(w, since, outer_version)?;
3742 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3743 l, "goto source code")?;
3745 render_stability_since_raw(w, since, outer_version)?;
3747 write!(w, "</span></td></tr></tbody></table></h3>")?;
3748 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3749 write!(w, "<div class='docblock'>{}</div>",
3750 Markdown(&*dox, &i.impl_item.links()))?;
3754 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3755 link: AssocItemLink, render_mode: RenderMode,
3756 is_default_item: bool, outer_version: Option<&str>,
3757 trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3758 let item_type = item.type_();
3759 let name = item.name.as_ref().unwrap();
3761 let render_method_item: bool = match render_mode {
3762 RenderMode::Normal => true,
3763 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3767 clean::MethodItem(clean::Method { ref decl, .. }) |
3768 clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3769 // Only render when the method is not static or we allow static methods
3770 if render_method_item {
3771 let id = derive_id(format!("{}.{}", item_type, name));
3772 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3773 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3774 write!(w, "{}", spotlight_decl(decl)?)?;
3775 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3776 write!(w, "<table class='table-display'><tbody><tr><td><code>")?;
3777 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3778 write!(w, "</code>")?;
3779 if let Some(l) = (Item { cx, item }).src_href() {
3780 write!(w, "</span></td><td><span class='out-of-band'>")?;
3781 write!(w, "<div class='ghost'></div>")?;
3782 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3783 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3784 l, "goto source code")?;
3786 write!(w, "</td><td>")?;
3787 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3789 write!(w, "</td></tr></tbody></table></span></h4>")?;
3792 clean::TypedefItem(ref tydef, _) => {
3793 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3794 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3795 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3796 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3797 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3798 write!(w, "</code></span></h4>\n")?;
3800 clean::AssociatedConstItem(ref ty, ref default) => {
3801 let id = derive_id(format!("{}.{}", item_type, name));
3802 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3803 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3804 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3805 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3806 write!(w, "</code></span></h4>\n")?;
3808 clean::AssociatedTypeItem(ref bounds, ref default) => {
3809 let id = derive_id(format!("{}.{}", item_type, name));
3810 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3811 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3812 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3813 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3814 write!(w, "</code></span></h4>\n")?;
3816 clean::StrippedItem(..) => return Ok(()),
3817 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3820 if render_method_item || render_mode == RenderMode::Normal {
3821 let prefix = render_assoc_const_value(item);
3823 if !is_default_item {
3824 if let Some(t) = trait_ {
3825 // The trait item may have been stripped so we might not
3826 // find any documentation or stability for it.
3827 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3828 // We need the stability of the item from the trait
3829 // because impls can't have a stability.
3830 document_stability(w, cx, it)?;
3831 if item.doc_value().is_some() {
3832 document_full(w, item, cx, &prefix)?;
3833 } else if show_def_docs {
3834 // In case the item isn't documented,
3835 // provide short documentation from the trait.
3836 document_short(w, it, link, &prefix)?;
3840 document_stability(w, cx, item)?;
3842 document_full(w, item, cx, &prefix)?;
3846 document_stability(w, cx, item)?;
3848 document_short(w, item, link, &prefix)?;
3855 let traits = &cache().traits;
3856 let trait_ = i.trait_did().map(|did| &traits[&did]);
3859 write!(w, "<span class='docblock autohide'>")?;
3862 write!(w, "<div class='impl-items'>")?;
3863 for trait_item in &i.inner_impl().items {
3864 doc_impl_item(w, cx, trait_item, link, render_mode,
3865 false, outer_version, trait_, show_def_docs)?;
3868 fn render_default_items(w: &mut fmt::Formatter,
3872 render_mode: RenderMode,
3873 outer_version: Option<&str>,
3874 show_def_docs: bool) -> fmt::Result {
3875 for trait_item in &t.items {
3876 let n = trait_item.name.clone();
3877 if i.items.iter().find(|m| m.name == n).is_some() {
3880 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3881 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3883 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3884 outer_version, None, show_def_docs)?;
3889 // If we've implemented a trait, then also emit documentation for all
3890 // default items which weren't overridden in the implementation block.
3891 if let Some(t) = trait_ {
3892 render_default_items(w, cx, t, &i.inner_impl(),
3893 render_mode, outer_version, show_def_docs)?;
3895 write!(w, "</div>")?;
3898 write!(w, "</span>")?;
3904 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3905 t: &clean::Typedef) -> fmt::Result {
3906 write!(w, "<pre class='rust typedef'>")?;
3907 render_attributes(w, it)?;
3908 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3909 it.name.as_ref().unwrap(),
3911 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3914 document(w, cx, it)?;
3916 // Render any items associated directly to this alias, as otherwise they
3917 // won't be visible anywhere in the docs. It would be nice to also show
3918 // associated items from the aliased type (see discussion in #32077), but
3919 // we need #14072 to make sense of the generics.
3920 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3923 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3924 writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3925 render_attributes(w, it)?;
3928 " {}type {};\n}}</pre>",
3929 VisSpace(&it.visibility),
3930 it.name.as_ref().unwrap(),
3933 document(w, cx, it)?;
3935 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3938 impl<'a> fmt::Display for Sidebar<'a> {
3939 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3942 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3944 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3945 || it.is_enum() || it.is_mod() || it.is_typedef() {
3946 write!(fmt, "<p class='location'>{}{}</p>",
3948 clean::StructItem(..) => "Struct ",
3949 clean::TraitItem(..) => "Trait ",
3950 clean::PrimitiveItem(..) => "Primitive Type ",
3951 clean::UnionItem(..) => "Union ",
3952 clean::EnumItem(..) => "Enum ",
3953 clean::TypedefItem(..) => "Type Definition ",
3954 clean::ForeignTypeItem => "Foreign Type ",
3955 clean::ModuleItem(..) => if it.is_crate() {
3962 it.name.as_ref().unwrap())?;
3966 if let Some(ref version) = cache().crate_version {
3968 "<div class='block version'>\
3971 <a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3973 it.name.as_ref().unwrap())?;
3977 write!(fmt, "<div class=\"sidebar-elems\">")?;
3979 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3980 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3981 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3982 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3983 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3984 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3985 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3986 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3990 // The sidebar is designed to display sibling functions, modules and
3991 // other miscellaneous information. since there are lots of sibling
3992 // items (and that causes quadratic growth in large modules),
3993 // we refactor common parts into a shared JavaScript file per module.
3994 // still, we don't move everything into JS because we want to preserve
3995 // as much HTML as possible in order to allow non-JS-enabled browsers
3996 // to navigate the documentation (though slightly inefficiently).
3998 write!(fmt, "<p class='location'>")?;
3999 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
4001 write!(fmt, "::<wbr>")?;
4003 write!(fmt, "<a href='{}index.html'>{}</a>",
4004 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
4007 write!(fmt, "</p>")?;
4009 // Sidebar refers to the enclosing module, not this module.
4010 let relpath = if it.is_mod() { "../" } else { "" };
4012 "<script>window.sidebarCurrent = {{\
4017 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
4018 ty = it.type_().css_class(),
4021 // There is no sidebar-items.js beyond the crate root path
4022 // FIXME maybe dynamic crate loading can be merged here
4024 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
4027 // Closes sidebar-elems div.
4028 write!(fmt, "</div>")?;
4034 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
4035 i.items.iter().filter_map(|item| {
4037 // Maybe check with clean::Visibility::Public as well?
4038 Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
4039 if !for_deref || should_render_item(item, false) {
4040 Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
4047 }).collect::<Vec<_>>()
4050 // The point is to url encode any potential character from a type with genericity.
4051 fn small_url_encode(s: &str) -> String {
4052 s.replace("<", "%3C")
4053 .replace(">", "%3E")
4054 .replace(" ", "%20")
4055 .replace("?", "%3F")
4056 .replace("'", "%27")
4057 .replace("&", "%26")
4058 .replace(",", "%2C")
4059 .replace(":", "%3A")
4060 .replace(";", "%3B")
4061 .replace("[", "%5B")
4062 .replace("]", "%5D")
4063 .replace("\"", "%22")
4066 fn sidebar_assoc_items(it: &clean::Item) -> String {
4067 let mut out = String::new();
4069 if let Some(v) = c.impls.get(&it.def_id) {
4071 .filter(|i| i.inner_impl().trait_.is_none())
4072 .flat_map(|i| get_methods(i.inner_impl(), false))
4073 .collect::<String>();
4074 if !ret.is_empty() {
4075 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
4076 </a><div class=\"sidebar-links\">{}</div>", ret));
4079 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4080 if let Some(impl_) = v.iter()
4081 .filter(|i| i.inner_impl().trait_.is_some())
4082 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
4083 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
4085 clean::TypedefItem(ref t, true) => Some(&t.type_),
4089 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
4090 c.primitive_locations.get(&prim).cloned()
4091 })).and_then(|did| c.impls.get(&did));
4092 if let Some(impls) = inner_impl {
4093 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4094 out.push_str(&format!("Methods from {}<Target={}>",
4095 Escape(&format!("{:#}",
4096 impl_.inner_impl().trait_.as_ref().unwrap())),
4097 Escape(&format!("{:#}", target))));
4098 out.push_str("</a>");
4099 let ret = impls.iter()
4100 .filter(|i| i.inner_impl().trait_.is_none())
4101 .flat_map(|i| get_methods(i.inner_impl(), true))
4102 .collect::<String>();
4103 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
4107 let format_impls = |impls: Vec<&Impl>| {
4108 let mut links = HashSet::new();
4111 let is_negative_impl = is_negative_impl(i.inner_impl());
4112 if let Some(ref i) = i.inner_impl().trait_ {
4113 let i_display = format!("{:#}", i);
4114 let out = Escape(&i_display);
4115 let encoded = small_url_encode(&format!("{:#}", i));
4116 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
4118 if is_negative_impl { "!" } else { "" },
4120 if links.insert(generated.clone()) {
4129 .collect::<String>()
4132 let (synthetic, concrete) = v
4134 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4136 let concrete_format = format_impls(concrete);
4137 let synthetic_format = format_impls(synthetic);
4139 if !concrete_format.is_empty() {
4140 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
4141 Trait Implementations</a>");
4142 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4145 if !synthetic_format.is_empty() {
4146 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4147 Auto Trait Implementations</a>");
4148 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4156 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
4157 s: &clean::Struct) -> fmt::Result {
4158 let mut sidebar = String::new();
4159 let fields = get_struct_fields_name(&s.fields);
4161 if !fields.is_empty() {
4162 if let doctree::Plain = s.struct_type {
4163 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4164 <div class=\"sidebar-links\">{}</div>", fields));
4168 sidebar.push_str(&sidebar_assoc_items(it));
4170 if !sidebar.is_empty() {
4171 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4176 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4178 clean::ItemEnum::ImplItem(ref i) => {
4179 if let Some(ref trait_) = i.trait_ {
4180 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
4189 fn is_negative_impl(i: &clean::Impl) -> bool {
4190 i.polarity == Some(clean::ImplPolarity::Negative)
4193 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
4194 t: &clean::Trait) -> fmt::Result {
4195 let mut sidebar = String::new();
4201 Some(ref name) if m.is_associated_type() => {
4202 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
4208 .collect::<String>();
4209 let consts = t.items
4213 Some(ref name) if m.is_associated_const() => {
4214 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
4220 .collect::<String>();
4221 let required = t.items
4225 Some(ref name) if m.is_ty_method() => {
4226 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
4232 .collect::<String>();
4233 let provided = t.items
4237 Some(ref name) if m.is_method() => {
4238 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
4243 .collect::<String>();
4245 if !types.is_empty() {
4246 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4247 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4250 if !consts.is_empty() {
4251 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4252 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4255 if !required.is_empty() {
4256 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4257 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4260 if !provided.is_empty() {
4261 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4262 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4268 if let Some(implementors) = c.implementors.get(&it.def_id) {
4269 let res = implementors.iter()
4270 .filter(|i| i.inner_impl().for_.def_id()
4271 .map_or(false, |d| !c.paths.contains_key(&d)))
4273 match extract_for_impl_name(&i.impl_item) {
4274 Some((ref name, ref url)) => {
4275 Some(format!("<a href=\"#impl-{}\">{}</a>",
4276 small_url_encode(url),
4282 .collect::<String>();
4283 if !res.is_empty() {
4284 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4285 Implementations on Foreign Types</a><div \
4286 class=\"sidebar-links\">{}</div>",
4291 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4293 sidebar.push_str("<a class=\"sidebar-title\" \
4294 href=\"#synthetic-implementors\">Auto Implementors</a>");
4297 sidebar.push_str(&sidebar_assoc_items(it));
4299 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
4302 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
4303 _p: &clean::PrimitiveType) -> fmt::Result {
4304 let sidebar = sidebar_assoc_items(it);
4306 if !sidebar.is_empty() {
4307 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4312 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
4313 _t: &clean::Typedef) -> fmt::Result {
4314 let sidebar = sidebar_assoc_items(it);
4316 if !sidebar.is_empty() {
4317 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4322 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4324 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4329 .filter_map(|f| match f.name {
4330 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4331 {name}</a>", name=name)),
4337 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
4338 u: &clean::Union) -> fmt::Result {
4339 let mut sidebar = String::new();
4340 let fields = get_struct_fields_name(&u.fields);
4342 if !fields.is_empty() {
4343 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4344 <div class=\"sidebar-links\">{}</div>", fields));
4347 sidebar.push_str(&sidebar_assoc_items(it));
4349 if !sidebar.is_empty() {
4350 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4355 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
4356 e: &clean::Enum) -> fmt::Result {
4357 let mut sidebar = String::new();
4359 let variants = e.variants.iter()
4360 .filter_map(|v| match v.name {
4361 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4362 </a>", name = name)),
4365 .collect::<String>();
4366 if !variants.is_empty() {
4367 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4368 <div class=\"sidebar-links\">{}</div>", variants));
4371 sidebar.push_str(&sidebar_assoc_items(it));
4373 if !sidebar.is_empty() {
4374 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4379 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4381 ItemType::ExternCrate |
4382 ItemType::Import => ("reexports", "Re-exports"),
4383 ItemType::Module => ("modules", "Modules"),
4384 ItemType::Struct => ("structs", "Structs"),
4385 ItemType::Union => ("unions", "Unions"),
4386 ItemType::Enum => ("enums", "Enums"),
4387 ItemType::Function => ("functions", "Functions"),
4388 ItemType::Typedef => ("types", "Type Definitions"),
4389 ItemType::Static => ("statics", "Statics"),
4390 ItemType::Constant => ("constants", "Constants"),
4391 ItemType::Trait => ("traits", "Traits"),
4392 ItemType::Impl => ("impls", "Implementations"),
4393 ItemType::TyMethod => ("tymethods", "Type Methods"),
4394 ItemType::Method => ("methods", "Methods"),
4395 ItemType::StructField => ("fields", "Struct Fields"),
4396 ItemType::Variant => ("variants", "Variants"),
4397 ItemType::Macro => ("macros", "Macros"),
4398 ItemType::Primitive => ("primitives", "Primitive Types"),
4399 ItemType::AssociatedType => ("associated-types", "Associated Types"),
4400 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4401 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4402 ItemType::Keyword => ("keywords", "Keywords"),
4406 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
4407 items: &[clean::Item]) -> fmt::Result {
4408 let mut sidebar = String::new();
4410 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4411 it.type_() == ItemType::Import) {
4412 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4414 name = "Re-exports"));
4417 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4418 // to print its headings
4419 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4420 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4421 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4422 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
4423 ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
4424 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4425 let (short, name) = item_ty_to_strs(&myty);
4426 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4432 if !sidebar.is_empty() {
4433 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4438 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4439 let sidebar = sidebar_assoc_items(it);
4440 if !sidebar.is_empty() {
4441 write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4446 impl<'a> fmt::Display for Source<'a> {
4447 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4448 let Source(s) = *self;
4449 let lines = s.lines().count();
4451 let mut tmp = lines;
4456 write!(fmt, "<pre class=\"line-numbers\">")?;
4457 for i in 1..lines + 1 {
4458 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4460 write!(fmt, "</pre>")?;
4462 highlight::render_with_highlighting(s, None, None, None, None))?;
4467 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4468 t: &clean::Macro) -> fmt::Result {
4469 wrap_into_docblock(w, |w| {
4470 w.write_str(&highlight::render_with_highlighting(&t.source,
4479 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4481 _p: &clean::PrimitiveType) -> fmt::Result {
4482 document(w, cx, it)?;
4483 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4486 fn item_keyword(w: &mut fmt::Formatter, cx: &Context,
4488 _p: &str) -> fmt::Result {
4492 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4494 fn make_item_keywords(it: &clean::Item) -> String {
4495 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4498 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4499 let decl = match item.inner {
4500 clean::FunctionItem(ref f) => &f.decl,
4501 clean::MethodItem(ref m) => &m.decl,
4502 clean::TyMethodItem(ref m) => &m.decl,
4506 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4507 let output = match decl.output {
4508 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4512 Some(IndexItemFunctionType { inputs: inputs, output: output })
4515 fn get_index_type(clean_type: &clean::Type) -> Type {
4517 name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4518 generics: get_generics(clean_type),
4523 /// Returns a list of all paths used in the type.
4524 /// This is used to help deduplicate imported impls
4525 /// for reexported types. If any of the contained
4526 /// types are re-exported, we don't use the corresponding
4527 /// entry from the js file, as inlining will have already
4528 /// picked up the impl
4529 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4530 let mut out = Vec::new();
4531 let mut visited = FxHashSet();
4532 let mut work = VecDeque::new();
4533 let cache = cache();
4535 work.push_back(first_ty);
4537 while let Some(ty) = work.pop_front() {
4538 if !visited.insert(ty.clone()) {
4543 clean::Type::ResolvedPath { did, .. } => {
4544 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4545 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4549 out.push(path.join("::"));
4555 clean::Type::Tuple(tys) => {
4556 work.extend(tys.into_iter());
4558 clean::Type::Slice(ty) => {
4559 work.push_back(*ty);
4561 clean::Type::Array(ty, _) => {
4562 work.push_back(*ty);
4564 clean::Type::Unique(ty) => {
4565 work.push_back(*ty);
4567 clean::Type::RawPointer(_, ty) => {
4568 work.push_back(*ty);
4570 clean::Type::BorrowedRef { type_, .. } => {
4571 work.push_back(*type_);
4573 clean::Type::QPath { self_type, trait_, .. } => {
4574 work.push_back(*self_type);
4575 work.push_back(*trait_);
4583 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4585 clean::ResolvedPath { ref path, .. } => {
4586 let segments = &path.segments;
4587 let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4588 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4589 clean_type, accept_generic
4591 Some(path_segment.name.clone())
4593 clean::Generic(ref s) if accept_generic => Some(s.clone()),
4594 clean::Primitive(ref p) => Some(format!("{:?}", p)),
4595 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4596 // FIXME: add all from clean::Type.
4601 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4602 clean_type.generics()
4604 let r = types.iter()
4605 .filter_map(|t| get_index_type_name(t, false))
4606 .map(|s| s.to_ascii_lowercase())
4607 .collect::<Vec<_>>();
4616 pub fn cache() -> Arc<Cache> {
4617 CACHE_KEY.with(|c| c.borrow().clone())
4622 fn test_unique_id() {
4623 let input = ["foo", "examples", "examples", "method.into_iter","examples",
4624 "method.into_iter", "foo", "main", "search", "methods",
4625 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4626 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4627 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4628 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4631 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4632 assert_eq!(&actual[..], expected);
4641 fn test_name_key() {
4642 assert_eq!(name_key("0"), ("", 0, 1));
4643 assert_eq!(name_key("123"), ("", 123, 0));
4644 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4645 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4646 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4647 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4648 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4649 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4654 fn test_name_sorting() {
4655 let names = ["Apple",
4657 "Fruit", "Fruit0", "Fruit00",
4658 "Fruit1", "Fruit01",
4659 "Fruit2", "Fruit02",
4663 let mut sorted = names.to_owned();
4664 sorted.sort_by_key(|&s| name_key(s));
4665 assert_eq!(names, sorted);