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};
80 /// A pair of name and its optional document.
81 pub type NameDoc = (String, Option<String>);
83 /// Major driving force in all rustdoc rendering. This contains information
84 /// about where in the tree-like hierarchy rendering is occurring and controls
85 /// how the current page is being rendered.
87 /// It is intended that this context is a lightweight object which can be fairly
88 /// easily cloned because it is cloned per work-job (about once per item in the
92 /// Current hierarchy of components leading down to what's currently being
94 pub current: Vec<String>,
95 /// The current destination folder of where HTML artifacts should be placed.
96 /// This changes as the context descends into the module hierarchy.
98 /// A flag, which when `true`, will render pages which redirect to the
99 /// real location of an item. This is used to allow external links to
100 /// publicly reused items to redirect to the right location.
101 pub render_redirect_pages: bool,
102 pub shared: Arc<SharedContext>,
103 pub render_type: RenderType,
106 pub struct SharedContext {
107 /// The path to the crate root source minus the file name.
108 /// Used for simplifying paths to the highlighted source code files.
109 pub src_root: PathBuf,
110 /// This describes the layout of each page, and is not modified after
111 /// creation of the context (contains info like the favicon and added html).
112 pub layout: layout::Layout,
113 /// This flag indicates whether [src] links should be generated or not. If
114 /// the source files are present in the html rendering, then this will be
116 pub include_sources: bool,
117 /// The local file sources we've emitted and their respective url-paths.
118 pub local_sources: FxHashMap<PathBuf, String>,
119 /// All the passes that were run on this crate.
120 pub passes: FxHashSet<String>,
121 /// The base-URL of the issue tracker for when an item has been tagged with
123 pub issue_tracker_base_url: Option<String>,
124 /// The given user css file which allow to customize the generated
125 /// documentation theme.
126 pub css_file_extension: Option<PathBuf>,
129 /// Indicates where an external crate can be found.
130 pub enum ExternalLocation {
131 /// Remote URL root of the external crate
133 /// This external crate can be found in the local doc/ folder
135 /// The external crate could not be found.
139 /// Metadata about an implementor of a trait.
140 pub struct Implementor {
142 pub stability: Option<clean::Stability>,
143 pub impl_: clean::Impl,
146 /// Metadata about implementations for a type.
149 pub impl_item: clean::Item,
153 fn inner_impl(&self) -> &clean::Impl {
154 match self.impl_item.inner {
155 clean::ImplItem(ref impl_) => impl_,
156 _ => panic!("non-impl item found in impl")
160 fn trait_did(&self) -> Option<DefId> {
161 self.inner_impl().trait_.def_id()
171 impl error::Error for Error {
172 fn description(&self) -> &str {
173 self.error.description()
177 impl Display for Error {
178 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
179 write!(f, "\"{}\": {}", self.file.display(), self.error)
184 pub fn new(e: io::Error, file: &Path) -> Error {
186 file: file.to_path_buf(),
192 macro_rules! try_err {
193 ($e:expr, $file:expr) => ({
196 Err(e) => return Err(Error::new(e, $file)),
201 /// This cache is used to store information about the `clean::Crate` being
202 /// rendered in order to provide more useful documentation. This contains
203 /// information like all implementors of a trait, all traits a type implements,
204 /// documentation for all known traits, etc.
206 /// This structure purposefully does not implement `Clone` because it's intended
207 /// to be a fairly large and expensive structure to clone. Instead this adheres
208 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
209 /// rendering threads.
212 /// Mapping of typaram ids to the name of the type parameter. This is used
213 /// when pretty-printing a type (so pretty printing doesn't have to
214 /// painfully maintain a context like this)
215 pub typarams: FxHashMap<DefId, String>,
217 /// Maps a type id to all known implementations for that type. This is only
218 /// recognized for intra-crate `ResolvedPath` types, and is used to print
219 /// out extra documentation on the page of an enum/struct.
221 /// The values of the map are a list of implementations and documentation
222 /// found on that implementation.
223 pub impls: FxHashMap<DefId, Vec<Impl>>,
225 /// Maintains a mapping of local crate node ids to the fully qualified name
226 /// and "short type description" of that node. This is used when generating
227 /// URLs when a type is being linked to. External paths are not located in
228 /// this map because the `External` type itself has all the information
230 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
232 /// Similar to `paths`, but only holds external paths. This is only used for
233 /// generating explicit hyperlinks to other crates.
234 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
236 /// This map contains information about all known traits of this crate.
237 /// Implementations of a crate should inherit the documentation of the
238 /// parent trait if no extra documentation is specified, and default methods
239 /// should show up in documentation about trait implementations.
240 pub traits: FxHashMap<DefId, clean::Trait>,
242 /// When rendering traits, it's often useful to be able to list all
243 /// implementors of the trait, and this mapping is exactly, that: a mapping
244 /// of trait ids to the list of known implementors of the trait
245 pub implementors: FxHashMap<DefId, Vec<Implementor>>,
247 /// Cache of where external crate documentation can be found.
248 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
250 /// Cache of where documentation for primitives can be found.
251 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
253 // Note that external items for which `doc(hidden)` applies to are shown as
254 // non-reachable while local items aren't. This is because we're reusing
255 // the access levels from crateanalysis.
256 pub access_levels: Arc<AccessLevels<DefId>>,
258 // Private fields only used when initially crawling a crate to build a cache
261 parent_stack: Vec<DefId>,
262 parent_is_trait_impl: bool,
263 search_index: Vec<IndexItem>,
265 deref_trait_did: Option<DefId>,
266 deref_mut_trait_did: Option<DefId>,
267 owned_box_did: Option<DefId>,
269 // In rare case where a structure is defined in one module but implemented
270 // in another, if the implementing module is parsed before defining module,
271 // then the fully qualified name of the structure isn't presented in `paths`
272 // yet when its implementation methods are being indexed. Caches such methods
273 // and their parent id here and indexes them at the end of crate parsing.
274 orphan_impl_items: Vec<(DefId, clean::Item)>,
277 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
278 /// Later on moved into `CACHE_KEY`.
280 pub struct RenderInfo {
281 pub inlined: FxHashSet<DefId>,
282 pub external_paths: ::core::ExternalPaths,
283 pub external_typarams: FxHashMap<DefId, String>,
284 pub deref_trait_did: Option<DefId>,
285 pub deref_mut_trait_did: Option<DefId>,
286 pub owned_box_did: Option<DefId>,
289 /// Helper struct to render all source code to HTML pages
290 struct SourceCollector<'a> {
291 scx: &'a mut SharedContext,
293 /// Root destination to place all HTML output into
297 /// Wrapper struct to render the source code of a file. This will do things like
298 /// adding line numbers to the left-hand side.
299 struct Source<'a>(&'a str);
301 // Helper structs for rendering items/sidebars and carrying along contextual
304 #[derive(Copy, Clone)]
307 item: &'a clean::Item,
310 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
312 /// Struct representing one entry in the JS search index. These are all emitted
313 /// by hand to a large JS file at the end of cache-creation.
319 parent: Option<DefId>,
320 parent_idx: Option<usize>,
321 search_type: Option<IndexItemFunctionType>,
324 impl ToJson for IndexItem {
325 fn to_json(&self) -> Json {
326 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
328 let mut data = Vec::with_capacity(6);
329 data.push((self.ty as usize).to_json());
330 data.push(self.name.to_json());
331 data.push(self.path.to_json());
332 data.push(self.desc.to_json());
333 data.push(self.parent_idx.to_json());
334 data.push(self.search_type.to_json());
340 /// A type used for the search index.
342 name: Option<String>,
345 impl ToJson for Type {
346 fn to_json(&self) -> Json {
349 let mut data = BTreeMap::new();
350 data.insert("name".to_owned(), name.to_json());
358 /// Full type of functions/methods in the search index.
359 struct IndexItemFunctionType {
364 impl ToJson for IndexItemFunctionType {
365 fn to_json(&self) -> Json {
366 // If we couldn't figure out a type, just write `null`.
367 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
370 let mut data = BTreeMap::new();
371 data.insert("inputs".to_owned(), self.inputs.to_json());
372 data.insert("output".to_owned(), self.output.to_json());
378 // TLS keys used to carry information around during rendering.
380 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
381 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
382 RefCell::new(Vec::new()));
383 thread_local!(static USED_ID_MAP: RefCell<FxHashMap<String, usize>> =
384 RefCell::new(init_ids()));
386 fn init_ids() -> FxHashMap<String, usize> {
402 ].into_iter().map(|id| (String::from(*id), 1)).collect()
405 /// This method resets the local table of used ID attributes. This is typically
406 /// used at the beginning of rendering an entire HTML page to reset from the
407 /// previous state (if any).
408 pub fn reset_ids(embedded: bool) {
409 USED_ID_MAP.with(|s| {
410 *s.borrow_mut() = if embedded {
418 pub fn derive_id(candidate: String) -> String {
419 USED_ID_MAP.with(|map| {
420 let id = match map.borrow_mut().get_mut(&candidate) {
423 let id = format!("{}-{}", candidate, *a);
429 map.borrow_mut().insert(id.clone(), 1);
434 /// Generates the documentation for `crate` into the directory `dst`
435 pub fn run(mut krate: clean::Crate,
436 external_html: &ExternalHtml,
437 playground_url: Option<String>,
439 passes: FxHashSet<String>,
440 css_file_extension: Option<PathBuf>,
441 renderinfo: RenderInfo,
442 render_type: RenderType) -> Result<(), Error> {
443 let src_root = match krate.src.parent() {
444 Some(p) => p.to_path_buf(),
445 None => PathBuf::new(),
447 let mut scx = SharedContext {
450 include_sources: true,
451 local_sources: FxHashMap(),
452 issue_tracker_base_url: None,
453 layout: layout::Layout {
454 logo: "".to_string(),
455 favicon: "".to_string(),
456 external_html: external_html.clone(),
457 krate: krate.name.clone(),
459 css_file_extension: css_file_extension.clone(),
462 // If user passed in `--playground-url` arg, we fill in crate name here
463 if let Some(url) = playground_url {
464 markdown::PLAYGROUND.with(|slot| {
465 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
469 // Crawl the crate attributes looking for attributes which control how we're
470 // going to emit HTML
471 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
472 for attr in attrs.lists("doc") {
473 let name = attr.name().map(|s| s.as_str());
474 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
475 (Some("html_favicon_url"), Some(s)) => {
476 scx.layout.favicon = s.to_string();
478 (Some("html_logo_url"), Some(s)) => {
479 scx.layout.logo = s.to_string();
481 (Some("html_playground_url"), Some(s)) => {
482 markdown::PLAYGROUND.with(|slot| {
483 let name = krate.name.clone();
484 *slot.borrow_mut() = Some((Some(name), s.to_string()));
487 (Some("issue_tracker_base_url"), Some(s)) => {
488 scx.issue_tracker_base_url = Some(s.to_string());
490 (Some("html_no_source"), None) if attr.is_word() => {
491 scx.include_sources = false;
497 try_err!(fs::create_dir_all(&dst), &dst);
498 krate = render_sources(&dst, &mut scx, krate)?;
502 render_redirect_pages: false,
503 shared: Arc::new(scx),
507 // Crawl the crate to build various caches used for the output
517 let external_paths = external_paths.into_iter()
518 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
521 let mut cache = Cache {
525 implementors: FxHashMap(),
527 parent_stack: Vec::new(),
528 search_index: Vec::new(),
529 parent_is_trait_impl: false,
530 extern_locations: FxHashMap(),
531 primitive_locations: FxHashMap(),
533 access_levels: krate.access_levels.clone(),
534 orphan_impl_items: Vec::new(),
535 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
539 typarams: external_typarams,
542 // Cache where all our extern crates are located
543 for &(n, ref e) in &krate.externs {
544 let src_root = match Path::new(&e.src).parent() {
545 Some(p) => p.to_path_buf(),
546 None => PathBuf::new(),
548 cache.extern_locations.insert(n, (e.name.clone(), src_root,
549 extern_location(e, &cx.dst)));
551 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
552 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
555 // Cache where all known primitives have their documentation located.
557 // Favor linking to as local extern as possible, so iterate all crates in
558 // reverse topological order.
559 for &(_, ref e) in krate.externs.iter().rev() {
560 for &(def_id, prim, _) in &e.primitives {
561 cache.primitive_locations.insert(prim, def_id);
564 for &(def_id, prim, _) in &krate.primitives {
565 cache.primitive_locations.insert(prim, def_id);
568 cache.stack.push(krate.name.clone());
569 krate = cache.fold_crate(krate);
571 // Build our search index
572 let index = build_index(&krate, &mut cache);
574 // Freeze the cache now that the index has been built. Put an Arc into TLS
575 // for future parallelization opportunities
576 let cache = Arc::new(cache);
577 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
578 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
580 write_shared(&cx, &krate, &*cache, index)?;
582 // And finally render the whole crate's documentation
586 /// Build the search index from the collected metadata
587 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
588 let mut nodeid_to_pathid = FxHashMap();
589 let mut crate_items = Vec::with_capacity(cache.search_index.len());
590 let mut crate_paths = Vec::<Json>::new();
592 let Cache { ref mut search_index,
593 ref orphan_impl_items,
594 ref mut paths, .. } = *cache;
596 // Attach all orphan items to the type's definition if the type
597 // has since been learned.
598 for &(did, ref item) in orphan_impl_items {
599 if let Some(&(ref fqp, _)) = paths.get(&did) {
600 search_index.push(IndexItem {
602 name: item.name.clone().unwrap(),
603 path: fqp[..fqp.len() - 1].join("::"),
604 desc: plain_summary_line(item.doc_value()),
607 search_type: get_index_search_type(&item),
612 // Reduce `NodeId` in paths into smaller sequential numbers,
613 // and prune the paths that do not appear in the index.
614 let mut lastpath = String::new();
615 let mut lastpathid = 0usize;
617 for item in search_index {
618 item.parent_idx = item.parent.map(|nodeid| {
619 if nodeid_to_pathid.contains_key(&nodeid) {
620 *nodeid_to_pathid.get(&nodeid).unwrap()
622 let pathid = lastpathid;
623 nodeid_to_pathid.insert(nodeid, pathid);
626 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
627 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
632 // Omit the parent path if it is same to that of the prior item.
633 if lastpath == item.path {
636 lastpath = item.path.clone();
638 crate_items.push(item.to_json());
641 let crate_doc = krate.module.as_ref().map(|module| {
642 plain_summary_line(module.doc_value())
643 }).unwrap_or(String::new());
645 let mut crate_data = BTreeMap::new();
646 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
647 crate_data.insert("items".to_owned(), Json::Array(crate_items));
648 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
650 // Collect the index into a string
651 format!("searchIndex[{}] = {};",
652 as_json(&krate.name),
653 Json::Object(crate_data))
656 fn write_shared(cx: &Context,
657 krate: &clean::Crate,
659 search_index: String) -> Result<(), Error> {
660 // Write out the shared files. Note that these are shared among all rustdoc
661 // docs placed in the output directory, so this needs to be a synchronized
662 // operation with respect to all other rustdocs running around.
663 try_err!(fs::create_dir_all(&cx.dst), &cx.dst);
664 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
666 // Add all the static files. These may already exist, but we just
667 // overwrite them anyway to make sure that they're fresh and up-to-date.
669 write(cx.dst.join("main.js"),
670 include_bytes!("static/main.js"))?;
671 write(cx.dst.join("rustdoc.css"),
672 include_bytes!("static/rustdoc.css"))?;
673 write(cx.dst.join("main.css"),
674 include_bytes!("static/styles/main.css"))?;
675 if let Some(ref css) = cx.shared.css_file_extension {
676 let mut content = String::new();
677 let css = css.as_path();
678 let mut f = try_err!(File::open(css), css);
680 try_err!(f.read_to_string(&mut content), css);
681 let css = cx.dst.join("theme.css");
682 let css = css.as_path();
683 let mut f = try_err!(File::create(css), css);
684 try_err!(write!(f, "{}", &content), css);
686 write(cx.dst.join("normalize.css"),
687 include_bytes!("static/normalize.css"))?;
688 write(cx.dst.join("FiraSans-Regular.woff"),
689 include_bytes!("static/FiraSans-Regular.woff"))?;
690 write(cx.dst.join("FiraSans-Medium.woff"),
691 include_bytes!("static/FiraSans-Medium.woff"))?;
692 write(cx.dst.join("FiraSans-LICENSE.txt"),
693 include_bytes!("static/FiraSans-LICENSE.txt"))?;
694 write(cx.dst.join("Heuristica-Italic.woff"),
695 include_bytes!("static/Heuristica-Italic.woff"))?;
696 write(cx.dst.join("Heuristica-LICENSE.txt"),
697 include_bytes!("static/Heuristica-LICENSE.txt"))?;
698 write(cx.dst.join("SourceSerifPro-Regular.woff"),
699 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
700 write(cx.dst.join("SourceSerifPro-Bold.woff"),
701 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
702 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
703 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
704 write(cx.dst.join("SourceCodePro-Regular.woff"),
705 include_bytes!("static/SourceCodePro-Regular.woff"))?;
706 write(cx.dst.join("SourceCodePro-Semibold.woff"),
707 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
708 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
709 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
710 write(cx.dst.join("LICENSE-MIT.txt"),
711 include_bytes!("static/LICENSE-MIT.txt"))?;
712 write(cx.dst.join("LICENSE-APACHE.txt"),
713 include_bytes!("static/LICENSE-APACHE.txt"))?;
714 write(cx.dst.join("COPYRIGHT.txt"),
715 include_bytes!("static/COPYRIGHT.txt"))?;
717 fn collect(path: &Path, krate: &str,
718 key: &str) -> io::Result<Vec<String>> {
719 let mut ret = Vec::new();
721 for line in BufReader::new(File::open(path)?).lines() {
723 if !line.starts_with(key) {
726 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
729 ret.push(line.to_string());
735 // Update the search index
736 let dst = cx.dst.join("search-index.js");
737 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
738 all_indexes.push(search_index);
739 // Sort the indexes by crate so the file will be generated identically even
740 // with rustdoc running in parallel.
742 let mut w = try_err!(File::create(&dst), &dst);
743 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
744 for index in &all_indexes {
745 try_err!(writeln!(&mut w, "{}", *index), &dst);
747 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
749 // Update the list of all implementors for traits
750 let dst = cx.dst.join("implementors");
751 for (&did, imps) in &cache.implementors {
752 // Private modules can leak through to this phase of rustdoc, which
753 // could contain implementations for otherwise private types. In some
754 // rare cases we could find an implementation for an item which wasn't
755 // indexed, so we just skip this step in that case.
757 // FIXME: this is a vague explanation for why this can't be a `get`, in
758 // theory it should be...
759 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
761 None => match cache.external_paths.get(&did) {
767 let mut have_impls = false;
768 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
770 // If the trait and implementation are in the same crate, then
771 // there's no need to emit information about it (there's inlining
772 // going on). If they're in different crates then the crate defining
773 // the trait will be interested in our implementation.
774 if imp.def_id.krate == did.krate { continue }
775 // If the implementation is from another crate then that crate
777 if !imp.def_id.is_local() { continue }
779 write!(implementors, "{},", as_json(&imp.impl_.to_string())).unwrap();
781 implementors.push_str("];");
783 // Only create a js file if we have impls to add to it. If the trait is
784 // documented locally though we always create the file to avoid dead
786 if !have_impls && !cache.paths.contains_key(&did) {
790 let mut mydst = dst.clone();
791 for part in &remote_path[..remote_path.len() - 1] {
794 try_err!(fs::create_dir_all(&mydst), &mydst);
795 mydst.push(&format!("{}.{}.js",
796 remote_item_type.css_class(),
797 remote_path[remote_path.len() - 1]));
799 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
800 all_implementors.push(implementors);
801 // Sort the implementors by crate so the file will be generated
802 // identically even with rustdoc running in parallel.
803 all_implementors.sort();
805 let mut f = try_err!(File::create(&mydst), &mydst);
806 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
807 for implementor in &all_implementors {
808 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
810 try_err!(writeln!(&mut f, "{}", r"
811 if (window.register_implementors) {
812 window.register_implementors(implementors);
814 window.pending_implementors = implementors;
817 try_err!(writeln!(&mut f, r"}})()"), &mydst);
822 fn render_sources(dst: &Path, scx: &mut SharedContext,
823 krate: clean::Crate) -> Result<clean::Crate, Error> {
824 info!("emitting source files");
825 let dst = dst.join("src").join(&krate.name);
826 try_err!(fs::create_dir_all(&dst), &dst);
827 let mut folder = SourceCollector {
831 Ok(folder.fold_crate(krate))
834 /// Writes the entire contents of a string to a destination, not attempting to
835 /// catch any errors.
836 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
837 Ok(try_err!(try_err!(File::create(&dst), &dst).write_all(contents), &dst))
840 /// Takes a path to a source file and cleans the path to it. This canonicalizes
841 /// things like ".." to components which preserve the "top down" hierarchy of a
842 /// static HTML tree. Each component in the cleaned path will be passed as an
843 /// argument to `f`. The very last component of the path (ie the file name) will
844 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
845 // FIXME (#9639): The closure should deal with &[u8] instead of &str
846 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
847 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
850 // make it relative, if possible
851 let p = p.strip_prefix(src_root).unwrap_or(p);
853 let mut iter = p.components().peekable();
855 while let Some(c) = iter.next() {
856 if !keep_filename && iter.peek().is_none() {
861 Component::ParentDir => f("up"),
862 Component::Normal(c) => f(c.to_str().unwrap()),
868 /// Attempts to find where an external crate is located, given that we're
869 /// rendering in to the specified source destination.
870 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
871 // See if there's documentation generated into the local directory
872 let local_location = dst.join(&e.name);
873 if local_location.is_dir() {
877 // Failing that, see if there's an attribute specifying where to find this
880 .filter(|a| a.check_name("html_root_url"))
881 .filter_map(|a| a.value_str())
883 let mut url = url.to_string();
884 if !url.ends_with("/") {
888 }).next().unwrap_or(Unknown) // Well, at least we tried.
891 impl<'a> DocFolder for SourceCollector<'a> {
892 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
893 // If we're including source files, and we haven't seen this file yet,
894 // then we need to render it out to the filesystem.
895 if self.scx.include_sources
896 // skip all invalid spans
897 && item.source.filename != ""
898 // skip non-local items
899 && item.def_id.is_local()
900 // Macros from other libraries get special filenames which we can
902 && !(item.source.filename.starts_with("<")
903 && item.source.filename.ends_with("macros>")) {
905 // If it turns out that we couldn't read this file, then we probably
906 // can't read any of the files (generating html output from json or
907 // something like that), so just don't include sources for the
908 // entire crate. The other option is maintaining this mapping on a
909 // per-file basis, but that's probably not worth it...
911 .include_sources = match self.emit_source(&item.source.filename) {
914 println!("warning: source code was requested to be rendered, \
915 but processing `{}` had an error: {}",
916 item.source.filename, e);
917 println!(" skipping rendering of source code");
922 self.fold_item_recur(item)
926 impl<'a> SourceCollector<'a> {
927 /// Renders the given filename into its corresponding HTML source file.
928 fn emit_source(&mut self, filename: &str) -> io::Result<()> {
929 let p = PathBuf::from(filename);
930 if self.scx.local_sources.contains_key(&p) {
931 // We've already emitted this source
935 let mut contents = Vec::new();
936 File::open(&p).and_then(|mut f| f.read_to_end(&mut contents))?;
938 let contents = str::from_utf8(&contents).unwrap();
940 // Remove the utf-8 BOM if any
941 let contents = if contents.starts_with("\u{feff}") {
947 // Create the intermediate directories
948 let mut cur = self.dst.clone();
949 let mut root_path = String::from("../../");
950 let mut href = String::new();
951 clean_srcpath(&self.scx.src_root, &p, false, |component| {
953 fs::create_dir_all(&cur).unwrap();
954 root_path.push_str("../");
955 href.push_str(component);
958 let mut fname = p.file_name().expect("source has no filename")
962 href.push_str(&fname.to_string_lossy());
964 let mut w = BufWriter::new(File::create(&cur)?);
965 let title = format!("{} -- source", cur.file_name().unwrap()
967 let desc = format!("Source to the Rust file `{}`.", filename);
968 let page = layout::Page {
971 root_path: &root_path,
973 keywords: BASIC_KEYWORDS,
975 layout::render(&mut w, &self.scx.layout,
976 &page, &(""), &Source(contents),
977 self.scx.css_file_extension.is_some())?;
979 self.scx.local_sources.insert(p, href);
984 impl DocFolder for Cache {
985 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
986 // If this is a stripped module,
987 // we don't want it or its children in the search index.
988 let orig_stripped_mod = match item.inner {
989 clean::StrippedItem(box clean::ModuleItem(..)) => {
990 mem::replace(&mut self.stripped_mod, true)
992 _ => self.stripped_mod,
995 // Register any generics to their corresponding string. This is used
996 // when pretty-printing types.
997 if let Some(generics) = item.inner.generics() {
998 self.generics(generics);
1001 // Propagate a trait method's documentation to all implementors of the
1003 if let clean::TraitItem(ref t) = item.inner {
1004 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1007 // Collect all the implementors of traits.
1008 if let clean::ImplItem(ref i) = item.inner {
1009 if let Some(did) = i.trait_.def_id() {
1010 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
1011 def_id: item.def_id,
1012 stability: item.stability.clone(),
1018 // Index this method for searching later on.
1019 if let Some(ref s) = item.name {
1020 let (parent, is_inherent_impl_item) = match item.inner {
1021 clean::StrippedItem(..) => ((None, None), false),
1022 clean::AssociatedConstItem(..) |
1023 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1024 // skip associated items in trait impls
1025 ((None, None), false)
1027 clean::AssociatedTypeItem(..) |
1028 clean::TyMethodItem(..) |
1029 clean::StructFieldItem(..) |
1030 clean::VariantItem(..) => {
1031 ((Some(*self.parent_stack.last().unwrap()),
1032 Some(&self.stack[..self.stack.len() - 1])),
1035 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1036 if self.parent_stack.is_empty() {
1037 ((None, None), false)
1039 let last = self.parent_stack.last().unwrap();
1041 let path = match self.paths.get(&did) {
1042 // The current stack not necessarily has correlation
1043 // for where the type was defined. On the other
1044 // hand, `paths` always has the right
1045 // information if present.
1046 Some(&(ref fqp, ItemType::Trait)) |
1047 Some(&(ref fqp, ItemType::Struct)) |
1048 Some(&(ref fqp, ItemType::Union)) |
1049 Some(&(ref fqp, ItemType::Enum)) =>
1050 Some(&fqp[..fqp.len() - 1]),
1051 Some(..) => Some(&*self.stack),
1054 ((Some(*last), path), true)
1057 _ => ((None, Some(&*self.stack)), false)
1061 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1062 debug_assert!(!item.is_stripped());
1064 // A crate has a module at its root, containing all items,
1065 // which should not be indexed. The crate-item itself is
1066 // inserted later on when serializing the search-index.
1067 if item.def_id.index != CRATE_DEF_INDEX {
1068 self.search_index.push(IndexItem {
1070 name: s.to_string(),
1071 path: path.join("::").to_string(),
1072 desc: plain_summary_line(item.doc_value()),
1075 search_type: get_index_search_type(&item),
1079 (Some(parent), None) if is_inherent_impl_item => {
1080 // We have a parent, but we don't know where they're
1081 // defined yet. Wait for later to index this item.
1082 self.orphan_impl_items.push((parent, item.clone()));
1088 // Keep track of the fully qualified path for this item.
1089 let pushed = match item.name {
1090 Some(ref n) if !n.is_empty() => {
1091 self.stack.push(n.to_string());
1098 clean::StructItem(..) | clean::EnumItem(..) |
1099 clean::TypedefItem(..) | clean::TraitItem(..) |
1100 clean::FunctionItem(..) | clean::ModuleItem(..) |
1101 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1102 clean::ConstantItem(..) | clean::StaticItem(..) |
1103 clean::UnionItem(..)
1104 if !self.stripped_mod => {
1105 // Reexported items mean that the same id can show up twice
1106 // in the rustdoc ast that we're looking at. We know,
1107 // however, that a reexported item doesn't show up in the
1108 // `public_items` map, so we can skip inserting into the
1109 // paths map if there was already an entry present and we're
1110 // not a public item.
1112 !self.paths.contains_key(&item.def_id) ||
1113 self.access_levels.is_public(item.def_id)
1115 self.paths.insert(item.def_id,
1116 (self.stack.clone(), item.type_()));
1119 // Link variants to their parent enum because pages aren't emitted
1120 // for each variant.
1121 clean::VariantItem(..) if !self.stripped_mod => {
1122 let mut stack = self.stack.clone();
1124 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1127 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1128 self.paths.insert(item.def_id, (self.stack.clone(),
1135 // Maintain the parent stack
1136 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1137 let parent_pushed = match item.inner {
1138 clean::TraitItem(..) | clean::EnumItem(..) |
1139 clean::StructItem(..) | clean::UnionItem(..) => {
1140 self.parent_stack.push(item.def_id);
1141 self.parent_is_trait_impl = false;
1144 clean::ImplItem(ref i) => {
1145 self.parent_is_trait_impl = i.trait_.is_some();
1147 clean::ResolvedPath{ did, .. } => {
1148 self.parent_stack.push(did);
1152 let prim_did = t.primitive_type().and_then(|t| {
1153 self.primitive_locations.get(&t).cloned()
1157 self.parent_stack.push(did);
1168 // Once we've recursively found all the generics, hoard off all the
1169 // implementations elsewhere.
1170 let ret = self.fold_item_recur(item).and_then(|item| {
1171 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1172 // Figure out the id of this impl. This may map to a
1173 // primitive rather than always to a struct/enum.
1174 // Note: matching twice to restrict the lifetime of the `i` borrow.
1175 let did = if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1177 clean::ResolvedPath { did, .. } |
1178 clean::BorrowedRef {
1179 type_: box clean::ResolvedPath { did, .. }, ..
1184 t.primitive_type().and_then(|t| {
1185 self.primitive_locations.get(&t).cloned()
1192 if let Some(did) = did {
1193 self.impls.entry(did).or_insert(vec![]).push(Impl {
1203 if pushed { self.stack.pop().unwrap(); }
1204 if parent_pushed { self.parent_stack.pop().unwrap(); }
1205 self.stripped_mod = orig_stripped_mod;
1206 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1212 fn generics(&mut self, generics: &clean::Generics) {
1213 for typ in &generics.type_params {
1214 self.typarams.insert(typ.did, typ.name.clone());
1220 /// String representation of how to get back to the root path of the 'doc/'
1221 /// folder in terms of a relative URL.
1222 fn root_path(&self) -> String {
1223 repeat("../").take(self.current.len()).collect::<String>()
1226 /// Recurse in the directory structure and change the "root path" to make
1227 /// sure it always points to the top (relatively).
1228 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1229 F: FnOnce(&mut Context) -> T,
1232 panic!("Unexpected empty destination: {:?}", self.current);
1234 let prev = self.dst.clone();
1236 self.current.push(s);
1238 info!("Recursing into {}", self.dst.display());
1242 info!("Recursed; leaving {}", self.dst.display());
1244 // Go back to where we were at
1246 self.current.pop().unwrap();
1251 /// Main method for rendering a crate.
1253 /// This currently isn't parallelized, but it'd be pretty easy to add
1254 /// parallelization to this function.
1255 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1256 let mut item = match krate.module.take() {
1258 None => return Ok(()),
1260 item.name = Some(krate.name);
1262 // Render the crate documentation
1263 let mut work = vec![(self, item)];
1265 while let Some((mut cx, item)) = work.pop() {
1266 cx.item(item, |cx, item| {
1267 work.push((cx.clone(), item))
1273 fn render_item(&self,
1274 writer: &mut io::Write,
1278 // A little unfortunate that this is done like this, but it sure
1279 // does make formatting *a lot* nicer.
1280 CURRENT_LOCATION_KEY.with(|slot| {
1281 *slot.borrow_mut() = self.current.clone();
1284 let mut title = if it.is_primitive() {
1285 // No need to include the namespace for primitive types
1288 self.current.join("::")
1291 if !title.is_empty() {
1292 title.push_str("::");
1294 title.push_str(it.name.as_ref().unwrap());
1296 title.push_str(" - Rust");
1297 let tyname = it.type_().css_class();
1298 let desc = if it.is_crate() {
1299 format!("API documentation for the Rust `{}` crate.",
1300 self.shared.layout.krate)
1302 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1303 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1305 let keywords = make_item_keywords(it);
1306 let page = layout::Page {
1308 root_path: &self.root_path(),
1311 keywords: &keywords,
1316 if !self.render_redirect_pages {
1317 layout::render(writer, &self.shared.layout, &page,
1318 &Sidebar{ cx: self, item: it },
1319 &Item{ cx: self, item: it },
1320 self.shared.css_file_extension.is_some())?;
1322 let mut url = self.root_path();
1323 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1324 for name in &names[..names.len() - 1] {
1328 url.push_str(&item_path(ty, names.last().unwrap()));
1329 layout::redirect(writer, &url)?;
1335 /// Non-parallelized version of rendering an item. This will take the input
1336 /// item, render its contents, and then invoke the specified closure with
1337 /// all sub-items which need to be rendered.
1339 /// The rendering driver uses this closure to queue up more work.
1340 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1341 F: FnMut(&mut Context, clean::Item),
1343 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1344 // if they contain impls for public types. These modules can also
1345 // contain items such as publicly reexported structures.
1347 // External crates will provide links to these structures, so
1348 // these modules are recursed into, but not rendered normally
1349 // (a flag on the context).
1350 if !self.render_redirect_pages {
1351 self.render_redirect_pages = item.is_stripped();
1355 // modules are special because they add a namespace. We also need to
1356 // recurse into the items of the module as well.
1357 let name = item.name.as_ref().unwrap().to_string();
1358 let mut item = Some(item);
1359 self.recurse(name, |this| {
1360 let item = item.take().unwrap();
1362 let mut buf = Vec::new();
1363 this.render_item(&mut buf, &item, false).unwrap();
1364 // buf will be empty if the module is stripped and there is no redirect for it
1365 if !buf.is_empty() {
1366 let joint_dst = this.dst.join("index.html");
1367 try_err!(fs::create_dir_all(&this.dst), &this.dst);
1368 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1369 try_err!(dst.write_all(&buf), &joint_dst);
1372 let m = match item.inner {
1373 clean::StrippedItem(box clean::ModuleItem(m)) |
1374 clean::ModuleItem(m) => m,
1378 // Render sidebar-items.js used throughout this module.
1379 if !this.render_redirect_pages {
1380 let items = this.build_sidebar_items(&m);
1381 let js_dst = this.dst.join("sidebar-items.js");
1382 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1383 try_err!(write!(&mut js_out, "initSidebarItems({});",
1384 as_json(&items)), &js_dst);
1387 for item in m.items {
1393 } else if item.name.is_some() {
1394 let mut buf = Vec::new();
1395 self.render_item(&mut buf, &item, true).unwrap();
1396 // buf will be empty if the item is stripped and there is no redirect for it
1397 if !buf.is_empty() {
1398 let name = item.name.as_ref().unwrap();
1399 let item_type = item.type_();
1400 let file_name = &item_path(item_type, name);
1401 let joint_dst = self.dst.join(file_name);
1402 try_err!(fs::create_dir_all(&self.dst), &self.dst);
1403 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1404 try_err!(dst.write_all(&buf), &joint_dst);
1406 // Redirect from a sane URL using the namespace to Rustdoc's
1407 // URL for the page.
1408 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1409 let redir_dst = self.dst.join(redir_name);
1410 if let Ok(mut redirect_out) = OpenOptions::new().create_new(true)
1413 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1416 // If the item is a macro, redirect from the old macro URL (with !)
1417 // to the new one (without).
1418 // FIXME(#35705) remove this redirect.
1419 if item_type == ItemType::Macro {
1420 let redir_name = format!("{}.{}!.html", item_type, name);
1421 let redir_dst = self.dst.join(redir_name);
1422 let mut redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1423 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1430 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1431 // BTreeMap instead of HashMap to get a sorted output
1432 let mut map = BTreeMap::new();
1433 for item in &m.items {
1434 if item.is_stripped() { continue }
1436 let short = item.type_().css_class();
1437 let myname = match item.name {
1439 Some(ref s) => s.to_string(),
1441 let short = short.to_string();
1442 map.entry(short).or_insert(vec![])
1443 .push((myname, Some(plain_summary_line(item.doc_value()))));
1446 for (_, items) in &mut map {
1454 /// Generate a url appropriate for an `href` attribute back to the source of
1457 /// The url generated, when clicked, will redirect the browser back to the
1458 /// original source code.
1460 /// If `None` is returned, then a source link couldn't be generated. This
1461 /// may happen, for example, with externally inlined items where the source
1462 /// of their crate documentation isn't known.
1463 fn src_href(&self) -> Option<String> {
1464 let mut root = self.cx.root_path();
1466 let cache = cache();
1467 let mut path = String::new();
1468 let (krate, path) = if self.item.def_id.is_local() {
1469 let path = PathBuf::from(&self.item.source.filename);
1470 if let Some(path) = self.cx.shared.local_sources.get(&path) {
1471 (&self.cx.shared.layout.krate, path)
1476 // Macros from other libraries get special filenames which we can
1478 if self.item.source.filename.starts_with("<") &&
1479 self.item.source.filename.ends_with("macros>") {
1483 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1484 Some(&(ref name, ref src, Local)) => (name, src),
1485 Some(&(ref name, ref src, Remote(ref s))) => {
1486 root = s.to_string();
1489 Some(&(_, _, Unknown)) | None => return None,
1492 let file = Path::new(&self.item.source.filename);
1493 clean_srcpath(&src_root, file, false, |component| {
1494 path.push_str(component);
1497 let mut fname = file.file_name().expect("source has no filename")
1499 fname.push(".html");
1500 path.push_str(&fname.to_string_lossy());
1504 let lines = if self.item.source.loline == self.item.source.hiline {
1505 format!("{}", self.item.source.loline)
1507 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1509 Some(format!("{root}src/{krate}/{path}#{lines}",
1517 impl<'a> fmt::Display for Item<'a> {
1518 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1519 debug_assert!(!self.item.is_stripped());
1520 // Write the breadcrumb trail header for the top
1521 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1522 match self.item.inner {
1523 clean::ModuleItem(ref m) => if m.is_crate {
1524 write!(fmt, "Crate ")?;
1526 write!(fmt, "Module ")?;
1528 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) =>
1529 write!(fmt, "Function ")?,
1530 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1531 clean::StructItem(..) => write!(fmt, "Struct ")?,
1532 clean::UnionItem(..) => write!(fmt, "Union ")?,
1533 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1534 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1535 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1536 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1537 clean::StaticItem(..) | clean::ForeignStaticItem(..) =>
1538 write!(fmt, "Static ")?,
1539 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1541 // We don't generate pages for any other type.
1545 if !self.item.is_primitive() {
1546 let cur = &self.cx.current;
1547 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1548 for (i, component) in cur.iter().enumerate().take(amt) {
1549 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1550 repeat("../").take(cur.len() - i - 1)
1551 .collect::<String>(),
1555 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1556 self.item.type_(), self.item.name.as_ref().unwrap())?;
1558 write!(fmt, "</span>")?; // in-band
1559 write!(fmt, "<span class='out-of-band'>")?;
1560 if let Some(version) = self.item.stable_since() {
1561 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1565 r##"<span id='render-detail'>
1566 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1567 [<span class='inner'>−</span>]
1573 // When this item is part of a `pub use` in a downstream crate, the
1574 // [src] link in the downstream documentation will actually come back to
1575 // this page, and this link will be auto-clicked. The `id` attribute is
1576 // used to find the link to auto-click.
1577 if self.cx.shared.include_sources && !self.item.is_primitive() {
1578 if let Some(l) = self.src_href() {
1579 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1580 l, "goto source code")?;
1584 write!(fmt, "</span>")?; // out-of-band
1586 write!(fmt, "</h1>\n")?;
1588 match self.item.inner {
1589 clean::ModuleItem(ref m) => {
1590 item_module(fmt, self.cx, self.item, &m.items)
1592 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1593 item_function(fmt, self.cx, self.item, f),
1594 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1595 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1596 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1597 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1598 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1599 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1600 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1601 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1602 item_static(fmt, self.cx, self.item, i),
1603 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1605 // We don't generate pages for any other type.
1612 fn item_path(ty: ItemType, name: &str) -> String {
1614 ItemType::Module => format!("{}/index.html", name),
1615 _ => format!("{}.{}.html", ty.css_class(), name),
1619 fn full_path(cx: &Context, item: &clean::Item) -> String {
1620 let mut s = cx.current.join("::");
1622 s.push_str(item.name.as_ref().unwrap());
1626 fn shorter<'a>(s: Option<&'a str>) -> String {
1628 Some(s) => s.lines().take_while(|line|{
1629 (*line).chars().any(|chr|{
1630 !chr.is_whitespace()
1632 }).collect::<Vec<_>>().join("\n"),
1633 None => "".to_string()
1638 fn plain_summary_line(s: Option<&str>) -> String {
1639 let line = shorter(s).replace("\n", " ");
1640 markdown::plain_summary_line(&line[..])
1643 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1644 document_stability(w, cx, item)?;
1645 let prefix = render_assoc_const_value(item);
1646 document_full(w, item, cx.render_type, &prefix)?;
1650 fn get_html_diff(w: &mut fmt::Formatter, md_text: &str, render_type: RenderType,
1651 prefix: &str) -> fmt::Result {
1652 let output = format!("{}", Markdown(md_text, render_type));
1653 let old = format!("{}", Markdown(md_text, match render_type {
1654 RenderType::Hoedown => RenderType::Pulldown,
1655 RenderType::Pulldown => RenderType::Hoedown,
1657 let differences = html_diff::get_differences(&output, &old);
1658 if !differences.is_empty() {
1659 println!("Differences spotted in {:?}:\n{}",
1662 .map(|s| format!("=> {}", s.to_string()))
1663 .collect::<Vec<String>>()
1666 write!(w, "<div class='docblock'>{}{}</div>", prefix, output)
1669 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1670 render_type: RenderType, prefix: &str) -> fmt::Result {
1671 if let Some(s) = item.doc_value() {
1672 let markdown = if s.contains('\n') {
1673 format!("{} [Read more]({})",
1674 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1676 format!("{}", &plain_summary_line(Some(s)))
1678 get_html_diff(w, &markdown, render_type, prefix)?;
1679 } else if !prefix.is_empty() {
1680 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1685 fn render_assoc_const_value(item: &clean::Item) -> String {
1687 clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1688 highlight::render_with_highlighting(
1689 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1699 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1700 render_type: RenderType, prefix: &str) -> fmt::Result {
1701 if let Some(s) = item.doc_value() {
1702 get_html_diff(w, s, render_type, prefix)?;
1703 } else if !prefix.is_empty() {
1704 write!(w, "<div class='docblock'>{}</div>", prefix)?;
1709 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1710 let stabilities = short_stability(item, cx, true);
1711 if !stabilities.is_empty() {
1712 write!(w, "<div class='stability'>")?;
1713 for stability in stabilities {
1714 write!(w, "{}", stability)?;
1716 write!(w, "</div>")?;
1721 fn name_key(name: &str) -> (&str, u64, usize) {
1722 // find number at end
1723 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1725 // count leading zeroes
1727 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1729 // sort leading zeroes last
1730 let num_zeroes = after_zeroes - split;
1732 match name[split..].parse() {
1733 Ok(n) => (&name[..split], n, num_zeroes),
1734 Err(_) => (name, 0, num_zeroes),
1738 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1739 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1740 document(w, cx, item)?;
1742 let mut indices = (0..items.len()).filter(|i| {
1743 if let clean::DefaultImplItem(..) = items[*i].inner {
1746 !items[*i].is_stripped()
1747 }).collect::<Vec<usize>>();
1749 // the order of item types in the listing
1750 fn reorder(ty: ItemType) -> u8 {
1752 ItemType::ExternCrate => 0,
1753 ItemType::Import => 1,
1754 ItemType::Primitive => 2,
1755 ItemType::Module => 3,
1756 ItemType::Macro => 4,
1757 ItemType::Struct => 5,
1758 ItemType::Enum => 6,
1759 ItemType::Constant => 7,
1760 ItemType::Static => 8,
1761 ItemType::Trait => 9,
1762 ItemType::Function => 10,
1763 ItemType::Typedef => 12,
1764 ItemType::Union => 13,
1769 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1770 let ty1 = i1.type_();
1771 let ty2 = i2.type_();
1773 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1775 let s1 = i1.stability.as_ref().map(|s| s.level);
1776 let s2 = i2.stability.as_ref().map(|s| s.level);
1778 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1779 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1782 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1783 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1784 name_key(lhs).cmp(&name_key(rhs))
1787 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1788 // This call is to remove reexport duplicates in cases such as:
1793 // pub trait Double { fn foo(); }
1797 // pub use foo::bar::*;
1801 // `Double` will appear twice in the generated docs.
1803 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1804 // can be identical even if the elements are different (mostly in imports).
1805 // So in case this is an import, we keep everything by adding a "unique id"
1806 // (which is the position in the vector).
1807 indices.dedup_by_key(|i| (items[*i].def_id,
1808 if items[*i].name.as_ref().is_some() {
1809 Some(full_path(cx, &items[*i]).clone())
1814 if items[*i].is_import() {
1820 debug!("{:?}", indices);
1821 let mut curty = None;
1822 for &idx in &indices {
1823 let myitem = &items[idx];
1824 if myitem.is_stripped() {
1828 let myty = Some(myitem.type_());
1829 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1830 // Put `extern crate` and `use` re-exports in the same section.
1832 } else if myty != curty {
1833 if curty.is_some() {
1834 write!(w, "</table>")?;
1837 let (short, name) = match myty.unwrap() {
1838 ItemType::ExternCrate |
1839 ItemType::Import => ("reexports", "Reexports"),
1840 ItemType::Module => ("modules", "Modules"),
1841 ItemType::Struct => ("structs", "Structs"),
1842 ItemType::Union => ("unions", "Unions"),
1843 ItemType::Enum => ("enums", "Enums"),
1844 ItemType::Function => ("functions", "Functions"),
1845 ItemType::Typedef => ("types", "Type Definitions"),
1846 ItemType::Static => ("statics", "Statics"),
1847 ItemType::Constant => ("constants", "Constants"),
1848 ItemType::Trait => ("traits", "Traits"),
1849 ItemType::Impl => ("impls", "Implementations"),
1850 ItemType::TyMethod => ("tymethods", "Type Methods"),
1851 ItemType::Method => ("methods", "Methods"),
1852 ItemType::StructField => ("fields", "Struct Fields"),
1853 ItemType::Variant => ("variants", "Variants"),
1854 ItemType::Macro => ("macros", "Macros"),
1855 ItemType::Primitive => ("primitives", "Primitive Types"),
1856 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1857 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1859 write!(w, "<h2 id='{id}' class='section-header'>\
1860 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1861 id = derive_id(short.to_owned()), name = name)?;
1864 match myitem.inner {
1865 clean::ExternCrateItem(ref name, ref src) => {
1866 use html::format::HRef;
1870 write!(w, "<tr><td><code>{}extern crate {} as {};",
1871 VisSpace(&myitem.visibility),
1872 HRef::new(myitem.def_id, src),
1876 write!(w, "<tr><td><code>{}extern crate {};",
1877 VisSpace(&myitem.visibility),
1878 HRef::new(myitem.def_id, name))?
1881 write!(w, "</code></td></tr>")?;
1884 clean::ImportItem(ref import) => {
1885 write!(w, "<tr><td><code>{}{}</code></td></tr>",
1886 VisSpace(&myitem.visibility), *import)?;
1890 if myitem.name.is_none() { continue }
1892 let stabilities = short_stability(myitem, cx, false);
1894 let stab_docs = if !stabilities.is_empty() {
1896 .map(|s| format!("[{}]", s))
1897 .collect::<Vec<_>>()
1904 let unsafety_flag = match myitem.inner {
1905 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
1906 if func.unsafety == hir::Unsafety::Unsafe => {
1907 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
1912 let doc_value = myitem.doc_value().unwrap_or("");
1914 <tr class='{stab} module-item'>
1915 <td><a class=\"{class}\" href=\"{href}\"
1916 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
1917 <td class='docblock-short'>
1921 name = *myitem.name.as_ref().unwrap(),
1922 stab_docs = stab_docs,
1923 docs = if cx.render_type == RenderType::Hoedown {
1925 shorter(Some(&Markdown(doc_value,
1926 RenderType::Hoedown).to_string())))
1928 format!("{}", MarkdownSummaryLine(doc_value))
1930 class = myitem.type_(),
1931 stab = myitem.stability_class().unwrap_or("".to_string()),
1932 unsafety_flag = unsafety_flag,
1933 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
1934 title_type = myitem.type_(),
1935 title = full_path(cx, myitem))?;
1940 if curty.is_some() {
1941 write!(w, "</table>")?;
1946 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
1947 let mut stability = vec![];
1949 if let Some(stab) = item.stability.as_ref() {
1950 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
1951 format!(": {}", stab.deprecated_reason)
1955 if !stab.deprecated_since.is_empty() {
1956 let since = if show_reason {
1957 format!(" since {}", Escape(&stab.deprecated_since))
1961 let text = format!("Deprecated{}{}",
1963 MarkdownHtml(&deprecated_reason, cx.render_type));
1964 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
1967 if stab.level == stability::Unstable {
1969 let unstable_extra = match (!stab.feature.is_empty(),
1970 &cx.shared.issue_tracker_base_url,
1972 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1973 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
1974 Escape(&stab.feature), tracker_url, issue_no, issue_no),
1975 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1976 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
1979 format!(" (<code>{}</code>)", Escape(&stab.feature)),
1982 if stab.unstable_reason.is_empty() {
1983 stability.push(format!("<div class='stab unstable'>\
1984 <span class=microscope>🔬</span> \
1985 This is a nightly-only experimental API. {}\
1989 let text = format!("<summary><span class=microscope>🔬</span> \
1990 This is a nightly-only experimental API. {}\
1993 MarkdownHtml(&stab.unstable_reason, cx.render_type));
1994 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
1998 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2001 } else if let Some(depr) = item.deprecation.as_ref() {
2002 let note = if show_reason && !depr.note.is_empty() {
2003 format!(": {}", depr.note)
2007 let since = if show_reason && !depr.since.is_empty() {
2008 format!(" since {}", Escape(&depr.since))
2013 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e, cx.render_type));
2014 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2017 if let Some(ref cfg) = item.attrs.cfg {
2018 stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2019 cfg.render_long_html()
2021 cfg.render_short_html()
2028 struct Initializer<'a>(&'a str);
2030 impl<'a> fmt::Display for Initializer<'a> {
2031 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2032 let Initializer(s) = *self;
2033 if s.is_empty() { return Ok(()); }
2034 write!(f, "<code> = </code>")?;
2035 write!(f, "<code>{}</code>", Escape(s))
2039 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2040 c: &clean::Constant) -> fmt::Result {
2041 write!(w, "<pre class='rust const'>")?;
2042 render_attributes(w, it)?;
2043 write!(w, "{vis}const \
2044 {name}: {typ}{init}</pre>",
2045 vis = VisSpace(&it.visibility),
2046 name = it.name.as_ref().unwrap(),
2048 init = Initializer(&c.expr))?;
2052 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2053 s: &clean::Static) -> fmt::Result {
2054 write!(w, "<pre class='rust static'>")?;
2055 render_attributes(w, it)?;
2056 write!(w, "{vis}static {mutability}\
2057 {name}: {typ}{init}</pre>",
2058 vis = VisSpace(&it.visibility),
2059 mutability = MutableSpace(s.mutability),
2060 name = it.name.as_ref().unwrap(),
2062 init = Initializer(&s.expr))?;
2066 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2067 f: &clean::Function) -> fmt::Result {
2068 // FIXME(#24111): remove when `const_fn` is stabilized
2069 let vis_constness = match UnstableFeatures::from_environment() {
2070 UnstableFeatures::Allow => f.constness,
2071 _ => hir::Constness::NotConst
2073 let name_len = format!("{}{}{}{:#}fn {}{:#}",
2074 VisSpace(&it.visibility),
2075 ConstnessSpace(vis_constness),
2076 UnsafetySpace(f.unsafety),
2078 it.name.as_ref().unwrap(),
2080 write!(w, "<pre class='rust fn'>")?;
2081 render_attributes(w, it)?;
2082 write!(w, "{vis}{constness}{unsafety}{abi}fn \
2083 {name}{generics}{decl}{where_clause}</pre>",
2084 vis = VisSpace(&it.visibility),
2085 constness = ConstnessSpace(vis_constness),
2086 unsafety = UnsafetySpace(f.unsafety),
2087 abi = AbiSpace(f.abi),
2088 name = it.name.as_ref().unwrap(),
2089 generics = f.generics,
2090 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2099 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2100 t: &clean::Trait) -> fmt::Result {
2101 let mut bounds = String::new();
2102 let mut bounds_plain = String::new();
2103 if !t.bounds.is_empty() {
2104 if !bounds.is_empty() {
2106 bounds_plain.push(' ');
2108 bounds.push_str(": ");
2109 bounds_plain.push_str(": ");
2110 for (i, p) in t.bounds.iter().enumerate() {
2112 bounds.push_str(" + ");
2113 bounds_plain.push_str(" + ");
2115 bounds.push_str(&format!("{}", *p));
2116 bounds_plain.push_str(&format!("{:#}", *p));
2120 // Output the trait definition
2121 write!(w, "<pre class='rust trait'>")?;
2122 render_attributes(w, it)?;
2123 write!(w, "{}{}trait {}{}{}",
2124 VisSpace(&it.visibility),
2125 UnsafetySpace(t.unsafety),
2126 it.name.as_ref().unwrap(),
2130 if !t.generics.where_predicates.is_empty() {
2131 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2136 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2137 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2138 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2139 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2141 if t.items.is_empty() {
2142 write!(w, "{{ }}")?;
2144 // FIXME: we should be using a derived_id for the Anchors here
2148 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2151 if !types.is_empty() && !consts.is_empty() {
2156 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2159 if !consts.is_empty() && !required.is_empty() {
2162 for (pos, m) in required.iter().enumerate() {
2164 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2167 if pos < required.len() - 1 {
2168 write!(w, "<div class='item-spacer'></div>")?;
2171 if !required.is_empty() && !provided.is_empty() {
2174 for (pos, m) in provided.iter().enumerate() {
2176 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2178 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2179 write!(w, ",\n {{ ... }}\n")?;
2182 write!(w, " {{ ... }}\n")?;
2185 if pos < provided.len() - 1 {
2186 write!(w, "<div class='item-spacer'></div>")?;
2191 write!(w, "</pre>")?;
2193 // Trait documentation
2194 document(w, cx, it)?;
2196 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2198 let name = m.name.as_ref().unwrap();
2199 let item_type = m.type_();
2200 let id = derive_id(format!("{}.{}", item_type, name));
2201 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2202 write!(w, "<h3 id='{id}' class='method'>\
2203 <span id='{ns_id}' class='invisible'><code>",
2206 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2207 write!(w, "</code>")?;
2208 render_stability_since(w, m, t)?;
2209 write!(w, "</span></h3>")?;
2210 document(w, cx, m)?;
2214 if !types.is_empty() {
2216 <h2 id='associated-types' class='small-section-header'>
2217 Associated Types<a href='#associated-types' class='anchor'></a>
2219 <div class='methods'>
2222 trait_item(w, cx, *t, it)?;
2224 write!(w, "</div>")?;
2227 if !consts.is_empty() {
2229 <h2 id='associated-const' class='small-section-header'>
2230 Associated Constants<a href='#associated-const' class='anchor'></a>
2232 <div class='methods'>
2235 trait_item(w, cx, *t, it)?;
2237 write!(w, "</div>")?;
2240 // Output the documentation for each function individually
2241 if !required.is_empty() {
2243 <h2 id='required-methods' class='small-section-header'>
2244 Required Methods<a href='#required-methods' class='anchor'></a>
2246 <div class='methods'>
2248 for m in &required {
2249 trait_item(w, cx, *m, it)?;
2251 write!(w, "</div>")?;
2253 if !provided.is_empty() {
2255 <h2 id='provided-methods' class='small-section-header'>
2256 Provided Methods<a href='#provided-methods' class='anchor'></a>
2258 <div class='methods'>
2260 for m in &provided {
2261 trait_item(w, cx, *m, it)?;
2263 write!(w, "</div>")?;
2266 // If there are methods directly on this trait object, render them here.
2267 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2269 let cache = cache();
2271 <h2 id='implementors' class='small-section-header'>
2272 Implementors<a href='#implementors' class='anchor'></a>
2274 <ul class='item-list' id='implementors-list'>
2276 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2277 // The DefId is for the first Type found with that name. The bool is
2278 // if any Types with the same name but different DefId have been found.
2279 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2280 for implementor in implementors {
2281 match implementor.impl_.for_ {
2282 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2283 clean::BorrowedRef {
2284 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2287 let &mut (prev_did, ref mut has_duplicates) =
2288 implementor_dups.entry(path.last_name()).or_insert((did, false));
2289 if prev_did != did {
2290 *has_duplicates = true;
2297 for implementor in implementors {
2298 write!(w, "<li><code>")?;
2299 // If there's already another implementor that has the same abbridged name, use the
2300 // full path, for example in `std::iter::ExactSizeIterator`
2301 let use_absolute = match implementor.impl_.for_ {
2302 clean::ResolvedPath { ref path, is_generic: false, .. } |
2303 clean::BorrowedRef {
2304 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2306 } => implementor_dups[path.last_name()].1,
2309 fmt_impl_for_trait_page(&implementor.impl_, w, use_absolute)?;
2310 for it in &implementor.impl_.items {
2311 if let clean::TypedefItem(ref tydef, _) = it.inner {
2312 write!(w, "<span class=\"where fmt-newline\"> ")?;
2313 assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2314 write!(w, ";</span>")?;
2317 writeln!(w, "</code></li>")?;
2320 write!(w, "</ul>")?;
2321 write!(w, r#"<script type="text/javascript" async
2322 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2324 root_path = vec![".."; cx.current.len()].join("/"),
2325 path = if it.def_id.is_local() {
2326 cx.current.join("/")
2328 let (ref path, _) = cache.external_paths[&it.def_id];
2329 path[..path.len() - 1].join("/")
2331 ty = it.type_().css_class(),
2332 name = *it.name.as_ref().unwrap())?;
2336 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2337 use html::item_type::ItemType::*;
2339 let name = it.name.as_ref().unwrap();
2340 let ty = match it.type_() {
2341 Typedef | AssociatedType => AssociatedType,
2345 let anchor = format!("#{}.{}", ty, name);
2347 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2348 AssocItemLink::Anchor(None) => anchor,
2349 AssocItemLink::GotoSource(did, _) => {
2350 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2355 fn assoc_const(w: &mut fmt::Formatter,
2358 _default: Option<&String>,
2359 link: AssocItemLink) -> fmt::Result {
2360 write!(w, "const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2361 naive_assoc_href(it, link),
2362 it.name.as_ref().unwrap(),
2367 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
2368 bounds: &Vec<clean::TyParamBound>,
2369 default: Option<&clean::Type>,
2370 link: AssocItemLink) -> fmt::Result {
2371 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2372 naive_assoc_href(it, link),
2373 it.name.as_ref().unwrap())?;
2374 if !bounds.is_empty() {
2375 write!(w, ": {}", TyParamBounds(bounds))?
2377 if let Some(default) = default {
2378 write!(w, " = {}", default)?;
2383 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2384 ver: Option<&'a str>,
2385 containing_ver: Option<&'a str>) -> fmt::Result {
2386 if let Some(v) = ver {
2387 if containing_ver != ver && v.len() > 0 {
2388 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2395 fn render_stability_since(w: &mut fmt::Formatter,
2397 containing_item: &clean::Item) -> fmt::Result {
2398 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2401 fn render_assoc_item(w: &mut fmt::Formatter,
2403 link: AssocItemLink,
2404 parent: ItemType) -> fmt::Result {
2405 fn method(w: &mut fmt::Formatter,
2407 unsafety: hir::Unsafety,
2408 constness: hir::Constness,
2410 g: &clean::Generics,
2412 link: AssocItemLink,
2415 let name = meth.name.as_ref().unwrap();
2416 let anchor = format!("#{}.{}", meth.type_(), name);
2417 let href = match link {
2418 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2419 AssocItemLink::Anchor(None) => anchor,
2420 AssocItemLink::GotoSource(did, provided_methods) => {
2421 // We're creating a link from an impl-item to the corresponding
2422 // trait-item and need to map the anchored type accordingly.
2423 let ty = if provided_methods.contains(name) {
2429 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2432 // FIXME(#24111): remove when `const_fn` is stabilized
2433 let vis_constness = if is_nightly_build() {
2436 hir::Constness::NotConst
2438 let mut head_len = format!("{}{}{:#}fn {}{:#}",
2439 ConstnessSpace(vis_constness),
2440 UnsafetySpace(unsafety),
2444 let (indent, end_newline) = if parent == ItemType::Trait {
2450 write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2451 {generics}{decl}{where_clause}",
2452 ConstnessSpace(vis_constness),
2453 UnsafetySpace(unsafety),
2463 where_clause = WhereClause {
2470 clean::StrippedItem(..) => Ok(()),
2471 clean::TyMethodItem(ref m) => {
2472 method(w, item, m.unsafety, hir::Constness::NotConst,
2473 m.abi, &m.generics, &m.decl, link, parent)
2475 clean::MethodItem(ref m) => {
2476 method(w, item, m.unsafety, m.constness,
2477 m.abi, &m.generics, &m.decl, link, parent)
2479 clean::AssociatedConstItem(ref ty, ref default) => {
2480 assoc_const(w, item, ty, default.as_ref(), link)
2482 clean::AssociatedTypeItem(ref bounds, ref default) => {
2483 assoc_type(w, item, bounds, default.as_ref(), link)
2485 _ => panic!("render_assoc_item called on non-associated-item")
2489 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2490 s: &clean::Struct) -> fmt::Result {
2491 write!(w, "<pre class='rust struct'>")?;
2492 render_attributes(w, it)?;
2500 write!(w, "</pre>")?;
2502 document(w, cx, it)?;
2503 let mut fields = s.fields.iter().filter_map(|f| {
2505 clean::StructFieldItem(ref ty) => Some((f, ty)),
2509 if let doctree::Plain = s.struct_type {
2510 if fields.peek().is_some() {
2511 write!(w, "<h2 id='fields' class='fields small-section-header'>
2512 Fields<a href='#fields' class='anchor'></a></h2>")?;
2513 for (field, ty) in fields {
2514 let id = derive_id(format!("{}.{}",
2515 ItemType::StructField,
2516 field.name.as_ref().unwrap()));
2517 let ns_id = derive_id(format!("{}.{}",
2518 field.name.as_ref().unwrap(),
2519 ItemType::StructField.name_space()));
2520 write!(w, "<span id='{id}' class=\"{item_type}\">
2521 <span id='{ns_id}' class='invisible'>
2522 <code>{name}: {ty}</code>
2524 item_type = ItemType::StructField,
2527 name = field.name.as_ref().unwrap(),
2529 if let Some(stability_class) = field.stability_class() {
2530 write!(w, "<span class='stab {stab}'></span>",
2531 stab = stability_class)?;
2533 document(w, cx, field)?;
2537 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2540 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2541 s: &clean::Union) -> fmt::Result {
2542 write!(w, "<pre class='rust union'>")?;
2543 render_attributes(w, it)?;
2550 write!(w, "</pre>")?;
2552 document(w, cx, it)?;
2553 let mut fields = s.fields.iter().filter_map(|f| {
2555 clean::StructFieldItem(ref ty) => Some((f, ty)),
2559 if fields.peek().is_some() {
2560 write!(w, "<h2 id='fields' class='fields small-section-header'>
2561 Fields<a href='#fields' class='anchor'></a></h2>")?;
2562 for (field, ty) in fields {
2563 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2565 shortty = ItemType::StructField,
2566 name = field.name.as_ref().unwrap(),
2568 if let Some(stability_class) = field.stability_class() {
2569 write!(w, "<span class='stab {stab}'></span>",
2570 stab = stability_class)?;
2572 document(w, cx, field)?;
2575 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2578 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2579 e: &clean::Enum) -> fmt::Result {
2580 write!(w, "<pre class='rust enum'>")?;
2581 render_attributes(w, it)?;
2582 write!(w, "{}enum {}{}{}",
2583 VisSpace(&it.visibility),
2584 it.name.as_ref().unwrap(),
2586 WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2587 if e.variants.is_empty() && !e.variants_stripped {
2588 write!(w, " {{}}")?;
2590 write!(w, " {{\n")?;
2591 for v in &e.variants {
2593 let name = v.name.as_ref().unwrap();
2595 clean::VariantItem(ref var) => {
2597 clean::VariantKind::CLike => write!(w, "{}", name)?,
2598 clean::VariantKind::Tuple(ref tys) => {
2599 write!(w, "{}(", name)?;
2600 for (i, ty) in tys.iter().enumerate() {
2602 write!(w, ", ")?
2604 write!(w, "{}", *ty)?;
2608 clean::VariantKind::Struct(ref s) => {
2624 if e.variants_stripped {
2625 write!(w, " // some variants omitted\n")?;
2629 write!(w, "</pre>")?;
2631 document(w, cx, it)?;
2632 if !e.variants.is_empty() {
2633 write!(w, "<h2 id='variants' class='variants small-section-header'>
2634 Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2635 for variant in &e.variants {
2636 let id = derive_id(format!("{}.{}",
2638 variant.name.as_ref().unwrap()));
2639 let ns_id = derive_id(format!("{}.{}",
2640 variant.name.as_ref().unwrap(),
2641 ItemType::Variant.name_space()));
2642 write!(w, "<span id='{id}' class='variant'>\
2643 <span id='{ns_id}' class='invisible'><code>{name}",
2646 name = variant.name.as_ref().unwrap())?;
2647 if let clean::VariantItem(ref var) = variant.inner {
2648 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2650 for (i, ty) in tys.iter().enumerate() {
2652 write!(w, ", ")?;
2654 write!(w, "{}", *ty)?;
2659 write!(w, "</code></span></span>")?;
2660 document(w, cx, variant)?;
2662 use clean::{Variant, VariantKind};
2663 if let clean::VariantItem(Variant {
2664 kind: VariantKind::Struct(ref s)
2665 }) = variant.inner {
2666 let variant_id = derive_id(format!("{}.{}.fields",
2668 variant.name.as_ref().unwrap()));
2669 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2671 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2672 <table>", name = variant.name.as_ref().unwrap())?;
2673 for field in &s.fields {
2674 use clean::StructFieldItem;
2675 if let StructFieldItem(ref ty) = field.inner {
2676 let id = derive_id(format!("variant.{}.field.{}",
2677 variant.name.as_ref().unwrap(),
2678 field.name.as_ref().unwrap()));
2679 let ns_id = derive_id(format!("{}.{}.{}.{}",
2680 variant.name.as_ref().unwrap(),
2681 ItemType::Variant.name_space(),
2682 field.name.as_ref().unwrap(),
2683 ItemType::StructField.name_space()));
2684 write!(w, "<tr><td \
2686 <span id='{ns_id}' class='invisible'>\
2687 <code>{f}: {t}</code></span></td><td>",
2690 f = field.name.as_ref().unwrap(),
2692 document(w, cx, field)?;
2693 write!(w, "</td></tr>")?;
2696 write!(w, "</table></span>")?;
2698 render_stability_since(w, variant, it)?;
2701 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2705 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2706 let name = attr.name();
2709 Some(format!("{}", name))
2710 } else if let Some(v) = attr.value_str() {
2711 Some(format!("{} = {:?}", name, v.as_str()))
2712 } else if let Some(values) = attr.meta_item_list() {
2713 let display: Vec<_> = values.iter().filter_map(|attr| {
2714 attr.meta_item().and_then(|mi| render_attribute(mi))
2717 if display.len() > 0 {
2718 Some(format!("{}({})", name, display.join(", ")))
2727 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2734 "unsafe_destructor_blind_to_params"
2737 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2738 let mut attrs = String::new();
2740 for attr in &it.attrs.other_attrs {
2741 let name = attr.name().unwrap();
2742 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2745 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2746 attrs.push_str(&format!("#[{}]\n", s));
2749 if attrs.len() > 0 {
2750 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2755 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2756 g: Option<&clean::Generics>,
2757 ty: doctree::StructType,
2758 fields: &[clean::Item],
2760 structhead: bool) -> fmt::Result {
2762 VisSpace(&it.visibility),
2763 if structhead {"struct "} else {""},
2764 it.name.as_ref().unwrap())?;
2765 if let Some(g) = g {
2770 if let Some(g) = g {
2771 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
2773 let mut has_visible_fields = false;
2775 for field in fields {
2776 if let clean::StructFieldItem(ref ty) = field.inner {
2777 write!(w, "\n{} {}{}: {},",
2779 VisSpace(&field.visibility),
2780 field.name.as_ref().unwrap(),
2782 has_visible_fields = true;
2786 if has_visible_fields {
2787 if it.has_stripped_fields().unwrap() {
2788 write!(w, "\n{} // some fields omitted", tab)?;
2790 write!(w, "\n{}", tab)?;
2791 } else if it.has_stripped_fields().unwrap() {
2792 // If there are no visible fields we can just display
2793 // `{ /* fields omitted */ }` to save space.
2794 write!(w, " /* fields omitted */ ")?;
2800 for (i, field) in fields.iter().enumerate() {
2805 clean::StrippedItem(box clean::StructFieldItem(..)) => {
2808 clean::StructFieldItem(ref ty) => {
2809 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
2815 if let Some(g) = g {
2816 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
2821 // Needed for PhantomData.
2822 if let Some(g) = g {
2823 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
2831 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
2832 g: Option<&clean::Generics>,
2833 fields: &[clean::Item],
2835 structhead: bool) -> fmt::Result {
2837 VisSpace(&it.visibility),
2838 if structhead {"union "} else {""},
2839 it.name.as_ref().unwrap())?;
2840 if let Some(g) = g {
2841 write!(w, "{}", g)?;
2842 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
2845 write!(w, " {{\n{}", tab)?;
2846 for field in fields {
2847 if let clean::StructFieldItem(ref ty) = field.inner {
2848 write!(w, " {}{}: {},\n{}",
2849 VisSpace(&field.visibility),
2850 field.name.as_ref().unwrap(),
2856 if it.has_stripped_fields().unwrap() {
2857 write!(w, " // some fields omitted\n{}", tab)?;
2863 #[derive(Copy, Clone)]
2864 enum AssocItemLink<'a> {
2865 Anchor(Option<&'a str>),
2866 GotoSource(DefId, &'a FxHashSet<String>),
2869 impl<'a> AssocItemLink<'a> {
2870 fn anchor(&self, id: &'a String) -> Self {
2872 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
2873 ref other => *other,
2878 enum AssocItemRender<'a> {
2880 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
2883 #[derive(Copy, Clone, PartialEq)]
2886 ForDeref { mut_: bool },
2889 fn render_assoc_items(w: &mut fmt::Formatter,
2891 containing_item: &clean::Item,
2893 what: AssocItemRender) -> fmt::Result {
2895 let v = match c.impls.get(&it) {
2897 None => return Ok(()),
2899 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
2900 i.inner_impl().trait_.is_none()
2902 if !non_trait.is_empty() {
2903 let render_mode = match what {
2904 AssocItemRender::All => {
2906 <h2 id='methods' class='small-section-header'>
2907 Methods<a href='#methods' class='anchor'></a>
2912 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
2914 <h2 id='deref-methods' class='small-section-header'>
2915 Methods from {}<Target = {}><a href='#deref-methods' class='anchor'></a>
2918 RenderMode::ForDeref { mut_: deref_mut_ }
2921 for i in &non_trait {
2922 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
2923 containing_item.stable_since())?;
2926 if let AssocItemRender::DerefFor { .. } = what {
2929 if !traits.is_empty() {
2930 let deref_impl = traits.iter().find(|t| {
2931 t.inner_impl().trait_.def_id() == c.deref_trait_did
2933 if let Some(impl_) = deref_impl {
2934 let has_deref_mut = traits.iter().find(|t| {
2935 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
2937 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
2940 <h2 id='implementations' class='small-section-header'>
2941 Trait Implementations<a href='#implementations' class='anchor'></a>
2945 let did = i.trait_did().unwrap();
2946 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2947 render_impl(w, cx, i, assoc_link,
2948 RenderMode::Normal, containing_item.stable_since())?;
2954 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
2955 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
2956 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
2957 let target = impl_.inner_impl().items.iter().filter_map(|item| {
2959 clean::TypedefItem(ref t, true) => Some(&t.type_),
2962 }).next().expect("Expected associated type binding");
2963 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
2964 deref_mut_: deref_mut };
2965 if let Some(did) = target.def_id() {
2966 render_assoc_items(w, cx, container_item, did, what)
2968 if let Some(prim) = target.primitive_type() {
2969 if let Some(&did) = cache().primitive_locations.get(&prim) {
2970 render_assoc_items(w, cx, container_item, did, what)?;
2977 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
2978 render_mode: RenderMode, outer_version: Option<&str>) -> fmt::Result {
2979 if render_mode == RenderMode::Normal {
2980 let id = derive_id(match i.inner_impl().trait_ {
2981 Some(ref t) => format!("impl-{}", Escape(&format!("{:#}", t))),
2982 None => "impl".to_string(),
2984 write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
2985 id, i.inner_impl())?;
2986 write!(w, "<a href='#{}' class='anchor'></a>", id)?;
2987 write!(w, "</span><span class='out-of-band'>")?;
2988 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
2989 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
2990 write!(w, "<div class='ghost'></div>")?;
2991 render_stability_since_raw(w, since, outer_version)?;
2992 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2993 l, "goto source code")?;
2995 render_stability_since_raw(w, since, outer_version)?;
2997 write!(w, "</span>")?;
2998 write!(w, "</h3>\n")?;
2999 if let Some(ref dox) = i.impl_item.doc_value() {
3000 write!(w, "<div class='docblock'>{}</div>", Markdown(dox, cx.render_type))?;
3004 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3005 link: AssocItemLink, render_mode: RenderMode,
3006 is_default_item: bool, outer_version: Option<&str>,
3007 trait_: Option<&clean::Trait>) -> fmt::Result {
3008 let item_type = item.type_();
3009 let name = item.name.as_ref().unwrap();
3011 let render_method_item: bool = match render_mode {
3012 RenderMode::Normal => true,
3013 RenderMode::ForDeref { mut_: deref_mut_ } => {
3014 let self_type_opt = match item.inner {
3015 clean::MethodItem(ref method) => method.decl.self_type(),
3016 clean::TyMethodItem(ref method) => method.decl.self_type(),
3020 if let Some(self_ty) = self_type_opt {
3021 let (by_mut_ref, by_box) = match self_ty {
3022 SelfTy::SelfBorrowed(_, mutability) |
3023 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3024 (mutability == Mutability::Mutable, false)
3026 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3027 (false, Some(did) == cache().owned_box_did)
3029 _ => (false, false),
3032 (deref_mut_ || !by_mut_ref) && !by_box
3040 clean::MethodItem(..) | clean::TyMethodItem(..) => {
3041 // Only render when the method is not static or we allow static methods
3042 if render_method_item {
3043 let id = derive_id(format!("{}.{}", item_type, name));
3044 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3045 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3046 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3047 write!(w, "<code>")?;
3048 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3049 write!(w, "</code>")?;
3050 if let Some(l) = (Item { cx, item }).src_href() {
3051 write!(w, "</span><span class='out-of-band'>")?;
3052 write!(w, "<div class='ghost'></div>")?;
3053 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3054 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3055 l, "goto source code")?;
3057 render_stability_since_raw(w, item.stable_since(), outer_version)?;
3059 write!(w, "</span></h4>\n")?;
3062 clean::TypedefItem(ref tydef, _) => {
3063 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3064 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3065 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3066 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3067 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3068 write!(w, "</code></span></h4>\n")?;
3070 clean::AssociatedConstItem(ref ty, ref default) => {
3071 let id = derive_id(format!("{}.{}", item_type, name));
3072 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3073 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3074 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3075 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3076 write!(w, "</code></span></h4>\n")?;
3078 clean::AssociatedTypeItem(ref bounds, ref default) => {
3079 let id = derive_id(format!("{}.{}", item_type, name));
3080 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3081 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3082 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3083 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3084 write!(w, "</code></span></h4>\n")?;
3086 clean::StrippedItem(..) => return Ok(()),
3087 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3090 if render_method_item || render_mode == RenderMode::Normal {
3091 let prefix = render_assoc_const_value(item);
3092 if !is_default_item {
3093 if let Some(t) = trait_ {
3094 // The trait item may have been stripped so we might not
3095 // find any documentation or stability for it.
3096 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3097 // We need the stability of the item from the trait
3098 // because impls can't have a stability.
3099 document_stability(w, cx, it)?;
3100 if item.doc_value().is_some() {
3101 document_full(w, item, cx.render_type, &prefix)?;
3103 // In case the item isn't documented,
3104 // provide short documentation from the trait.
3105 document_short(w, it, link, cx.render_type, &prefix)?;
3109 document_stability(w, cx, item)?;
3110 document_full(w, item, cx.render_type, &prefix)?;
3113 document_stability(w, cx, item)?;
3114 document_short(w, item, link, cx.render_type, &prefix)?;
3120 let traits = &cache().traits;
3121 let trait_ = i.trait_did().and_then(|did| traits.get(&did));
3123 write!(w, "<div class='impl-items'>")?;
3124 for trait_item in &i.inner_impl().items {
3125 doc_impl_item(w, cx, trait_item, link, render_mode,
3126 false, outer_version, trait_)?;
3129 fn render_default_items(w: &mut fmt::Formatter,
3133 render_mode: RenderMode,
3134 outer_version: Option<&str>) -> fmt::Result {
3135 for trait_item in &t.items {
3136 let n = trait_item.name.clone();
3137 if i.items.iter().find(|m| m.name == n).is_some() {
3140 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3141 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3143 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3144 outer_version, None)?;
3149 // If we've implemented a trait, then also emit documentation for all
3150 // default items which weren't overridden in the implementation block.
3151 if let Some(t) = trait_ {
3152 render_default_items(w, cx, t, &i.inner_impl(), render_mode, outer_version)?;
3154 write!(w, "</div>")?;
3158 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3159 t: &clean::Typedef) -> fmt::Result {
3160 write!(w, "<pre class='rust typedef'>")?;
3161 render_attributes(w, it)?;
3162 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3163 it.name.as_ref().unwrap(),
3165 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3168 document(w, cx, it)?;
3170 // Render any items associated directly to this alias, as otherwise they
3171 // won't be visible anywhere in the docs. It would be nice to also show
3172 // associated items from the aliased type (see discussion in #32077), but
3173 // we need #14072 to make sense of the generics.
3174 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3177 impl<'a> fmt::Display for Sidebar<'a> {
3178 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3181 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3183 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3184 || it.is_enum() || it.is_mod() || it.is_typedef()
3186 write!(fmt, "<p class='location'>")?;
3188 clean::StructItem(..) => write!(fmt, "Struct ")?,
3189 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3190 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3191 clean::UnionItem(..) => write!(fmt, "Union ")?,
3192 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3193 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3194 clean::ModuleItem(..) => if it.is_crate() {
3195 write!(fmt, "Crate ")?;
3197 write!(fmt, "Module ")?;
3201 write!(fmt, "{}", it.name.as_ref().unwrap())?;
3202 write!(fmt, "</p>")?;
3205 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3206 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3207 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3208 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3209 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3210 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3211 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3216 // The sidebar is designed to display sibling functions, modules and
3217 // other miscellaneous information. since there are lots of sibling
3218 // items (and that causes quadratic growth in large modules),
3219 // we refactor common parts into a shared JavaScript file per module.
3220 // still, we don't move everything into JS because we want to preserve
3221 // as much HTML as possible in order to allow non-JS-enabled browsers
3222 // to navigate the documentation (though slightly inefficiently).
3224 write!(fmt, "<p class='location'>")?;
3225 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3227 write!(fmt, "::<wbr>")?;
3229 write!(fmt, "<a href='{}index.html'>{}</a>",
3230 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3233 write!(fmt, "</p>")?;
3235 // Sidebar refers to the enclosing module, not this module.
3236 let relpath = if it.is_mod() { "../" } else { "" };
3238 "<script>window.sidebarCurrent = {{\
3243 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3244 ty = it.type_().css_class(),
3247 // There is no sidebar-items.js beyond the crate root path
3248 // FIXME maybe dynamic crate loading can be merged here
3250 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3258 fn sidebar_assoc_items(it: &clean::Item) -> String {
3259 let mut out = String::new();
3261 if let Some(v) = c.impls.get(&it.def_id) {
3262 if v.iter().any(|i| i.inner_impl().trait_.is_none()) {
3263 out.push_str("<li><a href=\"#methods\">Methods</a></li>");
3266 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3267 if let Some(impl_) = v.iter()
3268 .filter(|i| i.inner_impl().trait_.is_some())
3269 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3270 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3272 clean::TypedefItem(ref t, true) => Some(&t.type_),
3276 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3277 c.primitive_locations.get(&prim).cloned()
3278 })).and_then(|did| c.impls.get(&did));
3279 if inner_impl.is_some() {
3280 out.push_str("<li><a href=\"#deref-methods\">");
3281 out.push_str(&format!("Methods from {:#}<Target={:#}>",
3282 impl_.inner_impl().trait_.as_ref().unwrap(),
3284 out.push_str("</a></li>");
3288 out.push_str("<li><a href=\"#implementations\">Trait Implementations</a></li>");
3295 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3296 s: &clean::Struct) -> fmt::Result {
3297 let mut sidebar = String::new();
3300 .any(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false }) {
3301 if let doctree::Plain = s.struct_type {
3302 sidebar.push_str("<li><a href=\"#fields\">Fields</a></li>");
3306 sidebar.push_str(&sidebar_assoc_items(it));
3308 if !sidebar.is_empty() {
3309 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3314 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3315 t: &clean::Trait) -> fmt::Result {
3316 let mut sidebar = String::new();
3318 let has_types = t.items.iter().any(|m| m.is_associated_type());
3319 let has_consts = t.items.iter().any(|m| m.is_associated_const());
3320 let has_required = t.items.iter().any(|m| m.is_ty_method());
3321 let has_provided = t.items.iter().any(|m| m.is_method());
3324 sidebar.push_str("<li><a href=\"#associated-types\">Associated Types</a></li>");
3327 sidebar.push_str("<li><a href=\"#associated-const\">Associated Constants</a></li>");
3330 sidebar.push_str("<li><a href=\"#required-methods\">Required Methods</a></li>");
3333 sidebar.push_str("<li><a href=\"#provided-methods\">Provided Methods</a></li>");
3336 sidebar.push_str(&sidebar_assoc_items(it));
3338 sidebar.push_str("<li><a href=\"#implementors\">Implementors</a></li>");
3340 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)
3343 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3344 _p: &clean::PrimitiveType) -> fmt::Result {
3345 let sidebar = sidebar_assoc_items(it);
3347 if !sidebar.is_empty() {
3348 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3353 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3354 _t: &clean::Typedef) -> fmt::Result {
3355 let sidebar = sidebar_assoc_items(it);
3357 if !sidebar.is_empty() {
3358 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3363 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3364 u: &clean::Union) -> fmt::Result {
3365 let mut sidebar = String::new();
3368 .any(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false }) {
3369 sidebar.push_str("<li><a href=\"#fields\">Fields</a></li>");
3372 sidebar.push_str(&sidebar_assoc_items(it));
3374 if !sidebar.is_empty() {
3375 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3380 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3381 e: &clean::Enum) -> fmt::Result {
3382 let mut sidebar = String::new();
3384 if !e.variants.is_empty() {
3385 sidebar.push_str("<li><a href=\"#variants\">Variants</a></li>");
3388 sidebar.push_str(&sidebar_assoc_items(it));
3390 if !sidebar.is_empty() {
3391 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3396 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3397 items: &[clean::Item]) -> fmt::Result {
3398 let mut sidebar = String::new();
3400 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3401 it.type_() == ItemType::Import) {
3402 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3404 name = "Reexports"));
3407 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3408 // to print its headings
3409 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3410 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3411 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3412 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3413 ItemType::AssociatedType, ItemType::AssociatedConst] {
3414 if items.iter().any(|it| {
3415 if let clean::DefaultImplItem(..) = it.inner {
3418 !it.is_stripped() && it.type_() == myty
3421 let (short, name) = match myty {
3422 ItemType::ExternCrate |
3423 ItemType::Import => ("reexports", "Reexports"),
3424 ItemType::Module => ("modules", "Modules"),
3425 ItemType::Struct => ("structs", "Structs"),
3426 ItemType::Union => ("unions", "Unions"),
3427 ItemType::Enum => ("enums", "Enums"),
3428 ItemType::Function => ("functions", "Functions"),
3429 ItemType::Typedef => ("types", "Type Definitions"),
3430 ItemType::Static => ("statics", "Statics"),
3431 ItemType::Constant => ("constants", "Constants"),
3432 ItemType::Trait => ("traits", "Traits"),
3433 ItemType::Impl => ("impls", "Implementations"),
3434 ItemType::TyMethod => ("tymethods", "Type Methods"),
3435 ItemType::Method => ("methods", "Methods"),
3436 ItemType::StructField => ("fields", "Struct Fields"),
3437 ItemType::Variant => ("variants", "Variants"),
3438 ItemType::Macro => ("macros", "Macros"),
3439 ItemType::Primitive => ("primitives", "Primitive Types"),
3440 ItemType::AssociatedType => ("associated-types", "Associated Types"),
3441 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
3443 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3449 if !sidebar.is_empty() {
3450 write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3455 impl<'a> fmt::Display for Source<'a> {
3456 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3457 let Source(s) = *self;
3458 let lines = s.lines().count();
3460 let mut tmp = lines;
3465 write!(fmt, "<pre class=\"line-numbers\">")?;
3466 for i in 1..lines + 1 {
3467 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
3469 write!(fmt, "</pre>")?;
3470 write!(fmt, "{}", highlight::render_with_highlighting(s, None, None, None))?;
3475 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3476 t: &clean::Macro) -> fmt::Result {
3477 w.write_str(&highlight::render_with_highlighting(&t.source,
3484 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
3486 _p: &clean::PrimitiveType) -> fmt::Result {
3487 document(w, cx, it)?;
3488 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3491 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
3493 fn make_item_keywords(it: &clean::Item) -> String {
3494 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
3497 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
3498 let decl = match item.inner {
3499 clean::FunctionItem(ref f) => &f.decl,
3500 clean::MethodItem(ref m) => &m.decl,
3501 clean::TyMethodItem(ref m) => &m.decl,
3505 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
3506 let output = match decl.output {
3507 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
3511 Some(IndexItemFunctionType { inputs: inputs, output: output })
3514 fn get_index_type(clean_type: &clean::Type) -> Type {
3515 Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
3518 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
3520 clean::ResolvedPath { ref path, .. } => {
3521 let segments = &path.segments;
3522 Some(segments[segments.len() - 1].name.clone())
3524 clean::Generic(ref s) => Some(s.clone()),
3525 clean::Primitive(ref p) => Some(format!("{:?}", p)),
3526 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
3527 // FIXME: add all from clean::Type.
3532 pub fn cache() -> Arc<Cache> {
3533 CACHE_KEY.with(|c| c.borrow().clone())
3538 fn test_unique_id() {
3539 let input = ["foo", "examples", "examples", "method.into_iter","examples",
3540 "method.into_iter", "foo", "main", "search", "methods",
3541 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
3542 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
3543 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
3544 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
3547 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
3548 assert_eq!(&actual[..], expected);
3557 fn test_name_key() {
3558 assert_eq!(name_key("0"), ("", 0, 1));
3559 assert_eq!(name_key("123"), ("", 123, 0));
3560 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
3561 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
3562 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
3563 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
3564 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
3565 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
3570 fn test_name_sorting() {
3571 let names = ["Apple",
3573 "Fruit", "Fruit0", "Fruit00",
3574 "Fruit1", "Fruit01",
3575 "Fruit2", "Fruit02",
3579 let mut sorted = names.to_owned();
3580 sorted.sort_by_key(|&s| name_key(s));
3581 assert_eq!(names, sorted);