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.
35 pub use self::ExternalLocation::*;
37 use std::ascii::AsciiExt;
38 use std::cell::RefCell;
39 use std::cmp::Ordering;
40 use std::collections::BTreeMap;
41 use std::default::Default;
43 use std::fmt::{self, Display, Formatter};
44 use std::fs::{self, File, OpenOptions};
45 use std::io::prelude::*;
46 use std::io::{self, BufWriter, BufReader};
47 use std::iter::repeat;
49 use std::path::{PathBuf, Path, Component};
53 use externalfiles::ExternalHtml;
55 use serialize::json::{ToJson, Json, as_json};
56 use syntax::{abi, ast};
57 use syntax::feature_gate::UnstableFeatures;
58 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
59 use rustc::middle::privacy::AccessLevels;
60 use rustc::middle::stability;
62 use rustc::util::nodemap::{FxHashMap, FxHashSet};
63 use rustc_data_structures::flock;
65 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
68 use html::escape::Escape;
69 use html::format::{ConstnessSpace};
70 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
71 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
72 use html::format::fmt_impl_for_trait_page;
73 use html::item_type::ItemType;
74 use html::markdown::{self, Markdown};
75 use html::{highlight, layout};
77 /// A pair of name and its optional document.
78 pub type NameDoc = (String, Option<String>);
80 /// Major driving force in all rustdoc rendering. This contains information
81 /// about where in the tree-like hierarchy rendering is occurring and controls
82 /// how the current page is being rendered.
84 /// It is intended that this context is a lightweight object which can be fairly
85 /// easily cloned because it is cloned per work-job (about once per item in the
89 /// Current hierarchy of components leading down to what's currently being
91 pub current: Vec<String>,
92 /// The current destination folder of where HTML artifacts should be placed.
93 /// This changes as the context descends into the module hierarchy.
95 /// A flag, which when `true`, will render pages which redirect to the
96 /// real location of an item. This is used to allow external links to
97 /// publicly reused items to redirect to the right location.
98 pub render_redirect_pages: bool,
99 pub shared: Arc<SharedContext>,
102 pub struct SharedContext {
103 /// The path to the crate root source minus the file name.
104 /// Used for simplifying paths to the highlighted source code files.
105 pub src_root: PathBuf,
106 /// This describes the layout of each page, and is not modified after
107 /// creation of the context (contains info like the favicon and added html).
108 pub layout: layout::Layout,
109 /// This flag indicates whether [src] links should be generated or not. If
110 /// the source files are present in the html rendering, then this will be
112 pub include_sources: bool,
113 /// The local file sources we've emitted and their respective url-paths.
114 pub local_sources: FxHashMap<PathBuf, String>,
115 /// All the passes that were run on this crate.
116 pub passes: FxHashSet<String>,
117 /// The base-URL of the issue tracker for when an item has been tagged with
119 pub issue_tracker_base_url: Option<String>,
120 /// The given user css file which allow to customize the generated
121 /// documentation theme.
122 pub css_file_extension: Option<PathBuf>,
125 /// Indicates where an external crate can be found.
126 pub enum ExternalLocation {
127 /// Remote URL root of the external crate
129 /// This external crate can be found in the local doc/ folder
131 /// The external crate could not be found.
135 /// Metadata about an implementor of a trait.
136 pub struct Implementor {
138 pub stability: Option<clean::Stability>,
139 pub impl_: clean::Impl,
142 /// Metadata about implementations for a type.
145 pub impl_item: clean::Item,
149 fn inner_impl(&self) -> &clean::Impl {
150 match self.impl_item.inner {
151 clean::ImplItem(ref impl_) => impl_,
152 _ => panic!("non-impl item found in impl")
156 fn trait_did(&self) -> Option<DefId> {
157 self.inner_impl().trait_.def_id()
167 impl error::Error for Error {
168 fn description(&self) -> &str {
169 self.error.description()
173 impl Display for Error {
174 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
175 write!(f, "\"{}\": {}", self.file.display(), self.error)
180 pub fn new(e: io::Error, file: &Path) -> Error {
182 file: file.to_path_buf(),
188 macro_rules! try_err {
189 ($e:expr, $file:expr) => ({
192 Err(e) => return Err(Error::new(e, $file)),
197 /// This cache is used to store information about the `clean::Crate` being
198 /// rendered in order to provide more useful documentation. This contains
199 /// information like all implementors of a trait, all traits a type implements,
200 /// documentation for all known traits, etc.
202 /// This structure purposefully does not implement `Clone` because it's intended
203 /// to be a fairly large and expensive structure to clone. Instead this adheres
204 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
205 /// rendering threads.
208 /// Mapping of typaram ids to the name of the type parameter. This is used
209 /// when pretty-printing a type (so pretty printing doesn't have to
210 /// painfully maintain a context like this)
211 pub typarams: FxHashMap<DefId, String>,
213 /// Maps a type id to all known implementations for that type. This is only
214 /// recognized for intra-crate `ResolvedPath` types, and is used to print
215 /// out extra documentation on the page of an enum/struct.
217 /// The values of the map are a list of implementations and documentation
218 /// found on that implementation.
219 pub impls: FxHashMap<DefId, Vec<Impl>>,
221 /// Maintains a mapping of local crate node ids to the fully qualified name
222 /// and "short type description" of that node. This is used when generating
223 /// URLs when a type is being linked to. External paths are not located in
224 /// this map because the `External` type itself has all the information
226 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
228 /// Similar to `paths`, but only holds external paths. This is only used for
229 /// generating explicit hyperlinks to other crates.
230 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
232 /// This map contains information about all known traits of this crate.
233 /// Implementations of a crate should inherit the documentation of the
234 /// parent trait if no extra documentation is specified, and default methods
235 /// should show up in documentation about trait implementations.
236 pub traits: FxHashMap<DefId, clean::Trait>,
238 /// When rendering traits, it's often useful to be able to list all
239 /// implementors of the trait, and this mapping is exactly, that: a mapping
240 /// of trait ids to the list of known implementors of the trait
241 pub implementors: FxHashMap<DefId, Vec<Implementor>>,
243 /// Cache of where external crate documentation can be found.
244 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
246 /// Cache of where documentation for primitives can be found.
247 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
249 // Note that external items for which `doc(hidden)` applies to are shown as
250 // non-reachable while local items aren't. This is because we're reusing
251 // the access levels from crateanalysis.
252 pub access_levels: Arc<AccessLevels<DefId>>,
254 // Private fields only used when initially crawling a crate to build a cache
257 parent_stack: Vec<DefId>,
258 parent_is_trait_impl: bool,
259 search_index: Vec<IndexItem>,
261 deref_trait_did: Option<DefId>,
262 deref_mut_trait_did: Option<DefId>,
264 // In rare case where a structure is defined in one module but implemented
265 // in another, if the implementing module is parsed before defining module,
266 // then the fully qualified name of the structure isn't presented in `paths`
267 // yet when its implementation methods are being indexed. Caches such methods
268 // and their parent id here and indexes them at the end of crate parsing.
269 orphan_impl_items: Vec<(DefId, clean::Item)>,
272 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
273 /// Later on moved into `CACHE_KEY`.
275 pub struct RenderInfo {
276 pub inlined: FxHashSet<DefId>,
277 pub external_paths: ::core::ExternalPaths,
278 pub external_typarams: FxHashMap<DefId, String>,
279 pub deref_trait_did: Option<DefId>,
280 pub deref_mut_trait_did: Option<DefId>,
283 /// Helper struct to render all source code to HTML pages
284 struct SourceCollector<'a> {
285 scx: &'a mut SharedContext,
287 /// Root destination to place all HTML output into
291 /// Wrapper struct to render the source code of a file. This will do things like
292 /// adding line numbers to the left-hand side.
293 struct Source<'a>(&'a str);
295 // Helper structs for rendering items/sidebars and carrying along contextual
298 #[derive(Copy, Clone)]
301 item: &'a clean::Item,
304 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
306 /// Struct representing one entry in the JS search index. These are all emitted
307 /// by hand to a large JS file at the end of cache-creation.
313 parent: Option<DefId>,
314 parent_idx: Option<usize>,
315 search_type: Option<IndexItemFunctionType>,
318 impl ToJson for IndexItem {
319 fn to_json(&self) -> Json {
320 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
322 let mut data = Vec::with_capacity(6);
323 data.push((self.ty as usize).to_json());
324 data.push(self.name.to_json());
325 data.push(self.path.to_json());
326 data.push(self.desc.to_json());
327 data.push(self.parent_idx.to_json());
328 data.push(self.search_type.to_json());
334 /// A type used for the search index.
336 name: Option<String>,
339 impl ToJson for Type {
340 fn to_json(&self) -> Json {
343 let mut data = BTreeMap::new();
344 data.insert("name".to_owned(), name.to_json());
352 /// Full type of functions/methods in the search index.
353 struct IndexItemFunctionType {
358 impl ToJson for IndexItemFunctionType {
359 fn to_json(&self) -> Json {
360 // If we couldn't figure out a type, just write `null`.
361 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
364 let mut data = BTreeMap::new();
365 data.insert("inputs".to_owned(), self.inputs.to_json());
366 data.insert("output".to_owned(), self.output.to_json());
372 // TLS keys used to carry information around during rendering.
374 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
375 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
376 RefCell::new(Vec::new()));
377 thread_local!(static USED_ID_MAP: RefCell<FxHashMap<String, usize>> =
378 RefCell::new(init_ids()));
380 fn init_ids() -> FxHashMap<String, usize> {
396 ].into_iter().map(|id| (String::from(*id), 1)).collect()
399 /// This method resets the local table of used ID attributes. This is typically
400 /// used at the beginning of rendering an entire HTML page to reset from the
401 /// previous state (if any).
402 pub fn reset_ids(embedded: bool) {
403 USED_ID_MAP.with(|s| {
404 *s.borrow_mut() = if embedded {
412 pub fn derive_id(candidate: String) -> String {
413 USED_ID_MAP.with(|map| {
414 let id = match map.borrow_mut().get_mut(&candidate) {
417 let id = format!("{}-{}", candidate, *a);
423 map.borrow_mut().insert(id.clone(), 1);
428 /// Generates the documentation for `crate` into the directory `dst`
429 pub fn run(mut krate: clean::Crate,
430 external_html: &ExternalHtml,
432 passes: FxHashSet<String>,
433 css_file_extension: Option<PathBuf>,
434 renderinfo: RenderInfo) -> Result<(), Error> {
435 let src_root = match krate.src.parent() {
436 Some(p) => p.to_path_buf(),
437 None => PathBuf::new(),
439 let mut scx = SharedContext {
442 include_sources: true,
443 local_sources: FxHashMap(),
444 issue_tracker_base_url: None,
445 layout: layout::Layout {
446 logo: "".to_string(),
447 favicon: "".to_string(),
448 external_html: external_html.clone(),
449 krate: krate.name.clone(),
451 css_file_extension: css_file_extension.clone(),
454 // Crawl the crate attributes looking for attributes which control how we're
455 // going to emit HTML
456 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
457 for attr in attrs.lists("doc") {
458 let name = attr.name().map(|s| s.as_str());
459 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
460 (Some("html_favicon_url"), Some(s)) => {
461 scx.layout.favicon = s.to_string();
463 (Some("html_logo_url"), Some(s)) => {
464 scx.layout.logo = s.to_string();
466 (Some("html_playground_url"), Some(s)) => {
467 markdown::PLAYGROUND.with(|slot| {
468 let name = krate.name.clone();
469 *slot.borrow_mut() = Some((Some(name), s.to_string()));
472 (Some("issue_tracker_base_url"), Some(s)) => {
473 scx.issue_tracker_base_url = Some(s.to_string());
475 (Some("html_no_source"), None) if attr.is_word() => {
476 scx.include_sources = false;
482 try_err!(mkdir(&dst), &dst);
483 krate = render_sources(&dst, &mut scx, krate)?;
487 render_redirect_pages: false,
488 shared: Arc::new(scx),
491 // Crawl the crate to build various caches used for the output
500 let external_paths = external_paths.into_iter()
501 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
504 let mut cache = Cache {
506 external_paths: external_paths,
508 implementors: FxHashMap(),
510 parent_stack: Vec::new(),
511 search_index: Vec::new(),
512 parent_is_trait_impl: false,
513 extern_locations: FxHashMap(),
514 primitive_locations: FxHashMap(),
516 access_levels: krate.access_levels.clone(),
517 orphan_impl_items: Vec::new(),
518 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
519 deref_trait_did: deref_trait_did,
520 deref_mut_trait_did: deref_mut_trait_did,
521 typarams: external_typarams,
524 // Cache where all our extern crates are located
525 for &(n, ref e) in &krate.externs {
526 let src_root = match Path::new(&e.src).parent() {
527 Some(p) => p.to_path_buf(),
528 None => PathBuf::new(),
530 cache.extern_locations.insert(n, (e.name.clone(), src_root,
531 extern_location(e, &cx.dst)));
533 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
534 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
537 // Cache where all known primitives have their documentation located.
539 // Favor linking to as local extern as possible, so iterate all crates in
540 // reverse topological order.
541 for &(_, ref e) in krate.externs.iter().rev() {
542 for &(def_id, prim, _) in &e.primitives {
543 cache.primitive_locations.insert(prim, def_id);
546 for &(def_id, prim, _) in &krate.primitives {
547 cache.primitive_locations.insert(prim, def_id);
550 cache.stack.push(krate.name.clone());
551 krate = cache.fold_crate(krate);
553 // Build our search index
554 let index = build_index(&krate, &mut cache);
556 // Freeze the cache now that the index has been built. Put an Arc into TLS
557 // for future parallelization opportunities
558 let cache = Arc::new(cache);
559 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
560 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
562 write_shared(&cx, &krate, &*cache, index)?;
564 // And finally render the whole crate's documentation
568 /// Build the search index from the collected metadata
569 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
570 let mut nodeid_to_pathid = FxHashMap();
571 let mut crate_items = Vec::with_capacity(cache.search_index.len());
572 let mut crate_paths = Vec::<Json>::new();
574 let Cache { ref mut search_index,
575 ref orphan_impl_items,
576 ref mut paths, .. } = *cache;
578 // Attach all orphan items to the type's definition if the type
579 // has since been learned.
580 for &(did, ref item) in orphan_impl_items {
581 if let Some(&(ref fqp, _)) = paths.get(&did) {
582 search_index.push(IndexItem {
584 name: item.name.clone().unwrap(),
585 path: fqp[..fqp.len() - 1].join("::"),
586 desc: Escape(&shorter(item.doc_value())).to_string(),
589 search_type: get_index_search_type(&item),
594 // Reduce `NodeId` in paths into smaller sequential numbers,
595 // and prune the paths that do not appear in the index.
596 let mut lastpath = String::new();
597 let mut lastpathid = 0usize;
599 for item in search_index {
600 item.parent_idx = item.parent.map(|nodeid| {
601 if nodeid_to_pathid.contains_key(&nodeid) {
602 *nodeid_to_pathid.get(&nodeid).unwrap()
604 let pathid = lastpathid;
605 nodeid_to_pathid.insert(nodeid, pathid);
608 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
609 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
614 // Omit the parent path if it is same to that of the prior item.
615 if lastpath == item.path {
618 lastpath = item.path.clone();
620 crate_items.push(item.to_json());
623 let crate_doc = krate.module.as_ref().map(|module| {
624 Escape(&shorter(module.doc_value())).to_string()
625 }).unwrap_or(String::new());
627 let mut crate_data = BTreeMap::new();
628 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
629 crate_data.insert("items".to_owned(), Json::Array(crate_items));
630 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
632 // Collect the index into a string
633 format!("searchIndex[{}] = {};",
634 as_json(&krate.name),
635 Json::Object(crate_data))
638 fn write_shared(cx: &Context,
639 krate: &clean::Crate,
641 search_index: String) -> Result<(), Error> {
642 // Write out the shared files. Note that these are shared among all rustdoc
643 // docs placed in the output directory, so this needs to be a synchronized
644 // operation with respect to all other rustdocs running around.
645 try_err!(mkdir(&cx.dst), &cx.dst);
646 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
648 // Add all the static files. These may already exist, but we just
649 // overwrite them anyway to make sure that they're fresh and up-to-date.
651 write(cx.dst.join("jquery.js"),
652 include_bytes!("static/jquery-2.1.4.min.js"))?;
653 write(cx.dst.join("main.js"),
654 include_bytes!("static/main.js"))?;
655 write(cx.dst.join("rustdoc.css"),
656 include_bytes!("static/rustdoc.css"))?;
657 write(cx.dst.join("main.css"),
658 include_bytes!("static/styles/main.css"))?;
659 if let Some(ref css) = cx.shared.css_file_extension {
660 let mut content = String::new();
661 let css = css.as_path();
662 let mut f = try_err!(File::open(css), css);
664 try_err!(f.read_to_string(&mut content), css);
665 let css = cx.dst.join("theme.css");
666 let css = css.as_path();
667 let mut f = try_err!(File::create(css), css);
668 try_err!(write!(f, "{}", &content), css);
670 write(cx.dst.join("normalize.css"),
671 include_bytes!("static/normalize.css"))?;
672 write(cx.dst.join("FiraSans-Regular.woff"),
673 include_bytes!("static/FiraSans-Regular.woff"))?;
674 write(cx.dst.join("FiraSans-Medium.woff"),
675 include_bytes!("static/FiraSans-Medium.woff"))?;
676 write(cx.dst.join("FiraSans-LICENSE.txt"),
677 include_bytes!("static/FiraSans-LICENSE.txt"))?;
678 write(cx.dst.join("Heuristica-Italic.woff"),
679 include_bytes!("static/Heuristica-Italic.woff"))?;
680 write(cx.dst.join("Heuristica-LICENSE.txt"),
681 include_bytes!("static/Heuristica-LICENSE.txt"))?;
682 write(cx.dst.join("SourceSerifPro-Regular.woff"),
683 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
684 write(cx.dst.join("SourceSerifPro-Bold.woff"),
685 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
686 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
687 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
688 write(cx.dst.join("SourceCodePro-Regular.woff"),
689 include_bytes!("static/SourceCodePro-Regular.woff"))?;
690 write(cx.dst.join("SourceCodePro-Semibold.woff"),
691 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
692 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
693 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
694 write(cx.dst.join("LICENSE-MIT.txt"),
695 include_bytes!("static/LICENSE-MIT.txt"))?;
696 write(cx.dst.join("LICENSE-APACHE.txt"),
697 include_bytes!("static/LICENSE-APACHE.txt"))?;
698 write(cx.dst.join("COPYRIGHT.txt"),
699 include_bytes!("static/COPYRIGHT.txt"))?;
701 fn collect(path: &Path, krate: &str,
702 key: &str) -> io::Result<Vec<String>> {
703 let mut ret = Vec::new();
705 for line in BufReader::new(File::open(path)?).lines() {
707 if !line.starts_with(key) {
710 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
713 ret.push(line.to_string());
719 // Update the search index
720 let dst = cx.dst.join("search-index.js");
721 let all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
722 let mut w = try_err!(File::create(&dst), &dst);
723 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
724 try_err!(writeln!(&mut w, "{}", search_index), &dst);
725 for index in &all_indexes {
726 try_err!(writeln!(&mut w, "{}", *index), &dst);
728 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
730 // Update the list of all implementors for traits
731 let dst = cx.dst.join("implementors");
732 try_err!(mkdir(&dst), &dst);
733 for (&did, imps) in &cache.implementors {
734 // Private modules can leak through to this phase of rustdoc, which
735 // could contain implementations for otherwise private types. In some
736 // rare cases we could find an implementation for an item which wasn't
737 // indexed, so we just skip this step in that case.
739 // FIXME: this is a vague explanation for why this can't be a `get`, in
740 // theory it should be...
741 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
743 None => match cache.external_paths.get(&did) {
749 let mut mydst = dst.clone();
750 for part in &remote_path[..remote_path.len() - 1] {
752 try_err!(mkdir(&mydst), &mydst);
754 mydst.push(&format!("{}.{}.js",
755 remote_item_type.css_class(),
756 remote_path[remote_path.len() - 1]));
757 let all_implementors = try_err!(collect(&mydst, &krate.name,
761 try_err!(mkdir(mydst.parent().unwrap()),
762 &mydst.parent().unwrap().to_path_buf());
763 let mut f = BufWriter::new(try_err!(File::create(&mydst), &mydst));
764 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
766 for implementor in &all_implementors {
767 try_err!(write!(&mut f, "{}", *implementor), &mydst);
770 try_err!(write!(&mut f, r#"implementors["{}"] = ["#, krate.name), &mydst);
772 // If the trait and implementation are in the same crate, then
773 // there's no need to emit information about it (there's inlining
774 // going on). If they're in different crates then the crate defining
775 // the trait will be interested in our implementation.
776 if imp.def_id.krate == did.krate { continue }
777 try_err!(write!(&mut f, r#""{}","#, imp.impl_), &mydst);
779 try_err!(writeln!(&mut f, r"];"), &mydst);
780 try_err!(writeln!(&mut f, "{}", r"
781 if (window.register_implementors) {
782 window.register_implementors(implementors);
784 window.pending_implementors = implementors;
787 try_err!(writeln!(&mut f, r"}})()"), &mydst);
792 fn render_sources(dst: &Path, scx: &mut SharedContext,
793 krate: clean::Crate) -> Result<clean::Crate, Error> {
794 info!("emitting source files");
795 let dst = dst.join("src");
796 try_err!(mkdir(&dst), &dst);
797 let dst = dst.join(&krate.name);
798 try_err!(mkdir(&dst), &dst);
799 let mut folder = SourceCollector {
803 Ok(folder.fold_crate(krate))
806 /// Writes the entire contents of a string to a destination, not attempting to
807 /// catch any errors.
808 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
809 Ok(try_err!(try_err!(File::create(&dst), &dst).write_all(contents), &dst))
812 /// Makes a directory on the filesystem, failing the thread if an error occurs
813 /// and skipping if the directory already exists.
815 /// Note that this also handles races as rustdoc is likely to be run
816 /// concurrently against another invocation.
817 fn mkdir(path: &Path) -> io::Result<()> {
818 match fs::create_dir(path) {
820 Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
825 /// Takes a path to a source file and cleans the path to it. This canonicalizes
826 /// things like ".." to components which preserve the "top down" hierarchy of a
827 /// static HTML tree. Each component in the cleaned path will be passed as an
828 /// argument to `f`. The very last component of the path (ie the file name) will
829 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
830 // FIXME (#9639): The closure should deal with &[u8] instead of &str
831 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
832 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
835 // make it relative, if possible
836 let p = p.strip_prefix(src_root).unwrap_or(p);
838 let mut iter = p.components().peekable();
840 while let Some(c) = iter.next() {
841 if !keep_filename && iter.peek().is_none() {
846 Component::ParentDir => f("up"),
847 Component::Normal(c) => f(c.to_str().unwrap()),
853 /// Attempts to find where an external crate is located, given that we're
854 /// rendering in to the specified source destination.
855 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
856 // See if there's documentation generated into the local directory
857 let local_location = dst.join(&e.name);
858 if local_location.is_dir() {
862 // Failing that, see if there's an attribute specifying where to find this
865 .filter(|a| a.check_name("html_root_url"))
866 .filter_map(|a| a.value_str())
868 let mut url = url.to_string();
869 if !url.ends_with("/") {
873 }).next().unwrap_or(Unknown) // Well, at least we tried.
876 impl<'a> DocFolder for SourceCollector<'a> {
877 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
878 // If we're including source files, and we haven't seen this file yet,
879 // then we need to render it out to the filesystem.
880 if self.scx.include_sources
881 // skip all invalid spans
882 && item.source.filename != ""
883 // skip non-local items
884 && item.def_id.is_local()
885 // Macros from other libraries get special filenames which we can
887 && !(item.source.filename.starts_with("<")
888 && item.source.filename.ends_with("macros>")) {
890 // If it turns out that we couldn't read this file, then we probably
891 // can't read any of the files (generating html output from json or
892 // something like that), so just don't include sources for the
893 // entire crate. The other option is maintaining this mapping on a
894 // per-file basis, but that's probably not worth it...
896 .include_sources = match self.emit_source(&item.source.filename) {
899 println!("warning: source code was requested to be rendered, \
900 but processing `{}` had an error: {}",
901 item.source.filename, e);
902 println!(" skipping rendering of source code");
907 self.fold_item_recur(item)
911 impl<'a> SourceCollector<'a> {
912 /// Renders the given filename into its corresponding HTML source file.
913 fn emit_source(&mut self, filename: &str) -> io::Result<()> {
914 let p = PathBuf::from(filename);
915 if self.scx.local_sources.contains_key(&p) {
916 // We've already emitted this source
920 let mut contents = Vec::new();
921 File::open(&p).and_then(|mut f| f.read_to_end(&mut contents))?;
923 let contents = str::from_utf8(&contents).unwrap();
925 // Remove the utf-8 BOM if any
926 let contents = if contents.starts_with("\u{feff}") {
932 // Create the intermediate directories
933 let mut cur = self.dst.clone();
934 let mut root_path = String::from("../../");
935 let mut href = String::new();
936 clean_srcpath(&self.scx.src_root, &p, false, |component| {
938 mkdir(&cur).unwrap();
939 root_path.push_str("../");
940 href.push_str(component);
943 let mut fname = p.file_name().expect("source has no filename")
947 href.push_str(&fname.to_string_lossy());
949 let mut w = BufWriter::new(File::create(&cur)?);
950 let title = format!("{} -- source", cur.file_name().unwrap()
952 let desc = format!("Source to the Rust file `{}`.", filename);
953 let page = layout::Page {
956 root_path: &root_path,
958 keywords: BASIC_KEYWORDS,
960 layout::render(&mut w, &self.scx.layout,
961 &page, &(""), &Source(contents),
962 self.scx.css_file_extension.is_some())?;
964 self.scx.local_sources.insert(p, href);
969 impl DocFolder for Cache {
970 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
971 // If this is a stripped module,
972 // we don't want it or its children in the search index.
973 let orig_stripped_mod = match item.inner {
974 clean::StrippedItem(box clean::ModuleItem(..)) => {
975 mem::replace(&mut self.stripped_mod, true)
977 _ => self.stripped_mod,
980 // Register any generics to their corresponding string. This is used
981 // when pretty-printing types.
982 if let Some(generics) = item.inner.generics() {
983 self.generics(generics);
986 // Propagate a trait method's documentation to all implementors of the
988 if let clean::TraitItem(ref t) = item.inner {
989 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
992 // Collect all the implementors of traits.
993 if let clean::ImplItem(ref i) = item.inner {
994 if let Some(did) = i.trait_.def_id() {
995 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
997 stability: item.stability.clone(),
1003 // Index this method for searching later on.
1004 if let Some(ref s) = item.name {
1005 let (parent, is_inherent_impl_item) = match item.inner {
1006 clean::StrippedItem(..) => ((None, None), false),
1007 clean::AssociatedConstItem(..) |
1008 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1009 // skip associated items in trait impls
1010 ((None, None), false)
1012 clean::AssociatedTypeItem(..) |
1013 clean::TyMethodItem(..) |
1014 clean::StructFieldItem(..) |
1015 clean::VariantItem(..) => {
1016 ((Some(*self.parent_stack.last().unwrap()),
1017 Some(&self.stack[..self.stack.len() - 1])),
1020 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1021 if self.parent_stack.is_empty() {
1022 ((None, None), false)
1024 let last = self.parent_stack.last().unwrap();
1026 let path = match self.paths.get(&did) {
1027 // The current stack not necessarily has correlation
1028 // for where the type was defined. On the other
1029 // hand, `paths` always has the right
1030 // information if present.
1031 Some(&(ref fqp, ItemType::Trait)) |
1032 Some(&(ref fqp, ItemType::Struct)) |
1033 Some(&(ref fqp, ItemType::Union)) |
1034 Some(&(ref fqp, ItemType::Enum)) =>
1035 Some(&fqp[..fqp.len() - 1]),
1036 Some(..) => Some(&*self.stack),
1039 ((Some(*last), path), true)
1042 _ => ((None, Some(&*self.stack)), false)
1046 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1047 debug_assert!(!item.is_stripped());
1049 // A crate has a module at its root, containing all items,
1050 // which should not be indexed. The crate-item itself is
1051 // inserted later on when serializing the search-index.
1052 if item.def_id.index != CRATE_DEF_INDEX {
1053 self.search_index.push(IndexItem {
1055 name: s.to_string(),
1056 path: path.join("::").to_string(),
1057 desc: Escape(&shorter(item.doc_value())).to_string(),
1060 search_type: get_index_search_type(&item),
1064 (Some(parent), None) if is_inherent_impl_item => {
1065 // We have a parent, but we don't know where they're
1066 // defined yet. Wait for later to index this item.
1067 self.orphan_impl_items.push((parent, item.clone()));
1073 // Keep track of the fully qualified path for this item.
1074 let pushed = match item.name {
1075 Some(ref n) if !n.is_empty() => {
1076 self.stack.push(n.to_string());
1083 clean::StructItem(..) | clean::EnumItem(..) |
1084 clean::TypedefItem(..) | clean::TraitItem(..) |
1085 clean::FunctionItem(..) | clean::ModuleItem(..) |
1086 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1087 clean::ConstantItem(..) | clean::StaticItem(..) |
1088 clean::UnionItem(..)
1089 if !self.stripped_mod => {
1090 // Reexported items mean that the same id can show up twice
1091 // in the rustdoc ast that we're looking at. We know,
1092 // however, that a reexported item doesn't show up in the
1093 // `public_items` map, so we can skip inserting into the
1094 // paths map if there was already an entry present and we're
1095 // not a public item.
1097 !self.paths.contains_key(&item.def_id) ||
1098 self.access_levels.is_public(item.def_id)
1100 self.paths.insert(item.def_id,
1101 (self.stack.clone(), item.type_()));
1104 // Link variants to their parent enum because pages aren't emitted
1105 // for each variant.
1106 clean::VariantItem(..) if !self.stripped_mod => {
1107 let mut stack = self.stack.clone();
1109 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1112 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1113 self.paths.insert(item.def_id, (self.stack.clone(),
1120 // Maintain the parent stack
1121 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1122 let parent_pushed = match item.inner {
1123 clean::TraitItem(..) | clean::EnumItem(..) |
1124 clean::StructItem(..) | clean::UnionItem(..) => {
1125 self.parent_stack.push(item.def_id);
1126 self.parent_is_trait_impl = false;
1129 clean::ImplItem(ref i) => {
1130 self.parent_is_trait_impl = i.trait_.is_some();
1132 clean::ResolvedPath{ did, .. } => {
1133 self.parent_stack.push(did);
1137 let prim_did = t.primitive_type().and_then(|t| {
1138 self.primitive_locations.get(&t).cloned()
1142 self.parent_stack.push(did);
1153 // Once we've recursively found all the generics, hoard off all the
1154 // implementations elsewhere.
1155 let ret = self.fold_item_recur(item).and_then(|item| {
1156 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1157 // Figure out the id of this impl. This may map to a
1158 // primitive rather than always to a struct/enum.
1159 // Note: matching twice to restrict the lifetime of the `i` borrow.
1160 let did = if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1162 clean::ResolvedPath { did, .. } |
1163 clean::BorrowedRef {
1164 type_: box clean::ResolvedPath { did, .. }, ..
1169 t.primitive_type().and_then(|t| {
1170 self.primitive_locations.get(&t).cloned()
1177 if let Some(did) = did {
1178 self.impls.entry(did).or_insert(vec![]).push(Impl {
1188 if pushed { self.stack.pop().unwrap(); }
1189 if parent_pushed { self.parent_stack.pop().unwrap(); }
1190 self.stripped_mod = orig_stripped_mod;
1191 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1197 fn generics(&mut self, generics: &clean::Generics) {
1198 for typ in &generics.type_params {
1199 self.typarams.insert(typ.did, typ.name.clone());
1205 /// String representation of how to get back to the root path of the 'doc/'
1206 /// folder in terms of a relative URL.
1207 fn root_path(&self) -> String {
1208 repeat("../").take(self.current.len()).collect::<String>()
1211 /// Recurse in the directory structure and change the "root path" to make
1212 /// sure it always points to the top (relatively).
1213 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1214 F: FnOnce(&mut Context) -> T,
1217 panic!("Unexpected empty destination: {:?}", self.current);
1219 let prev = self.dst.clone();
1221 self.current.push(s);
1223 info!("Recursing into {}", self.dst.display());
1227 info!("Recursed; leaving {}", self.dst.display());
1229 // Go back to where we were at
1231 self.current.pop().unwrap();
1236 /// Main method for rendering a crate.
1238 /// This currently isn't parallelized, but it'd be pretty easy to add
1239 /// parallelization to this function.
1240 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1241 let mut item = match krate.module.take() {
1243 None => return Ok(()),
1245 item.name = Some(krate.name);
1247 // Render the crate documentation
1248 let mut work = vec![(self, item)];
1250 while let Some((mut cx, item)) = work.pop() {
1251 cx.item(item, |cx, item| {
1252 work.push((cx.clone(), item))
1258 fn render_item(&self,
1259 writer: &mut io::Write,
1263 // A little unfortunate that this is done like this, but it sure
1264 // does make formatting *a lot* nicer.
1265 CURRENT_LOCATION_KEY.with(|slot| {
1266 *slot.borrow_mut() = self.current.clone();
1269 let mut title = if it.is_primitive() {
1270 // No need to include the namespace for primitive types
1273 self.current.join("::")
1276 if !title.is_empty() {
1277 title.push_str("::");
1279 title.push_str(it.name.as_ref().unwrap());
1281 title.push_str(" - Rust");
1282 let tyname = it.type_().css_class();
1283 let desc = if it.is_crate() {
1284 format!("API documentation for the Rust `{}` crate.",
1285 self.shared.layout.krate)
1287 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1288 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1290 let keywords = make_item_keywords(it);
1291 let page = layout::Page {
1293 root_path: &self.root_path(),
1296 keywords: &keywords,
1301 if !self.render_redirect_pages {
1302 layout::render(writer, &self.shared.layout, &page,
1303 &Sidebar{ cx: self, item: it },
1304 &Item{ cx: self, item: it },
1305 self.shared.css_file_extension.is_some())?;
1307 let mut url = self.root_path();
1308 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1309 for name in &names[..names.len() - 1] {
1313 url.push_str(&item_path(ty, names.last().unwrap()));
1314 layout::redirect(writer, &url)?;
1320 /// Non-parallelized version of rendering an item. This will take the input
1321 /// item, render its contents, and then invoke the specified closure with
1322 /// all sub-items which need to be rendered.
1324 /// The rendering driver uses this closure to queue up more work.
1325 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1326 F: FnMut(&mut Context, clean::Item),
1328 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1329 // if they contain impls for public types. These modules can also
1330 // contain items such as publicly reexported structures.
1332 // External crates will provide links to these structures, so
1333 // these modules are recursed into, but not rendered normally
1334 // (a flag on the context).
1335 if !self.render_redirect_pages {
1336 self.render_redirect_pages = maybe_ignore_item(&item);
1340 // modules are special because they add a namespace. We also need to
1341 // recurse into the items of the module as well.
1342 let name = item.name.as_ref().unwrap().to_string();
1343 let mut item = Some(item);
1344 self.recurse(name, |this| {
1345 let item = item.take().unwrap();
1347 let mut buf = Vec::new();
1348 this.render_item(&mut buf, &item, false).unwrap();
1349 // buf will be empty if the module is stripped and there is no redirect for it
1350 if !buf.is_empty() {
1351 let joint_dst = this.dst.join("index.html");
1352 try_err!(fs::create_dir_all(&this.dst), &this.dst);
1353 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1354 try_err!(dst.write_all(&buf), &joint_dst);
1357 let m = match item.inner {
1358 clean::StrippedItem(box clean::ModuleItem(m)) |
1359 clean::ModuleItem(m) => m,
1363 // Render sidebar-items.js used throughout this module.
1364 if !this.render_redirect_pages {
1365 let items = this.build_sidebar_items(&m);
1366 let js_dst = this.dst.join("sidebar-items.js");
1367 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1368 try_err!(write!(&mut js_out, "initSidebarItems({});",
1369 as_json(&items)), &js_dst);
1372 for item in m.items {
1378 } else if item.name.is_some() {
1379 let mut buf = Vec::new();
1380 self.render_item(&mut buf, &item, true).unwrap();
1381 // buf will be empty if the item is stripped and there is no redirect for it
1382 if !buf.is_empty() {
1383 let name = item.name.as_ref().unwrap();
1384 let item_type = item.type_();
1385 let file_name = &item_path(item_type, name);
1386 let joint_dst = self.dst.join(file_name);
1387 try_err!(fs::create_dir_all(&self.dst), &self.dst);
1388 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1389 try_err!(dst.write_all(&buf), &joint_dst);
1391 // Redirect from a sane URL using the namespace to Rustdoc's
1392 // URL for the page.
1393 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1394 let redir_dst = self.dst.join(redir_name);
1395 if let Ok(mut redirect_out) = OpenOptions::new().create_new(true)
1398 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1401 // If the item is a macro, redirect from the old macro URL (with !)
1402 // to the new one (without).
1403 // FIXME(#35705) remove this redirect.
1404 if item_type == ItemType::Macro {
1405 let redir_name = format!("{}.{}!.html", item_type, name);
1406 let redir_dst = self.dst.join(redir_name);
1407 let mut redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1408 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1415 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1416 // BTreeMap instead of HashMap to get a sorted output
1417 let mut map = BTreeMap::new();
1418 for item in &m.items {
1419 if maybe_ignore_item(item) { continue }
1421 let short = item.type_().css_class();
1422 let myname = match item.name {
1424 Some(ref s) => s.to_string(),
1426 let short = short.to_string();
1427 map.entry(short).or_insert(vec![])
1428 .push((myname, Some(plain_summary_line(item.doc_value()))));
1431 for (_, items) in &mut map {
1439 /// Generate a url appropriate for an `href` attribute back to the source of
1442 /// The url generated, when clicked, will redirect the browser back to the
1443 /// original source code.
1445 /// If `None` is returned, then a source link couldn't be generated. This
1446 /// may happen, for example, with externally inlined items where the source
1447 /// of their crate documentation isn't known.
1448 fn src_href(&self) -> Option<String> {
1449 let mut root = self.cx.root_path();
1451 let cache = cache();
1452 let mut path = String::new();
1453 let (krate, path) = if self.item.def_id.is_local() {
1454 let path = PathBuf::from(&self.item.source.filename);
1455 if let Some(path) = self.cx.shared.local_sources.get(&path) {
1456 (&self.cx.shared.layout.krate, path)
1461 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1462 Some(&(ref name, ref src, Local)) => (name, src),
1463 Some(&(ref name, ref src, Remote(ref s))) => {
1464 root = s.to_string();
1467 Some(&(_, _, Unknown)) | None => return None,
1470 let file = Path::new(&self.item.source.filename);
1471 clean_srcpath(&src_root, file, false, |component| {
1472 path.push_str(component);
1475 let mut fname = file.file_name().expect("source has no filename")
1477 fname.push(".html");
1478 path.push_str(&fname.to_string_lossy());
1482 let lines = if self.item.source.loline == self.item.source.hiline {
1483 format!("{}", self.item.source.loline)
1485 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1487 Some(format!("{root}src/{krate}/{path}#{lines}",
1495 impl<'a> fmt::Display for Item<'a> {
1496 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1497 debug_assert!(!self.item.is_stripped());
1498 // Write the breadcrumb trail header for the top
1499 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1500 match self.item.inner {
1501 clean::ModuleItem(ref m) => if m.is_crate {
1502 write!(fmt, "Crate ")?;
1504 write!(fmt, "Module ")?;
1506 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) =>
1507 write!(fmt, "Function ")?,
1508 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1509 clean::StructItem(..) => write!(fmt, "Struct ")?,
1510 clean::UnionItem(..) => write!(fmt, "Union ")?,
1511 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1512 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1513 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1514 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1515 clean::StaticItem(..) | clean::ForeignStaticItem(..) =>
1516 write!(fmt, "Static ")?,
1517 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1519 // We don't generate pages for any other type.
1523 if !self.item.is_primitive() {
1524 let cur = &self.cx.current;
1525 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1526 for (i, component) in cur.iter().enumerate().take(amt) {
1527 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1528 repeat("../").take(cur.len() - i - 1)
1529 .collect::<String>(),
1533 write!(fmt, "<a class='{}' href=''>{}</a>",
1534 self.item.type_(), self.item.name.as_ref().unwrap())?;
1536 write!(fmt, "</span>")?; // in-band
1537 write!(fmt, "<span class='out-of-band'>")?;
1538 if let Some(version) = self.item.stable_since() {
1539 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1543 r##"<span id='render-detail'>
1544 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1545 [<span class='inner'>−</span>]
1551 // When this item is part of a `pub use` in a downstream crate, the
1552 // [src] link in the downstream documentation will actually come back to
1553 // this page, and this link will be auto-clicked. The `id` attribute is
1554 // used to find the link to auto-click.
1555 if self.cx.shared.include_sources && !self.item.is_primitive() {
1556 if let Some(l) = self.src_href() {
1557 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1558 l, "goto source code")?;
1562 write!(fmt, "</span>")?; // out-of-band
1564 write!(fmt, "</h1>\n")?;
1566 match self.item.inner {
1567 clean::ModuleItem(ref m) => {
1568 item_module(fmt, self.cx, self.item, &m.items)
1570 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1571 item_function(fmt, self.cx, self.item, f),
1572 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1573 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1574 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1575 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1576 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1577 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1578 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1579 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1580 item_static(fmt, self.cx, self.item, i),
1581 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1583 // We don't generate pages for any other type.
1590 fn item_path(ty: ItemType, name: &str) -> String {
1592 ItemType::Module => format!("{}/index.html", name),
1593 _ => format!("{}.{}.html", ty.css_class(), name),
1597 fn full_path(cx: &Context, item: &clean::Item) -> String {
1598 let mut s = cx.current.join("::");
1600 s.push_str(item.name.as_ref().unwrap());
1604 fn shorter<'a>(s: Option<&'a str>) -> String {
1606 Some(s) => s.lines().take_while(|line|{
1607 (*line).chars().any(|chr|{
1608 !chr.is_whitespace()
1610 }).collect::<Vec<_>>().join("\n"),
1611 None => "".to_string()
1616 fn plain_summary_line(s: Option<&str>) -> String {
1617 let line = shorter(s).replace("\n", " ");
1618 markdown::plain_summary_line(&line[..])
1621 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1622 document_stability(w, cx, item)?;
1623 document_full(w, item)?;
1627 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink) -> fmt::Result {
1628 if let Some(s) = item.doc_value() {
1629 let markdown = if s.contains('\n') {
1630 format!("{} [Read more]({})",
1631 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1633 format!("{}", &plain_summary_line(Some(s)))
1635 write!(w, "<div class='docblock'>{}</div>", Markdown(&markdown))?;
1640 fn document_full(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
1641 if let Some(s) = item.doc_value() {
1642 write!(w, "<div class='docblock'>{}</div>", Markdown(s))?;
1647 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1648 for stability in short_stability(item, cx, true) {
1649 write!(w, "<div class='stability'>{}</div>", stability)?;
1654 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1655 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1656 document(w, cx, item)?;
1658 let mut indices = (0..items.len()).filter(|i| {
1659 if let clean::DefaultImplItem(..) = items[*i].inner {
1662 !maybe_ignore_item(&items[*i])
1663 }).collect::<Vec<usize>>();
1665 // the order of item types in the listing
1666 fn reorder(ty: ItemType) -> u8 {
1668 ItemType::ExternCrate => 0,
1669 ItemType::Import => 1,
1670 ItemType::Primitive => 2,
1671 ItemType::Module => 3,
1672 ItemType::Macro => 4,
1673 ItemType::Struct => 5,
1674 ItemType::Enum => 6,
1675 ItemType::Constant => 7,
1676 ItemType::Static => 8,
1677 ItemType::Trait => 9,
1678 ItemType::Function => 10,
1679 ItemType::Typedef => 12,
1680 ItemType::Union => 13,
1685 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1686 let ty1 = i1.type_();
1687 let ty2 = i2.type_();
1689 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1691 let s1 = i1.stability.as_ref().map(|s| s.level);
1692 let s2 = i2.stability.as_ref().map(|s| s.level);
1694 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1695 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1698 i1.name.cmp(&i2.name)
1701 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1703 debug!("{:?}", indices);
1704 let mut curty = None;
1705 for &idx in &indices {
1706 let myitem = &items[idx];
1707 if myitem.is_stripped() {
1711 let myty = Some(myitem.type_());
1712 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1713 // Put `extern crate` and `use` re-exports in the same section.
1715 } else if myty != curty {
1716 if curty.is_some() {
1717 write!(w, "</table>")?;
1720 let (short, name) = match myty.unwrap() {
1721 ItemType::ExternCrate |
1722 ItemType::Import => ("reexports", "Reexports"),
1723 ItemType::Module => ("modules", "Modules"),
1724 ItemType::Struct => ("structs", "Structs"),
1725 ItemType::Union => ("unions", "Unions"),
1726 ItemType::Enum => ("enums", "Enums"),
1727 ItemType::Function => ("functions", "Functions"),
1728 ItemType::Typedef => ("types", "Type Definitions"),
1729 ItemType::Static => ("statics", "Statics"),
1730 ItemType::Constant => ("constants", "Constants"),
1731 ItemType::Trait => ("traits", "Traits"),
1732 ItemType::Impl => ("impls", "Implementations"),
1733 ItemType::TyMethod => ("tymethods", "Type Methods"),
1734 ItemType::Method => ("methods", "Methods"),
1735 ItemType::StructField => ("fields", "Struct Fields"),
1736 ItemType::Variant => ("variants", "Variants"),
1737 ItemType::Macro => ("macros", "Macros"),
1738 ItemType::Primitive => ("primitives", "Primitive Types"),
1739 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1740 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1742 write!(w, "<h2 id='{id}' class='section-header'>\
1743 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1744 id = derive_id(short.to_owned()), name = name)?;
1747 match myitem.inner {
1748 clean::ExternCrateItem(ref name, ref src) => {
1749 use html::format::HRef;
1753 write!(w, "<tr><td><code>{}extern crate {} as {};",
1754 VisSpace(&myitem.visibility),
1755 HRef::new(myitem.def_id, src),
1759 write!(w, "<tr><td><code>{}extern crate {};",
1760 VisSpace(&myitem.visibility),
1761 HRef::new(myitem.def_id, name))?
1764 write!(w, "</code></td></tr>")?;
1767 clean::ImportItem(ref import) => {
1768 write!(w, "<tr><td><code>{}{}</code></td></tr>",
1769 VisSpace(&myitem.visibility), *import)?;
1773 if myitem.name.is_none() { continue }
1775 let stabilities = short_stability(myitem, cx, false);
1777 let stab_docs = if !stabilities.is_empty() {
1779 .map(|s| format!("[{}]", s))
1780 .collect::<Vec<_>>()
1787 let mut unsafety_flag = "";
1788 if let clean::FunctionItem(ref func) = myitem.inner {
1789 if func.unsafety == hir::Unsafety::Unsafe {
1790 unsafety_flag = "<a title='unsafe function' href='#'><sup>âš </sup></a>";
1794 let doc_value = myitem.doc_value().unwrap_or("");
1796 <tr class='{stab} module-item'>
1797 <td><a class='{class}' href='{href}'
1798 title='{title}'>{name}</a>{unsafety_flag}</td>
1799 <td class='docblock-short'>
1803 name = *myitem.name.as_ref().unwrap(),
1804 stab_docs = stab_docs,
1805 docs = shorter(Some(&Markdown(doc_value).to_string())),
1806 class = myitem.type_(),
1807 stab = myitem.stability_class(),
1808 unsafety_flag = unsafety_flag,
1809 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
1810 title = full_path(cx, myitem))?;
1815 if curty.is_some() {
1816 write!(w, "</table>")?;
1821 fn maybe_ignore_item(it: &clean::Item) -> bool {
1823 clean::StrippedItem(..) => true,
1824 clean::ModuleItem(ref m) => {
1825 it.doc_value().is_none() && m.items.is_empty()
1826 && it.visibility != Some(clean::Public)
1832 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
1833 let mut stability = vec![];
1835 if let Some(stab) = item.stability.as_ref() {
1836 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
1837 format!(": {}", stab.deprecated_reason)
1841 if !stab.deprecated_since.is_empty() {
1842 let since = if show_reason {
1843 format!(" since {}", Escape(&stab.deprecated_since))
1847 let text = format!("Deprecated{}{}", since, Markdown(&deprecated_reason));
1848 stability.push(format!("<em class='stab deprecated'>{}</em>", text))
1851 if stab.level == stability::Unstable {
1852 let unstable_extra = if show_reason {
1853 match (!stab.feature.is_empty(), &cx.shared.issue_tracker_base_url, stab.issue) {
1854 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1855 format!(" (<code>{}</code> <a href=\"{}{}\">#{}</a>)",
1856 Escape(&stab.feature), tracker_url, issue_no, issue_no),
1857 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1858 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
1861 format!(" (<code>{}</code>)", Escape(&stab.feature)),
1867 let unstable_reason = if show_reason && !stab.unstable_reason.is_empty() {
1868 format!(": {}", stab.unstable_reason)
1872 let text = format!("Unstable{}{}", unstable_extra, Markdown(&unstable_reason));
1873 stability.push(format!("<em class='stab unstable'>{}</em>", text))
1875 } else if let Some(depr) = item.deprecation.as_ref() {
1876 let note = if show_reason && !depr.note.is_empty() {
1877 format!(": {}", depr.note)
1881 let since = if show_reason && !depr.since.is_empty() {
1882 format!(" since {}", Escape(&depr.since))
1887 let text = format!("Deprecated{}{}", since, Markdown(¬e));
1888 stability.push(format!("<em class='stab deprecated'>{}</em>", text))
1894 struct Initializer<'a>(&'a str);
1896 impl<'a> fmt::Display for Initializer<'a> {
1897 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1898 let Initializer(s) = *self;
1899 if s.is_empty() { return Ok(()); }
1900 write!(f, "<code> = </code>")?;
1901 write!(f, "<code>{}</code>", Escape(s))
1905 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1906 c: &clean::Constant) -> fmt::Result {
1907 write!(w, "<pre class='rust const'>{vis}const \
1908 {name}: {typ}{init}</pre>",
1909 vis = VisSpace(&it.visibility),
1910 name = it.name.as_ref().unwrap(),
1912 init = Initializer(&c.expr))?;
1916 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1917 s: &clean::Static) -> fmt::Result {
1918 write!(w, "<pre class='rust static'>{vis}static {mutability}\
1919 {name}: {typ}{init}</pre>",
1920 vis = VisSpace(&it.visibility),
1921 mutability = MutableSpace(s.mutability),
1922 name = it.name.as_ref().unwrap(),
1924 init = Initializer(&s.expr))?;
1928 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1929 f: &clean::Function) -> fmt::Result {
1930 // FIXME(#24111): remove when `const_fn` is stabilized
1931 let vis_constness = match UnstableFeatures::from_environment() {
1932 UnstableFeatures::Allow => f.constness,
1933 _ => hir::Constness::NotConst
1935 let indent = format!("{}{}{}{:#}fn {}{:#}",
1936 VisSpace(&it.visibility),
1937 ConstnessSpace(vis_constness),
1938 UnsafetySpace(f.unsafety),
1940 it.name.as_ref().unwrap(),
1942 write!(w, "<pre class='rust fn'>{vis}{constness}{unsafety}{abi}fn \
1943 {name}{generics}{decl}{where_clause}</pre>",
1944 vis = VisSpace(&it.visibility),
1945 constness = ConstnessSpace(vis_constness),
1946 unsafety = UnsafetySpace(f.unsafety),
1947 abi = AbiSpace(f.abi),
1948 name = it.name.as_ref().unwrap(),
1949 generics = f.generics,
1950 where_clause = WhereClause(&f.generics, 2),
1951 decl = Method(&f.decl, indent))?;
1955 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1956 t: &clean::Trait) -> fmt::Result {
1957 let mut bounds = String::new();
1958 let mut bounds_plain = String::new();
1959 if !t.bounds.is_empty() {
1960 if !bounds.is_empty() {
1962 bounds_plain.push(' ');
1964 bounds.push_str(": ");
1965 bounds_plain.push_str(": ");
1966 for (i, p) in t.bounds.iter().enumerate() {
1968 bounds.push_str(" + ");
1969 bounds_plain.push_str(" + ");
1971 bounds.push_str(&format!("{}", *p));
1972 bounds_plain.push_str(&format!("{:#}", *p));
1976 // Output the trait definition
1977 write!(w, "<pre class='rust trait'>{}{}trait {}{}{}{} ",
1978 VisSpace(&it.visibility),
1979 UnsafetySpace(t.unsafety),
1980 it.name.as_ref().unwrap(),
1983 // Where clauses in traits are indented nine spaces, per rustdoc.css
1984 WhereClause(&t.generics, 9))?;
1986 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
1987 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
1988 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
1989 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
1991 if t.items.is_empty() {
1992 write!(w, "{{ }}")?;
1994 // FIXME: we should be using a derived_id for the Anchors here
1998 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2001 if !types.is_empty() && !consts.is_empty() {
2006 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2009 if !consts.is_empty() && !required.is_empty() {
2012 for m in &required {
2014 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2017 if !required.is_empty() && !provided.is_empty() {
2020 for m in &provided {
2022 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2023 write!(w, " {{ ... }}\n")?;
2027 write!(w, "</pre>")?;
2029 // Trait documentation
2030 document(w, cx, it)?;
2032 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2034 let name = m.name.as_ref().unwrap();
2035 let item_type = m.type_();
2036 let id = derive_id(format!("{}.{}", item_type, name));
2037 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2038 write!(w, "<h3 id='{id}' class='method stab {stab}'>\
2039 <span id='{ns_id}' class='invisible'><code>",
2041 stab = m.stability_class(),
2043 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2044 write!(w, "</code>")?;
2045 render_stability_since(w, m, t)?;
2046 write!(w, "</span></h3>")?;
2047 document(w, cx, m)?;
2051 if !types.is_empty() {
2053 <h2 id='associated-types'>Associated Types</h2>
2054 <div class='methods'>
2057 trait_item(w, cx, *t, it)?;
2059 write!(w, "</div>")?;
2062 if !consts.is_empty() {
2064 <h2 id='associated-const'>Associated Constants</h2>
2065 <div class='methods'>
2068 trait_item(w, cx, *t, it)?;
2070 write!(w, "</div>")?;
2073 // Output the documentation for each function individually
2074 if !required.is_empty() {
2076 <h2 id='required-methods'>Required Methods</h2>
2077 <div class='methods'>
2079 for m in &required {
2080 trait_item(w, cx, *m, it)?;
2082 write!(w, "</div>")?;
2084 if !provided.is_empty() {
2086 <h2 id='provided-methods'>Provided Methods</h2>
2087 <div class='methods'>
2089 for m in &provided {
2090 trait_item(w, cx, *m, it)?;
2092 write!(w, "</div>")?;
2095 // If there are methods directly on this trait object, render them here.
2096 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2098 let cache = cache();
2100 <h2 id='implementors'>Implementors</h2>
2101 <ul class='item-list' id='implementors-list'>
2103 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2104 for i in implementors {
2105 write!(w, "<li><code>")?;
2106 fmt_impl_for_trait_page(&i.impl_, w)?;
2107 writeln!(w, "</code></li>")?;
2110 write!(w, "</ul>")?;
2111 write!(w, r#"<script type="text/javascript" async
2112 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2114 root_path = vec![".."; cx.current.len()].join("/"),
2115 path = if it.def_id.is_local() {
2116 cx.current.join("/")
2118 let (ref path, _) = cache.external_paths[&it.def_id];
2119 path[..path.len() - 1].join("/")
2121 ty = it.type_().css_class(),
2122 name = *it.name.as_ref().unwrap())?;
2126 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2127 use html::item_type::ItemType::*;
2129 let name = it.name.as_ref().unwrap();
2130 let ty = match it.type_() {
2131 Typedef | AssociatedType => AssociatedType,
2135 let anchor = format!("#{}.{}", ty, name);
2137 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2138 AssocItemLink::Anchor(None) => anchor,
2139 AssocItemLink::GotoSource(did, _) => {
2140 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2145 fn assoc_const(w: &mut fmt::Formatter,
2148 default: Option<&String>,
2149 link: AssocItemLink) -> fmt::Result {
2150 write!(w, "const <a href='{}' class='constant'>{}</a>",
2151 naive_assoc_href(it, link),
2152 it.name.as_ref().unwrap())?;
2154 write!(w, ": {}", ty)?;
2155 if let Some(default) = default {
2156 write!(w, " = {}", Escape(default))?;
2161 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
2162 bounds: &Vec<clean::TyParamBound>,
2163 default: Option<&clean::Type>,
2164 link: AssocItemLink) -> fmt::Result {
2165 write!(w, "type <a href='{}' class='type'>{}</a>",
2166 naive_assoc_href(it, link),
2167 it.name.as_ref().unwrap())?;
2168 if !bounds.is_empty() {
2169 write!(w, ": {}", TyParamBounds(bounds))?
2171 if let Some(default) = default {
2172 write!(w, " = {}", default)?;
2177 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2178 ver: Option<&'a str>,
2179 containing_ver: Option<&'a str>) -> fmt::Result {
2180 if let Some(v) = ver {
2181 if containing_ver != ver && v.len() > 0 {
2182 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2189 fn render_stability_since(w: &mut fmt::Formatter,
2191 containing_item: &clean::Item) -> fmt::Result {
2192 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2195 fn render_assoc_item(w: &mut fmt::Formatter,
2197 link: AssocItemLink,
2198 parent: ItemType) -> fmt::Result {
2199 fn method(w: &mut fmt::Formatter,
2201 unsafety: hir::Unsafety,
2202 constness: hir::Constness,
2204 g: &clean::Generics,
2206 link: AssocItemLink,
2209 let name = meth.name.as_ref().unwrap();
2210 let anchor = format!("#{}.{}", meth.type_(), name);
2211 let href = match link {
2212 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2213 AssocItemLink::Anchor(None) => anchor,
2214 AssocItemLink::GotoSource(did, provided_methods) => {
2215 // We're creating a link from an impl-item to the corresponding
2216 // trait-item and need to map the anchored type accordingly.
2217 let ty = if provided_methods.contains(name) {
2223 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2226 // FIXME(#24111): remove when `const_fn` is stabilized
2227 let vis_constness = match UnstableFeatures::from_environment() {
2228 UnstableFeatures::Allow => constness,
2229 _ => hir::Constness::NotConst
2231 let prefix = format!("{}{}{:#}fn {}{:#}",
2232 ConstnessSpace(vis_constness),
2233 UnsafetySpace(unsafety),
2237 let mut indent = prefix.len();
2238 let where_indent = if parent == ItemType::Trait {
2241 } else if parent == ItemType::Impl {
2244 let prefix = prefix + &format!("{:#}", Method(d, indent));
2245 prefix.lines().last().unwrap().len() + 1
2247 write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2248 {generics}{decl}{where_clause}",
2249 ConstnessSpace(vis_constness),
2250 UnsafetySpace(unsafety),
2255 decl = Method(d, indent),
2256 where_clause = WhereClause(g, where_indent))
2259 clean::StrippedItem(..) => Ok(()),
2260 clean::TyMethodItem(ref m) => {
2261 method(w, item, m.unsafety, hir::Constness::NotConst,
2262 m.abi, &m.generics, &m.decl, link, parent)
2264 clean::MethodItem(ref m) => {
2265 method(w, item, m.unsafety, m.constness,
2266 m.abi, &m.generics, &m.decl, link, parent)
2268 clean::AssociatedConstItem(ref ty, ref default) => {
2269 assoc_const(w, item, ty, default.as_ref(), link)
2271 clean::AssociatedTypeItem(ref bounds, ref default) => {
2272 assoc_type(w, item, bounds, default.as_ref(), link)
2274 _ => panic!("render_assoc_item called on non-associated-item")
2278 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2279 s: &clean::Struct) -> fmt::Result {
2280 write!(w, "<pre class='rust struct'>")?;
2281 render_attributes(w, it)?;
2289 write!(w, "</pre>")?;
2291 document(w, cx, it)?;
2292 let mut fields = s.fields.iter().filter_map(|f| {
2294 clean::StructFieldItem(ref ty) => Some((f, ty)),
2298 if let doctree::Plain = s.struct_type {
2299 if fields.peek().is_some() {
2300 write!(w, "<h2 class='fields'>Fields</h2>")?;
2301 for (field, ty) in fields {
2302 let id = derive_id(format!("{}.{}",
2303 ItemType::StructField,
2304 field.name.as_ref().unwrap()));
2305 let ns_id = derive_id(format!("{}.{}",
2306 field.name.as_ref().unwrap(),
2307 ItemType::StructField.name_space()));
2308 write!(w, "<span id='{id}' class='{item_type}'>
2309 <span id='{ns_id}' class='invisible'>
2310 <code>{name}: {ty}</code>
2311 </span></span><span class='stab {stab}'></span>",
2312 item_type = ItemType::StructField,
2315 stab = field.stability_class(),
2316 name = field.name.as_ref().unwrap(),
2318 document(w, cx, field)?;
2322 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2325 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2326 s: &clean::Union) -> fmt::Result {
2327 write!(w, "<pre class='rust union'>")?;
2328 render_attributes(w, it)?;
2335 write!(w, "</pre>")?;
2337 document(w, cx, it)?;
2338 let mut fields = s.fields.iter().filter_map(|f| {
2340 clean::StructFieldItem(ref ty) => Some((f, ty)),
2344 if fields.peek().is_some() {
2345 write!(w, "<h2 class='fields'>Fields</h2>")?;
2346 for (field, ty) in fields {
2347 write!(w, "<span id='{shortty}.{name}' class='{shortty}'><code>{name}: {ty}</code>
2348 </span><span class='stab {stab}'></span>",
2349 shortty = ItemType::StructField,
2350 stab = field.stability_class(),
2351 name = field.name.as_ref().unwrap(),
2353 document(w, cx, field)?;
2356 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2359 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2360 e: &clean::Enum) -> fmt::Result {
2361 write!(w, "<pre class='rust enum'>")?;
2362 render_attributes(w, it)?;
2363 let padding = format!("{}enum {}{:#} ",
2364 VisSpace(&it.visibility),
2365 it.name.as_ref().unwrap(),
2367 write!(w, "{}enum {}{}{}",
2368 VisSpace(&it.visibility),
2369 it.name.as_ref().unwrap(),
2371 WhereClause(&e.generics, padding))?;
2372 if e.variants.is_empty() && !e.variants_stripped {
2373 write!(w, " {{}}")?;
2375 write!(w, " {{\n")?;
2376 for v in &e.variants {
2378 let name = v.name.as_ref().unwrap();
2380 clean::VariantItem(ref var) => {
2382 clean::VariantKind::CLike => write!(w, "{}", name)?,
2383 clean::VariantKind::Tuple(ref tys) => {
2384 write!(w, "{}(", name)?;
2385 for (i, ty) in tys.iter().enumerate() {
2387 write!(w, ", ")?
2389 write!(w, "{}", *ty)?;
2393 clean::VariantKind::Struct(ref s) => {
2409 if e.variants_stripped {
2410 write!(w, " // some variants omitted\n")?;
2414 write!(w, "</pre>")?;
2416 document(w, cx, it)?;
2417 if !e.variants.is_empty() {
2418 write!(w, "<h2 class='variants'>Variants</h2>\n")?;
2419 for variant in &e.variants {
2420 let id = derive_id(format!("{}.{}",
2422 variant.name.as_ref().unwrap()));
2423 let ns_id = derive_id(format!("{}.{}",
2424 variant.name.as_ref().unwrap(),
2425 ItemType::Variant.name_space()));
2426 write!(w, "<span id='{id}' class='variant'>\
2427 <span id='{ns_id}' class='invisible'><code>{name}",
2430 name = variant.name.as_ref().unwrap())?;
2431 if let clean::VariantItem(ref var) = variant.inner {
2432 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2434 for (i, ty) in tys.iter().enumerate() {
2436 write!(w, ", ")?;
2438 write!(w, "{}", *ty)?;
2443 write!(w, "</code></span></span>")?;
2444 document(w, cx, variant)?;
2446 use clean::{Variant, VariantKind};
2447 if let clean::VariantItem(Variant {
2448 kind: VariantKind::Struct(ref s)
2449 }) = variant.inner {
2450 let variant_id = derive_id(format!("{}.{}.fields",
2452 variant.name.as_ref().unwrap()));
2453 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2455 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2456 <table>", name = variant.name.as_ref().unwrap())?;
2457 for field in &s.fields {
2458 use clean::StructFieldItem;
2459 if let StructFieldItem(ref ty) = field.inner {
2460 let id = derive_id(format!("variant.{}.field.{}",
2461 variant.name.as_ref().unwrap(),
2462 field.name.as_ref().unwrap()));
2463 let ns_id = derive_id(format!("{}.{}.{}.{}",
2464 variant.name.as_ref().unwrap(),
2465 ItemType::Variant.name_space(),
2466 field.name.as_ref().unwrap(),
2467 ItemType::StructField.name_space()));
2468 write!(w, "<tr><td \
2470 <span id='{ns_id}' class='invisible'>\
2471 <code>{f}: {t}</code></span></td><td>",
2474 f = field.name.as_ref().unwrap(),
2476 document(w, cx, field)?;
2477 write!(w, "</td></tr>")?;
2480 write!(w, "</table></span>")?;
2482 render_stability_since(w, variant, it)?;
2485 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2489 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2490 let name = attr.name();
2493 Some(format!("{}", name))
2494 } else if let Some(v) = attr.value_str() {
2495 Some(format!("{} = {:?}", name, &v.as_str()[..]))
2496 } else if let Some(values) = attr.meta_item_list() {
2497 let display: Vec<_> = values.iter().filter_map(|attr| {
2498 attr.meta_item().and_then(|mi| render_attribute(mi))
2501 if display.len() > 0 {
2502 Some(format!("{}({})", name, display.join(", ")))
2511 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2518 "unsafe_destructor_blind_to_params"
2521 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2522 let mut attrs = String::new();
2524 for attr in &it.attrs.other_attrs {
2525 let name = attr.name();
2526 if !ATTRIBUTE_WHITELIST.contains(&&name.as_str()[..]) {
2529 if let Some(s) = render_attribute(attr.meta()) {
2530 attrs.push_str(&format!("#[{}]\n", s));
2533 if attrs.len() > 0 {
2534 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2539 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2540 g: Option<&clean::Generics>,
2541 ty: doctree::StructType,
2542 fields: &[clean::Item],
2544 structhead: bool) -> fmt::Result {
2545 let mut plain = String::new();
2547 VisSpace(&it.visibility),
2548 if structhead {"struct "} else {""},
2549 it.name.as_ref().unwrap())?;
2550 plain.push_str(&format!("{}{}{}",
2551 VisSpace(&it.visibility),
2552 if structhead {"struct "} else {""},
2553 it.name.as_ref().unwrap()));
2554 if let Some(g) = g {
2555 plain.push_str(&format!("{:#}", g));
2560 if let Some(g) = g {
2561 write!(w, "{}", WhereClause(g, plain.len() + 1))?
2563 let mut has_visible_fields = false;
2565 for field in fields {
2566 if let clean::StructFieldItem(ref ty) = field.inner {
2567 write!(w, "\n{} {}{}: {},",
2569 VisSpace(&field.visibility),
2570 field.name.as_ref().unwrap(),
2572 has_visible_fields = true;
2576 if has_visible_fields {
2577 if it.has_stripped_fields().unwrap() {
2578 write!(w, "\n{} // some fields omitted", tab)?;
2580 write!(w, "\n{}", tab)?;
2581 } else if it.has_stripped_fields().unwrap() {
2582 // If there are no visible fields we can just display
2583 // `{ /* fields omitted */ }` to save space.
2584 write!(w, " /* fields omitted */ ")?;
2590 plain.push_str("(");
2591 for (i, field) in fields.iter().enumerate() {
2594 plain.push_str(", ");
2597 clean::StrippedItem(box clean::StructFieldItem(..)) => {
2598 plain.push_str("_");
2601 clean::StructFieldItem(ref ty) => {
2602 plain.push_str(&format!("{}{:#}", VisSpace(&field.visibility), *ty));
2603 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
2609 plain.push_str(")");
2610 if let Some(g) = g {
2611 write!(w, "{}", WhereClause(g, plain.len() + 1))?
2616 // Needed for PhantomData.
2617 if let Some(g) = g {
2618 write!(w, "{}", WhereClause(g, plain.len() + 1))?
2626 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
2627 g: Option<&clean::Generics>,
2628 fields: &[clean::Item],
2630 structhead: bool) -> fmt::Result {
2631 let mut plain = String::new();
2633 VisSpace(&it.visibility),
2634 if structhead {"union "} else {""},
2635 it.name.as_ref().unwrap())?;
2636 plain.push_str(&format!("{}{}{}",
2637 VisSpace(&it.visibility),
2638 if structhead {"union "} else {""},
2639 it.name.as_ref().unwrap()));
2640 if let Some(g) = g {
2641 write!(w, "{}", g)?;
2642 plain.push_str(&format!("{:#}", g));
2643 write!(w, "{}", WhereClause(g, plain.len() + 1))?;
2646 write!(w, " {{\n{}", tab)?;
2647 for field in fields {
2648 if let clean::StructFieldItem(ref ty) = field.inner {
2649 write!(w, " {}{}: {},\n{}",
2650 VisSpace(&field.visibility),
2651 field.name.as_ref().unwrap(),
2657 if it.has_stripped_fields().unwrap() {
2658 write!(w, " // some fields omitted\n{}", tab)?;
2664 #[derive(Copy, Clone)]
2665 enum AssocItemLink<'a> {
2666 Anchor(Option<&'a str>),
2667 GotoSource(DefId, &'a FxHashSet<String>),
2670 impl<'a> AssocItemLink<'a> {
2671 fn anchor(&self, id: &'a String) -> Self {
2673 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
2674 ref other => *other,
2679 enum AssocItemRender<'a> {
2681 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
2684 #[derive(Copy, Clone, PartialEq)]
2687 ForDeref { mut_: bool },
2690 fn render_assoc_items(w: &mut fmt::Formatter,
2692 containing_item: &clean::Item,
2694 what: AssocItemRender) -> fmt::Result {
2696 let v = match c.impls.get(&it) {
2698 None => return Ok(()),
2700 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
2701 i.inner_impl().trait_.is_none()
2703 if !non_trait.is_empty() {
2704 let render_mode = match what {
2705 AssocItemRender::All => {
2706 write!(w, "<h2 id='methods'>Methods</h2>")?;
2709 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
2710 write!(w, "<h2 id='deref-methods'>Methods from \
2711 {}<Target={}></h2>", trait_, type_)?;
2712 RenderMode::ForDeref { mut_: deref_mut_ }
2715 for i in &non_trait {
2716 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
2717 containing_item.stable_since())?;
2720 if let AssocItemRender::DerefFor { .. } = what {
2723 if !traits.is_empty() {
2724 let deref_impl = traits.iter().find(|t| {
2725 t.inner_impl().trait_.def_id() == c.deref_trait_did
2727 if let Some(impl_) = deref_impl {
2728 let has_deref_mut = traits.iter().find(|t| {
2729 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
2731 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
2733 write!(w, "<h2 id='implementations'>Trait \
2734 Implementations</h2>")?;
2736 let did = i.trait_did().unwrap();
2737 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2738 render_impl(w, cx, i, assoc_link,
2739 RenderMode::Normal, containing_item.stable_since())?;
2745 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
2746 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
2747 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
2748 let target = impl_.inner_impl().items.iter().filter_map(|item| {
2750 clean::TypedefItem(ref t, true) => Some(&t.type_),
2753 }).next().expect("Expected associated type binding");
2754 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
2755 deref_mut_: deref_mut };
2756 if let Some(did) = target.def_id() {
2757 render_assoc_items(w, cx, container_item, did, what)
2759 if let Some(prim) = target.primitive_type() {
2760 if let Some(&did) = cache().primitive_locations.get(&prim) {
2761 render_assoc_items(w, cx, container_item, did, what)?;
2768 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
2769 render_mode: RenderMode, outer_version: Option<&str>) -> fmt::Result {
2770 if render_mode == RenderMode::Normal {
2771 write!(w, "<h3 class='impl'><span class='in-band'><code>{}</code>", i.inner_impl())?;
2772 write!(w, "</span><span class='out-of-band'>")?;
2773 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
2774 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
2775 write!(w, "<div class='ghost'></div>")?;
2776 render_stability_since_raw(w, since, outer_version)?;
2777 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2778 l, "goto source code")?;
2780 render_stability_since_raw(w, since, outer_version)?;
2782 write!(w, "</span>")?;
2783 write!(w, "</h3>\n")?;
2784 if let Some(ref dox) = i.impl_item.doc_value() {
2785 write!(w, "<div class='docblock'>{}</div>", Markdown(dox))?;
2789 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2790 link: AssocItemLink, render_mode: RenderMode,
2791 is_default_item: bool, outer_version: Option<&str>,
2792 trait_: Option<&clean::Trait>) -> fmt::Result {
2793 let item_type = item.type_();
2794 let name = item.name.as_ref().unwrap();
2796 let render_method_item: bool = match render_mode {
2797 RenderMode::Normal => true,
2798 RenderMode::ForDeref { mut_: deref_mut_ } => {
2799 let self_type_opt = match item.inner {
2800 clean::MethodItem(ref method) => method.decl.self_type(),
2801 clean::TyMethodItem(ref method) => method.decl.self_type(),
2805 if let Some(self_ty) = self_type_opt {
2806 let by_mut_ref = match self_ty {
2807 SelfTy::SelfBorrowed(_lifetime, mutability) => {
2808 mutability == Mutability::Mutable
2810 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
2811 mutability == Mutability::Mutable
2816 deref_mut_ || !by_mut_ref
2824 clean::MethodItem(..) | clean::TyMethodItem(..) => {
2825 // Only render when the method is not static or we allow static methods
2826 if render_method_item {
2827 let id = derive_id(format!("{}.{}", item_type, name));
2828 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2829 write!(w, "<h4 id='{}' class='{}'>", id, item_type)?;
2830 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
2831 write!(w, "<code>")?;
2832 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
2833 write!(w, "</code>")?;
2834 render_stability_since_raw(w, item.stable_since(), outer_version)?;
2835 write!(w, "</span></h4>\n")?;
2838 clean::TypedefItem(ref tydef, _) => {
2839 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
2840 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2841 write!(w, "<h4 id='{}' class='{}'>", id, item_type)?;
2842 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2843 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
2844 write!(w, "</code></span></h4>\n")?;
2846 clean::AssociatedConstItem(ref ty, ref default) => {
2847 let id = derive_id(format!("{}.{}", item_type, name));
2848 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2849 write!(w, "<h4 id='{}' class='{}'>", id, item_type)?;
2850 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2851 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
2852 write!(w, "</code></span></h4>\n")?;
2854 clean::ConstantItem(ref c) => {
2855 let id = derive_id(format!("{}.{}", item_type, name));
2856 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2857 write!(w, "<h4 id='{}' class='{}'>", id, item_type)?;
2858 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2859 assoc_const(w, item, &c.type_, Some(&c.expr), link.anchor(&id))?;
2860 write!(w, "</code></span></h4>\n")?;
2862 clean::AssociatedTypeItem(ref bounds, ref default) => {
2863 let id = derive_id(format!("{}.{}", item_type, name));
2864 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2865 write!(w, "<h4 id='{}' class='{}'>", id, item_type)?;
2866 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2867 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
2868 write!(w, "</code></span></h4>\n")?;
2870 clean::StrippedItem(..) => return Ok(()),
2871 _ => panic!("can't make docs for trait item with name {:?}", item.name)
2874 if render_method_item || render_mode == RenderMode::Normal {
2875 if !is_default_item {
2876 if let Some(t) = trait_ {
2877 // The trait item may have been stripped so we might not
2878 // find any documentation or stability for it.
2879 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
2880 // We need the stability of the item from the trait
2881 // because impls can't have a stability.
2882 document_stability(w, cx, it)?;
2883 if item.doc_value().is_some() {
2884 document_full(w, item)?;
2886 // In case the item isn't documented,
2887 // provide short documentation from the trait.
2888 document_short(w, it, link)?;
2892 document(w, cx, item)?;
2895 document_stability(w, cx, item)?;
2896 document_short(w, item, link)?;
2902 let traits = &cache().traits;
2903 let trait_ = i.trait_did().and_then(|did| traits.get(&did));
2905 write!(w, "<div class='impl-items'>")?;
2906 for trait_item in &i.inner_impl().items {
2907 doc_impl_item(w, cx, trait_item, link, render_mode,
2908 false, outer_version, trait_)?;
2911 fn render_default_items(w: &mut fmt::Formatter,
2915 render_mode: RenderMode,
2916 outer_version: Option<&str>) -> fmt::Result {
2917 for trait_item in &t.items {
2918 let n = trait_item.name.clone();
2919 if i.items.iter().find(|m| m.name == n).is_some() {
2922 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
2923 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
2925 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
2926 outer_version, None)?;
2931 // If we've implemented a trait, then also emit documentation for all
2932 // default items which weren't overridden in the implementation block.
2933 if let Some(t) = trait_ {
2934 render_default_items(w, cx, t, &i.inner_impl(), render_mode, outer_version)?;
2936 write!(w, "</div>")?;
2940 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2941 t: &clean::Typedef) -> fmt::Result {
2942 let indent = format!("type {}{:#} ", it.name.as_ref().unwrap(), t.generics).len();
2943 write!(w, "<pre class='rust typedef'>type {}{}{where_clause} = {type_};</pre>",
2944 it.name.as_ref().unwrap(),
2946 where_clause = WhereClause(&t.generics, indent),
2952 impl<'a> fmt::Display for Sidebar<'a> {
2953 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2956 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
2958 // The sidebar is designed to display sibling functions, modules and
2959 // other miscellaneous information. since there are lots of sibling
2960 // items (and that causes quadratic growth in large modules),
2961 // we refactor common parts into a shared JavaScript file per module.
2962 // still, we don't move everything into JS because we want to preserve
2963 // as much HTML as possible in order to allow non-JS-enabled browsers
2964 // to navigate the documentation (though slightly inefficiently).
2966 write!(fmt, "<p class='location'>")?;
2967 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
2969 write!(fmt, "::<wbr>")?;
2971 write!(fmt, "<a href='{}index.html'>{}</a>",
2972 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
2975 write!(fmt, "</p>")?;
2977 // Sidebar refers to the enclosing module, not this module.
2978 let relpath = if it.is_mod() { "../" } else { "" };
2980 "<script>window.sidebarCurrent = {{\
2985 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
2986 ty = it.type_().css_class(),
2989 // There is no sidebar-items.js beyond the crate root path
2990 // FIXME maybe dynamic crate loading can be merged here
2992 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3000 impl<'a> fmt::Display for Source<'a> {
3001 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3002 let Source(s) = *self;
3003 let lines = s.lines().count();
3005 let mut tmp = lines;
3010 write!(fmt, "<pre class=\"line-numbers\">")?;
3011 for i in 1..lines + 1 {
3012 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
3014 write!(fmt, "</pre>")?;
3015 write!(fmt, "{}", highlight::render_with_highlighting(s, None, None, None))?;
3020 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3021 t: &clean::Macro) -> fmt::Result {
3022 w.write_str(&highlight::render_with_highlighting(&t.source,
3029 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
3031 _p: &clean::PrimitiveType) -> fmt::Result {
3032 document(w, cx, it)?;
3033 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3036 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
3038 fn make_item_keywords(it: &clean::Item) -> String {
3039 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
3042 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
3043 let decl = match item.inner {
3044 clean::FunctionItem(ref f) => &f.decl,
3045 clean::MethodItem(ref m) => &m.decl,
3046 clean::TyMethodItem(ref m) => &m.decl,
3050 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
3051 let output = match decl.output {
3052 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
3056 Some(IndexItemFunctionType { inputs: inputs, output: output })
3059 fn get_index_type(clean_type: &clean::Type) -> Type {
3060 Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
3063 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
3065 clean::ResolvedPath { ref path, .. } => {
3066 let segments = &path.segments;
3067 Some(segments[segments.len() - 1].name.clone())
3069 clean::Generic(ref s) => Some(s.clone()),
3070 clean::Primitive(ref p) => Some(format!("{:?}", p)),
3071 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
3072 // FIXME: add all from clean::Type.
3077 pub fn cache() -> Arc<Cache> {
3078 CACHE_KEY.with(|c| c.borrow().clone())
3083 fn test_unique_id() {
3084 let input = ["foo", "examples", "examples", "method.into_iter","examples",
3085 "method.into_iter", "foo", "main", "search", "methods",
3086 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
3087 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
3088 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
3089 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
3092 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
3093 assert_eq!(&actual[..], expected);