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};
76 use html::{highlight, layout};
78 /// A pair of name and its optional document.
79 pub type NameDoc = (String, Option<String>);
81 /// Major driving force in all rustdoc rendering. This contains information
82 /// about where in the tree-like hierarchy rendering is occurring and controls
83 /// how the current page is being rendered.
85 /// It is intended that this context is a lightweight object which can be fairly
86 /// easily cloned because it is cloned per work-job (about once per item in the
90 /// Current hierarchy of components leading down to what's currently being
92 pub current: Vec<String>,
93 /// The current destination folder of where HTML artifacts should be placed.
94 /// This changes as the context descends into the module hierarchy.
96 /// A flag, which when `true`, will render pages which redirect to the
97 /// real location of an item. This is used to allow external links to
98 /// publicly reused items to redirect to the right location.
99 pub render_redirect_pages: bool,
100 pub shared: Arc<SharedContext>,
103 pub struct SharedContext {
104 /// The path to the crate root source minus the file name.
105 /// Used for simplifying paths to the highlighted source code files.
106 pub src_root: PathBuf,
107 /// This describes the layout of each page, and is not modified after
108 /// creation of the context (contains info like the favicon and added html).
109 pub layout: layout::Layout,
110 /// This flag indicates whether [src] links should be generated or not. If
111 /// the source files are present in the html rendering, then this will be
113 pub include_sources: bool,
114 /// The local file sources we've emitted and their respective url-paths.
115 pub local_sources: FxHashMap<PathBuf, String>,
116 /// All the passes that were run on this crate.
117 pub passes: FxHashSet<String>,
118 /// The base-URL of the issue tracker for when an item has been tagged with
120 pub issue_tracker_base_url: Option<String>,
121 /// The given user css file which allow to customize the generated
122 /// documentation theme.
123 pub css_file_extension: Option<PathBuf>,
126 /// Indicates where an external crate can be found.
127 pub enum ExternalLocation {
128 /// Remote URL root of the external crate
130 /// This external crate can be found in the local doc/ folder
132 /// The external crate could not be found.
136 /// Metadata about an implementor of a trait.
137 pub struct Implementor {
139 pub stability: Option<clean::Stability>,
140 pub impl_: clean::Impl,
143 /// Metadata about implementations for a type.
146 pub impl_item: clean::Item,
150 fn inner_impl(&self) -> &clean::Impl {
151 match self.impl_item.inner {
152 clean::ImplItem(ref impl_) => impl_,
153 _ => panic!("non-impl item found in impl")
157 fn trait_did(&self) -> Option<DefId> {
158 self.inner_impl().trait_.def_id()
168 impl error::Error for Error {
169 fn description(&self) -> &str {
170 self.error.description()
174 impl Display for Error {
175 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
176 write!(f, "\"{}\": {}", self.file.display(), self.error)
181 pub fn new(e: io::Error, file: &Path) -> Error {
183 file: file.to_path_buf(),
189 macro_rules! try_err {
190 ($e:expr, $file:expr) => ({
193 Err(e) => return Err(Error::new(e, $file)),
198 /// This cache is used to store information about the `clean::Crate` being
199 /// rendered in order to provide more useful documentation. This contains
200 /// information like all implementors of a trait, all traits a type implements,
201 /// documentation for all known traits, etc.
203 /// This structure purposefully does not implement `Clone` because it's intended
204 /// to be a fairly large and expensive structure to clone. Instead this adheres
205 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
206 /// rendering threads.
209 /// Mapping of typaram ids to the name of the type parameter. This is used
210 /// when pretty-printing a type (so pretty printing doesn't have to
211 /// painfully maintain a context like this)
212 pub typarams: FxHashMap<DefId, String>,
214 /// Maps a type id to all known implementations for that type. This is only
215 /// recognized for intra-crate `ResolvedPath` types, and is used to print
216 /// out extra documentation on the page of an enum/struct.
218 /// The values of the map are a list of implementations and documentation
219 /// found on that implementation.
220 pub impls: FxHashMap<DefId, Vec<Impl>>,
222 /// Maintains a mapping of local crate node ids to the fully qualified name
223 /// and "short type description" of that node. This is used when generating
224 /// URLs when a type is being linked to. External paths are not located in
225 /// this map because the `External` type itself has all the information
227 pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
229 /// Similar to `paths`, but only holds external paths. This is only used for
230 /// generating explicit hyperlinks to other crates.
231 pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
233 /// This map contains information about all known traits of this crate.
234 /// Implementations of a crate should inherit the documentation of the
235 /// parent trait if no extra documentation is specified, and default methods
236 /// should show up in documentation about trait implementations.
237 pub traits: FxHashMap<DefId, clean::Trait>,
239 /// When rendering traits, it's often useful to be able to list all
240 /// implementors of the trait, and this mapping is exactly, that: a mapping
241 /// of trait ids to the list of known implementors of the trait
242 pub implementors: FxHashMap<DefId, Vec<Implementor>>,
244 /// Cache of where external crate documentation can be found.
245 pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
247 /// Cache of where documentation for primitives can be found.
248 pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
250 // Note that external items for which `doc(hidden)` applies to are shown as
251 // non-reachable while local items aren't. This is because we're reusing
252 // the access levels from crateanalysis.
253 pub access_levels: Arc<AccessLevels<DefId>>,
255 // Private fields only used when initially crawling a crate to build a cache
258 parent_stack: Vec<DefId>,
259 parent_is_trait_impl: bool,
260 search_index: Vec<IndexItem>,
262 deref_trait_did: Option<DefId>,
263 deref_mut_trait_did: Option<DefId>,
265 // In rare case where a structure is defined in one module but implemented
266 // in another, if the implementing module is parsed before defining module,
267 // then the fully qualified name of the structure isn't presented in `paths`
268 // yet when its implementation methods are being indexed. Caches such methods
269 // and their parent id here and indexes them at the end of crate parsing.
270 orphan_impl_items: Vec<(DefId, clean::Item)>,
273 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
274 /// Later on moved into `CACHE_KEY`.
276 pub struct RenderInfo {
277 pub inlined: FxHashSet<DefId>,
278 pub external_paths: ::core::ExternalPaths,
279 pub external_typarams: FxHashMap<DefId, String>,
280 pub deref_trait_did: Option<DefId>,
281 pub deref_mut_trait_did: Option<DefId>,
284 /// Helper struct to render all source code to HTML pages
285 struct SourceCollector<'a> {
286 scx: &'a mut SharedContext,
288 /// Root destination to place all HTML output into
292 /// Wrapper struct to render the source code of a file. This will do things like
293 /// adding line numbers to the left-hand side.
294 struct Source<'a>(&'a str);
296 // Helper structs for rendering items/sidebars and carrying along contextual
299 #[derive(Copy, Clone)]
302 item: &'a clean::Item,
305 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
307 /// Struct representing one entry in the JS search index. These are all emitted
308 /// by hand to a large JS file at the end of cache-creation.
314 parent: Option<DefId>,
315 parent_idx: Option<usize>,
316 search_type: Option<IndexItemFunctionType>,
319 impl ToJson for IndexItem {
320 fn to_json(&self) -> Json {
321 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
323 let mut data = Vec::with_capacity(6);
324 data.push((self.ty as usize).to_json());
325 data.push(self.name.to_json());
326 data.push(self.path.to_json());
327 data.push(self.desc.to_json());
328 data.push(self.parent_idx.to_json());
329 data.push(self.search_type.to_json());
335 /// A type used for the search index.
337 name: Option<String>,
340 impl ToJson for Type {
341 fn to_json(&self) -> Json {
344 let mut data = BTreeMap::new();
345 data.insert("name".to_owned(), name.to_json());
353 /// Full type of functions/methods in the search index.
354 struct IndexItemFunctionType {
359 impl ToJson for IndexItemFunctionType {
360 fn to_json(&self) -> Json {
361 // If we couldn't figure out a type, just write `null`.
362 if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
365 let mut data = BTreeMap::new();
366 data.insert("inputs".to_owned(), self.inputs.to_json());
367 data.insert("output".to_owned(), self.output.to_json());
373 // TLS keys used to carry information around during rendering.
375 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
376 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
377 RefCell::new(Vec::new()));
378 thread_local!(static USED_ID_MAP: RefCell<FxHashMap<String, usize>> =
379 RefCell::new(init_ids()));
381 fn init_ids() -> FxHashMap<String, usize> {
397 ].into_iter().map(|id| (String::from(*id), 1)).collect()
400 /// This method resets the local table of used ID attributes. This is typically
401 /// used at the beginning of rendering an entire HTML page to reset from the
402 /// previous state (if any).
403 pub fn reset_ids(embedded: bool) {
404 USED_ID_MAP.with(|s| {
405 *s.borrow_mut() = if embedded {
413 pub fn derive_id(candidate: String) -> String {
414 USED_ID_MAP.with(|map| {
415 let id = match map.borrow_mut().get_mut(&candidate) {
418 let id = format!("{}-{}", candidate, *a);
424 map.borrow_mut().insert(id.clone(), 1);
429 /// Generates the documentation for `crate` into the directory `dst`
430 pub fn run(mut krate: clean::Crate,
431 external_html: &ExternalHtml,
432 playground_url: Option<String>,
434 passes: FxHashSet<String>,
435 css_file_extension: Option<PathBuf>,
436 renderinfo: RenderInfo) -> Result<(), Error> {
437 let src_root = match krate.src.parent() {
438 Some(p) => p.to_path_buf(),
439 None => PathBuf::new(),
441 let mut scx = SharedContext {
444 include_sources: true,
445 local_sources: FxHashMap(),
446 issue_tracker_base_url: None,
447 layout: layout::Layout {
448 logo: "".to_string(),
449 favicon: "".to_string(),
450 external_html: external_html.clone(),
451 krate: krate.name.clone(),
453 css_file_extension: css_file_extension.clone(),
456 // If user passed in `--playground-url` arg, we fill in crate name here
457 if let Some(url) = playground_url {
458 markdown::PLAYGROUND.with(|slot| {
459 *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
463 // Crawl the crate attributes looking for attributes which control how we're
464 // going to emit HTML
465 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
466 for attr in attrs.lists("doc") {
467 let name = attr.name().map(|s| s.as_str());
468 match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
469 (Some("html_favicon_url"), Some(s)) => {
470 scx.layout.favicon = s.to_string();
472 (Some("html_logo_url"), Some(s)) => {
473 scx.layout.logo = s.to_string();
475 (Some("html_playground_url"), Some(s)) => {
476 markdown::PLAYGROUND.with(|slot| {
477 let name = krate.name.clone();
478 *slot.borrow_mut() = Some((Some(name), s.to_string()));
481 (Some("issue_tracker_base_url"), Some(s)) => {
482 scx.issue_tracker_base_url = Some(s.to_string());
484 (Some("html_no_source"), None) if attr.is_word() => {
485 scx.include_sources = false;
491 try_err!(mkdir(&dst), &dst);
492 krate = render_sources(&dst, &mut scx, krate)?;
496 render_redirect_pages: false,
497 shared: Arc::new(scx),
500 // Crawl the crate to build various caches used for the output
509 let external_paths = external_paths.into_iter()
510 .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
513 let mut cache = Cache {
515 external_paths: external_paths,
517 implementors: FxHashMap(),
519 parent_stack: Vec::new(),
520 search_index: Vec::new(),
521 parent_is_trait_impl: false,
522 extern_locations: FxHashMap(),
523 primitive_locations: FxHashMap(),
525 access_levels: krate.access_levels.clone(),
526 orphan_impl_items: Vec::new(),
527 traits: mem::replace(&mut krate.external_traits, FxHashMap()),
528 deref_trait_did: deref_trait_did,
529 deref_mut_trait_did: deref_mut_trait_did,
530 typarams: external_typarams,
533 // Cache where all our extern crates are located
534 for &(n, ref e) in &krate.externs {
535 let src_root = match Path::new(&e.src).parent() {
536 Some(p) => p.to_path_buf(),
537 None => PathBuf::new(),
539 cache.extern_locations.insert(n, (e.name.clone(), src_root,
540 extern_location(e, &cx.dst)));
542 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
543 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
546 // Cache where all known primitives have their documentation located.
548 // Favor linking to as local extern as possible, so iterate all crates in
549 // reverse topological order.
550 for &(_, ref e) in krate.externs.iter().rev() {
551 for &(def_id, prim, _) in &e.primitives {
552 cache.primitive_locations.insert(prim, def_id);
555 for &(def_id, prim, _) in &krate.primitives {
556 cache.primitive_locations.insert(prim, def_id);
559 cache.stack.push(krate.name.clone());
560 krate = cache.fold_crate(krate);
562 // Build our search index
563 let index = build_index(&krate, &mut cache);
565 // Freeze the cache now that the index has been built. Put an Arc into TLS
566 // for future parallelization opportunities
567 let cache = Arc::new(cache);
568 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
569 CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
571 write_shared(&cx, &krate, &*cache, index)?;
573 // And finally render the whole crate's documentation
577 /// Build the search index from the collected metadata
578 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
579 let mut nodeid_to_pathid = FxHashMap();
580 let mut crate_items = Vec::with_capacity(cache.search_index.len());
581 let mut crate_paths = Vec::<Json>::new();
583 let Cache { ref mut search_index,
584 ref orphan_impl_items,
585 ref mut paths, .. } = *cache;
587 // Attach all orphan items to the type's definition if the type
588 // has since been learned.
589 for &(did, ref item) in orphan_impl_items {
590 if let Some(&(ref fqp, _)) = paths.get(&did) {
591 search_index.push(IndexItem {
593 name: item.name.clone().unwrap(),
594 path: fqp[..fqp.len() - 1].join("::"),
595 desc: plain_summary_line(item.doc_value()),
598 search_type: get_index_search_type(&item),
603 // Reduce `NodeId` in paths into smaller sequential numbers,
604 // and prune the paths that do not appear in the index.
605 let mut lastpath = String::new();
606 let mut lastpathid = 0usize;
608 for item in search_index {
609 item.parent_idx = item.parent.map(|nodeid| {
610 if nodeid_to_pathid.contains_key(&nodeid) {
611 *nodeid_to_pathid.get(&nodeid).unwrap()
613 let pathid = lastpathid;
614 nodeid_to_pathid.insert(nodeid, pathid);
617 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
618 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
623 // Omit the parent path if it is same to that of the prior item.
624 if lastpath == item.path {
627 lastpath = item.path.clone();
629 crate_items.push(item.to_json());
632 let crate_doc = krate.module.as_ref().map(|module| {
633 plain_summary_line(module.doc_value())
634 }).unwrap_or(String::new());
636 let mut crate_data = BTreeMap::new();
637 crate_data.insert("doc".to_owned(), Json::String(crate_doc));
638 crate_data.insert("items".to_owned(), Json::Array(crate_items));
639 crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
641 // Collect the index into a string
642 format!("searchIndex[{}] = {};",
643 as_json(&krate.name),
644 Json::Object(crate_data))
647 fn write_shared(cx: &Context,
648 krate: &clean::Crate,
650 search_index: String) -> Result<(), Error> {
651 // Write out the shared files. Note that these are shared among all rustdoc
652 // docs placed in the output directory, so this needs to be a synchronized
653 // operation with respect to all other rustdocs running around.
654 try_err!(mkdir(&cx.dst), &cx.dst);
655 let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
657 // Add all the static files. These may already exist, but we just
658 // overwrite them anyway to make sure that they're fresh and up-to-date.
660 write(cx.dst.join("jquery.js"),
661 include_bytes!("static/jquery-2.1.4.min.js"))?;
662 write(cx.dst.join("main.js"),
663 include_bytes!("static/main.js"))?;
664 write(cx.dst.join("rustdoc.css"),
665 include_bytes!("static/rustdoc.css"))?;
666 write(cx.dst.join("main.css"),
667 include_bytes!("static/styles/main.css"))?;
668 if let Some(ref css) = cx.shared.css_file_extension {
669 let mut content = String::new();
670 let css = css.as_path();
671 let mut f = try_err!(File::open(css), css);
673 try_err!(f.read_to_string(&mut content), css);
674 let css = cx.dst.join("theme.css");
675 let css = css.as_path();
676 let mut f = try_err!(File::create(css), css);
677 try_err!(write!(f, "{}", &content), css);
679 write(cx.dst.join("normalize.css"),
680 include_bytes!("static/normalize.css"))?;
681 write(cx.dst.join("FiraSans-Regular.woff"),
682 include_bytes!("static/FiraSans-Regular.woff"))?;
683 write(cx.dst.join("FiraSans-Medium.woff"),
684 include_bytes!("static/FiraSans-Medium.woff"))?;
685 write(cx.dst.join("FiraSans-LICENSE.txt"),
686 include_bytes!("static/FiraSans-LICENSE.txt"))?;
687 write(cx.dst.join("Heuristica-Italic.woff"),
688 include_bytes!("static/Heuristica-Italic.woff"))?;
689 write(cx.dst.join("Heuristica-LICENSE.txt"),
690 include_bytes!("static/Heuristica-LICENSE.txt"))?;
691 write(cx.dst.join("SourceSerifPro-Regular.woff"),
692 include_bytes!("static/SourceSerifPro-Regular.woff"))?;
693 write(cx.dst.join("SourceSerifPro-Bold.woff"),
694 include_bytes!("static/SourceSerifPro-Bold.woff"))?;
695 write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
696 include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
697 write(cx.dst.join("SourceCodePro-Regular.woff"),
698 include_bytes!("static/SourceCodePro-Regular.woff"))?;
699 write(cx.dst.join("SourceCodePro-Semibold.woff"),
700 include_bytes!("static/SourceCodePro-Semibold.woff"))?;
701 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
702 include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
703 write(cx.dst.join("LICENSE-MIT.txt"),
704 include_bytes!("static/LICENSE-MIT.txt"))?;
705 write(cx.dst.join("LICENSE-APACHE.txt"),
706 include_bytes!("static/LICENSE-APACHE.txt"))?;
707 write(cx.dst.join("COPYRIGHT.txt"),
708 include_bytes!("static/COPYRIGHT.txt"))?;
710 fn collect(path: &Path, krate: &str,
711 key: &str) -> io::Result<Vec<String>> {
712 let mut ret = Vec::new();
714 for line in BufReader::new(File::open(path)?).lines() {
716 if !line.starts_with(key) {
719 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
722 ret.push(line.to_string());
728 // Update the search index
729 let dst = cx.dst.join("search-index.js");
730 let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
731 all_indexes.push(search_index);
732 // Sort the indexes by crate so the file will be generated identically even
733 // with rustdoc running in parallel.
735 let mut w = try_err!(File::create(&dst), &dst);
736 try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
737 for index in &all_indexes {
738 try_err!(writeln!(&mut w, "{}", *index), &dst);
740 try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
742 // Update the list of all implementors for traits
743 let dst = cx.dst.join("implementors");
744 for (&did, imps) in &cache.implementors {
745 // Private modules can leak through to this phase of rustdoc, which
746 // could contain implementations for otherwise private types. In some
747 // rare cases we could find an implementation for an item which wasn't
748 // indexed, so we just skip this step in that case.
750 // FIXME: this is a vague explanation for why this can't be a `get`, in
751 // theory it should be...
752 let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
754 None => match cache.external_paths.get(&did) {
760 let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
762 // If the trait and implementation are in the same crate, then
763 // there's no need to emit information about it (there's inlining
764 // going on). If they're in different crates then the crate defining
765 // the trait will be interested in our implementation.
766 if imp.def_id.krate == did.krate { continue }
767 write!(implementors, "{},", as_json(&imp.impl_.to_string())).unwrap();
769 implementors.push_str("];");
771 let mut mydst = dst.clone();
772 for part in &remote_path[..remote_path.len() - 1] {
775 try_err!(fs::create_dir_all(&mydst), &mydst);
776 mydst.push(&format!("{}.{}.js",
777 remote_item_type.css_class(),
778 remote_path[remote_path.len() - 1]));
780 let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
781 all_implementors.push(implementors);
782 // Sort the implementors by crate so the file will be generated
783 // identically even with rustdoc running in parallel.
784 all_implementors.sort();
786 let mut f = try_err!(File::create(&mydst), &mydst);
787 try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
788 for implementor in &all_implementors {
789 try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
791 try_err!(writeln!(&mut f, "{}", r"
792 if (window.register_implementors) {
793 window.register_implementors(implementors);
795 window.pending_implementors = implementors;
798 try_err!(writeln!(&mut f, r"}})()"), &mydst);
803 fn render_sources(dst: &Path, scx: &mut SharedContext,
804 krate: clean::Crate) -> Result<clean::Crate, Error> {
805 info!("emitting source files");
806 let dst = dst.join("src");
807 try_err!(mkdir(&dst), &dst);
808 let dst = dst.join(&krate.name);
809 try_err!(mkdir(&dst), &dst);
810 let mut folder = SourceCollector {
814 Ok(folder.fold_crate(krate))
817 /// Writes the entire contents of a string to a destination, not attempting to
818 /// catch any errors.
819 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
820 Ok(try_err!(try_err!(File::create(&dst), &dst).write_all(contents), &dst))
823 /// Makes a directory on the filesystem, failing the thread if an error occurs
824 /// and skipping if the directory already exists.
826 /// Note that this also handles races as rustdoc is likely to be run
827 /// concurrently against another invocation.
828 fn mkdir(path: &Path) -> io::Result<()> {
829 match fs::create_dir(path) {
831 Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
836 /// Takes a path to a source file and cleans the path to it. This canonicalizes
837 /// things like ".." to components which preserve the "top down" hierarchy of a
838 /// static HTML tree. Each component in the cleaned path will be passed as an
839 /// argument to `f`. The very last component of the path (ie the file name) will
840 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
841 // FIXME (#9639): The closure should deal with &[u8] instead of &str
842 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
843 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
846 // make it relative, if possible
847 let p = p.strip_prefix(src_root).unwrap_or(p);
849 let mut iter = p.components().peekable();
851 while let Some(c) = iter.next() {
852 if !keep_filename && iter.peek().is_none() {
857 Component::ParentDir => f("up"),
858 Component::Normal(c) => f(c.to_str().unwrap()),
864 /// Attempts to find where an external crate is located, given that we're
865 /// rendering in to the specified source destination.
866 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
867 // See if there's documentation generated into the local directory
868 let local_location = dst.join(&e.name);
869 if local_location.is_dir() {
873 // Failing that, see if there's an attribute specifying where to find this
876 .filter(|a| a.check_name("html_root_url"))
877 .filter_map(|a| a.value_str())
879 let mut url = url.to_string();
880 if !url.ends_with("/") {
884 }).next().unwrap_or(Unknown) // Well, at least we tried.
887 impl<'a> DocFolder for SourceCollector<'a> {
888 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
889 // If we're including source files, and we haven't seen this file yet,
890 // then we need to render it out to the filesystem.
891 if self.scx.include_sources
892 // skip all invalid spans
893 && item.source.filename != ""
894 // skip non-local items
895 && item.def_id.is_local()
896 // Macros from other libraries get special filenames which we can
898 && !(item.source.filename.starts_with("<")
899 && item.source.filename.ends_with("macros>")) {
901 // If it turns out that we couldn't read this file, then we probably
902 // can't read any of the files (generating html output from json or
903 // something like that), so just don't include sources for the
904 // entire crate. The other option is maintaining this mapping on a
905 // per-file basis, but that's probably not worth it...
907 .include_sources = match self.emit_source(&item.source.filename) {
910 println!("warning: source code was requested to be rendered, \
911 but processing `{}` had an error: {}",
912 item.source.filename, e);
913 println!(" skipping rendering of source code");
918 self.fold_item_recur(item)
922 impl<'a> SourceCollector<'a> {
923 /// Renders the given filename into its corresponding HTML source file.
924 fn emit_source(&mut self, filename: &str) -> io::Result<()> {
925 let p = PathBuf::from(filename);
926 if self.scx.local_sources.contains_key(&p) {
927 // We've already emitted this source
931 let mut contents = Vec::new();
932 File::open(&p).and_then(|mut f| f.read_to_end(&mut contents))?;
934 let contents = str::from_utf8(&contents).unwrap();
936 // Remove the utf-8 BOM if any
937 let contents = if contents.starts_with("\u{feff}") {
943 // Create the intermediate directories
944 let mut cur = self.dst.clone();
945 let mut root_path = String::from("../../");
946 let mut href = String::new();
947 clean_srcpath(&self.scx.src_root, &p, false, |component| {
949 mkdir(&cur).unwrap();
950 root_path.push_str("../");
951 href.push_str(component);
954 let mut fname = p.file_name().expect("source has no filename")
958 href.push_str(&fname.to_string_lossy());
960 let mut w = BufWriter::new(File::create(&cur)?);
961 let title = format!("{} -- source", cur.file_name().unwrap()
963 let desc = format!("Source to the Rust file `{}`.", filename);
964 let page = layout::Page {
967 root_path: &root_path,
969 keywords: BASIC_KEYWORDS,
971 layout::render(&mut w, &self.scx.layout,
972 &page, &(""), &Source(contents),
973 self.scx.css_file_extension.is_some())?;
975 self.scx.local_sources.insert(p, href);
980 impl DocFolder for Cache {
981 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
982 // If this is a stripped module,
983 // we don't want it or its children in the search index.
984 let orig_stripped_mod = match item.inner {
985 clean::StrippedItem(box clean::ModuleItem(..)) => {
986 mem::replace(&mut self.stripped_mod, true)
988 _ => self.stripped_mod,
991 // Register any generics to their corresponding string. This is used
992 // when pretty-printing types.
993 if let Some(generics) = item.inner.generics() {
994 self.generics(generics);
997 // Propagate a trait method's documentation to all implementors of the
999 if let clean::TraitItem(ref t) = item.inner {
1000 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1003 // Collect all the implementors of traits.
1004 if let clean::ImplItem(ref i) = item.inner {
1005 if let Some(did) = i.trait_.def_id() {
1006 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
1007 def_id: item.def_id,
1008 stability: item.stability.clone(),
1014 // Index this method for searching later on.
1015 if let Some(ref s) = item.name {
1016 let (parent, is_inherent_impl_item) = match item.inner {
1017 clean::StrippedItem(..) => ((None, None), false),
1018 clean::AssociatedConstItem(..) |
1019 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1020 // skip associated items in trait impls
1021 ((None, None), false)
1023 clean::AssociatedTypeItem(..) |
1024 clean::TyMethodItem(..) |
1025 clean::StructFieldItem(..) |
1026 clean::VariantItem(..) => {
1027 ((Some(*self.parent_stack.last().unwrap()),
1028 Some(&self.stack[..self.stack.len() - 1])),
1031 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1032 if self.parent_stack.is_empty() {
1033 ((None, None), false)
1035 let last = self.parent_stack.last().unwrap();
1037 let path = match self.paths.get(&did) {
1038 // The current stack not necessarily has correlation
1039 // for where the type was defined. On the other
1040 // hand, `paths` always has the right
1041 // information if present.
1042 Some(&(ref fqp, ItemType::Trait)) |
1043 Some(&(ref fqp, ItemType::Struct)) |
1044 Some(&(ref fqp, ItemType::Union)) |
1045 Some(&(ref fqp, ItemType::Enum)) =>
1046 Some(&fqp[..fqp.len() - 1]),
1047 Some(..) => Some(&*self.stack),
1050 ((Some(*last), path), true)
1053 _ => ((None, Some(&*self.stack)), false)
1057 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1058 debug_assert!(!item.is_stripped());
1060 // A crate has a module at its root, containing all items,
1061 // which should not be indexed. The crate-item itself is
1062 // inserted later on when serializing the search-index.
1063 if item.def_id.index != CRATE_DEF_INDEX {
1064 self.search_index.push(IndexItem {
1066 name: s.to_string(),
1067 path: path.join("::").to_string(),
1068 desc: plain_summary_line(item.doc_value()),
1071 search_type: get_index_search_type(&item),
1075 (Some(parent), None) if is_inherent_impl_item => {
1076 // We have a parent, but we don't know where they're
1077 // defined yet. Wait for later to index this item.
1078 self.orphan_impl_items.push((parent, item.clone()));
1084 // Keep track of the fully qualified path for this item.
1085 let pushed = match item.name {
1086 Some(ref n) if !n.is_empty() => {
1087 self.stack.push(n.to_string());
1094 clean::StructItem(..) | clean::EnumItem(..) |
1095 clean::TypedefItem(..) | clean::TraitItem(..) |
1096 clean::FunctionItem(..) | clean::ModuleItem(..) |
1097 clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1098 clean::ConstantItem(..) | clean::StaticItem(..) |
1099 clean::UnionItem(..)
1100 if !self.stripped_mod => {
1101 // Reexported items mean that the same id can show up twice
1102 // in the rustdoc ast that we're looking at. We know,
1103 // however, that a reexported item doesn't show up in the
1104 // `public_items` map, so we can skip inserting into the
1105 // paths map if there was already an entry present and we're
1106 // not a public item.
1108 !self.paths.contains_key(&item.def_id) ||
1109 self.access_levels.is_public(item.def_id)
1111 self.paths.insert(item.def_id,
1112 (self.stack.clone(), item.type_()));
1115 // Link variants to their parent enum because pages aren't emitted
1116 // for each variant.
1117 clean::VariantItem(..) if !self.stripped_mod => {
1118 let mut stack = self.stack.clone();
1120 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1123 clean::PrimitiveItem(..) if item.visibility.is_some() => {
1124 self.paths.insert(item.def_id, (self.stack.clone(),
1131 // Maintain the parent stack
1132 let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1133 let parent_pushed = match item.inner {
1134 clean::TraitItem(..) | clean::EnumItem(..) |
1135 clean::StructItem(..) | clean::UnionItem(..) => {
1136 self.parent_stack.push(item.def_id);
1137 self.parent_is_trait_impl = false;
1140 clean::ImplItem(ref i) => {
1141 self.parent_is_trait_impl = i.trait_.is_some();
1143 clean::ResolvedPath{ did, .. } => {
1144 self.parent_stack.push(did);
1148 let prim_did = t.primitive_type().and_then(|t| {
1149 self.primitive_locations.get(&t).cloned()
1153 self.parent_stack.push(did);
1164 // Once we've recursively found all the generics, hoard off all the
1165 // implementations elsewhere.
1166 let ret = self.fold_item_recur(item).and_then(|item| {
1167 if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1168 // Figure out the id of this impl. This may map to a
1169 // primitive rather than always to a struct/enum.
1170 // Note: matching twice to restrict the lifetime of the `i` borrow.
1171 let did = if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1173 clean::ResolvedPath { did, .. } |
1174 clean::BorrowedRef {
1175 type_: box clean::ResolvedPath { did, .. }, ..
1180 t.primitive_type().and_then(|t| {
1181 self.primitive_locations.get(&t).cloned()
1188 if let Some(did) = did {
1189 self.impls.entry(did).or_insert(vec![]).push(Impl {
1199 if pushed { self.stack.pop().unwrap(); }
1200 if parent_pushed { self.parent_stack.pop().unwrap(); }
1201 self.stripped_mod = orig_stripped_mod;
1202 self.parent_is_trait_impl = orig_parent_is_trait_impl;
1208 fn generics(&mut self, generics: &clean::Generics) {
1209 for typ in &generics.type_params {
1210 self.typarams.insert(typ.did, typ.name.clone());
1216 /// String representation of how to get back to the root path of the 'doc/'
1217 /// folder in terms of a relative URL.
1218 fn root_path(&self) -> String {
1219 repeat("../").take(self.current.len()).collect::<String>()
1222 /// Recurse in the directory structure and change the "root path" to make
1223 /// sure it always points to the top (relatively).
1224 fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1225 F: FnOnce(&mut Context) -> T,
1228 panic!("Unexpected empty destination: {:?}", self.current);
1230 let prev = self.dst.clone();
1232 self.current.push(s);
1234 info!("Recursing into {}", self.dst.display());
1238 info!("Recursed; leaving {}", self.dst.display());
1240 // Go back to where we were at
1242 self.current.pop().unwrap();
1247 /// Main method for rendering a crate.
1249 /// This currently isn't parallelized, but it'd be pretty easy to add
1250 /// parallelization to this function.
1251 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1252 let mut item = match krate.module.take() {
1254 None => return Ok(()),
1256 item.name = Some(krate.name);
1258 // Render the crate documentation
1259 let mut work = vec![(self, item)];
1261 while let Some((mut cx, item)) = work.pop() {
1262 cx.item(item, |cx, item| {
1263 work.push((cx.clone(), item))
1269 fn render_item(&self,
1270 writer: &mut io::Write,
1274 // A little unfortunate that this is done like this, but it sure
1275 // does make formatting *a lot* nicer.
1276 CURRENT_LOCATION_KEY.with(|slot| {
1277 *slot.borrow_mut() = self.current.clone();
1280 let mut title = if it.is_primitive() {
1281 // No need to include the namespace for primitive types
1284 self.current.join("::")
1287 if !title.is_empty() {
1288 title.push_str("::");
1290 title.push_str(it.name.as_ref().unwrap());
1292 title.push_str(" - Rust");
1293 let tyname = it.type_().css_class();
1294 let desc = if it.is_crate() {
1295 format!("API documentation for the Rust `{}` crate.",
1296 self.shared.layout.krate)
1298 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1299 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1301 let keywords = make_item_keywords(it);
1302 let page = layout::Page {
1304 root_path: &self.root_path(),
1307 keywords: &keywords,
1312 if !self.render_redirect_pages {
1313 layout::render(writer, &self.shared.layout, &page,
1314 &Sidebar{ cx: self, item: it },
1315 &Item{ cx: self, item: it },
1316 self.shared.css_file_extension.is_some())?;
1318 let mut url = self.root_path();
1319 if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1320 for name in &names[..names.len() - 1] {
1324 url.push_str(&item_path(ty, names.last().unwrap()));
1325 layout::redirect(writer, &url)?;
1331 /// Non-parallelized version of rendering an item. This will take the input
1332 /// item, render its contents, and then invoke the specified closure with
1333 /// all sub-items which need to be rendered.
1335 /// The rendering driver uses this closure to queue up more work.
1336 fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1337 F: FnMut(&mut Context, clean::Item),
1339 // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1340 // if they contain impls for public types. These modules can also
1341 // contain items such as publicly reexported structures.
1343 // External crates will provide links to these structures, so
1344 // these modules are recursed into, but not rendered normally
1345 // (a flag on the context).
1346 if !self.render_redirect_pages {
1347 self.render_redirect_pages = maybe_ignore_item(&item);
1351 // modules are special because they add a namespace. We also need to
1352 // recurse into the items of the module as well.
1353 let name = item.name.as_ref().unwrap().to_string();
1354 let mut item = Some(item);
1355 self.recurse(name, |this| {
1356 let item = item.take().unwrap();
1358 let mut buf = Vec::new();
1359 this.render_item(&mut buf, &item, false).unwrap();
1360 // buf will be empty if the module is stripped and there is no redirect for it
1361 if !buf.is_empty() {
1362 let joint_dst = this.dst.join("index.html");
1363 try_err!(fs::create_dir_all(&this.dst), &this.dst);
1364 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1365 try_err!(dst.write_all(&buf), &joint_dst);
1368 let m = match item.inner {
1369 clean::StrippedItem(box clean::ModuleItem(m)) |
1370 clean::ModuleItem(m) => m,
1374 // Render sidebar-items.js used throughout this module.
1375 if !this.render_redirect_pages {
1376 let items = this.build_sidebar_items(&m);
1377 let js_dst = this.dst.join("sidebar-items.js");
1378 let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1379 try_err!(write!(&mut js_out, "initSidebarItems({});",
1380 as_json(&items)), &js_dst);
1383 for item in m.items {
1389 } else if item.name.is_some() {
1390 let mut buf = Vec::new();
1391 self.render_item(&mut buf, &item, true).unwrap();
1392 // buf will be empty if the item is stripped and there is no redirect for it
1393 if !buf.is_empty() {
1394 let name = item.name.as_ref().unwrap();
1395 let item_type = item.type_();
1396 let file_name = &item_path(item_type, name);
1397 let joint_dst = self.dst.join(file_name);
1398 try_err!(fs::create_dir_all(&self.dst), &self.dst);
1399 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1400 try_err!(dst.write_all(&buf), &joint_dst);
1402 // Redirect from a sane URL using the namespace to Rustdoc's
1403 // URL for the page.
1404 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1405 let redir_dst = self.dst.join(redir_name);
1406 if let Ok(mut redirect_out) = OpenOptions::new().create_new(true)
1409 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1412 // If the item is a macro, redirect from the old macro URL (with !)
1413 // to the new one (without).
1414 // FIXME(#35705) remove this redirect.
1415 if item_type == ItemType::Macro {
1416 let redir_name = format!("{}.{}!.html", item_type, name);
1417 let redir_dst = self.dst.join(redir_name);
1418 let mut redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1419 try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1426 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1427 // BTreeMap instead of HashMap to get a sorted output
1428 let mut map = BTreeMap::new();
1429 for item in &m.items {
1430 if maybe_ignore_item(item) { continue }
1432 let short = item.type_().css_class();
1433 let myname = match item.name {
1435 Some(ref s) => s.to_string(),
1437 let short = short.to_string();
1438 map.entry(short).or_insert(vec![])
1439 .push((myname, Some(plain_summary_line(item.doc_value()))));
1442 for (_, items) in &mut map {
1450 /// Generate a url appropriate for an `href` attribute back to the source of
1453 /// The url generated, when clicked, will redirect the browser back to the
1454 /// original source code.
1456 /// If `None` is returned, then a source link couldn't be generated. This
1457 /// may happen, for example, with externally inlined items where the source
1458 /// of their crate documentation isn't known.
1459 fn src_href(&self) -> Option<String> {
1460 let mut root = self.cx.root_path();
1462 let cache = cache();
1463 let mut path = String::new();
1464 let (krate, path) = if self.item.def_id.is_local() {
1465 let path = PathBuf::from(&self.item.source.filename);
1466 if let Some(path) = self.cx.shared.local_sources.get(&path) {
1467 (&self.cx.shared.layout.krate, path)
1472 // Macros from other libraries get special filenames which we can
1474 if self.item.source.filename.starts_with("<") &&
1475 self.item.source.filename.ends_with("macros>") {
1479 let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1480 Some(&(ref name, ref src, Local)) => (name, src),
1481 Some(&(ref name, ref src, Remote(ref s))) => {
1482 root = s.to_string();
1485 Some(&(_, _, Unknown)) | None => return None,
1488 let file = Path::new(&self.item.source.filename);
1489 clean_srcpath(&src_root, file, false, |component| {
1490 path.push_str(component);
1493 let mut fname = file.file_name().expect("source has no filename")
1495 fname.push(".html");
1496 path.push_str(&fname.to_string_lossy());
1500 let lines = if self.item.source.loline == self.item.source.hiline {
1501 format!("{}", self.item.source.loline)
1503 format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1505 Some(format!("{root}src/{krate}/{path}#{lines}",
1513 impl<'a> fmt::Display for Item<'a> {
1514 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1515 debug_assert!(!self.item.is_stripped());
1516 // Write the breadcrumb trail header for the top
1517 write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1518 match self.item.inner {
1519 clean::ModuleItem(ref m) => if m.is_crate {
1520 write!(fmt, "Crate ")?;
1522 write!(fmt, "Module ")?;
1524 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) =>
1525 write!(fmt, "Function ")?,
1526 clean::TraitItem(..) => write!(fmt, "Trait ")?,
1527 clean::StructItem(..) => write!(fmt, "Struct ")?,
1528 clean::UnionItem(..) => write!(fmt, "Union ")?,
1529 clean::EnumItem(..) => write!(fmt, "Enum ")?,
1530 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1531 clean::MacroItem(..) => write!(fmt, "Macro ")?,
1532 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1533 clean::StaticItem(..) | clean::ForeignStaticItem(..) =>
1534 write!(fmt, "Static ")?,
1535 clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1537 // We don't generate pages for any other type.
1541 if !self.item.is_primitive() {
1542 let cur = &self.cx.current;
1543 let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1544 for (i, component) in cur.iter().enumerate().take(amt) {
1545 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1546 repeat("../").take(cur.len() - i - 1)
1547 .collect::<String>(),
1551 write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1552 self.item.type_(), self.item.name.as_ref().unwrap())?;
1554 write!(fmt, "</span>")?; // in-band
1555 write!(fmt, "<span class='out-of-band'>")?;
1556 if let Some(version) = self.item.stable_since() {
1557 write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1561 r##"<span id='render-detail'>
1562 <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1563 [<span class='inner'>−</span>]
1569 // When this item is part of a `pub use` in a downstream crate, the
1570 // [src] link in the downstream documentation will actually come back to
1571 // this page, and this link will be auto-clicked. The `id` attribute is
1572 // used to find the link to auto-click.
1573 if self.cx.shared.include_sources && !self.item.is_primitive() {
1574 if let Some(l) = self.src_href() {
1575 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1576 l, "goto source code")?;
1580 write!(fmt, "</span>")?; // out-of-band
1582 write!(fmt, "</h1>\n")?;
1584 match self.item.inner {
1585 clean::ModuleItem(ref m) => {
1586 item_module(fmt, self.cx, self.item, &m.items)
1588 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1589 item_function(fmt, self.cx, self.item, f),
1590 clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1591 clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1592 clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1593 clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1594 clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1595 clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1596 clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1597 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1598 item_static(fmt, self.cx, self.item, i),
1599 clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1601 // We don't generate pages for any other type.
1608 fn item_path(ty: ItemType, name: &str) -> String {
1610 ItemType::Module => format!("{}/index.html", name),
1611 _ => format!("{}.{}.html", ty.css_class(), name),
1615 fn full_path(cx: &Context, item: &clean::Item) -> String {
1616 let mut s = cx.current.join("::");
1618 s.push_str(item.name.as_ref().unwrap());
1622 fn shorter<'a>(s: Option<&'a str>) -> String {
1624 Some(s) => s.lines().take_while(|line|{
1625 (*line).chars().any(|chr|{
1626 !chr.is_whitespace()
1628 }).collect::<Vec<_>>().join("\n"),
1629 None => "".to_string()
1634 fn plain_summary_line(s: Option<&str>) -> String {
1635 let line = shorter(s).replace("\n", " ");
1636 markdown::plain_summary_line(&line[..])
1639 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1640 document_stability(w, cx, item)?;
1641 document_full(w, item)?;
1645 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink) -> fmt::Result {
1646 if let Some(s) = item.doc_value() {
1647 let markdown = if s.contains('\n') {
1648 format!("{} [Read more]({})",
1649 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1651 format!("{}", &plain_summary_line(Some(s)))
1653 write!(w, "<div class='docblock'>{}</div>",
1654 Markdown(&markdown))?;
1659 fn md_render_assoc_item(item: &clean::Item) -> String {
1661 clean::AssociatedConstItem(ref ty, ref default) => {
1662 if let Some(default) = default.as_ref() {
1663 format!("```\n{}: {:?} = {}\n```\n\n", item.name.as_ref().unwrap(), ty, default)
1665 format!("```\n{}: {:?}\n```\n\n", item.name.as_ref().unwrap(), ty)
1672 fn get_doc_value(item: &clean::Item) -> Option<&str> {
1673 let x = item.doc_value();
1676 clean::AssociatedConstItem(_, _) => Some(""),
1684 fn document_full(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
1685 if let Some(s) = get_doc_value(item) {
1686 write!(w, "<div class='docblock'>{}</div>",
1687 Markdown(&format!("{}{}", md_render_assoc_item(item), s)))?;
1692 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1693 let stabilities = short_stability(item, cx, true);
1694 if !stabilities.is_empty() {
1695 write!(w, "<div class='stability'>")?;
1696 for stability in stabilities {
1697 write!(w, "{}", stability)?;
1699 write!(w, "</div>")?;
1704 fn name_key(name: &str) -> (&str, u64, usize) {
1705 // find number at end
1706 let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1708 // count leading zeroes
1710 name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1712 // sort leading zeroes last
1713 let num_zeroes = after_zeroes - split;
1715 match name[split..].parse() {
1716 Ok(n) => (&name[..split], n, num_zeroes),
1717 Err(_) => (name, 0, num_zeroes),
1721 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1722 item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1723 document(w, cx, item)?;
1725 let mut indices = (0..items.len()).filter(|i| {
1726 if let clean::DefaultImplItem(..) = items[*i].inner {
1729 !maybe_ignore_item(&items[*i])
1730 }).collect::<Vec<usize>>();
1732 // the order of item types in the listing
1733 fn reorder(ty: ItemType) -> u8 {
1735 ItemType::ExternCrate => 0,
1736 ItemType::Import => 1,
1737 ItemType::Primitive => 2,
1738 ItemType::Module => 3,
1739 ItemType::Macro => 4,
1740 ItemType::Struct => 5,
1741 ItemType::Enum => 6,
1742 ItemType::Constant => 7,
1743 ItemType::Static => 8,
1744 ItemType::Trait => 9,
1745 ItemType::Function => 10,
1746 ItemType::Typedef => 12,
1747 ItemType::Union => 13,
1752 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1753 let ty1 = i1.type_();
1754 let ty2 = i2.type_();
1756 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1758 let s1 = i1.stability.as_ref().map(|s| s.level);
1759 let s2 = i2.stability.as_ref().map(|s| s.level);
1761 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1762 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1765 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1766 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1767 name_key(lhs).cmp(&name_key(rhs))
1770 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1772 debug!("{:?}", indices);
1773 let mut curty = None;
1774 for &idx in &indices {
1775 let myitem = &items[idx];
1776 if myitem.is_stripped() {
1780 let myty = Some(myitem.type_());
1781 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1782 // Put `extern crate` and `use` re-exports in the same section.
1784 } else if myty != curty {
1785 if curty.is_some() {
1786 write!(w, "</table>")?;
1789 let (short, name) = match myty.unwrap() {
1790 ItemType::ExternCrate |
1791 ItemType::Import => ("reexports", "Reexports"),
1792 ItemType::Module => ("modules", "Modules"),
1793 ItemType::Struct => ("structs", "Structs"),
1794 ItemType::Union => ("unions", "Unions"),
1795 ItemType::Enum => ("enums", "Enums"),
1796 ItemType::Function => ("functions", "Functions"),
1797 ItemType::Typedef => ("types", "Type Definitions"),
1798 ItemType::Static => ("statics", "Statics"),
1799 ItemType::Constant => ("constants", "Constants"),
1800 ItemType::Trait => ("traits", "Traits"),
1801 ItemType::Impl => ("impls", "Implementations"),
1802 ItemType::TyMethod => ("tymethods", "Type Methods"),
1803 ItemType::Method => ("methods", "Methods"),
1804 ItemType::StructField => ("fields", "Struct Fields"),
1805 ItemType::Variant => ("variants", "Variants"),
1806 ItemType::Macro => ("macros", "Macros"),
1807 ItemType::Primitive => ("primitives", "Primitive Types"),
1808 ItemType::AssociatedType => ("associated-types", "Associated Types"),
1809 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1811 write!(w, "<h2 id='{id}' class='section-header'>\
1812 <a href=\"#{id}\">{name}</a></h2>\n<table>",
1813 id = derive_id(short.to_owned()), name = name)?;
1816 match myitem.inner {
1817 clean::ExternCrateItem(ref name, ref src) => {
1818 use html::format::HRef;
1822 write!(w, "<tr><td><code>{}extern crate {} as {};",
1823 VisSpace(&myitem.visibility),
1824 HRef::new(myitem.def_id, src),
1828 write!(w, "<tr><td><code>{}extern crate {};",
1829 VisSpace(&myitem.visibility),
1830 HRef::new(myitem.def_id, name))?
1833 write!(w, "</code></td></tr>")?;
1836 clean::ImportItem(ref import) => {
1837 write!(w, "<tr><td><code>{}{}</code></td></tr>",
1838 VisSpace(&myitem.visibility), *import)?;
1842 if myitem.name.is_none() { continue }
1844 let stabilities = short_stability(myitem, cx, false);
1846 let stab_docs = if !stabilities.is_empty() {
1848 .map(|s| format!("[{}]", s))
1849 .collect::<Vec<_>>()
1856 let unsafety_flag = match myitem.inner {
1857 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
1858 if func.unsafety == hir::Unsafety::Unsafe => {
1859 "<a title='unsafe function' href='#'><sup>âš </sup></a>"
1864 let doc_value = myitem.doc_value().unwrap_or("");
1866 <tr class='{stab} module-item'>
1867 <td><a class=\"{class}\" href=\"{href}\"
1868 title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
1869 <td class='docblock-short'>
1873 name = *myitem.name.as_ref().unwrap(),
1874 stab_docs = stab_docs,
1875 docs = MarkdownSummaryLine(doc_value),
1876 class = myitem.type_(),
1877 stab = myitem.stability_class().unwrap_or("".to_string()),
1878 unsafety_flag = unsafety_flag,
1879 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
1880 title_type = myitem.type_(),
1881 title = full_path(cx, myitem))?;
1886 if curty.is_some() {
1887 write!(w, "</table>")?;
1892 fn maybe_ignore_item(it: &clean::Item) -> bool {
1894 clean::StrippedItem(..) => true,
1895 clean::ModuleItem(ref m) => {
1896 it.doc_value().is_none() && m.items.is_empty()
1897 && it.visibility != Some(clean::Public)
1903 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
1904 let mut stability = vec![];
1906 if let Some(stab) = item.stability.as_ref() {
1907 let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
1908 format!(": {}", stab.deprecated_reason)
1912 if !stab.deprecated_since.is_empty() {
1913 let since = if show_reason {
1914 format!(" since {}", Escape(&stab.deprecated_since))
1918 let text = format!("Deprecated{}{}", since, MarkdownHtml(&deprecated_reason));
1919 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
1922 if stab.level == stability::Unstable {
1924 let unstable_extra = match (!stab.feature.is_empty(),
1925 &cx.shared.issue_tracker_base_url,
1927 (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1928 format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
1929 Escape(&stab.feature), tracker_url, issue_no, issue_no),
1930 (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1931 format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
1934 format!(" (<code>{}</code>)", Escape(&stab.feature)),
1937 if stab.unstable_reason.is_empty() {
1938 stability.push(format!("<div class='stab unstable'>\
1939 <span class=microscope>🔬</span> \
1940 This is a nightly-only experimental API. {}\
1944 let text = format!("<summary><span class=microscope>🔬</span> \
1945 This is a nightly-only experimental API. {}\
1947 unstable_extra, MarkdownHtml(&stab.unstable_reason));
1948 stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
1952 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
1955 } else if let Some(depr) = item.deprecation.as_ref() {
1956 let note = if show_reason && !depr.note.is_empty() {
1957 format!(": {}", depr.note)
1961 let since = if show_reason && !depr.since.is_empty() {
1962 format!(" since {}", Escape(&depr.since))
1967 let text = format!("Deprecated{}{}", since, MarkdownHtml(¬e));
1968 stability.push(format!("<div class='stab deprecated'>{}</div>", text))
1974 struct Initializer<'a>(&'a str);
1976 impl<'a> fmt::Display for Initializer<'a> {
1977 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1978 let Initializer(s) = *self;
1979 if s.is_empty() { return Ok(()); }
1980 write!(f, "<code> = </code>")?;
1981 write!(f, "<code>{}</code>", Escape(s))
1985 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1986 c: &clean::Constant) -> fmt::Result {
1987 write!(w, "<pre class='rust const'>")?;
1988 render_attributes(w, it)?;
1989 write!(w, "{vis}const \
1990 {name}: {typ}{init}</pre>",
1991 vis = VisSpace(&it.visibility),
1992 name = it.name.as_ref().unwrap(),
1994 init = Initializer(&c.expr))?;
1998 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1999 s: &clean::Static) -> fmt::Result {
2000 write!(w, "<pre class='rust static'>")?;
2001 render_attributes(w, it)?;
2002 write!(w, "{vis}static {mutability}\
2003 {name}: {typ}{init}</pre>",
2004 vis = VisSpace(&it.visibility),
2005 mutability = MutableSpace(s.mutability),
2006 name = it.name.as_ref().unwrap(),
2008 init = Initializer(&s.expr))?;
2012 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2013 f: &clean::Function) -> fmt::Result {
2014 // FIXME(#24111): remove when `const_fn` is stabilized
2015 let vis_constness = match UnstableFeatures::from_environment() {
2016 UnstableFeatures::Allow => f.constness,
2017 _ => hir::Constness::NotConst
2019 let indent = format!("{}{}{}{:#}fn {}{:#}",
2020 VisSpace(&it.visibility),
2021 ConstnessSpace(vis_constness),
2022 UnsafetySpace(f.unsafety),
2024 it.name.as_ref().unwrap(),
2026 write!(w, "<pre class='rust fn'>")?;
2027 render_attributes(w, it)?;
2028 write!(w, "{vis}{constness}{unsafety}{abi}fn \
2029 {name}{generics}{decl}{where_clause}</pre>",
2030 vis = VisSpace(&it.visibility),
2031 constness = ConstnessSpace(vis_constness),
2032 unsafety = UnsafetySpace(f.unsafety),
2033 abi = AbiSpace(f.abi),
2034 name = it.name.as_ref().unwrap(),
2035 generics = f.generics,
2036 where_clause = WhereClause(&f.generics, 2),
2037 decl = Method(&f.decl, indent))?;
2041 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2042 t: &clean::Trait) -> fmt::Result {
2043 let mut bounds = String::new();
2044 let mut bounds_plain = String::new();
2045 if !t.bounds.is_empty() {
2046 if !bounds.is_empty() {
2048 bounds_plain.push(' ');
2050 bounds.push_str(": ");
2051 bounds_plain.push_str(": ");
2052 for (i, p) in t.bounds.iter().enumerate() {
2054 bounds.push_str(" + ");
2055 bounds_plain.push_str(" + ");
2057 bounds.push_str(&format!("{}", *p));
2058 bounds_plain.push_str(&format!("{:#}", *p));
2062 // Output the trait definition
2063 write!(w, "<pre class='rust trait'>")?;
2064 render_attributes(w, it)?;
2065 write!(w, "{}{}trait {}{}{}{} ",
2066 VisSpace(&it.visibility),
2067 UnsafetySpace(t.unsafety),
2068 it.name.as_ref().unwrap(),
2071 // Where clauses in traits are indented nine spaces, per rustdoc.css
2072 WhereClause(&t.generics, 9))?;
2074 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2075 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2076 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2077 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2079 if t.items.is_empty() {
2080 write!(w, "{{ }}")?;
2082 // FIXME: we should be using a derived_id for the Anchors here
2086 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2089 if !types.is_empty() && !consts.is_empty() {
2094 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2097 if !consts.is_empty() && !required.is_empty() {
2100 for m in &required {
2102 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2105 if !required.is_empty() && !provided.is_empty() {
2108 for m in &provided {
2110 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2111 write!(w, " {{ ... }}\n")?;
2115 write!(w, "</pre>")?;
2117 // Trait documentation
2118 document(w, cx, it)?;
2120 fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2122 let name = m.name.as_ref().unwrap();
2123 let item_type = m.type_();
2124 let id = derive_id(format!("{}.{}", item_type, name));
2125 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2126 write!(w, "<h3 id='{id}' class='method'>\
2127 <span id='{ns_id}' class='invisible'><code>",
2130 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2131 write!(w, "</code>")?;
2132 render_stability_since(w, m, t)?;
2133 write!(w, "</span></h3>")?;
2134 document(w, cx, m)?;
2138 if !types.is_empty() {
2140 <h2 id='associated-types'>Associated Types</h2>
2141 <div class='methods'>
2144 trait_item(w, cx, *t, it)?;
2146 write!(w, "</div>")?;
2149 if !consts.is_empty() {
2151 <h2 id='associated-const'>Associated Constants</h2>
2152 <div class='methods'>
2155 trait_item(w, cx, *t, it)?;
2157 write!(w, "</div>")?;
2160 // Output the documentation for each function individually
2161 if !required.is_empty() {
2163 <h2 id='required-methods'>Required Methods</h2>
2164 <div class='methods'>
2166 for m in &required {
2167 trait_item(w, cx, *m, it)?;
2169 write!(w, "</div>")?;
2171 if !provided.is_empty() {
2173 <h2 id='provided-methods'>Provided Methods</h2>
2174 <div class='methods'>
2176 for m in &provided {
2177 trait_item(w, cx, *m, it)?;
2179 write!(w, "</div>")?;
2182 // If there are methods directly on this trait object, render them here.
2183 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2185 let cache = cache();
2187 <h2 id='implementors'>Implementors</h2>
2188 <ul class='item-list' id='implementors-list'>
2190 if let Some(implementors) = cache.implementors.get(&it.def_id) {
2191 // The DefId is for the first Type found with that name. The bool is
2192 // if any Types with the same name but different DefId have been found.
2193 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2194 for implementor in implementors {
2195 match implementor.impl_.for_ {
2196 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2197 clean::BorrowedRef {
2198 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2201 let &mut (prev_did, ref mut has_duplicates) =
2202 implementor_dups.entry(path.last_name()).or_insert((did, false));
2203 if prev_did != did {
2204 *has_duplicates = true;
2211 for implementor in implementors {
2212 write!(w, "<li><code>")?;
2213 // If there's already another implementor that has the same abbridged name, use the
2214 // full path, for example in `std::iter::ExactSizeIterator`
2215 let use_absolute = match implementor.impl_.for_ {
2216 clean::ResolvedPath { ref path, is_generic: false, .. } |
2217 clean::BorrowedRef {
2218 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2220 } => implementor_dups[path.last_name()].1,
2223 fmt_impl_for_trait_page(&implementor.impl_, w, use_absolute)?;
2224 writeln!(w, "</code></li>")?;
2227 write!(w, "</ul>")?;
2228 write!(w, r#"<script type="text/javascript" async
2229 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2231 root_path = vec![".."; cx.current.len()].join("/"),
2232 path = if it.def_id.is_local() {
2233 cx.current.join("/")
2235 let (ref path, _) = cache.external_paths[&it.def_id];
2236 path[..path.len() - 1].join("/")
2238 ty = it.type_().css_class(),
2239 name = *it.name.as_ref().unwrap())?;
2243 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2244 use html::item_type::ItemType::*;
2246 let name = it.name.as_ref().unwrap();
2247 let ty = match it.type_() {
2248 Typedef | AssociatedType => AssociatedType,
2252 let anchor = format!("#{}.{}", ty, name);
2254 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2255 AssocItemLink::Anchor(None) => anchor,
2256 AssocItemLink::GotoSource(did, _) => {
2257 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2262 fn assoc_const(w: &mut fmt::Formatter,
2265 _default: Option<&String>,
2266 link: AssocItemLink) -> fmt::Result {
2267 write!(w, "const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2268 naive_assoc_href(it, link),
2269 it.name.as_ref().unwrap(),
2274 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
2275 bounds: &Vec<clean::TyParamBound>,
2276 default: Option<&clean::Type>,
2277 link: AssocItemLink) -> fmt::Result {
2278 write!(w, "type <a href='{}' class=\"type\">{}</a>",
2279 naive_assoc_href(it, link),
2280 it.name.as_ref().unwrap())?;
2281 if !bounds.is_empty() {
2282 write!(w, ": {}", TyParamBounds(bounds))?
2284 if let Some(default) = default {
2285 write!(w, " = {}", default)?;
2290 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2291 ver: Option<&'a str>,
2292 containing_ver: Option<&'a str>) -> fmt::Result {
2293 if let Some(v) = ver {
2294 if containing_ver != ver && v.len() > 0 {
2295 write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2302 fn render_stability_since(w: &mut fmt::Formatter,
2304 containing_item: &clean::Item) -> fmt::Result {
2305 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2308 fn render_assoc_item(w: &mut fmt::Formatter,
2310 link: AssocItemLink,
2311 parent: ItemType) -> fmt::Result {
2312 fn method(w: &mut fmt::Formatter,
2314 unsafety: hir::Unsafety,
2315 constness: hir::Constness,
2317 g: &clean::Generics,
2319 link: AssocItemLink,
2322 let name = meth.name.as_ref().unwrap();
2323 let anchor = format!("#{}.{}", meth.type_(), name);
2324 let href = match link {
2325 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2326 AssocItemLink::Anchor(None) => anchor,
2327 AssocItemLink::GotoSource(did, provided_methods) => {
2328 // We're creating a link from an impl-item to the corresponding
2329 // trait-item and need to map the anchored type accordingly.
2330 let ty = if provided_methods.contains(name) {
2336 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2339 // FIXME(#24111): remove when `const_fn` is stabilized
2340 let vis_constness = if is_nightly_build() {
2343 hir::Constness::NotConst
2345 let prefix = format!("{}{}{:#}fn {}{:#}",
2346 ConstnessSpace(vis_constness),
2347 UnsafetySpace(unsafety),
2351 let mut indent = prefix.len();
2352 let where_indent = if parent == ItemType::Trait {
2355 } else if parent == ItemType::Impl {
2358 let prefix = prefix + &format!("{:#}", Method(d, indent));
2359 prefix.lines().last().unwrap().len() + 1
2361 write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2362 {generics}{decl}{where_clause}",
2363 ConstnessSpace(vis_constness),
2364 UnsafetySpace(unsafety),
2369 decl = Method(d, indent),
2370 where_clause = WhereClause(g, where_indent))
2373 clean::StrippedItem(..) => Ok(()),
2374 clean::TyMethodItem(ref m) => {
2375 method(w, item, m.unsafety, hir::Constness::NotConst,
2376 m.abi, &m.generics, &m.decl, link, parent)
2378 clean::MethodItem(ref m) => {
2379 method(w, item, m.unsafety, m.constness,
2380 m.abi, &m.generics, &m.decl, link, parent)
2382 clean::AssociatedConstItem(ref ty, ref default) => {
2383 assoc_const(w, item, ty, default.as_ref(), link)
2385 clean::AssociatedTypeItem(ref bounds, ref default) => {
2386 assoc_type(w, item, bounds, default.as_ref(), link)
2388 _ => panic!("render_assoc_item called on non-associated-item")
2392 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2393 s: &clean::Struct) -> fmt::Result {
2394 write!(w, "<pre class='rust struct'>")?;
2395 render_attributes(w, it)?;
2403 write!(w, "</pre>")?;
2405 document(w, cx, it)?;
2406 let mut fields = s.fields.iter().filter_map(|f| {
2408 clean::StructFieldItem(ref ty) => Some((f, ty)),
2412 if let doctree::Plain = s.struct_type {
2413 if fields.peek().is_some() {
2414 write!(w, "<h2 class='fields'>Fields</h2>")?;
2415 for (field, ty) in fields {
2416 let id = derive_id(format!("{}.{}",
2417 ItemType::StructField,
2418 field.name.as_ref().unwrap()));
2419 let ns_id = derive_id(format!("{}.{}",
2420 field.name.as_ref().unwrap(),
2421 ItemType::StructField.name_space()));
2422 write!(w, "<span id='{id}' class=\"{item_type}\">
2423 <span id='{ns_id}' class='invisible'>
2424 <code>{name}: {ty}</code>
2426 item_type = ItemType::StructField,
2429 name = field.name.as_ref().unwrap(),
2431 if let Some(stability_class) = field.stability_class() {
2432 write!(w, "<span class='stab {stab}'></span>",
2433 stab = stability_class)?;
2435 document(w, cx, field)?;
2439 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2442 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2443 s: &clean::Union) -> fmt::Result {
2444 write!(w, "<pre class='rust union'>")?;
2445 render_attributes(w, it)?;
2452 write!(w, "</pre>")?;
2454 document(w, cx, it)?;
2455 let mut fields = s.fields.iter().filter_map(|f| {
2457 clean::StructFieldItem(ref ty) => Some((f, ty)),
2461 if fields.peek().is_some() {
2462 write!(w, "<h2 class='fields'>Fields</h2>")?;
2463 for (field, ty) in fields {
2464 write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2466 shortty = ItemType::StructField,
2467 name = field.name.as_ref().unwrap(),
2469 if let Some(stability_class) = field.stability_class() {
2470 write!(w, "<span class='stab {stab}'></span>",
2471 stab = stability_class)?;
2473 document(w, cx, field)?;
2476 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2479 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2480 e: &clean::Enum) -> fmt::Result {
2481 write!(w, "<pre class='rust enum'>")?;
2482 render_attributes(w, it)?;
2483 let padding = format!("{}enum {}{:#} ",
2484 VisSpace(&it.visibility),
2485 it.name.as_ref().unwrap(),
2487 write!(w, "{}enum {}{}{}",
2488 VisSpace(&it.visibility),
2489 it.name.as_ref().unwrap(),
2491 WhereClause(&e.generics, padding))?;
2492 if e.variants.is_empty() && !e.variants_stripped {
2493 write!(w, " {{}}")?;
2495 write!(w, " {{\n")?;
2496 for v in &e.variants {
2498 let name = v.name.as_ref().unwrap();
2500 clean::VariantItem(ref var) => {
2502 clean::VariantKind::CLike => write!(w, "{}", name)?,
2503 clean::VariantKind::Tuple(ref tys) => {
2504 write!(w, "{}(", name)?;
2505 for (i, ty) in tys.iter().enumerate() {
2507 write!(w, ", ")?
2509 write!(w, "{}", *ty)?;
2513 clean::VariantKind::Struct(ref s) => {
2529 if e.variants_stripped {
2530 write!(w, " // some variants omitted\n")?;
2534 write!(w, "</pre>")?;
2536 document(w, cx, it)?;
2537 if !e.variants.is_empty() {
2538 write!(w, "<h2 class='variants'>Variants</h2>\n")?;
2539 for variant in &e.variants {
2540 let id = derive_id(format!("{}.{}",
2542 variant.name.as_ref().unwrap()));
2543 let ns_id = derive_id(format!("{}.{}",
2544 variant.name.as_ref().unwrap(),
2545 ItemType::Variant.name_space()));
2546 write!(w, "<span id='{id}' class='variant'>\
2547 <span id='{ns_id}' class='invisible'><code>{name}",
2550 name = variant.name.as_ref().unwrap())?;
2551 if let clean::VariantItem(ref var) = variant.inner {
2552 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2554 for (i, ty) in tys.iter().enumerate() {
2556 write!(w, ", ")?;
2558 write!(w, "{}", *ty)?;
2563 write!(w, "</code></span></span>")?;
2564 document(w, cx, variant)?;
2566 use clean::{Variant, VariantKind};
2567 if let clean::VariantItem(Variant {
2568 kind: VariantKind::Struct(ref s)
2569 }) = variant.inner {
2570 let variant_id = derive_id(format!("{}.{}.fields",
2572 variant.name.as_ref().unwrap()));
2573 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2575 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2576 <table>", name = variant.name.as_ref().unwrap())?;
2577 for field in &s.fields {
2578 use clean::StructFieldItem;
2579 if let StructFieldItem(ref ty) = field.inner {
2580 let id = derive_id(format!("variant.{}.field.{}",
2581 variant.name.as_ref().unwrap(),
2582 field.name.as_ref().unwrap()));
2583 let ns_id = derive_id(format!("{}.{}.{}.{}",
2584 variant.name.as_ref().unwrap(),
2585 ItemType::Variant.name_space(),
2586 field.name.as_ref().unwrap(),
2587 ItemType::StructField.name_space()));
2588 write!(w, "<tr><td \
2590 <span id='{ns_id}' class='invisible'>\
2591 <code>{f}: {t}</code></span></td><td>",
2594 f = field.name.as_ref().unwrap(),
2596 document(w, cx, field)?;
2597 write!(w, "</td></tr>")?;
2600 write!(w, "</table></span>")?;
2602 render_stability_since(w, variant, it)?;
2605 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2609 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2610 let name = attr.name();
2613 Some(format!("{}", name))
2614 } else if let Some(v) = attr.value_str() {
2615 Some(format!("{} = {:?}", name, v.as_str()))
2616 } else if let Some(values) = attr.meta_item_list() {
2617 let display: Vec<_> = values.iter().filter_map(|attr| {
2618 attr.meta_item().and_then(|mi| render_attribute(mi))
2621 if display.len() > 0 {
2622 Some(format!("{}({})", name, display.join(", ")))
2631 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2638 "unsafe_destructor_blind_to_params"
2641 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2642 let mut attrs = String::new();
2644 for attr in &it.attrs.other_attrs {
2645 let name = attr.name().unwrap();
2646 if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2649 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2650 attrs.push_str(&format!("#[{}]\n", s));
2653 if attrs.len() > 0 {
2654 write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2659 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2660 g: Option<&clean::Generics>,
2661 ty: doctree::StructType,
2662 fields: &[clean::Item],
2664 structhead: bool) -> fmt::Result {
2665 let mut plain = String::new();
2667 VisSpace(&it.visibility),
2668 if structhead {"struct "} else {""},
2669 it.name.as_ref().unwrap())?;
2670 plain.push_str(&format!("{}{}{}",
2671 VisSpace(&it.visibility),
2672 if structhead {"struct "} else {""},
2673 it.name.as_ref().unwrap()));
2674 if let Some(g) = g {
2675 plain.push_str(&format!("{:#}", g));
2680 if let Some(g) = g {
2681 write!(w, "{}", WhereClause(g, plain.len() + 1))?
2683 let mut has_visible_fields = false;
2685 for field in fields {
2686 if let clean::StructFieldItem(ref ty) = field.inner {
2687 write!(w, "\n{} {}{}: {},",
2689 VisSpace(&field.visibility),
2690 field.name.as_ref().unwrap(),
2692 has_visible_fields = true;
2696 if has_visible_fields {
2697 if it.has_stripped_fields().unwrap() {
2698 write!(w, "\n{} // some fields omitted", tab)?;
2700 write!(w, "\n{}", tab)?;
2701 } else if it.has_stripped_fields().unwrap() {
2702 // If there are no visible fields we can just display
2703 // `{ /* fields omitted */ }` to save space.
2704 write!(w, " /* fields omitted */ ")?;
2710 plain.push_str("(");
2711 for (i, field) in fields.iter().enumerate() {
2714 plain.push_str(", ");
2717 clean::StrippedItem(box clean::StructFieldItem(..)) => {
2718 plain.push_str("_");
2721 clean::StructFieldItem(ref ty) => {
2722 plain.push_str(&format!("{}{:#}", VisSpace(&field.visibility), *ty));
2723 write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
2729 plain.push_str(")");
2730 if let Some(g) = g {
2731 write!(w, "{}", WhereClause(g, plain.len() + 1))?
2736 // Needed for PhantomData.
2737 if let Some(g) = g {
2738 write!(w, "{}", WhereClause(g, plain.len() + 1))?
2746 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
2747 g: Option<&clean::Generics>,
2748 fields: &[clean::Item],
2750 structhead: bool) -> fmt::Result {
2751 let mut plain = String::new();
2753 VisSpace(&it.visibility),
2754 if structhead {"union "} else {""},
2755 it.name.as_ref().unwrap())?;
2756 plain.push_str(&format!("{}{}{}",
2757 VisSpace(&it.visibility),
2758 if structhead {"union "} else {""},
2759 it.name.as_ref().unwrap()));
2760 if let Some(g) = g {
2761 write!(w, "{}", g)?;
2762 plain.push_str(&format!("{:#}", g));
2763 write!(w, "{}", WhereClause(g, plain.len() + 1))?;
2766 write!(w, " {{\n{}", tab)?;
2767 for field in fields {
2768 if let clean::StructFieldItem(ref ty) = field.inner {
2769 write!(w, " {}{}: {},\n{}",
2770 VisSpace(&field.visibility),
2771 field.name.as_ref().unwrap(),
2777 if it.has_stripped_fields().unwrap() {
2778 write!(w, " // some fields omitted\n{}", tab)?;
2784 #[derive(Copy, Clone)]
2785 enum AssocItemLink<'a> {
2786 Anchor(Option<&'a str>),
2787 GotoSource(DefId, &'a FxHashSet<String>),
2790 impl<'a> AssocItemLink<'a> {
2791 fn anchor(&self, id: &'a String) -> Self {
2793 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
2794 ref other => *other,
2799 enum AssocItemRender<'a> {
2801 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
2804 #[derive(Copy, Clone, PartialEq)]
2807 ForDeref { mut_: bool },
2810 fn render_assoc_items(w: &mut fmt::Formatter,
2812 containing_item: &clean::Item,
2814 what: AssocItemRender) -> fmt::Result {
2816 let v = match c.impls.get(&it) {
2818 None => return Ok(()),
2820 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
2821 i.inner_impl().trait_.is_none()
2823 if !non_trait.is_empty() {
2824 let render_mode = match what {
2825 AssocItemRender::All => {
2826 write!(w, "<h2 id='methods'>Methods</h2>")?;
2829 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
2830 write!(w, "<h2 id='deref-methods'>Methods from \
2831 {}<Target = {}></h2>", trait_, type_)?;
2832 RenderMode::ForDeref { mut_: deref_mut_ }
2835 for i in &non_trait {
2836 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
2837 containing_item.stable_since())?;
2840 if let AssocItemRender::DerefFor { .. } = what {
2843 if !traits.is_empty() {
2844 let deref_impl = traits.iter().find(|t| {
2845 t.inner_impl().trait_.def_id() == c.deref_trait_did
2847 if let Some(impl_) = deref_impl {
2848 let has_deref_mut = traits.iter().find(|t| {
2849 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
2851 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
2853 write!(w, "<h2 id='implementations'>Trait \
2854 Implementations</h2>")?;
2856 let did = i.trait_did().unwrap();
2857 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2858 render_impl(w, cx, i, assoc_link,
2859 RenderMode::Normal, containing_item.stable_since())?;
2865 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
2866 container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
2867 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
2868 let target = impl_.inner_impl().items.iter().filter_map(|item| {
2870 clean::TypedefItem(ref t, true) => Some(&t.type_),
2873 }).next().expect("Expected associated type binding");
2874 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
2875 deref_mut_: deref_mut };
2876 if let Some(did) = target.def_id() {
2877 render_assoc_items(w, cx, container_item, did, what)
2879 if let Some(prim) = target.primitive_type() {
2880 if let Some(&did) = cache().primitive_locations.get(&prim) {
2881 render_assoc_items(w, cx, container_item, did, what)?;
2888 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
2889 render_mode: RenderMode, outer_version: Option<&str>) -> fmt::Result {
2890 if render_mode == RenderMode::Normal {
2891 write!(w, "<h3 class='impl'><span class='in-band'><code>{}</code>", i.inner_impl())?;
2892 write!(w, "</span><span class='out-of-band'>")?;
2893 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
2894 if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
2895 write!(w, "<div class='ghost'></div>")?;
2896 render_stability_since_raw(w, since, outer_version)?;
2897 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2898 l, "goto source code")?;
2900 render_stability_since_raw(w, since, outer_version)?;
2902 write!(w, "</span>")?;
2903 write!(w, "</h3>\n")?;
2904 if let Some(ref dox) = i.impl_item.doc_value() {
2905 write!(w, "<div class='docblock'>{}</div>", Markdown(dox))?;
2909 fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2910 link: AssocItemLink, render_mode: RenderMode,
2911 is_default_item: bool, outer_version: Option<&str>,
2912 trait_: Option<&clean::Trait>) -> fmt::Result {
2913 let item_type = item.type_();
2914 let name = item.name.as_ref().unwrap();
2916 let render_method_item: bool = match render_mode {
2917 RenderMode::Normal => true,
2918 RenderMode::ForDeref { mut_: deref_mut_ } => {
2919 let self_type_opt = match item.inner {
2920 clean::MethodItem(ref method) => method.decl.self_type(),
2921 clean::TyMethodItem(ref method) => method.decl.self_type(),
2925 if let Some(self_ty) = self_type_opt {
2926 let by_mut_ref = match self_ty {
2927 SelfTy::SelfBorrowed(_lifetime, mutability) => {
2928 mutability == Mutability::Mutable
2930 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
2931 mutability == Mutability::Mutable
2936 deref_mut_ || !by_mut_ref
2944 clean::MethodItem(..) | clean::TyMethodItem(..) => {
2945 // Only render when the method is not static or we allow static methods
2946 if render_method_item {
2947 let id = derive_id(format!("{}.{}", item_type, name));
2948 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2949 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
2950 write!(w, "<span id='{}' class='invisible'>", ns_id)?;
2951 write!(w, "<code>")?;
2952 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
2953 write!(w, "</code>")?;
2954 render_stability_since_raw(w, item.stable_since(), outer_version)?;
2955 write!(w, "</span></h4>\n")?;
2958 clean::TypedefItem(ref tydef, _) => {
2959 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
2960 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2961 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
2962 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2963 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
2964 write!(w, "</code></span></h4>\n")?;
2966 clean::AssociatedConstItem(ref ty, ref default) => {
2967 let id = derive_id(format!("{}.{}", item_type, name));
2968 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2969 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
2970 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2971 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
2972 write!(w, "</code></span></h4>\n")?;
2974 clean::ConstantItem(ref c) => {
2975 let id = derive_id(format!("{}.{}", item_type, name));
2976 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2977 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
2978 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2979 assoc_const(w, item, &c.type_, Some(&c.expr), link.anchor(&id))?;
2980 write!(w, "</code></span></h4>\n")?;
2982 clean::AssociatedTypeItem(ref bounds, ref default) => {
2983 let id = derive_id(format!("{}.{}", item_type, name));
2984 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2985 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
2986 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2987 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
2988 write!(w, "</code></span></h4>\n")?;
2990 clean::StrippedItem(..) => return Ok(()),
2991 _ => panic!("can't make docs for trait item with name {:?}", item.name)
2994 if render_method_item || render_mode == RenderMode::Normal {
2995 if !is_default_item {
2996 if let Some(t) = trait_ {
2997 // The trait item may have been stripped so we might not
2998 // find any documentation or stability for it.
2999 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3000 // We need the stability of the item from the trait
3001 // because impls can't have a stability.
3002 document_stability(w, cx, it)?;
3003 if get_doc_value(item).is_some() {
3004 document_full(w, item)?;
3006 // In case the item isn't documented,
3007 // provide short documentation from the trait.
3008 document_short(w, it, link)?;
3012 document(w, cx, item)?;
3015 document_stability(w, cx, item)?;
3016 document_short(w, item, link)?;
3022 let traits = &cache().traits;
3023 let trait_ = i.trait_did().and_then(|did| traits.get(&did));
3025 write!(w, "<div class='impl-items'>")?;
3026 for trait_item in &i.inner_impl().items {
3027 doc_impl_item(w, cx, trait_item, link, render_mode,
3028 false, outer_version, trait_)?;
3031 fn render_default_items(w: &mut fmt::Formatter,
3035 render_mode: RenderMode,
3036 outer_version: Option<&str>) -> fmt::Result {
3037 for trait_item in &t.items {
3038 let n = trait_item.name.clone();
3039 if i.items.iter().find(|m| m.name == n).is_some() {
3042 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3043 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3045 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3046 outer_version, None)?;
3051 // If we've implemented a trait, then also emit documentation for all
3052 // default items which weren't overridden in the implementation block.
3053 if let Some(t) = trait_ {
3054 render_default_items(w, cx, t, &i.inner_impl(), render_mode, outer_version)?;
3056 write!(w, "</div>")?;
3060 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3061 t: &clean::Typedef) -> fmt::Result {
3062 let indent = format!("type {}{:#} ", it.name.as_ref().unwrap(), t.generics).len();
3063 write!(w, "<pre class='rust typedef'>")?;
3064 render_attributes(w, it)?;
3065 write!(w, "type {}{}{where_clause} = {type_};</pre>",
3066 it.name.as_ref().unwrap(),
3068 where_clause = WhereClause(&t.generics, indent),
3074 impl<'a> fmt::Display for Sidebar<'a> {
3075 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3078 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3080 // The sidebar is designed to display sibling functions, modules and
3081 // other miscellaneous information. since there are lots of sibling
3082 // items (and that causes quadratic growth in large modules),
3083 // we refactor common parts into a shared JavaScript file per module.
3084 // still, we don't move everything into JS because we want to preserve
3085 // as much HTML as possible in order to allow non-JS-enabled browsers
3086 // to navigate the documentation (though slightly inefficiently).
3088 write!(fmt, "<p class='location'>")?;
3089 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3091 write!(fmt, "::<wbr>")?;
3093 write!(fmt, "<a href='{}index.html'>{}</a>",
3094 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3097 write!(fmt, "</p>")?;
3099 // Sidebar refers to the enclosing module, not this module.
3100 let relpath = if it.is_mod() { "../" } else { "" };
3102 "<script>window.sidebarCurrent = {{\
3107 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3108 ty = it.type_().css_class(),
3111 // There is no sidebar-items.js beyond the crate root path
3112 // FIXME maybe dynamic crate loading can be merged here
3114 write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3122 impl<'a> fmt::Display for Source<'a> {
3123 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3124 let Source(s) = *self;
3125 let lines = s.lines().count();
3127 let mut tmp = lines;
3132 write!(fmt, "<pre class=\"line-numbers\">")?;
3133 for i in 1..lines + 1 {
3134 write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
3136 write!(fmt, "</pre>")?;
3137 write!(fmt, "{}", highlight::render_with_highlighting(s, None, None, None))?;
3142 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3143 t: &clean::Macro) -> fmt::Result {
3144 w.write_str(&highlight::render_with_highlighting(&t.source,
3151 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
3153 _p: &clean::PrimitiveType) -> fmt::Result {
3154 document(w, cx, it)?;
3155 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3158 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
3160 fn make_item_keywords(it: &clean::Item) -> String {
3161 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
3164 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
3165 let decl = match item.inner {
3166 clean::FunctionItem(ref f) => &f.decl,
3167 clean::MethodItem(ref m) => &m.decl,
3168 clean::TyMethodItem(ref m) => &m.decl,
3172 let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
3173 let output = match decl.output {
3174 clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
3178 Some(IndexItemFunctionType { inputs: inputs, output: output })
3181 fn get_index_type(clean_type: &clean::Type) -> Type {
3182 Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
3185 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
3187 clean::ResolvedPath { ref path, .. } => {
3188 let segments = &path.segments;
3189 Some(segments[segments.len() - 1].name.clone())
3191 clean::Generic(ref s) => Some(s.clone()),
3192 clean::Primitive(ref p) => Some(format!("{:?}", p)),
3193 clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
3194 // FIXME: add all from clean::Type.
3199 pub fn cache() -> Arc<Cache> {
3200 CACHE_KEY.with(|c| c.borrow().clone())
3205 fn test_unique_id() {
3206 let input = ["foo", "examples", "examples", "method.into_iter","examples",
3207 "method.into_iter", "foo", "main", "search", "methods",
3208 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
3209 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
3210 "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
3211 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
3214 let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
3215 assert_eq!(&actual[..], expected);
3224 fn test_name_key() {
3225 assert_eq!(name_key("0"), ("", 0, 1));
3226 assert_eq!(name_key("123"), ("", 123, 0));
3227 assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
3228 assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
3229 assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
3230 assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
3231 assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
3232 assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
3237 fn test_name_sorting() {
3238 let names = ["Apple",
3240 "Fruit", "Fruit0", "Fruit00",
3241 "Fruit1", "Fruit01",
3242 "Fruit2", "Fruit02",
3246 let mut sorted = names.to_owned();
3247 sorted.sort_by_key(|&s| name_key(s));
3248 assert_eq!(names, sorted);