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, Write as FmtWrite};
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::session::config::nightly_options::is_nightly_build;
64 use rustc_data_structures::flock;
66 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
69 use html::escape::Escape;
70 use html::format::{ConstnessSpace};
71 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
72 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
73 use html::format::fmt_impl_for_trait_page;
74 use html::item_type::ItemType;
75 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, RenderType};
76 use html::{highlight, layout};
78 /// A pair of name and its optional document.
79 pub type NameDoc = (String, Option<String>);
81 /// Major driving force in all rustdoc rendering. This contains information
82 /// about where in the tree-like hierarchy rendering is occurring and controls
83 /// how the current page is being rendered.
85 /// It is intended that this context is a lightweight object which can be fairly
86 /// easily cloned because it is cloned per work-job (about once per item in the
90 /// Current hierarchy of components leading down to what's currently being
92 pub current: Vec<String>,
93 /// The current destination folder of where HTML artifacts should be placed.
94 /// This changes as the context descends into the module hierarchy.
96 /// A flag, which when `true`, will render pages which redirect to the
97 /// real location of an item. This is used to allow external links to
98 /// publicly reused items to redirect to the right location.
99 pub render_redirect_pages: bool,
100 pub shared: Arc<SharedContext>,
101 pub render_type: RenderType,
104 pub struct SharedContext {
105 /// The path to the crate root source minus the file name.
106 /// Used for simplifying paths to the highlighted source code files.
107 pub src_root: PathBuf,
108 /// This describes the layout of each page, and is not modified after
109 /// creation of the context (contains info like the favicon and added html).
110 pub layout: layout::Layout,
111 /// This flag indicates whether [src] links should be generated or not. If
112 /// the source files are present in the html rendering, then this will be
114 pub include_sources: bool,
115 /// The local file sources we've emitted and their respective url-paths.
116 pub local_sources: FxHashMap<PathBuf, String>,
117 /// All the passes that were run on this crate.
118 pub passes: FxHashSet<String>,
119 /// The base-URL of the issue tracker for when an item has been tagged with
121 pub issue_tracker_base_url: Option<String>,
122 /// The given user css file which allow to customize the generated
123 /// documentation theme.
124 pub css_file_extension: Option<PathBuf>,
127 /// Indicates where an external crate can be found.
128 pub enum ExternalLocation {
129 /// Remote URL root of the external crate
131 /// This external crate can be found in the local doc/ folder
133 /// The external crate could not be found.
137 /// Metadata about an implementor of a trait.
138 pub struct Implementor {
140 pub stability: Option<clean::Stability>,
141 pub impl_: clean::Impl,
144 /// Metadata about implementations for a type.
147 pub impl_item: clean::Item,
151 fn inner_impl(&self) -> &clean::Impl {
152 match self.impl_item.inner {
153 clean::ImplItem(ref impl_) => impl_,
154 _ => panic!("non-impl item found in impl")
158 fn trait_did(&self) -> Option<DefId> {
159 self.inner_impl().trait_.def_id()
169 impl error::Error for Error {
170 fn description(&self) -> &str {
171 self.error.description()
175 impl Display for Error {
176 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
177 write!(f, "\"{}\": {}", self.file.display(), self.error)
182 pub fn new(e: io::Error, file: &Path) -> Error {
184 file: file.to_path_buf(),
190 macro_rules! try_err {
191 ($e:expr, $file:expr) => ({
194 Err(e) => return Err(Error::new(e, $file)),
199 /// This cache is used to store information about the `clean::Crate` being
200 /// rendered in order to provide more useful documentation. This contains
201 /// information like all implementors of a trait, all traits a type implements,
202 /// documentation for all known traits, etc.
204 /// This structure purposefully does not implement `Clone` because it's intended
205 /// to be a fairly large and expensive structure to clone. Instead this adheres
206 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
207 /// rendering threads.
210 /// Mapping of typaram ids to the name of the type parameter. This is used
211 /// when pretty-printing a type (so pretty printing doesn't have to
212 /// painfully maintain a context like this)
213 pub typarams: FxHashMap<DefId, String>,
215 /// Maps a type id to all known implementations for that type. This is only
216 /// recognized for intra-crate `ResolvedPath` types, and is used to print
217 /// out extra documentation on the page of an enum/struct.
219 /// The values of the map are a list of implementations and documentation
220 /// found on that implementation.
221 pub impls: FxHashMap<DefId, Vec<Impl>>,
223 /// Maintains a mapping of local crate node ids to the fully qualified name
224 /// and "short type description" of that node. This is used when generating
225 /// URLs when a type is being linked to. External paths are not located in
226 /// this map because the `External` type itself has all the information
228 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
230 /// Similar to `paths`, but only holds external paths. This is only used for
231 /// generating explicit hyperlinks to other crates.
232 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
234 /// This map contains information about all known traits of this crate.
235 /// Implementations of a crate should inherit the documentation of the
236 /// parent trait if no extra documentation is specified, and default methods
237 /// should show up in documentation about trait implementations.
238 pub traits: FxHashMap<DefId, clean::Trait>,
240 /// When rendering traits, it's often useful to be able to list all
241 /// implementors of the trait, and this mapping is exactly, that: a mapping
242 /// of trait ids to the list of known implementors of the trait
243 pub implementors: FxHashMap<DefId, Vec<Implementor>>,
245 /// Cache of where external crate documentation can be found.
246 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
248 /// Cache of where documentation for primitives can be found.
249 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
251 // Note that external items for which `doc(hidden)` applies to are shown as
252 // non-reachable while local items aren't. This is because we're reusing
253 // the access levels from crateanalysis.
254 pub access_levels: Arc<AccessLevels<DefId>>,
256 // Private fields only used when initially crawling a crate to build a cache
259 parent_stack: Vec<DefId>,
260 parent_is_trait_impl: bool,
261 search_index: Vec<IndexItem>,
263 deref_trait_did: Option<DefId>,
264 deref_mut_trait_did: Option<DefId>,
266 // In rare case where a structure is defined in one module but implemented
267 // in another, if the implementing module is parsed before defining module,
268 // then the fully qualified name of the structure isn't presented in `paths`
269 // yet when its implementation methods are being indexed. Caches such methods
270 // and their parent id here and indexes them at the end of crate parsing.
271 orphan_impl_items: Vec<(DefId, clean::Item)>,
274 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
275 /// Later on moved into `CACHE_KEY`.
277 pub struct RenderInfo {
278 pub inlined: FxHashSet<DefId>,
279 pub external_paths: ::core::ExternalPaths,
280 pub external_typarams: FxHashMap<DefId, String>,
281 pub deref_trait_did: Option<DefId>,
282 pub deref_mut_trait_did: Option<DefId>,
285 /// Helper struct to render all source code to HTML pages
286 struct SourceCollector<'a> {
287 scx: &'a mut SharedContext,
289 /// Root destination to place all HTML output into
293 /// Wrapper struct to render the source code of a file. This will do things like
294 /// adding line numbers to the left-hand side.
295 struct Source<'a>(&'a str);
297 // Helper structs for rendering items/sidebars and carrying along contextual
300 #[derive(Copy, Clone)]
303 item: &'a clean::Item,
306 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
308 /// Struct representing one entry in the JS search index. These are all emitted
309 /// by hand to a large JS file at the end of cache-creation.
315 parent: Option<DefId>,
316 parent_idx: Option<usize>,
317 search_type: Option<IndexItemFunctionType>,
320 impl ToJson for IndexItem {
321 fn to_json(&self) -> Json {
322 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
324 let mut data = Vec::with_capacity(6);
325 data.push((self.ty as usize).to_json());
326 data.push(self.name.to_json());
327 data.push(self.path.to_json());
328 data.push(self.desc.to_json());
329 data.push(self.parent_idx.to_json());
330 data.push(self.search_type.to_json());
336 /// A type used for the search index.
338 name: Option<String>,
341 impl ToJson for Type {
342 fn to_json(&self) -> Json {
345 let mut data = BTreeMap::new();
346 data.insert("name".to_owned(), name.to_json());
354 /// Full type of functions/methods in the search index.
355 struct IndexItemFunctionType {
360 impl ToJson for IndexItemFunctionType {
361 fn to_json(&self) -> Json {
362 // If we couldn't figure out a type, just write `null`.
363 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
366 let mut data = BTreeMap::new();
367 data.insert("inputs".to_owned(), self.inputs.to_json());
368 data.insert("output".to_owned(), self.output.to_json());
374 // TLS keys used to carry information around during rendering.
376 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
377 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
378 RefCell::new(Vec::new()));
379 thread_local!(static USED_ID_MAP: RefCell<FxHashMap<String, usize>> =
380 RefCell::new(init_ids()));
382 fn init_ids() -> FxHashMap<String, usize> {
398 ].into_iter().map(|id| (String::from(*id), 1)).collect()
401 /// This method resets the local table of used ID attributes. This is typically
402 /// used at the beginning of rendering an entire HTML page to reset from the
403 /// previous state (if any).
404 pub fn reset_ids(embedded: bool) {
405 USED_ID_MAP.with(|s| {
406 *s.borrow_mut() = if embedded {
414 pub fn derive_id(candidate: String) -> String {
415 USED_ID_MAP.with(|map| {
416 let id = match map.borrow_mut().get_mut(&candidate) {
419 let id = format!("{}-{}", candidate, *a);
425 map.borrow_mut().insert(id.clone(), 1);
430 /// Generates the documentation for `crate` into the directory `dst`
431 pub fn run(mut krate: clean::Crate,
432 external_html: &ExternalHtml,
433 playground_url: Option<String>,
435 passes: FxHashSet<String>,
436 css_file_extension: Option<PathBuf>,
437 renderinfo: RenderInfo,
438 render_type: RenderType) -> Result<(), Error> {
439 let src_root = match krate.src.parent() {
440 Some(p) => p.to_path_buf(),
441 None => PathBuf::new(),
443 let mut scx = SharedContext {
446 include_sources: true,
447 local_sources: FxHashMap(),
448 issue_tracker_base_url: None,
449 layout: layout::Layout {
450 logo: "".to_string(),
451 favicon: "".to_string(),
452 external_html: external_html.clone(),
453 krate: krate.name.clone(),
455 css_file_extension: css_file_extension.clone(),
458 // If user passed in `--playground-url` arg, we fill in crate name here
459 if let Some(url) = playground_url {
460 markdown::PLAYGROUND.with(|slot| {
461 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
465 // Crawl the crate attributes looking for attributes which control how we're
466 // going to emit HTML
467 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
468 for attr in attrs.lists("doc") {
469 let name = attr.name().map(|s| s.as_str());
470 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
471 (Some("html_favicon_url"), Some(s)) => {
472 scx.layout.favicon = s.to_string();
474 (Some("html_logo_url"), Some(s)) => {
475 scx.layout.logo = s.to_string();
477 (Some("html_playground_url"), Some(s)) => {
478 markdown::PLAYGROUND.with(|slot| {
479 let name = krate.name.clone();
480 *slot.borrow_mut() = Some((Some(name), s.to_string()));
483 (Some("issue_tracker_base_url"), Some(s)) => {
484 scx.issue_tracker_base_url = Some(s.to_string());
486 (Some("html_no_source"), None) if attr.is_word() => {
487 scx.include_sources = false;
493 try_err!(mkdir(&dst), &dst);
494 krate = render_sources(&dst, &mut scx, krate)?;
498 render_redirect_pages: false,
499 shared: Arc::new(scx),
500 render_type: render_type,
503 // Crawl the crate to build various caches used for the output
512 let external_paths = external_paths.into_iter()
513 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
516 let mut cache = Cache {
518 external_paths: external_paths,
520 implementors: FxHashMap(),
522 parent_stack: Vec::new(),
523 search_index: Vec::new(),
524 parent_is_trait_impl: false,
525 extern_locations: FxHashMap(),
526 primitive_locations: FxHashMap(),
528 access_levels: krate.access_levels.clone(),
529 orphan_impl_items: Vec::new(),
530 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
531 deref_trait_did: deref_trait_did,
532 deref_mut_trait_did: deref_mut_trait_did,
533 typarams: external_typarams,
536 // Cache where all our extern crates are located
537 for &(n, ref e) in &krate.externs {
538 let src_root = match Path::new(&e.src).parent() {
539 Some(p) => p.to_path_buf(),
540 None => PathBuf::new(),
542 cache.extern_locations.insert(n, (e.name.clone(), src_root,
543 extern_location(e, &cx.dst)));
545 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
546 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
549 // Cache where all known primitives have their documentation located.
551 // Favor linking to as local extern as possible, so iterate all crates in
552 // reverse topological order.
553 for &(_, ref e) in krate.externs.iter().rev() {
554 for &(def_id, prim, _) in &e.primitives {
555 cache.primitive_locations.insert(prim, def_id);
558 for &(def_id, prim, _) in &krate.primitives {
559 cache.primitive_locations.insert(prim, def_id);
562 cache.stack.push(krate.name.clone());
563 krate = cache.fold_crate(krate);
565 // Build our search index
566 let index = build_index(&krate, &mut cache);
568 // Freeze the cache now that the index has been built. Put an Arc into TLS
569 // for future parallelization opportunities
570 let cache = Arc::new(cache);
571 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
572 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
574 write_shared(&cx, &krate, &*cache, index)?;
576 // And finally render the whole crate's documentation
580 /// Build the search index from the collected metadata
581 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
582 let mut nodeid_to_pathid = FxHashMap();
583 let mut crate_items = Vec::with_capacity(cache.search_index.len());
584 let mut crate_paths = Vec::<Json>::new();
586 let Cache { ref mut search_index,
587 ref orphan_impl_items,
588 ref mut paths, .. } = *cache;
590 // Attach all orphan items to the type's definition if the type
591 // has since been learned.
592 for &(did, ref item) in orphan_impl_items {
593 if let Some(&(ref fqp, _)) = paths.get(&did) {
594 search_index.push(IndexItem {
596 name: item.name.clone().unwrap(),
597 path: fqp[..fqp.len() - 1].join("::"),
598 desc: plain_summary_line(item.doc_value()),
601 search_type: get_index_search_type(&item),
606 // Reduce `NodeId` in paths into smaller sequential numbers,
607 // and prune the paths that do not appear in the index.
608 let mut lastpath = String::new();
609 let mut lastpathid = 0usize;
611 for item in search_index {
612 item.parent_idx = item.parent.map(|nodeid| {
613 if nodeid_to_pathid.contains_key(&nodeid) {
614 *nodeid_to_pathid.get(&nodeid).unwrap()
616 let pathid = lastpathid;
617 nodeid_to_pathid.insert(nodeid, pathid);
620 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
621 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
626 // Omit the parent path if it is same to that of the prior item.
627 if lastpath == item.path {
630 lastpath = item.path.clone();
632 crate_items.push(item.to_json());
635 let crate_doc = krate.module.as_ref().map(|module| {
636 plain_summary_line(module.doc_value())
637 }).unwrap_or(String::new());
639 let mut crate_data = BTreeMap::new();
640 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
641 crate_data.insert("items".to_owned(), Json::Array(crate_items));
642 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
644 // Collect the index into a string
645 format!("searchIndex[{}] = {};",
646 as_json(&krate.name),
647 Json::Object(crate_data))
650 fn write_shared(cx: &Context,
651 krate: &clean::Crate,
653 search_index: String) -> Result<(), Error> {
654 // Write out the shared files. Note that these are shared among all rustdoc
655 // docs placed in the output directory, so this needs to be a synchronized
656 // operation with respect to all other rustdocs running around.
657 try_err!(mkdir(&cx.dst), &cx.dst);
658 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
660 // Add all the static files. These may already exist, but we just
661 // overwrite them anyway to make sure that they're fresh and up-to-date.
663 write(cx.dst.join("main.js"),
664 include_bytes!("static/main.js"))?;
665 write(cx.dst.join("rustdoc.css"),
666 include_bytes!("static/rustdoc.css"))?;
667 write(cx.dst.join("main.css"),
668 include_bytes!("static/styles/main.css"))?;
669 if let Some(ref css) = cx.shared.css_file_extension {
670 let mut content = String::new();
671 let css = css.as_path();
672 let mut f = try_err!(File::open(css), css);
674 try_err!(f.read_to_string(&mut content), css);
675 let css = cx.dst.join("theme.css");
676 let css = css.as_path();
677 let mut f = try_err!(File::create(css), css);
678 try_err!(write!(f, "{}", &content), css);
680 write(cx.dst.join("normalize.css"),
681 include_bytes!("static/normalize.css"))?;
682 write(cx.dst.join("FiraSans-Regular.woff"),
683 include_bytes!("static/FiraSans-Regular.woff"))?;
684 write(cx.dst.join("FiraSans-Medium.woff"),
685 include_bytes!("static/FiraSans-Medium.woff"))?;
686 write(cx.dst.join("FiraSans-LICENSE.txt"),
687 include_bytes!("static/FiraSans-LICENSE.txt"))?;
688 write(cx.dst.join("Heuristica-Italic.woff"),
689 include_bytes!("static/Heuristica-Italic.woff"))?;
690 write(cx.dst.join("Heuristica-LICENSE.txt"),
691 include_bytes!("static/Heuristica-LICENSE.txt"))?;
692 write(cx.dst.join("SourceSerifPro-Regular.woff"),
693 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
694 write(cx.dst.join("SourceSerifPro-Bold.woff"),
695 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
696 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
697 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
698 write(cx.dst.join("SourceCodePro-Regular.woff"),
699 include_bytes!("static/SourceCodePro-Regular.woff"))?;
700 write(cx.dst.join("SourceCodePro-Semibold.woff"),
701 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
702 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
703 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
704 write(cx.dst.join("LICENSE-MIT.txt"),
705 include_bytes!("static/LICENSE-MIT.txt"))?;
706 write(cx.dst.join("LICENSE-APACHE.txt"),
707 include_bytes!("static/LICENSE-APACHE.txt"))?;
708 write(cx.dst.join("COPYRIGHT.txt"),
709 include_bytes!("static/COPYRIGHT.txt"))?;
711 fn collect(path: &Path, krate: &str,
712 key: &str) -> io::Result<Vec<String>> {
713 let mut ret = Vec::new();
715 for line in BufReader::new(File::open(path)?).lines() {
717 if !line.starts_with(key) {
720 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
723 ret.push(line.to_string());
729 // Update the search index
730 let dst = cx.dst.join("search-index.js");
731 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
732 all_indexes.push(search_index);
733 // Sort the indexes by crate so the file will be generated identically even
734 // with rustdoc running in parallel.
736 let mut w = try_err!(File::create(&dst), &dst);
737 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
738 for index in &all_indexes {
739 try_err!(writeln!(&mut w, "{}", *index), &dst);
741 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
743 // Update the list of all implementors for traits
744 let dst = cx.dst.join("implementors");
745 for (&did, imps) in &cache.implementors {
746 // Private modules can leak through to this phase of rustdoc, which
747 // could contain implementations for otherwise private types. In some
748 // rare cases we could find an implementation for an item which wasn't
749 // indexed, so we just skip this step in that case.
751 // FIXME: this is a vague explanation for why this can't be a `get`, in
752 // theory it should be...
753 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
755 None => match cache.external_paths.get(&did) {
761 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
763 // If the trait and implementation are in the same crate, then
764 // there's no need to emit information about it (there's inlining
765 // going on). If they're in different crates then the crate defining
766 // the trait will be interested in our implementation.
767 if imp.def_id.krate == did.krate { continue }
768 write!(implementors, "{},", as_json(&imp.impl_.to_string())).unwrap();
770 implementors.push_str("];");
772 let mut mydst = dst.clone();
773 for part in &remote_path[..remote_path.len() - 1] {
776 try_err!(fs::create_dir_all(&mydst), &mydst);
777 mydst.push(&format!("{}.{}.js",
778 remote_item_type.css_class(),
779 remote_path[remote_path.len() - 1]));
781 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
782 all_implementors.push(implementors);
783 // Sort the implementors by crate so the file will be generated
784 // identically even with rustdoc running in parallel.
785 all_implementors.sort();
787 let mut f = try_err!(File::create(&mydst), &mydst);
788 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
789 for implementor in &all_implementors {
790 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
792 try_err!(writeln!(&mut f, "{}", r"
793 if (window.register_implementors) {
794 window.register_implementors(implementors);
796 window.pending_implementors = implementors;
799 try_err!(writeln!(&mut f, r"}})()"), &mydst);
804 fn render_sources(dst: &Path, scx: &mut SharedContext,
805 krate: clean::Crate) -> Result<clean::Crate, Error> {
806 info!("emitting source files");
807 let dst = dst.join("src");
808 try_err!(mkdir(&dst), &dst);
809 let dst = dst.join(&krate.name);
810 try_err!(mkdir(&dst), &dst);
811 let mut folder = SourceCollector {
815 Ok(folder.fold_crate(krate))
818 /// Writes the entire contents of a string to a destination, not attempting to
819 /// catch any errors.
820 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
821 Ok(try_err!(try_err!(File::create(&dst), &dst).write_all(contents), &dst))
824 /// Makes a directory on the filesystem, failing the thread if an error occurs
825 /// and skipping if the directory already exists.
827 /// Note that this also handles races as rustdoc is likely to be run
828 /// concurrently against another invocation.
829 fn mkdir(path: &Path) -> io::Result<()> {
830 match fs::create_dir(path) {
832 Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
837 /// Takes a path to a source file and cleans the path to it. This canonicalizes
838 /// things like ".." to components which preserve the "top down" hierarchy of a
839 /// static HTML tree. Each component in the cleaned path will be passed as an
840 /// argument to `f`. The very last component of the path (ie the file name) will
841 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
842 // FIXME (#9639): The closure should deal with &[u8] instead of &str
843 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
844 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
847 // make it relative, if possible
848 let p = p.strip_prefix(src_root).unwrap_or(p);
850 let mut iter = p.components().peekable();
852 while let Some(c) = iter.next() {
853 if !keep_filename && iter.peek().is_none() {
858 Component::ParentDir => f("up"),
859 Component::Normal(c) => f(c.to_str().unwrap()),
865 /// Attempts to find where an external crate is located, given that we're
866 /// rendering in to the specified source destination.
867 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
868 // See if there's documentation generated into the local directory
869 let local_location = dst.join(&e.name);
870 if local_location.is_dir() {
874 // Failing that, see if there's an attribute specifying where to find this
877 .filter(|a| a.check_name("html_root_url"))
878 .filter_map(|a| a.value_str())
880 let mut url = url.to_string();
881 if !url.ends_with("/") {
885 }).next().unwrap_or(Unknown) // Well, at least we tried.
888 impl<'a> DocFolder for SourceCollector<'a> {
889 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
890 // If we're including source files, and we haven't seen this file yet,
891 // then we need to render it out to the filesystem.
892 if self.scx.include_sources
893 // skip all invalid spans
894 && item.source.filename != ""
895 // skip non-local items
896 && item.def_id.is_local()
897 // Macros from other libraries get special filenames which we can
899 && !(item.source.filename.starts_with("<")
900 && item.source.filename.ends_with("macros>")) {
902 // If it turns out that we couldn't read this file, then we probably
903 // can't read any of the files (generating html output from json or
904 // something like that), so just don't include sources for the
905 // entire crate. The other option is maintaining this mapping on a
906 // per-file basis, but that's probably not worth it...
908 .include_sources = match self.emit_source(&item.source.filename) {
911 println!("warning: source code was requested to be rendered, \
912 but processing `{}` had an error: {}",
913 item.source.filename, e);
914 println!(" skipping rendering of source code");
919 self.fold_item_recur(item)
923 impl<'a> SourceCollector<'a> {
924 /// Renders the given filename into its corresponding HTML source file.
925 fn emit_source(&mut self, filename: &str) -> io::Result<()> {
926 let p = PathBuf::from(filename);
927 if self.scx.local_sources.contains_key(&p) {
928 // We've already emitted this source
932 let mut contents = Vec::new();
933 File::open(&p).and_then(|mut f| f.read_to_end(&mut contents))?;
935 let contents = str::from_utf8(&contents).unwrap();
937 // Remove the utf-8 BOM if any
938 let contents = if contents.starts_with("\u{feff}") {
944 // Create the intermediate directories
945 let mut cur = self.dst.clone();
946 let mut root_path = String::from("../../");
947 let mut href = String::new();
948 clean_srcpath(&self.scx.src_root, &p, false, |component| {
950 mkdir(&cur).unwrap();
951 root_path.push_str("../");
952 href.push_str(component);
955 let mut fname = p.file_name().expect("source has no filename")
959 href.push_str(&fname.to_string_lossy());
961 let mut w = BufWriter::new(File::create(&cur)?);
962 let title = format!("{} -- source", cur.file_name().unwrap()
964 let desc = format!("Source to the Rust file `{}`.", filename);
965 let page = layout::Page {
968 root_path: &root_path,
970 keywords: BASIC_KEYWORDS,
972 layout::render(&mut w, &self.scx.layout,
973 &page, &(""), &Source(contents),
974 self.scx.css_file_extension.is_some())?;
976 self.scx.local_sources.insert(p, href);
981 impl DocFolder for Cache {
982 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
983 // If this is a stripped module,
984 // we don't want it or its children in the search index.
985 let orig_stripped_mod = match item.inner {
986 clean::StrippedItem(box clean::ModuleItem(..)) => {
987 mem::replace(&mut self.stripped_mod, true)
989 _ => self.stripped_mod,
992 // Register any generics to their corresponding string. This is used
993 // when pretty-printing types.
994 if let Some(generics) = item.inner.generics() {
995 self.generics(generics);
998 // Propagate a trait method's documentation to all implementors of the
1000 if let clean::TraitItem(ref t) = item.inner {
1001 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1004 // Collect all the implementors of traits.
1005 if let clean::ImplItem(ref i) = item.inner {
1006 if let Some(did) = i.trait_.def_id() {
1007 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
1008 def_id: item.def_id,
1009 stability: item.stability.clone(),
1015 // Index this method for searching later on.
1016 if let Some(ref s) = item.name {
1017 let (parent, is_inherent_impl_item) = match item.inner {
1018 clean::StrippedItem(..) => ((None, None), false),
1019 clean::AssociatedConstItem(..) |
1020 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1021 // skip associated items in trait impls
1022 ((None, None), false)
1024 clean::AssociatedTypeItem(..) |
1025 clean::TyMethodItem(..) |
1026 clean::StructFieldItem(..) |
1027 clean::VariantItem(..) => {
1028 ((Some(*self.parent_stack.last().unwrap()),
1029 Some(&self.stack[..self.stack.len() - 1])),
1032 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1033 if self.parent_stack.is_empty() {
1034 ((None, None), false)
1036 let last = self.parent_stack.last().unwrap();
1038 let path = match self.paths.get(&did) {
1039 // The current stack not necessarily has correlation
1040 // for where the type was defined. On the other
1041 // hand, `paths` always has the right
1042 // information if present.
1043 Some(&(ref fqp, ItemType::Trait)) |
1044 Some(&(ref fqp, ItemType::Struct)) |
1045 Some(&(ref fqp, ItemType::Union)) |
1046 Some(&(ref fqp, ItemType::Enum)) =>
1047 Some(&fqp[..fqp.len() - 1]),
1048 Some(..) => Some(&*self.stack),
1051 ((Some(*last), path), true)
1054 _ => ((None, Some(&*self.stack)), false)
1058 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1059 debug_assert!(!item.is_stripped());
1061 // A crate has a module at its root, containing all items,
1062 // which should not be indexed. The crate-item itself is
1063 // inserted later on when serializing the search-index.
1064 if item.def_id.index != CRATE_DEF_INDEX {
1065 self.search_index.push(IndexItem {
1067 name: s.to_string(),
1068 path: path.join("::").to_string(),
1069 desc: plain_summary_line(item.doc_value()),
1072 search_type: get_index_search_type(&item),
1076 (Some(parent), None) if is_inherent_impl_item => {
1077 // We have a parent, but we don't know where they're
1078 // defined yet. Wait for later to index this item.
1079 self.orphan_impl_items.push((parent, item.clone()));
1085 // Keep track of the fully qualified path for this item.
1086 let pushed = match item.name {
1087 Some(ref n) if !n.is_empty() => {
1088 self.stack.push(n.to_string());
1095 clean::StructItem(..) | clean::EnumItem(..) |
1096 clean::TypedefItem(..) | clean::TraitItem(..) |
1097 clean::FunctionItem(..) | clean::ModuleItem(..) |
1098 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1099 clean::ConstantItem(..) | clean::StaticItem(..) |
1100 clean::UnionItem(..)
1101 if !self.stripped_mod => {
1102 // Reexported items mean that the same id can show up twice
1103 // in the rustdoc ast that we're looking at. We know,
1104 // however, that a reexported item doesn't show up in the
1105 // `public_items` map, so we can skip inserting into the
1106 // paths map if there was already an entry present and we're
1107 // not a public item.
1109 !self.paths.contains_key(&item.def_id) ||
1110 self.access_levels.is_public(item.def_id)
1112 self.paths.insert(item.def_id,
1113 (self.stack.clone(), item.type_()));
1116 // Link variants to their parent enum because pages aren't emitted
1117 // for each variant.
1118 clean::VariantItem(..) if !self.stripped_mod => {
1119 let mut stack = self.stack.clone();
1121 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1124 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1125 self.paths.insert(item.def_id, (self.stack.clone(),
1132 // Maintain the parent stack
1133 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1134 let parent_pushed = match item.inner {
1135 clean::TraitItem(..) | clean::EnumItem(..) |
1136 clean::StructItem(..) | clean::UnionItem(..) => {
1137 self.parent_stack.push(item.def_id);
1138 self.parent_is_trait_impl = false;
1141 clean::ImplItem(ref i) => {
1142 self.parent_is_trait_impl = i.trait_.is_some();
1144 clean::ResolvedPath{ did, .. } => {
1145 self.parent_stack.push(did);
1149 let prim_did = t.primitive_type().and_then(|t| {
1150 self.primitive_locations.get(&t).cloned()
1154 self.parent_stack.push(did);
1165 // Once we've recursively found all the generics, hoard off all the
1166 // implementations elsewhere.
1167 let ret = self.fold_item_recur(item).and_then(|item| {
1168 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1169 // Figure out the id of this impl. This may map to a
1170 // primitive rather than always to a struct/enum.
1171 // Note: matching twice to restrict the lifetime of the `i` borrow.
1172 let did = if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1174 clean::ResolvedPath { did, .. } |
1175 clean::BorrowedRef {
1176 type_: box clean::ResolvedPath { did, .. }, ..
1181 t.primitive_type().and_then(|t| {
1182 self.primitive_locations.get(&t).cloned()
1189 if let Some(did) = did {
1190 self.impls.entry(did).or_insert(vec![]).push(Impl {
1200 if pushed { self.stack.pop().unwrap(); }
1201 if parent_pushed { self.parent_stack.pop().unwrap(); }
1202 self.stripped_mod = orig_stripped_mod;
1203 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1209 fn generics(&mut self, generics: &clean::Generics) {
1210 for typ in &generics.type_params {
1211 self.typarams.insert(typ.did, typ.name.clone());
1217 /// String representation of how to get back to the root path of the 'doc/'
1218 /// folder in terms of a relative URL.
1219 fn root_path(&self) -> String {
1220 repeat("../").take(self.current.len()).collect::<String>()
1223 /// Recurse in the directory structure and change the "root path" to make
1224 /// sure it always points to the top (relatively).
1225 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1226 F: FnOnce(&mut Context) -> T,
1229 panic!("Unexpected empty destination: {:?}", self.current);
1231 let prev = self.dst.clone();
1233 self.current.push(s);
1235 info!("Recursing into {}", self.dst.display());
1239 info!("Recursed; leaving {}", self.dst.display());
1241 // Go back to where we were at
1243 self.current.pop().unwrap();
1248 /// Main method for rendering a crate.
1250 /// This currently isn't parallelized, but it'd be pretty easy to add
1251 /// parallelization to this function.
1252 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1253 let mut item = match krate.module.take() {
1255 None => return Ok(()),
1257 item.name = Some(krate.name);
1259 // Render the crate documentation
1260 let mut work = vec![(self, item)];
1262 while let Some((mut cx, item)) = work.pop() {
1263 cx.item(item, |cx, item| {
1264 work.push((cx.clone(), item))
1270 fn render_item(&self,
1271 writer: &mut io::Write,
1275 // A little unfortunate that this is done like this, but it sure
1276 // does make formatting *a lot* nicer.
1277 CURRENT_LOCATION_KEY.with(|slot| {
1278 *slot.borrow_mut() = self.current.clone();
1281 let mut title = if it.is_primitive() {
1282 // No need to include the namespace for primitive types
1285 self.current.join("::")
1288 if !title.is_empty() {
1289 title.push_str("::");
1291 title.push_str(it.name.as_ref().unwrap());
1293 title.push_str(" - Rust");
1294 let tyname = it.type_().css_class();
1295 let desc = if it.is_crate() {
1296 format!("API documentation for the Rust `{}` crate.",
1297 self.shared.layout.krate)
1299 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1300 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1302 let keywords = make_item_keywords(it);
1303 let page = layout::Page {
1305 root_path: &self.root_path(),
1308 keywords: &keywords,
1313 if !self.render_redirect_pages {
1314 layout::render(writer, &self.shared.layout, &page,
1315 &Sidebar{ cx: self, item: it },
1316 &Item{ cx: self, item: it },
1317 self.shared.css_file_extension.is_some())?;
1319 let mut url = self.root_path();
1320 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1321 for name in &names[..names.len() - 1] {
1325 url.push_str(&item_path(ty, names.last().unwrap()));
1326 layout::redirect(writer, &url)?;
1332 /// Non-parallelized version of rendering an item. This will take the input
1333 /// item, render its contents, and then invoke the specified closure with
1334 /// all sub-items which need to be rendered.
1336 /// The rendering driver uses this closure to queue up more work.
1337 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1338 F: FnMut(&mut Context, clean::Item),
1340 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1341 // if they contain impls for public types. These modules can also
1342 // contain items such as publicly reexported structures.
1344 // External crates will provide links to these structures, so
1345 // these modules are recursed into, but not rendered normally
1346 // (a flag on the context).
1347 if !self.render_redirect_pages {
1348 self.render_redirect_pages = maybe_ignore_item(&item);
1352 // modules are special because they add a namespace. We also need to
1353 // recurse into the items of the module as well.
1354 let name = item.name.as_ref().unwrap().to_string();
1355 let mut item = Some(item);
1356 self.recurse(name, |this| {
1357 let item = item.take().unwrap();
1359 let mut buf = Vec::new();
1360 this.render_item(&mut buf, &item, false).unwrap();
1361 // buf will be empty if the module is stripped and there is no redirect for it
1362 if !buf.is_empty() {
1363 let joint_dst = this.dst.join("index.html");
1364 try_err!(fs::create_dir_all(&this.dst), &this.dst);
1365 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1366 try_err!(dst.write_all(&buf), &joint_dst);
1369 let m = match item.inner {
1370 clean::StrippedItem(box clean::ModuleItem(m)) |
1371 clean::ModuleItem(m) => m,
1375 // Render sidebar-items.js used throughout this module.
1376 if !this.render_redirect_pages {
1377 let items = this.build_sidebar_items(&m);
1378 let js_dst = this.dst.join("sidebar-items.js");
1379 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1380 try_err!(write!(&mut js_out, "initSidebarItems({});",
1381 as_json(&items)), &js_dst);
1384 for item in m.items {
1390 } else if item.name.is_some() {
1391 let mut buf = Vec::new();
1392 self.render_item(&mut buf, &item, true).unwrap();
1393 // buf will be empty if the item is stripped and there is no redirect for it
1394 if !buf.is_empty() {
1395 let name = item.name.as_ref().unwrap();
1396 let item_type = item.type_();
1397 let file_name = &item_path(item_type, name);
1398 let joint_dst = self.dst.join(file_name);
1399 try_err!(fs::create_dir_all(&self.dst), &self.dst);
1400 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1401 try_err!(dst.write_all(&buf), &joint_dst);
1403 // Redirect from a sane URL using the namespace to Rustdoc's
1404 // URL for the page.
1405 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1406 let redir_dst = self.dst.join(redir_name);
1407 if let Ok(mut redirect_out) = OpenOptions::new().create_new(true)
1410 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1413 // If the item is a macro, redirect from the old macro URL (with !)
1414 // to the new one (without).
1415 // FIXME(#35705) remove this redirect.
1416 if item_type == ItemType::Macro {
1417 let redir_name = format!("{}.{}!.html", item_type, name);
1418 let redir_dst = self.dst.join(redir_name);
1419 let mut redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1420 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1427 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1428 // BTreeMap instead of HashMap to get a sorted output
1429 let mut map = BTreeMap::new();
1430 for item in &m.items {
1431 if maybe_ignore_item(item) { continue }
1433 let short = item.type_().css_class();
1434 let myname = match item.name {
1436 Some(ref s) => s.to_string(),
1438 let short = short.to_string();
1439 map.entry(short).or_insert(vec![])
1440 .push((myname, Some(plain_summary_line(item.doc_value()))));
1443 for (_, items) in &mut map {
1451 /// Generate a url appropriate for an `href` attribute back to the source of
1454 /// The url generated, when clicked, will redirect the browser back to the
1455 /// original source code.
1457 /// If `None` is returned, then a source link couldn't be generated. This
1458 /// may happen, for example, with externally inlined items where the source
1459 /// of their crate documentation isn't known.
1460 fn src_href(&self) -> Option<String> {
1461 let mut root = self.cx.root_path();
1463 let cache = cache();
1464 let mut path = String::new();
1465 let (krate, path) = if self.item.def_id.is_local() {
1466 let path = PathBuf::from(&self.item.source.filename);
1467 if let Some(path) = self.cx.shared.local_sources.get(&path) {
1468 (&self.cx.shared.layout.krate, path)
1473 // Macros from other libraries get special filenames which we can
1475 if self.item.source.filename.starts_with("<") &&
1476 self.item.source.filename.ends_with("macros>") {
1480 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1481 Some(&(ref name, ref src, Local)) => (name, src),
1482 Some(&(ref name, ref src, Remote(ref s))) => {
1483 root = s.to_string();
1486 Some(&(_, _, Unknown)) | None => return None,
1489 let file = Path::new(&self.item.source.filename);
1490 clean_srcpath(&src_root, file, false, |component| {
1491 path.push_str(component);
1494 let mut fname = file.file_name().expect("source has no filename")
1496 fname.push(".html");
1497 path.push_str(&fname.to_string_lossy());
1501 let lines = if self.item.source.loline == self.item.source.hiline {
1502 format!("{}", self.item.source.loline)
1504 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1506 Some(format!("{root}src/{krate}/{path}#{lines}",
1514 impl<'a> fmt::Display for Item<'a> {
1515 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1516 debug_assert!(!self.item.is_stripped());
1517 // Write the breadcrumb trail header for the top
1518 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1519 match self.item.inner {
1520 clean::ModuleItem(ref m) => if m.is_crate {
1521 write!(fmt, "Crate ")?;
1523 write!(fmt, "Module ")?;
1525 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) =>
1526 write!(fmt, "Function ")?,
1527 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1528 clean::StructItem(..) => write!(fmt, "Struct ")?,
1529 clean::UnionItem(..) => write!(fmt, "Union ")?,
1530 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1531 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1532 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1533 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1534 clean::StaticItem(..) | clean::ForeignStaticItem(..) =>
1535 write!(fmt, "Static ")?,
1536 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1538 // We don't generate pages for any other type.
1542 if !self.item.is_primitive() {
1543 let cur = &self.cx.current;
1544 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1545 for (i, component) in cur.iter().enumerate().take(amt) {
1546 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1547 repeat("../").take(cur.len() - i - 1)
1548 .collect::<String>(),
1552 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1553 self.item.type_(), self.item.name.as_ref().unwrap())?;
1555 write!(fmt, "</span>")?; // in-band
1556 write!(fmt, "<span class='out-of-band'>")?;
1557 if let Some(version) = self.item.stable_since() {
1558 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1562 r##"<span id='render-detail'>
1563 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1564 [<span class='inner'>−</span>]
1570 // When this item is part of a `pub use` in a downstream crate, the
1571 // [src] link in the downstream documentation will actually come back to
1572 // this page, and this link will be auto-clicked. The `id` attribute is
1573 // used to find the link to auto-click.
1574 if self.cx.shared.include_sources && !self.item.is_primitive() {
1575 if let Some(l) = self.src_href() {
1576 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1577 l, "goto source code")?;
1581 write!(fmt, "</span>")?; // out-of-band
1583 write!(fmt, "</h1>\n")?;
1585 match self.item.inner {
1586 clean::ModuleItem(ref m) => {
1587 item_module(fmt, self.cx, self.item, &m.items)
1589 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1590 item_function(fmt, self.cx, self.item, f),
1591 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1592 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1593 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1594 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1595 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1596 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1597 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1598 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1599 item_static(fmt, self.cx, self.item, i),
1600 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1602 // We don't generate pages for any other type.
1609 fn item_path(ty: ItemType, name: &str) -> String {
1611 ItemType::Module => format!("{}/index.html", name),
1612 _ => format!("{}.{}.html", ty.css_class(), name),
1616 fn full_path(cx: &Context, item: &clean::Item) -> String {
1617 let mut s = cx.current.join("::");
1619 s.push_str(item.name.as_ref().unwrap());
1623 fn shorter<'a>(s: Option<&'a str>) -> String {
1625 Some(s) => s.lines().take_while(|line|{
1626 (*line).chars().any(|chr|{
1627 !chr.is_whitespace()
1629 }).collect::<Vec<_>>().join("\n"),
1630 None => "".to_string()
1635 fn plain_summary_line(s: Option<&str>) -> String {
1636 let line = shorter(s).replace("\n", " ");
1637 markdown::plain_summary_line(&line[..])
1640 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1641 document_stability(w, cx, item)?;
1642 document_full(w, item, cx.render_type)?;
1646 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1647 render_type: RenderType) -> fmt::Result {
1648 if let Some(s) = item.doc_value() {
1649 let markdown = if s.contains('\n') {
1650 format!("{} [Read more]({})",
1651 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1653 format!("{}", &plain_summary_line(Some(s)))
1655 write!(w, "<div class='docblock'>{}</div>",
1656 Markdown(&markdown, render_type))?;
1661 fn md_render_assoc_item(item: &clean::Item) -> String {
1663 clean::AssociatedConstItem(ref ty, ref default) => {
1664 if let Some(default) = default.as_ref() {
1665 format!("```\n{}: {:#} = {}\n```\n\n", item.name.as_ref().unwrap(), ty, default)
1667 format!("```\n{}: {:#}\n```\n\n", item.name.as_ref().unwrap(), ty)
1674 fn get_doc_value(item: &clean::Item) -> Option<&str> {
1675 let x = item.doc_value();
1678 clean::AssociatedConstItem(_, _) => Some(""),
1686 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1687 render_type: RenderType) -> fmt::Result {
1688 if let Some(s) = get_doc_value(item) {
1689 write!(w, "<div class='docblock'>{}</div>",
1690 Markdown(&format!("{}{}", md_render_assoc_item(item), s), render_type))?;
1695 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1696 let stabilities = short_stability(item, cx, true);
1697 if !stabilities.is_empty() {
1698 write!(w, "<div class='stability'>")?;
1699 for stability in stabilities {
1700 write!(w, "{}", stability)?;
1702 write!(w, "</div>")?;
1707 fn name_key(name: &str) -> (&str, u64, usize) {
1708 // find number at end
1709 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1711 // count leading zeroes
1713 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1715 // sort leading zeroes last
1716 let num_zeroes = after_zeroes - split;
1718 match name[split..].parse() {
1719 Ok(n) => (&name[..split], n, num_zeroes),
1720 Err(_) => (name, 0, num_zeroes),
1724 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1725 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1726 document(w, cx, item)?;
1728 let mut indices = (0..items.len()).filter(|i| {
1729 if let clean::DefaultImplItem(..) = items[*i].inner {
1732 !maybe_ignore_item(&items[*i])
1733 }).collect::<Vec<usize>>();
1735 // the order of item types in the listing
1736 fn reorder(ty: ItemType) -> u8 {
1738 ItemType::ExternCrate => 0,
1739 ItemType::Import => 1,
1740 ItemType::Primitive => 2,
1741 ItemType::Module => 3,
1742 ItemType::Macro => 4,
1743 ItemType::Struct => 5,
1744 ItemType::Enum => 6,
1745 ItemType::Constant => 7,
1746 ItemType::Static => 8,
1747 ItemType::Trait => 9,
1748 ItemType::Function => 10,
1749 ItemType::Typedef => 12,
1750 ItemType::Union => 13,
1755 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1756 let ty1 = i1.type_();
1757 let ty2 = i2.type_();
1759 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1761 let s1 = i1.stability.as_ref().map(|s| s.level);
1762 let s2 = i2.stability.as_ref().map(|s| s.level);
1764 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1765 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1768 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1769 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1770 name_key(lhs).cmp(&name_key(rhs))
1773 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1775 debug!("{:?}", indices);
1776 let mut curty = None;
1777 for &idx in &indices {
1778 let myitem = &items[idx];
1779 if myitem.is_stripped() {
1783 let myty = Some(myitem.type_());
1784 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1785 // Put `extern crate` and `use` re-exports in the same section.
1787 } else if myty != curty {
1788 if curty.is_some() {
1789 write!(w, "</table>")?;
1792 let (short, name) = match myty.unwrap() {
1793 ItemType::ExternCrate |
1794 ItemType::Import => ("reexports", "Reexports"),
1795 ItemType::Module => ("modules", "Modules"),
1796 ItemType::Struct => ("structs", "Structs"),
1797 ItemType::Union => ("unions", "Unions"),
1798 ItemType::Enum => ("enums", "Enums"),
1799 ItemType::Function => ("functions", "Functions"),
1800 ItemType::Typedef => ("types", "Type Definitions"),
1801 ItemType::Static => ("statics", "Statics"),
1802 ItemType::Constant => ("constants", "Constants"),
1803 ItemType::Trait => ("traits", "Traits"),
1804 ItemType::Impl => ("impls", "Implementations"),
1805 ItemType::TyMethod => ("tymethods", "Type Methods"),
1806 ItemType::Method => ("methods", "Methods"),
1807 ItemType::StructField => ("fields", "Struct Fields"),
1808 ItemType::Variant => ("variants", "Variants"),
1809 ItemType::Macro => ("macros", "Macros"),
1810 ItemType::Primitive => ("primitives", "Primitive Types"),
1811 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1812 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1814 write!(w, "<h2 id='{id}' class='section-header'>\
1815 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1816 id = derive_id(short.to_owned()), name = name)?;
1819 match myitem.inner {
1820 clean::ExternCrateItem(ref name, ref src) => {
1821 use html::format::HRef;
1825 write!(w, "<tr><td><code>{}extern crate {} as {};",
1826 VisSpace(&myitem.visibility),
1827 HRef::new(myitem.def_id, src),
1831 write!(w, "<tr><td><code>{}extern crate {};",
1832 VisSpace(&myitem.visibility),
1833 HRef::new(myitem.def_id, name))?
1836 write!(w, "</code></td></tr>")?;
1839 clean::ImportItem(ref import) => {
1840 write!(w, "<tr><td><code>{}{}</code></td></tr>",
1841 VisSpace(&myitem.visibility), *import)?;
1845 if myitem.name.is_none() { continue }
1847 let stabilities = short_stability(myitem, cx, false);
1849 let stab_docs = if !stabilities.is_empty() {
1851 .map(|s| format!("[{}]", s))
1852 .collect::<Vec<_>>()
1859 let unsafety_flag = match myitem.inner {
1860 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
1861 if func.unsafety == hir::Unsafety::Unsafe => {
1862 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
1867 let doc_value = myitem.doc_value().unwrap_or("");
1869 <tr class='{stab} module-item'>
1870 <td><a class=\"{class}\" href=\"{href}\"
1871 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
1872 <td class='docblock-short'>
1876 name = *myitem.name.as_ref().unwrap(),
1877 stab_docs = stab_docs,
1878 docs = if cx.render_type == RenderType::Hoedown {
1880 shorter(Some(&Markdown(doc_value,
1881 RenderType::Hoedown).to_string())))
1883 format!("{}", MarkdownSummaryLine(doc_value))
1885 class = myitem.type_(),
1886 stab = myitem.stability_class().unwrap_or("".to_string()),
1887 unsafety_flag = unsafety_flag,
1888 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
1889 title_type = myitem.type_(),
1890 title = full_path(cx, myitem))?;
1895 if curty.is_some() {
1896 write!(w, "</table>")?;
1901 fn maybe_ignore_item(it: &clean::Item) -> bool {
1903 clean::StrippedItem(..) => true,
1904 clean::ModuleItem(ref m) => {
1905 it.doc_value().is_none() && m.items.is_empty()
1906 && it.visibility != Some(clean::Public)
1912 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
1913 let mut stability = vec![];
1915 if let Some(stab) = item.stability.as_ref() {
1916 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
1917 format!(": {}", stab.deprecated_reason)
1921 if !stab.deprecated_since.is_empty() {
1922 let since = if show_reason {
1923 format!(" since {}", Escape(&stab.deprecated_since))
1927 let text = format!("Deprecated{}{}",
1929 MarkdownHtml(&deprecated_reason, cx.render_type));
1930 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
1933 if stab.level == stability::Unstable {
1935 let unstable_extra = match (!stab.feature.is_empty(),
1936 &cx.shared.issue_tracker_base_url,
1938 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1939 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
1940 Escape(&stab.feature), tracker_url, issue_no, issue_no),
1941 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1942 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
1945 format!(" (<code>{}</code>)", Escape(&stab.feature)),
1948 if stab.unstable_reason.is_empty() {
1949 stability.push(format!("<div class='stab unstable'>\
1950 <span class=microscope>🔬</span> \
1951 This is a nightly-only experimental API. {}\
1955 let text = format!("<summary><span class=microscope>🔬</span> \
1956 This is a nightly-only experimental API. {}\
1959 MarkdownHtml(&stab.unstable_reason, cx.render_type));
1960 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
1964 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
1967 } else if let Some(depr) = item.deprecation.as_ref() {
1968 let note = if show_reason && !depr.note.is_empty() {
1969 format!(": {}", depr.note)
1973 let since = if show_reason && !depr.since.is_empty() {
1974 format!(" since {}", Escape(&depr.since))
1979 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e, cx.render_type));
1980 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
1986 struct Initializer<'a>(&'a str);
1988 impl<'a> fmt::Display for Initializer<'a> {
1989 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1990 let Initializer(s) = *self;
1991 if s.is_empty() { return Ok(()); }
1992 write!(f, "<code> = </code>")?;
1993 write!(f, "<code>{}</code>", Escape(s))
1997 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1998 c: &clean::Constant) -> fmt::Result {
1999 write!(w, "<pre class='rust const'>")?;
2000 render_attributes(w, it)?;
2001 write!(w, "{vis}const \
2002 {name}: {typ}{init}</pre>",
2003 vis = VisSpace(&it.visibility),
2004 name = it.name.as_ref().unwrap(),
2006 init = Initializer(&c.expr))?;
2010 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2011 s: &clean::Static) -> fmt::Result {
2012 write!(w, "<pre class='rust static'>")?;
2013 render_attributes(w, it)?;
2014 write!(w, "{vis}static {mutability}\
2015 {name}: {typ}{init}</pre>",
2016 vis = VisSpace(&it.visibility),
2017 mutability = MutableSpace(s.mutability),
2018 name = it.name.as_ref().unwrap(),
2020 init = Initializer(&s.expr))?;
2024 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2025 f: &clean::Function) -> fmt::Result {
2026 // FIXME(#24111): remove when `const_fn` is stabilized
2027 let vis_constness = match UnstableFeatures::from_environment() {
2028 UnstableFeatures::Allow => f.constness,
2029 _ => hir::Constness::NotConst
2031 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2032 VisSpace(&it.visibility),
2033 ConstnessSpace(vis_constness),
2034 UnsafetySpace(f.unsafety),
2036 it.name.as_ref().unwrap(),
2038 write!(w, "<pre class='rust fn'>")?;
2039 render_attributes(w, it)?;
2040 write!(w, "{vis}{constness}{unsafety}{abi}fn \
2041 {name}{generics}{decl}{where_clause}</pre>",
2042 vis = VisSpace(&it.visibility),
2043 constness = ConstnessSpace(vis_constness),
2044 unsafety = UnsafetySpace(f.unsafety),
2045 abi = AbiSpace(f.abi),
2046 name = it.name.as_ref().unwrap(),
2047 generics = f.generics,
2048 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2057 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2058 t: &clean::Trait) -> fmt::Result {
2059 let mut bounds = String::new();
2060 let mut bounds_plain = String::new();
2061 if !t.bounds.is_empty() {
2062 if !bounds.is_empty() {
2064 bounds_plain.push(' ');
2066 bounds.push_str(": ");
2067 bounds_plain.push_str(": ");
2068 for (i, p) in t.bounds.iter().enumerate() {
2070 bounds.push_str(" + ");
2071 bounds_plain.push_str(" + ");
2073 bounds.push_str(&format!("{}", *p));
2074 bounds_plain.push_str(&format!("{:#}", *p));
2078 // Output the trait definition
2079 write!(w, "<pre class='rust trait'>")?;
2080 render_attributes(w, it)?;
2081 write!(w, "{}{}trait {}{}{}",
2082 VisSpace(&it.visibility),
2083 UnsafetySpace(t.unsafety),
2084 it.name.as_ref().unwrap(),
2088 if !t.generics.where_predicates.is_empty() {
2089 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2094 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2095 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2096 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2097 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2099 if t.items.is_empty() {
2100 write!(w, "{{ }}")?;
2102 // FIXME: we should be using a derived_id for the Anchors here
2106 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2109 if !types.is_empty() && !consts.is_empty() {
2114 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2117 if !consts.is_empty() && !required.is_empty() {
2120 for m in &required {
2122 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2125 if !required.is_empty() && !provided.is_empty() {
2128 for m in &provided {
2130 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2132 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2133 write!(w, ",\n {{ ... }}\n")?;
2136 write!(w, " {{ ... }}\n")?;
2142 write!(w, "</pre>")?;
2144 // Trait documentation
2145 document(w, cx, it)?;
2147 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2149 let name = m.name.as_ref().unwrap();
2150 let item_type = m.type_();
2151 let id = derive_id(format!("{}.{}", item_type, name));
2152 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2153 write!(w, "<h3 id='{id}' class='method'>\
2154 <span id='{ns_id}' class='invisible'><code>",
2157 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2158 write!(w, "</code>")?;
2159 render_stability_since(w, m, t)?;
2160 write!(w, "</span></h3>")?;
2161 document(w, cx, m)?;
2165 if !types.is_empty() {
2167 <h2 id='associated-types'>Associated Types</h2>
2168 <div class='methods'>
2171 trait_item(w, cx, *t, it)?;
2173 write!(w, "</div>")?;
2176 if !consts.is_empty() {
2178 <h2 id='associated-const'>Associated Constants</h2>
2179 <div class='methods'>
2182 trait_item(w, cx, *t, it)?;
2184 write!(w, "</div>")?;
2187 // Output the documentation for each function individually
2188 if !required.is_empty() {
2190 <h2 id='required-methods'>Required Methods</h2>
2191 <div class='methods'>
2193 for m in &required {
2194 trait_item(w, cx, *m, it)?;
2196 write!(w, "</div>")?;
2198 if !provided.is_empty() {
2200 <h2 id='provided-methods'>Provided Methods</h2>
2201 <div class='methods'>
2203 for m in &provided {
2204 trait_item(w, cx, *m, it)?;
2206 write!(w, "</div>")?;
2209 // If there are methods directly on this trait object, render them here.
2210 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2212 let cache = cache();
2214 <h2 id='implementors'>Implementors</h2>
2215 <ul class='item-list' id='implementors-list'>
2217 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2218 // The DefId is for the first Type found with that name. The bool is
2219 // if any Types with the same name but different DefId have been found.
2220 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2221 for implementor in implementors {
2222 match implementor.impl_.for_ {
2223 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2224 clean::BorrowedRef {
2225 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2228 let &mut (prev_did, ref mut has_duplicates) =
2229 implementor_dups.entry(path.last_name()).or_insert((did, false));
2230 if prev_did != did {
2231 *has_duplicates = true;
2238 for implementor in implementors {
2239 write!(w, "<li><code>")?;
2240 // If there's already another implementor that has the same abbridged name, use the
2241 // full path, for example in `std::iter::ExactSizeIterator`
2242 let use_absolute = match implementor.impl_.for_ {
2243 clean::ResolvedPath { ref path, is_generic: false, .. } |
2244 clean::BorrowedRef {
2245 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2247 } => implementor_dups[path.last_name()].1,
2250 fmt_impl_for_trait_page(&implementor.impl_, w, use_absolute)?;
2251 writeln!(w, "</code></li>")?;
2254 write!(w, "</ul>")?;
2255 write!(w, r#"<script type="text/javascript" async
2256 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2258 root_path = vec![".."; cx.current.len()].join("/"),
2259 path = if it.def_id.is_local() {
2260 cx.current.join("/")
2262 let (ref path, _) = cache.external_paths[&it.def_id];
2263 path[..path.len() - 1].join("/")
2265 ty = it.type_().css_class(),
2266 name = *it.name.as_ref().unwrap())?;
2270 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2271 use html::item_type::ItemType::*;
2273 let name = it.name.as_ref().unwrap();
2274 let ty = match it.type_() {
2275 Typedef | AssociatedType => AssociatedType,
2279 let anchor = format!("#{}.{}", ty, name);
2281 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2282 AssocItemLink::Anchor(None) => anchor,
2283 AssocItemLink::GotoSource(did, _) => {
2284 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2289 fn assoc_const(w: &mut fmt::Formatter,
2292 _default: Option<&String>,
2293 link: AssocItemLink) -> fmt::Result {
2294 write!(w, "const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2295 naive_assoc_href(it, link),
2296 it.name.as_ref().unwrap(),
2301 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
2302 bounds: &Vec<clean::TyParamBound>,
2303 default: Option<&clean::Type>,
2304 link: AssocItemLink) -> fmt::Result {
2305 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2306 naive_assoc_href(it, link),
2307 it.name.as_ref().unwrap())?;
2308 if !bounds.is_empty() {
2309 write!(w, ": {}", TyParamBounds(bounds))?
2311 if let Some(default) = default {
2312 write!(w, " = {}", default)?;
2317 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2318 ver: Option<&'a str>,
2319 containing_ver: Option<&'a str>) -> fmt::Result {
2320 if let Some(v) = ver {
2321 if containing_ver != ver && v.len() > 0 {
2322 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2329 fn render_stability_since(w: &mut fmt::Formatter,
2331 containing_item: &clean::Item) -> fmt::Result {
2332 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2335 fn render_assoc_item(w: &mut fmt::Formatter,
2337 link: AssocItemLink,
2338 parent: ItemType) -> fmt::Result {
2339 fn method(w: &mut fmt::Formatter,
2341 unsafety: hir::Unsafety,
2342 constness: hir::Constness,
2344 g: &clean::Generics,
2346 link: AssocItemLink,
2349 let name = meth.name.as_ref().unwrap();
2350 let anchor = format!("#{}.{}", meth.type_(), name);
2351 let href = match link {
2352 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2353 AssocItemLink::Anchor(None) => anchor,
2354 AssocItemLink::GotoSource(did, provided_methods) => {
2355 // We're creating a link from an impl-item to the corresponding
2356 // trait-item and need to map the anchored type accordingly.
2357 let ty = if provided_methods.contains(name) {
2363 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2366 // FIXME(#24111): remove when `const_fn` is stabilized
2367 let vis_constness = if is_nightly_build() {
2370 hir::Constness::NotConst
2372 let mut head_len = format!("{}{}{:#}fn {}{:#}",
2373 ConstnessSpace(vis_constness),
2374 UnsafetySpace(unsafety),
2378 let (indent, end_newline) = if parent == ItemType::Trait {
2384 write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2385 {generics}{decl}{where_clause}",
2386 ConstnessSpace(vis_constness),
2387 UnsafetySpace(unsafety),
2397 where_clause = WhereClause {
2400 end_newline: end_newline,
2404 clean::StrippedItem(..) => Ok(()),
2405 clean::TyMethodItem(ref m) => {
2406 method(w, item, m.unsafety, hir::Constness::NotConst,
2407 m.abi, &m.generics, &m.decl, link, parent)
2409 clean::MethodItem(ref m) => {
2410 method(w, item, m.unsafety, m.constness,
2411 m.abi, &m.generics, &m.decl, link, parent)
2413 clean::AssociatedConstItem(ref ty, ref default) => {
2414 assoc_const(w, item, ty, default.as_ref(), link)
2416 clean::AssociatedTypeItem(ref bounds, ref default) => {
2417 assoc_type(w, item, bounds, default.as_ref(), link)
2419 _ => panic!("render_assoc_item called on non-associated-item")
2423 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2424 s: &clean::Struct) -> fmt::Result {
2425 write!(w, "<pre class='rust struct'>")?;
2426 render_attributes(w, it)?;
2434 write!(w, "</pre>")?;
2436 document(w, cx, it)?;
2437 let mut fields = s.fields.iter().filter_map(|f| {
2439 clean::StructFieldItem(ref ty) => Some((f, ty)),
2443 if let doctree::Plain = s.struct_type {
2444 if fields.peek().is_some() {
2445 write!(w, "<h2 id='fields' class='fields'>Fields</h2>")?;
2446 for (field, ty) in fields {
2447 let id = derive_id(format!("{}.{}",
2448 ItemType::StructField,
2449 field.name.as_ref().unwrap()));
2450 let ns_id = derive_id(format!("{}.{}",
2451 field.name.as_ref().unwrap(),
2452 ItemType::StructField.name_space()));
2453 write!(w, "<span id='{id}' class=\"{item_type}\">
2454 <span id='{ns_id}' class='invisible'>
2455 <code>{name}: {ty}</code>
2457 item_type = ItemType::StructField,
2460 name = field.name.as_ref().unwrap(),
2462 if let Some(stability_class) = field.stability_class() {
2463 write!(w, "<span class='stab {stab}'></span>",
2464 stab = stability_class)?;
2466 document(w, cx, field)?;
2470 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2473 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2474 s: &clean::Union) -> fmt::Result {
2475 write!(w, "<pre class='rust union'>")?;
2476 render_attributes(w, it)?;
2483 write!(w, "</pre>")?;
2485 document(w, cx, it)?;
2486 let mut fields = s.fields.iter().filter_map(|f| {
2488 clean::StructFieldItem(ref ty) => Some((f, ty)),
2492 if fields.peek().is_some() {
2493 write!(w, "<h2 id='fields' class='fields'>Fields</h2>")?;
2494 for (field, ty) in fields {
2495 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2497 shortty = ItemType::StructField,
2498 name = field.name.as_ref().unwrap(),
2500 if let Some(stability_class) = field.stability_class() {
2501 write!(w, "<span class='stab {stab}'></span>",
2502 stab = stability_class)?;
2504 document(w, cx, field)?;
2507 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2510 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2511 e: &clean::Enum) -> fmt::Result {
2512 write!(w, "<pre class='rust enum'>")?;
2513 render_attributes(w, it)?;
2514 write!(w, "{}enum {}{}{}",
2515 VisSpace(&it.visibility),
2516 it.name.as_ref().unwrap(),
2518 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2519 if e.variants.is_empty() && !e.variants_stripped {
2520 write!(w, " {{}}")?;
2522 write!(w, " {{\n")?;
2523 for v in &e.variants {
2525 let name = v.name.as_ref().unwrap();
2527 clean::VariantItem(ref var) => {
2529 clean::VariantKind::CLike => write!(w, "{}", name)?,
2530 clean::VariantKind::Tuple(ref tys) => {
2531 write!(w, "{}(", name)?;
2532 for (i, ty) in tys.iter().enumerate() {
2534 write!(w, ", ")?
2536 write!(w, "{}", *ty)?;
2540 clean::VariantKind::Struct(ref s) => {
2556 if e.variants_stripped {
2557 write!(w, " // some variants omitted\n")?;
2561 write!(w, "</pre>")?;
2563 document(w, cx, it)?;
2564 if !e.variants.is_empty() {
2565 write!(w, "<h2 id='variants' class='variants'>Variants</h2>\n")?;
2566 for variant in &e.variants {
2567 let id = derive_id(format!("{}.{}",
2569 variant.name.as_ref().unwrap()));
2570 let ns_id = derive_id(format!("{}.{}",
2571 variant.name.as_ref().unwrap(),
2572 ItemType::Variant.name_space()));
2573 write!(w, "<span id='{id}' class='variant'>\
2574 <span id='{ns_id}' class='invisible'><code>{name}",
2577 name = variant.name.as_ref().unwrap())?;
2578 if let clean::VariantItem(ref var) = variant.inner {
2579 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2581 for (i, ty) in tys.iter().enumerate() {
2583 write!(w, ", ")?;
2585 write!(w, "{}", *ty)?;
2590 write!(w, "</code></span></span>")?;
2591 document(w, cx, variant)?;
2593 use clean::{Variant, VariantKind};
2594 if let clean::VariantItem(Variant {
2595 kind: VariantKind::Struct(ref s)
2596 }) = variant.inner {
2597 let variant_id = derive_id(format!("{}.{}.fields",
2599 variant.name.as_ref().unwrap()));
2600 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2602 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2603 <table>", name = variant.name.as_ref().unwrap())?;
2604 for field in &s.fields {
2605 use clean::StructFieldItem;
2606 if let StructFieldItem(ref ty) = field.inner {
2607 let id = derive_id(format!("variant.{}.field.{}",
2608 variant.name.as_ref().unwrap(),
2609 field.name.as_ref().unwrap()));
2610 let ns_id = derive_id(format!("{}.{}.{}.{}",
2611 variant.name.as_ref().unwrap(),
2612 ItemType::Variant.name_space(),
2613 field.name.as_ref().unwrap(),
2614 ItemType::StructField.name_space()));
2615 write!(w, "<tr><td \
2617 <span id='{ns_id}' class='invisible'>\
2618 <code>{f}: {t}</code></span></td><td>",
2621 f = field.name.as_ref().unwrap(),
2623 document(w, cx, field)?;
2624 write!(w, "</td></tr>")?;
2627 write!(w, "</table></span>")?;
2629 render_stability_since(w, variant, it)?;
2632 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2636 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2637 let name = attr.name();
2640 Some(format!("{}", name))
2641 } else if let Some(v) = attr.value_str() {
2642 Some(format!("{} = {:?}", name, v.as_str()))
2643 } else if let Some(values) = attr.meta_item_list() {
2644 let display: Vec<_> = values.iter().filter_map(|attr| {
2645 attr.meta_item().and_then(|mi| render_attribute(mi))
2648 if display.len() > 0 {
2649 Some(format!("{}({})", name, display.join(", ")))
2658 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2665 "unsafe_destructor_blind_to_params"
2668 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2669 let mut attrs = String::new();
2671 for attr in &it.attrs.other_attrs {
2672 let name = attr.name().unwrap();
2673 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2676 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2677 attrs.push_str(&format!("#[{}]\n", s));
2680 if attrs.len() > 0 {
2681 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2686 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2687 g: Option<&clean::Generics>,
2688 ty: doctree::StructType,
2689 fields: &[clean::Item],
2691 structhead: bool) -> fmt::Result {
2693 VisSpace(&it.visibility),
2694 if structhead {"struct "} else {""},
2695 it.name.as_ref().unwrap())?;
2696 if let Some(g) = g {
2701 if let Some(g) = g {
2702 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
2704 let mut has_visible_fields = false;
2706 for field in fields {
2707 if let clean::StructFieldItem(ref ty) = field.inner {
2708 write!(w, "\n{} {}{}: {},",
2710 VisSpace(&field.visibility),
2711 field.name.as_ref().unwrap(),
2713 has_visible_fields = true;
2717 if has_visible_fields {
2718 if it.has_stripped_fields().unwrap() {
2719 write!(w, "\n{} // some fields omitted", tab)?;
2721 write!(w, "\n{}", tab)?;
2722 } else if it.has_stripped_fields().unwrap() {
2723 // If there are no visible fields we can just display
2724 // `{ /* fields omitted */ }` to save space.
2725 write!(w, " /* fields omitted */ ")?;
2731 for (i, field) in fields.iter().enumerate() {
2736 clean::StrippedItem(box clean::StructFieldItem(..)) => {
2739 clean::StructFieldItem(ref ty) => {
2740 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
2746 if let Some(g) = g {
2747 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
2752 // Needed for PhantomData.
2753 if let Some(g) = g {
2754 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
2762 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
2763 g: Option<&clean::Generics>,
2764 fields: &[clean::Item],
2766 structhead: bool) -> fmt::Result {
2768 VisSpace(&it.visibility),
2769 if structhead {"union "} else {""},
2770 it.name.as_ref().unwrap())?;
2771 if let Some(g) = g {
2772 write!(w, "{}", g)?;
2773 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
2776 write!(w, " {{\n{}", tab)?;
2777 for field in fields {
2778 if let clean::StructFieldItem(ref ty) = field.inner {
2779 write!(w, " {}{}: {},\n{}",
2780 VisSpace(&field.visibility),
2781 field.name.as_ref().unwrap(),
2787 if it.has_stripped_fields().unwrap() {
2788 write!(w, " // some fields omitted\n{}", tab)?;
2794 #[derive(Copy, Clone)]
2795 enum AssocItemLink<'a> {
2796 Anchor(Option<&'a str>),
2797 GotoSource(DefId, &'a FxHashSet<String>),
2800 impl<'a> AssocItemLink<'a> {
2801 fn anchor(&self, id: &'a String) -> Self {
2803 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
2804 ref other => *other,
2809 enum AssocItemRender<'a> {
2811 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
2814 #[derive(Copy, Clone, PartialEq)]
2817 ForDeref { mut_: bool },
2820 fn render_assoc_items(w: &mut fmt::Formatter,
2822 containing_item: &clean::Item,
2824 what: AssocItemRender) -> fmt::Result {
2826 let v = match c.impls.get(&it) {
2828 None => return Ok(()),
2830 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
2831 i.inner_impl().trait_.is_none()
2833 if !non_trait.is_empty() {
2834 let render_mode = match what {
2835 AssocItemRender::All => {
2836 write!(w, "<h2 id='methods'>Methods</h2>")?;
2839 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
2840 write!(w, "<h2 id='deref-methods'>Methods from \
2841 {}<Target = {}></h2>", trait_, type_)?;
2842 RenderMode::ForDeref { mut_: deref_mut_ }
2845 for i in &non_trait {
2846 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
2847 containing_item.stable_since())?;
2850 if let AssocItemRender::DerefFor { .. } = what {
2853 if !traits.is_empty() {
2854 let deref_impl = traits.iter().find(|t| {
2855 t.inner_impl().trait_.def_id() == c.deref_trait_did
2857 if let Some(impl_) = deref_impl {
2858 let has_deref_mut = traits.iter().find(|t| {
2859 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
2861 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
2863 write!(w, "<h2 id='implementations'>Trait \
2864 Implementations</h2>")?;
2866 let did = i.trait_did().unwrap();
2867 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2868 render_impl(w, cx, i, assoc_link,
2869 RenderMode::Normal, containing_item.stable_since())?;
2875 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
2876 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
2877 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
2878 let target = impl_.inner_impl().items.iter().filter_map(|item| {
2880 clean::TypedefItem(ref t, true) => Some(&t.type_),
2883 }).next().expect("Expected associated type binding");
2884 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
2885 deref_mut_: deref_mut };
2886 if let Some(did) = target.def_id() {
2887 render_assoc_items(w, cx, container_item, did, what)
2889 if let Some(prim) = target.primitive_type() {
2890 if let Some(&did) = cache().primitive_locations.get(&prim) {
2891 render_assoc_items(w, cx, container_item, did, what)?;
2898 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
2899 render_mode: RenderMode, outer_version: Option<&str>) -> fmt::Result {
2900 if render_mode == RenderMode::Normal {
2901 write!(w, "<h3 class='impl'><span class='in-band'><code>{}</code>", i.inner_impl())?;
2902 write!(w, "</span><span class='out-of-band'>")?;
2903 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
2904 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
2905 write!(w, "<div class='ghost'></div>")?;
2906 render_stability_since_raw(w, since, outer_version)?;
2907 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2908 l, "goto source code")?;
2910 render_stability_since_raw(w, since, outer_version)?;
2912 write!(w, "</span>")?;
2913 write!(w, "</h3>\n")?;
2914 if let Some(ref dox) = i.impl_item.doc_value() {
2915 write!(w, "<div class='docblock'>{}</div>", Markdown(dox, cx.render_type))?;
2919 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2920 link: AssocItemLink, render_mode: RenderMode,
2921 is_default_item: bool, outer_version: Option<&str>,
2922 trait_: Option<&clean::Trait>) -> fmt::Result {
2923 let item_type = item.type_();
2924 let name = item.name.as_ref().unwrap();
2926 let render_method_item: bool = match render_mode {
2927 RenderMode::Normal => true,
2928 RenderMode::ForDeref { mut_: deref_mut_ } => {
2929 let self_type_opt = match item.inner {
2930 clean::MethodItem(ref method) => method.decl.self_type(),
2931 clean::TyMethodItem(ref method) => method.decl.self_type(),
2935 if let Some(self_ty) = self_type_opt {
2936 let by_mut_ref = match self_ty {
2937 SelfTy::SelfBorrowed(_lifetime, mutability) => {
2938 mutability == Mutability::Mutable
2940 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
2941 mutability == Mutability::Mutable
2946 deref_mut_ || !by_mut_ref
2954 clean::MethodItem(..) | clean::TyMethodItem(..) => {
2955 // Only render when the method is not static or we allow static methods
2956 if render_method_item {
2957 let id = derive_id(format!("{}.{}", item_type, name));
2958 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2959 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
2960 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
2961 write!(w, "<code>")?;
2962 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
2963 write!(w, "</code>")?;
2964 render_stability_since_raw(w, item.stable_since(), outer_version)?;
2965 write!(w, "</span></h4>\n")?;
2968 clean::TypedefItem(ref tydef, _) => {
2969 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
2970 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2971 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
2972 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2973 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
2974 write!(w, "</code></span></h4>\n")?;
2976 clean::AssociatedConstItem(ref ty, ref default) => {
2977 let id = derive_id(format!("{}.{}", item_type, name));
2978 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2979 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
2980 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2981 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
2982 write!(w, "</code></span></h4>\n")?;
2984 clean::ConstantItem(ref c) => {
2985 let id = derive_id(format!("{}.{}", item_type, name));
2986 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2987 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
2988 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2989 assoc_const(w, item, &c.type_, Some(&c.expr), link.anchor(&id))?;
2990 write!(w, "</code></span></h4>\n")?;
2992 clean::AssociatedTypeItem(ref bounds, ref default) => {
2993 let id = derive_id(format!("{}.{}", item_type, name));
2994 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2995 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
2996 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2997 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
2998 write!(w, "</code></span></h4>\n")?;
3000 clean::StrippedItem(..) => return Ok(()),
3001 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3004 if render_method_item || render_mode == RenderMode::Normal {
3005 if !is_default_item {
3006 if let Some(t) = trait_ {
3007 // The trait item may have been stripped so we might not
3008 // find any documentation or stability for it.
3009 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3010 // We need the stability of the item from the trait
3011 // because impls can't have a stability.
3012 document_stability(w, cx, it)?;
3013 if get_doc_value(item).is_some() {
3014 document_full(w, item, cx.render_type)?;
3016 // In case the item isn't documented,
3017 // provide short documentation from the trait.
3018 document_short(w, it, link, cx.render_type)?;
3022 document(w, cx, item)?;
3025 document_stability(w, cx, item)?;
3026 document_short(w, item, link, cx.render_type)?;
3032 let traits = &cache().traits;
3033 let trait_ = i.trait_did().and_then(|did| traits.get(&did));
3035 write!(w, "<div class='impl-items'>")?;
3036 for trait_item in &i.inner_impl().items {
3037 doc_impl_item(w, cx, trait_item, link, render_mode,
3038 false, outer_version, trait_)?;
3041 fn render_default_items(w: &mut fmt::Formatter,
3045 render_mode: RenderMode,
3046 outer_version: Option<&str>) -> fmt::Result {
3047 for trait_item in &t.items {
3048 let n = trait_item.name.clone();
3049 if i.items.iter().find(|m| m.name == n).is_some() {
3052 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3053 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3055 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3056 outer_version, None)?;
3061 // If we've implemented a trait, then also emit documentation for all
3062 // default items which weren't overridden in the implementation block.
3063 if let Some(t) = trait_ {
3064 render_default_items(w, cx, t, &i.inner_impl(), render_mode, outer_version)?;
3066 write!(w, "</div>")?;
3070 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3071 t: &clean::Typedef) -> fmt::Result {
3072 write!(w, "<pre class='rust typedef'>")?;
3073 render_attributes(w, it)?;
3074 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3075 it.name.as_ref().unwrap(),
3077 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3083 impl<'a> fmt::Display for Sidebar<'a> {
3084 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3087 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3089 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3090 || it.is_enum() || it.is_mod()
3092 write!(fmt, "<p class='location'>")?;
3094 clean::StructItem(..) => write!(fmt, "Struct ")?,
3095 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3096 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3097 clean::UnionItem(..) => write!(fmt, "Union ")?,
3098 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3099 clean::ModuleItem(..) => if it.is_crate() {
3100 write!(fmt, "Crate ")?;
3102 write!(fmt, "Module ")?;
3106 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3107 write!(fmt, "</p>")?;
3110 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3111 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3112 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3113 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3114 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3115 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3120 // The sidebar is designed to display sibling functions, modules and
3121 // other miscellaneous information. since there are lots of sibling
3122 // items (and that causes quadratic growth in large modules),
3123 // we refactor common parts into a shared JavaScript file per module.
3124 // still, we don't move everything into JS because we want to preserve
3125 // as much HTML as possible in order to allow non-JS-enabled browsers
3126 // to navigate the documentation (though slightly inefficiently).
3128 write!(fmt, "<p class='location'>")?;
3129 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3131 write!(fmt, "::<wbr>")?;
3133 write!(fmt, "<a href='{}index.html'>{}</a>",
3134 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3137 write!(fmt, "</p>")?;
3139 // Sidebar refers to the enclosing module, not this module.
3140 let relpath = if it.is_mod() { "../" } else { "" };
3142 "<script>window.sidebarCurrent = {{\
3147 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3148 ty = it.type_().css_class(),
3151 // There is no sidebar-items.js beyond the crate root path
3152 // FIXME maybe dynamic crate loading can be merged here
3154 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3162 fn sidebar_assoc_items(it: &clean::Item) -> String {
3163 let mut out = String::new();
3165 if let Some(v) = c.impls.get(&it.def_id) {
3166 if v.iter().any(|i| i.inner_impl().trait_.is_none()) {
3167 out.push_str("<li><a href=\"#methods\">Methods</a></li>");
3170 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3171 if let Some(impl_) = v.iter()
3172 .filter(|i| i.inner_impl().trait_.is_some())
3173 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3174 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3176 clean::TypedefItem(ref t, true) => Some(&t.type_),
3180 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3181 c.primitive_locations.get(&prim).cloned()
3182 })).and_then(|did| c.impls.get(&did));
3183 if inner_impl.is_some() {
3184 out.push_str("<li><a href=\"#deref-methods\">");
3185 out.push_str(&format!("Methods from {:#}<Target={:#}>",
3186 impl_.inner_impl().trait_.as_ref().unwrap(),
3188 out.push_str("</a></li>");
3192 out.push_str("<li><a href=\"#implementations\">Trait Implementations</a></li>");
3199 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3200 s: &clean::Struct) -> fmt::Result {
3201 let mut sidebar = String::new();
3204 .any(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false }) {
3205 if let doctree::Plain = s.struct_type {
3206 sidebar.push_str("<li><a href=\"#fields\">Fields</a></li>");
3210 sidebar.push_str(&sidebar_assoc_items(it));
3212 if !sidebar.is_empty() {
3213 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3218 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3219 t: &clean::Trait) -> fmt::Result {
3220 let mut sidebar = String::new();
3222 let has_types = t.items.iter().any(|m| m.is_associated_type());
3223 let has_consts = t.items.iter().any(|m| m.is_associated_const());
3224 let has_required = t.items.iter().any(|m| m.is_ty_method());
3225 let has_provided = t.items.iter().any(|m| m.is_method());
3228 sidebar.push_str("<li><a href=\"#associated-types\">Associated Types</a></li>");
3231 sidebar.push_str("<li><a href=\"#associated-const\">Associated Constants</a></li>");
3234 sidebar.push_str("<li><a href=\"#required-methods\">Required Methods</a></li>");
3237 sidebar.push_str("<li><a href=\"#provided-methods\">Provided Methods</a></li>");
3240 sidebar.push_str(&sidebar_assoc_items(it));
3242 sidebar.push_str("<li><a href=\"#implementors\">Implementors</a></li>");
3244 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)
3247 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3248 _p: &clean::PrimitiveType) -> fmt::Result {
3249 let sidebar = sidebar_assoc_items(it);
3251 if !sidebar.is_empty() {
3252 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3257 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3258 u: &clean::Union) -> fmt::Result {
3259 let mut sidebar = String::new();
3262 .any(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false }) {
3263 sidebar.push_str("<li><a href=\"#fields\">Fields</a></li>");
3266 sidebar.push_str(&sidebar_assoc_items(it));
3268 if !sidebar.is_empty() {
3269 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3274 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3275 e: &clean::Enum) -> fmt::Result {
3276 let mut sidebar = String::new();
3278 if !e.variants.is_empty() {
3279 sidebar.push_str("<li><a href=\"#variants\">Variants</a></li>");
3282 sidebar.push_str(&sidebar_assoc_items(it));
3284 if !sidebar.is_empty() {
3285 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3290 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3291 items: &[clean::Item]) -> fmt::Result {
3292 let mut sidebar = String::new();
3294 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3295 it.type_() == ItemType::Import) {
3296 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3298 name = "Reexports"));
3301 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3302 // to print its headings
3303 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3304 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3305 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3306 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3307 ItemType::AssociatedType, ItemType::AssociatedConst] {
3308 if items.iter().any(|it| {
3309 if let clean::DefaultImplItem(..) = it.inner {
3312 !maybe_ignore_item(it) && !it.is_stripped() && it.type_() == myty
3315 let (short, name) = match myty {
3316 ItemType::ExternCrate |
3317 ItemType::Import => ("reexports", "Reexports"),
3318 ItemType::Module => ("modules", "Modules"),
3319 ItemType::Struct => ("structs", "Structs"),
3320 ItemType::Union => ("unions", "Unions"),
3321 ItemType::Enum => ("enums", "Enums"),
3322 ItemType::Function => ("functions", "Functions"),
3323 ItemType::Typedef => ("types", "Type Definitions"),
3324 ItemType::Static => ("statics", "Statics"),
3325 ItemType::Constant => ("constants", "Constants"),
3326 ItemType::Trait => ("traits", "Traits"),
3327 ItemType::Impl => ("impls", "Implementations"),
3328 ItemType::TyMethod => ("tymethods", "Type Methods"),
3329 ItemType::Method => ("methods", "Methods"),
3330 ItemType::StructField => ("fields", "Struct Fields"),
3331 ItemType::Variant => ("variants", "Variants"),
3332 ItemType::Macro => ("macros", "Macros"),
3333 ItemType::Primitive => ("primitives", "Primitive Types"),
3334 ItemType::AssociatedType => ("associated-types", "Associated Types"),
3335 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
3337 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3343 if !sidebar.is_empty() {
3344 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3349 impl<'a> fmt::Display for Source<'a> {
3350 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3351 let Source(s) = *self;
3352 let lines = s.lines().count();
3354 let mut tmp = lines;
3359 write!(fmt, "<pre class=\"line-numbers\">")?;
3360 for i in 1..lines + 1 {
3361 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
3363 write!(fmt, "</pre>")?;
3364 write!(fmt, "{}", highlight::render_with_highlighting(s, None, None, None))?;
3369 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3370 t: &clean::Macro) -> fmt::Result {
3371 w.write_str(&highlight::render_with_highlighting(&t.source,
3378 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
3380 _p: &clean::PrimitiveType) -> fmt::Result {
3381 document(w, cx, it)?;
3382 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3385 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
3387 fn make_item_keywords(it: &clean::Item) -> String {
3388 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
3391 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
3392 let decl = match item.inner {
3393 clean::FunctionItem(ref f) => &f.decl,
3394 clean::MethodItem(ref m) => &m.decl,
3395 clean::TyMethodItem(ref m) => &m.decl,
3399 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
3400 let output = match decl.output {
3401 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
3405 Some(IndexItemFunctionType { inputs: inputs, output: output })
3408 fn get_index_type(clean_type: &clean::Type) -> Type {
3409 Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
3412 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
3414 clean::ResolvedPath { ref path, .. } => {
3415 let segments = &path.segments;
3416 Some(segments[segments.len() - 1].name.clone())
3418 clean::Generic(ref s) => Some(s.clone()),
3419 clean::Primitive(ref p) => Some(format!("{:?}", p)),
3420 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
3421 // FIXME: add all from clean::Type.
3426 pub fn cache() -> Arc<Cache> {
3427 CACHE_KEY.with(|c| c.borrow().clone())
3432 fn test_unique_id() {
3433 let input = ["foo", "examples", "examples", "method.into_iter","examples",
3434 "method.into_iter", "foo", "main", "search", "methods",
3435 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
3436 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
3437 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
3438 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
3441 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
3442 assert_eq!(&actual[..], expected);
3451 fn test_name_key() {
3452 assert_eq!(name_key("0"), ("", 0, 1));
3453 assert_eq!(name_key("123"), ("", 123, 0));
3454 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
3455 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
3456 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
3457 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
3458 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
3459 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
3464 fn test_name_sorting() {
3465 let names = ["Apple",
3467 "Fruit", "Fruit0", "Fruit00",
3468 "Fruit1", "Fruit01",
3469 "Fruit2", "Fruit02",
3473 let mut sorted = names.to_owned();
3474 sorted.sort_by_key(|&s| name_key(s));
3475 assert_eq!(names, sorted);